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.cjs CHANGED
@@ -10,7 +10,6 @@ var async_hooks = require('async_hooks');
10
10
  var sdkTraceBase = require('@opentelemetry/sdk-trace-base');
11
11
  var nodeServerSdk = require('@traceloop/node-server-sdk');
12
12
  var shimmer = require('shimmer');
13
- var dotenv = require('dotenv');
14
13
  var core = require('@opentelemetry/core');
15
14
  var http = require('http');
16
15
  var https = require('https');
@@ -41,7 +40,6 @@ function _interopNamespace(e) {
41
40
 
42
41
  var crypto__default = /*#__PURE__*/_interopDefault(crypto);
43
42
  var shimmer__default = /*#__PURE__*/_interopDefault(shimmer);
44
- var dotenv__namespace = /*#__PURE__*/_interopNamespace(dotenv);
45
43
  var http__namespace = /*#__PURE__*/_interopNamespace(http);
46
44
  var https__namespace = /*#__PURE__*/_interopNamespace(https);
47
45
  var pLimit__default = /*#__PURE__*/_interopDefault(pLimit);
@@ -2462,14 +2460,14 @@ var require_otel = __commonJS({
2462
2460
  getActiveSpan() {
2463
2461
  return void 0;
2464
2462
  }
2465
- setSpan(context17, _span) {
2466
- return context17;
2463
+ setSpan(context18, _span) {
2464
+ return context18;
2467
2465
  }
2468
2466
  getSpan(_context) {
2469
2467
  return void 0;
2470
2468
  }
2471
- setSpanContext(context17, _spanContext) {
2472
- return context17;
2469
+ setSpanContext(context18, _spanContext) {
2470
+ return context18;
2473
2471
  }
2474
2472
  getTracerProvider() {
2475
2473
  return void 0;
@@ -3036,17 +3034,17 @@ var require_p_retry = __commonJS({
3036
3034
  }
3037
3035
  const retriesLeft = Number.isFinite(options.retries) ? Math.max(0, options.retries - retriesConsumed) : options.retries;
3038
3036
  const maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY;
3039
- const context17 = Object.freeze({
3037
+ const context18 = Object.freeze({
3040
3038
  error: normalizedError,
3041
3039
  attemptNumber,
3042
3040
  retriesLeft,
3043
3041
  retriesConsumed
3044
3042
  });
3045
- await options.onFailedAttempt(context17);
3043
+ await options.onFailedAttempt(context18);
3046
3044
  if (calculateRemainingTime(startTime, maxRetryTime) <= 0) {
3047
3045
  throw normalizedError;
3048
3046
  }
3049
- const consumeRetry = await options.shouldConsumeRetry(context17);
3047
+ const consumeRetry = await options.shouldConsumeRetry(context18);
3050
3048
  const remainingTime = calculateRemainingTime(startTime, maxRetryTime);
3051
3049
  if (remainingTime <= 0 || retriesLeft <= 0) {
3052
3050
  throw normalizedError;
@@ -3058,7 +3056,7 @@ var require_p_retry = __commonJS({
3058
3056
  options.signal?.throwIfAborted();
3059
3057
  return false;
3060
3058
  }
3061
- if (!await options.shouldRetry(context17)) {
3059
+ if (!await options.shouldRetry(context18)) {
3062
3060
  throw normalizedError;
3063
3061
  }
3064
3062
  if (!consumeRetry) {
@@ -3166,16 +3164,16 @@ var require_eventemitter3 = __commonJS({
3166
3164
  Events.prototype = /* @__PURE__ */ Object.create(null);
3167
3165
  if (!new Events().__proto__) prefix = false;
3168
3166
  }
3169
- function EE(fn, context17, once) {
3167
+ function EE(fn, context18, once) {
3170
3168
  this.fn = fn;
3171
- this.context = context17;
3169
+ this.context = context18;
3172
3170
  this.once = once || false;
3173
3171
  }
3174
- function addListener(emitter, event, fn, context17, once) {
3172
+ function addListener(emitter, event, fn, context18, once) {
3175
3173
  if (typeof fn !== "function") {
3176
3174
  throw new TypeError("The listener must be a function");
3177
3175
  }
3178
- var listener = new EE(fn, context17 || emitter, once), evt = prefix ? prefix + event : event;
3176
+ var listener = new EE(fn, context18 || emitter, once), evt = prefix ? prefix + event : event;
3179
3177
  if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
3180
3178
  else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
3181
3179
  else emitter._events[evt] = [emitter._events[evt], listener];
@@ -3266,13 +3264,13 @@ var require_eventemitter3 = __commonJS({
3266
3264
  }
3267
3265
  return true;
3268
3266
  };
3269
- EventEmitter.prototype.on = function on(event, fn, context17) {
3270
- return addListener(this, event, fn, context17, false);
3267
+ EventEmitter.prototype.on = function on(event, fn, context18) {
3268
+ return addListener(this, event, fn, context18, false);
3271
3269
  };
3272
- EventEmitter.prototype.once = function once(event, fn, context17) {
3273
- return addListener(this, event, fn, context17, true);
3270
+ EventEmitter.prototype.once = function once(event, fn, context18) {
3271
+ return addListener(this, event, fn, context18, true);
3274
3272
  };
3275
- EventEmitter.prototype.removeListener = function removeListener(event, fn, context17, once) {
3273
+ EventEmitter.prototype.removeListener = function removeListener(event, fn, context18, once) {
3276
3274
  var evt = prefix ? prefix + event : event;
3277
3275
  if (!this._events[evt]) return this;
3278
3276
  if (!fn) {
@@ -3281,12 +3279,12 @@ var require_eventemitter3 = __commonJS({
3281
3279
  }
3282
3280
  var listeners = this._events[evt];
3283
3281
  if (listeners.fn) {
3284
- if (listeners.fn === fn && (!once || listeners.once) && (!context17 || listeners.context === context17)) {
3282
+ if (listeners.fn === fn && (!once || listeners.once) && (!context18 || listeners.context === context18)) {
3285
3283
  clearEvent(this, evt);
3286
3284
  }
3287
3285
  } else {
3288
3286
  for (var i = 0, events = [], length = listeners.length; i < length; i++) {
3289
- if (listeners[i].fn !== fn || once && !listeners[i].once || context17 && listeners[i].context !== context17) {
3287
+ if (listeners[i].fn !== fn || once && !listeners[i].once || context18 && listeners[i].context !== context18) {
3290
3288
  events.push(listeners[i]);
3291
3289
  }
3292
3290
  }
@@ -5845,7 +5843,7 @@ var require_error = __commonJS({
5845
5843
  }
5846
5844
  };
5847
5845
  exports$1.LangSmithConflictError = LangSmithConflictError;
5848
- async function raiseForStatus(response, context17, consumeOnSuccess) {
5846
+ async function raiseForStatus(response, context18, consumeOnSuccess) {
5849
5847
  let errorBody;
5850
5848
  if (response.ok) {
5851
5849
  if (consumeOnSuccess) {
@@ -5873,7 +5871,7 @@ var require_error = __commonJS({
5873
5871
  errorBody = "";
5874
5872
  }
5875
5873
  }
5876
- const fullMessage = `Failed to ${context17}. Received status [${response.status}]: ${response.statusText}. Message: ${errorBody}`;
5874
+ const fullMessage = `Failed to ${context18}. Received status [${response.status}]: ${response.statusText}. Message: ${errorBody}`;
5877
5875
  if (response.status === 409) {
5878
5876
  throw new LangSmithConflictError(fullMessage);
5879
5877
  }
@@ -6278,7 +6276,7 @@ var require_client = __commonJS({
6278
6276
  get _fetch() {
6279
6277
  return this.fetchImplementation || (0, fetch_js_1._getFetchImplementation)(this.debug);
6280
6278
  }
6281
- constructor(config2 = {}) {
6279
+ constructor(config = {}) {
6282
6280
  Object.defineProperty(this, "apiKey", {
6283
6281
  enumerable: true,
6284
6282
  configurable: true,
@@ -6466,48 +6464,48 @@ var require_client = __commonJS({
6466
6464
  value: (0, env_js_1.getEnvironmentVariable)("LANGSMITH_DEBUG") === "true"
6467
6465
  });
6468
6466
  const defaultConfig = _Client.getDefaultClientConfig();
6469
- this.tracingSampleRate = getTracingSamplingRate(config2.tracingSamplingRate);
6470
- this.apiUrl = trimQuotes(config2.apiUrl ?? defaultConfig.apiUrl) ?? "";
6467
+ this.tracingSampleRate = getTracingSamplingRate(config.tracingSamplingRate);
6468
+ this.apiUrl = trimQuotes(config.apiUrl ?? defaultConfig.apiUrl) ?? "";
6471
6469
  if (this.apiUrl.endsWith("/")) {
6472
6470
  this.apiUrl = this.apiUrl.slice(0, -1);
6473
6471
  }
6474
- this.apiKey = trimQuotes(config2.apiKey ?? defaultConfig.apiKey);
6475
- this.webUrl = trimQuotes(config2.webUrl ?? defaultConfig.webUrl);
6472
+ this.apiKey = trimQuotes(config.apiKey ?? defaultConfig.apiKey);
6473
+ this.webUrl = trimQuotes(config.webUrl ?? defaultConfig.webUrl);
6476
6474
  if (this.webUrl?.endsWith("/")) {
6477
6475
  this.webUrl = this.webUrl.slice(0, -1);
6478
6476
  }
6479
- this.workspaceId = trimQuotes(config2.workspaceId ?? (0, env_js_1.getLangSmithEnvironmentVariable)("WORKSPACE_ID"));
6480
- this.timeout_ms = config2.timeout_ms ?? 9e4;
6477
+ this.workspaceId = trimQuotes(config.workspaceId ?? (0, env_js_1.getLangSmithEnvironmentVariable)("WORKSPACE_ID"));
6478
+ this.timeout_ms = config.timeout_ms ?? 9e4;
6481
6479
  this.caller = new async_caller_js_1.AsyncCaller({
6482
- ...config2.callerOptions ?? {},
6480
+ ...config.callerOptions ?? {},
6483
6481
  maxRetries: 4,
6484
- debug: config2.debug ?? this.debug
6482
+ debug: config.debug ?? this.debug
6485
6483
  });
6486
- this.traceBatchConcurrency = config2.traceBatchConcurrency ?? this.traceBatchConcurrency;
6484
+ this.traceBatchConcurrency = config.traceBatchConcurrency ?? this.traceBatchConcurrency;
6487
6485
  if (this.traceBatchConcurrency < 1) {
6488
6486
  throw new Error("Trace batch concurrency must be positive.");
6489
6487
  }
6490
- this.debug = config2.debug ?? this.debug;
6491
- this.fetchImplementation = config2.fetchImplementation;
6492
- const maxMemory = config2.maxIngestMemoryBytes ?? exports$1.DEFAULT_MAX_SIZE_BYTES;
6488
+ this.debug = config.debug ?? this.debug;
6489
+ this.fetchImplementation = config.fetchImplementation;
6490
+ const maxMemory = config.maxIngestMemoryBytes ?? exports$1.DEFAULT_MAX_SIZE_BYTES;
6493
6491
  this.batchIngestCaller = new async_caller_js_1.AsyncCaller({
6494
6492
  maxRetries: 4,
6495
6493
  maxConcurrency: this.traceBatchConcurrency,
6496
6494
  maxQueueSizeBytes: maxMemory,
6497
- ...config2.callerOptions ?? {},
6495
+ ...config.callerOptions ?? {},
6498
6496
  onFailedResponseHook: handle429,
6499
- debug: config2.debug ?? this.debug
6497
+ debug: config.debug ?? this.debug
6500
6498
  });
6501
- this.hideInputs = config2.hideInputs ?? config2.anonymizer ?? defaultConfig.hideInputs;
6502
- this.hideOutputs = config2.hideOutputs ?? config2.anonymizer ?? defaultConfig.hideOutputs;
6503
- this.omitTracedRuntimeInfo = config2.omitTracedRuntimeInfo ?? false;
6504
- this.autoBatchTracing = config2.autoBatchTracing ?? this.autoBatchTracing;
6499
+ this.hideInputs = config.hideInputs ?? config.anonymizer ?? defaultConfig.hideInputs;
6500
+ this.hideOutputs = config.hideOutputs ?? config.anonymizer ?? defaultConfig.hideOutputs;
6501
+ this.omitTracedRuntimeInfo = config.omitTracedRuntimeInfo ?? false;
6502
+ this.autoBatchTracing = config.autoBatchTracing ?? this.autoBatchTracing;
6505
6503
  this.autoBatchQueue = new AutoBatchQueue(maxMemory);
6506
- this.blockOnRootRunFinalization = config2.blockOnRootRunFinalization ?? this.blockOnRootRunFinalization;
6507
- this.batchSizeBytesLimit = config2.batchSizeBytesLimit;
6508
- this.batchSizeLimit = config2.batchSizeLimit;
6509
- this.fetchOptions = config2.fetchOptions || {};
6510
- this.manualFlushMode = config2.manualFlushMode ?? this.manualFlushMode;
6504
+ this.blockOnRootRunFinalization = config.blockOnRootRunFinalization ?? this.blockOnRootRunFinalization;
6505
+ this.batchSizeBytesLimit = config.batchSizeBytesLimit;
6506
+ this.batchSizeLimit = config.batchSizeLimit;
6507
+ this.fetchOptions = config.fetchOptions || {};
6508
+ this.manualFlushMode = config.manualFlushMode ?? this.manualFlushMode;
6511
6509
  if ((0, env_js_1.getOtelEnabled)()) {
6512
6510
  this.langSmithToOTELTranslator = new translator_js_1.LangSmithToOTELTranslator();
6513
6511
  }
@@ -7226,7 +7224,7 @@ var require_client = __commonJS({
7226
7224
  });
7227
7225
  return stream;
7228
7226
  }
7229
- async _sendMultipartRequest(parts, context17, options) {
7227
+ async _sendMultipartRequest(parts, context18, options) {
7230
7228
  const boundary = "----LangSmithFormBoundary" + Math.random().toString(36).slice(2);
7231
7229
  const isNodeFetch = (0, fetch_js_1._globalFetchImplementationIsNodeFetch)();
7232
7230
  const buildBuffered = () => this._createNodeFetchBody(parts, boundary);
@@ -7268,14 +7266,14 @@ var require_client = __commonJS({
7268
7266
  res = await sendWithRetry(buildBuffered);
7269
7267
  }
7270
7268
  if ((!this.multipartStreamingDisabled || streamedAttempt) && res.status === 422 && (options?.apiUrl ?? this.apiUrl) !== DEFAULT_API_URL) {
7271
- console.warn(`Streaming multipart upload to ${options?.apiUrl ?? this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${context17}".`);
7269
+ console.warn(`Streaming multipart upload to ${options?.apiUrl ?? this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${context18}".`);
7272
7270
  this.multipartStreamingDisabled = true;
7273
7271
  res = await sendWithRetry(buildBuffered);
7274
7272
  }
7275
7273
  } catch (e) {
7276
7274
  console.warn(`${e.message.trim()}
7277
7275
 
7278
- Context: ${context17}`);
7276
+ Context: ${context18}`);
7279
7277
  }
7280
7278
  }
7281
7279
  async updateRun(runId, run, options) {
@@ -7608,7 +7606,7 @@ Context: ${context17}`);
7608
7606
  }
7609
7607
  }
7610
7608
  }
7611
- async getRunStats({ id, trace: trace24, parentRun, runType, projectNames, projectIds, referenceExampleIds, startTime, endTime, error, query, filter, traceFilter, treeFilter, isRoot, dataSourceType }) {
7609
+ async getRunStats({ id, trace: trace25, parentRun, runType, projectNames, projectIds, referenceExampleIds, startTime, endTime, error, query, filter, traceFilter, treeFilter, isRoot, dataSourceType }) {
7612
7610
  let projectIds_ = projectIds || [];
7613
7611
  if (projectNames) {
7614
7612
  projectIds_ = [
@@ -7618,7 +7616,7 @@ Context: ${context17}`);
7618
7616
  }
7619
7617
  const payload = {
7620
7618
  id,
7621
- trace: trace24,
7619
+ trace: trace25,
7622
7620
  parent_run: parentRun,
7623
7621
  run_type: runType,
7624
7622
  session: projectIds_,
@@ -10107,17 +10105,17 @@ var require_run_trees = __commonJS({
10107
10105
  return;
10108
10106
  }
10109
10107
  const defaultConfig = _RunTree.getDefaultConfig();
10110
- const { metadata, ...config2 } = originalConfig;
10111
- const client = config2.client ?? _RunTree.getSharedClient();
10108
+ const { metadata, ...config } = originalConfig;
10109
+ const client = config.client ?? _RunTree.getSharedClient();
10112
10110
  const dedupedMetadata = {
10113
10111
  ...metadata,
10114
- ...config2?.extra?.metadata
10112
+ ...config?.extra?.metadata
10115
10113
  };
10116
- config2.extra = { ...config2.extra, metadata: dedupedMetadata };
10117
- if ("id" in config2 && config2.id == null) {
10118
- delete config2.id;
10114
+ config.extra = { ...config.extra, metadata: dedupedMetadata };
10115
+ if ("id" in config && config.id == null) {
10116
+ delete config.id;
10119
10117
  }
10120
- Object.assign(this, { ...defaultConfig, ...config2, client });
10118
+ Object.assign(this, { ...defaultConfig, ...config, client });
10121
10119
  this.execution_order ?? (this.execution_order = 1);
10122
10120
  this.child_execution_order ?? (this.child_execution_order = 1);
10123
10121
  if (!this.dotted_order) {
@@ -10176,15 +10174,15 @@ var require_run_trees = __commonJS({
10176
10174
  }
10177
10175
  return _RunTree.sharedClient;
10178
10176
  }
10179
- createChild(config2) {
10177
+ createChild(config) {
10180
10178
  const child_execution_order = this.child_execution_order + 1;
10181
10179
  const inheritedReplicas = this.replicas?.map((replica) => {
10182
10180
  const { reroot, ...rest } = replica;
10183
10181
  return rest;
10184
10182
  });
10185
- const childReplicas = config2.replicas ?? inheritedReplicas;
10183
+ const childReplicas = config.replicas ?? inheritedReplicas;
10186
10184
  const child = new _RunTree({
10187
- ...config2,
10185
+ ...config,
10188
10186
  parent_run: this,
10189
10187
  project_name: this.project_name,
10190
10188
  replicas: childReplicas,
@@ -10197,7 +10195,7 @@ var require_run_trees = __commonJS({
10197
10195
  child[constants_js_1._LC_CONTEXT_VARIABLES_KEY] = this[constants_js_1._LC_CONTEXT_VARIABLES_KEY];
10198
10196
  }
10199
10197
  const LC_CHILD = /* @__PURE__ */ Symbol.for("lc:child_config");
10200
- const presentConfig = config2.extra?.[LC_CHILD] ?? this.extra[LC_CHILD];
10198
+ const presentConfig = config.extra?.[LC_CHILD] ?? this.extra[LC_CHILD];
10201
10199
  if (isRunnableConfigLike(presentConfig)) {
10202
10200
  const newConfig = { ...presentConfig };
10203
10201
  const callbacks = isCallbackManagerLike(newConfig.callbacks) ? newConfig.callbacks.copy?.() : void 0;
@@ -10581,7 +10579,7 @@ var require_run_trees = __commonJS({
10581
10579
  return { strTime, time: Date.parse(strTime + "Z"), uuid };
10582
10580
  });
10583
10581
  const traceId = parsedDottedOrder[0].uuid;
10584
- const config2 = {
10582
+ const config = {
10585
10583
  ...inheritArgs,
10586
10584
  name: inheritArgs?.["name"] ?? "parent",
10587
10585
  run_type: inheritArgs?.["run_type"] ?? "chain",
@@ -10592,12 +10590,12 @@ var require_run_trees = __commonJS({
10592
10590
  };
10593
10591
  if (rawHeaders["baggage"] && typeof rawHeaders["baggage"] === "string") {
10594
10592
  const baggage = Baggage.fromHeader(rawHeaders["baggage"]);
10595
- config2.metadata = baggage.metadata;
10596
- config2.tags = baggage.tags;
10597
- config2.project_name = baggage.project_name;
10598
- config2.replicas = baggage.replicas;
10593
+ config.metadata = baggage.metadata;
10594
+ config.tags = baggage.tags;
10595
+ config.project_name = baggage.project_name;
10596
+ config.replicas = baggage.replicas;
10599
10597
  }
10600
- const runTree = new _RunTree(config2);
10598
+ const runTree = new _RunTree(config);
10601
10599
  runTree.distributedParentId = runTree.id;
10602
10600
  return runTree;
10603
10601
  }
@@ -11472,8 +11470,8 @@ var require_utils = __commonJS({
11472
11470
  function _isToolCall(toolCall) {
11473
11471
  return !!(toolCall && typeof toolCall === "object" && "type" in toolCall && toolCall.type === "tool_call");
11474
11472
  }
11475
- function _configHasToolCallId(config2) {
11476
- return !!(config2 && typeof config2 === "object" && "toolCall" in config2 && config2.toolCall != null && typeof config2.toolCall === "object" && "id" in config2.toolCall && typeof config2.toolCall.id === "string");
11473
+ function _configHasToolCallId(config) {
11474
+ return !!(config && typeof config === "object" && "toolCall" in config && config.toolCall != null && typeof config.toolCall === "object" && "id" in config.toolCall && typeof config.toolCall.id === "string");
11477
11475
  }
11478
11476
  var ToolInputParsingException = class extends Error {
11479
11477
  constructor(message, output) {
@@ -13329,11 +13327,11 @@ var require_context = __commonJS({
13329
13327
  var LC_CONFIGURE_HOOKS_KEY = /* @__PURE__ */ Symbol("lc:configure_hooks");
13330
13328
  var _getConfigureHooks = () => getContextVariable(LC_CONFIGURE_HOOKS_KEY) || [];
13331
13329
  exports$1._getConfigureHooks = _getConfigureHooks;
13332
- var registerConfigureHook = (config2) => {
13333
- if (config2.envVar && !config2.handlerClass) {
13330
+ var registerConfigureHook = (config) => {
13331
+ if (config.envVar && !config.handlerClass) {
13334
13332
  throw new Error("If envVar is set, handlerClass must also be set to a non-None value.");
13335
13333
  }
13336
- setContextVariable(LC_CONFIGURE_HOOKS_KEY, [...(0, exports$1._getConfigureHooks)(), config2]);
13334
+ setContextVariable(LC_CONFIGURE_HOOKS_KEY, [...(0, exports$1._getConfigureHooks)(), config]);
13337
13335
  };
13338
13336
  exports$1.registerConfigureHook = registerConfigureHook;
13339
13337
  }
@@ -14437,8 +14435,8 @@ var init_dist = __esm({
14437
14435
  };
14438
14436
  version2 = "0.22.6";
14439
14437
  LangChainInstrumentation = class extends instrumentation.InstrumentationBase {
14440
- constructor(config2 = {}) {
14441
- super("@traceloop/instrumentation-langchain", version2, config2);
14438
+ constructor(config = {}) {
14439
+ super("@traceloop/instrumentation-langchain", version2, config);
14442
14440
  this.instrumentCallbackManagerDirectly();
14443
14441
  }
14444
14442
  manuallyInstrument({ callbackManagerModule }) {
@@ -14547,9 +14545,9 @@ function netraExpressMiddleware() {
14547
14545
 
14548
14546
  // src/api/http-client.ts
14549
14547
  var NetraHttpClient = class {
14550
- constructor(config2, timeoutEnvVar, defaultTimeout) {
14548
+ constructor(config, timeoutEnvVar, defaultTimeout) {
14551
14549
  this.initialized = false;
14552
- const endpoint = config2.otlpEndpoint?.trim() || "";
14550
+ const endpoint = config.otlpEndpoint?.trim() || "";
14553
14551
  if (!endpoint) {
14554
14552
  Logger.error(
14555
14553
  "netra: NETRA_OTLP_ENDPOINT is required for API calls"
@@ -14560,7 +14558,7 @@ var NetraHttpClient = class {
14560
14558
  return;
14561
14559
  }
14562
14560
  this.baseUrl = this.resolveBaseUrl(endpoint);
14563
- this.headers = this.buildHeaders(config2);
14561
+ this.headers = this.buildHeaders(config);
14564
14562
  this.timeout = this.getTimeout(timeoutEnvVar, defaultTimeout);
14565
14563
  this.initialized = true;
14566
14564
  }
@@ -14571,10 +14569,10 @@ var NetraHttpClient = class {
14571
14569
  }
14572
14570
  return baseUrl;
14573
14571
  }
14574
- buildHeaders(config2) {
14575
- const headers = { ...config2.headers };
14576
- if (config2.apiKey) {
14577
- headers["x-api-key"] = config2.apiKey;
14572
+ buildHeaders(config) {
14573
+ const headers = { ...config.headers };
14574
+ if (config.apiKey) {
14575
+ headers["x-api-key"] = config.apiKey;
14578
14576
  }
14579
14577
  headers["Content-Type"] = "application/json";
14580
14578
  return headers;
@@ -14680,8 +14678,8 @@ var NetraHttpClient = class {
14680
14678
 
14681
14679
  // src/api/usage/client.ts
14682
14680
  var UsageHttpClient = class extends NetraHttpClient {
14683
- constructor(config2) {
14684
- super(config2, "NETRA_USAGE_TIMEOUT", 10);
14681
+ constructor(config) {
14682
+ super(config, "NETRA_USAGE_TIMEOUT", 10);
14685
14683
  }
14686
14684
  async getSessionUsage(sessionId, startTime, endTime) {
14687
14685
  if (!this.isInitialized()) {
@@ -14769,9 +14767,9 @@ var UsageHttpClient = class extends NetraHttpClient {
14769
14767
 
14770
14768
  // src/api/usage/api.ts
14771
14769
  var Usage = class {
14772
- constructor(config2) {
14773
- this.config = config2;
14774
- this.client = new UsageHttpClient(config2);
14770
+ constructor(config) {
14771
+ this.config = config;
14772
+ this.client = new UsageHttpClient(config);
14775
14773
  }
14776
14774
  /**
14777
14775
  * Get session usage data
@@ -14936,8 +14934,8 @@ var Usage = class {
14936
14934
  if (!page) {
14937
14935
  break;
14938
14936
  }
14939
- for (const trace24 of page.traces) {
14940
- yield trace24;
14937
+ for (const trace25 of page.traces) {
14938
+ yield trace25;
14941
14939
  }
14942
14940
  if (!page.hasNextPage || !page.nextCursor) {
14943
14941
  break;
@@ -15050,13 +15048,14 @@ var Usage = class {
15050
15048
  };
15051
15049
 
15052
15050
  // src/version.ts
15053
- var SDK_VERSION = "1.4.0";
15051
+ var SDK_VERSION = "1.5.0";
15054
15052
 
15055
15053
  // src/config.ts
15056
15054
  var NetraInstruments = /* @__PURE__ */ ((NetraInstruments2) => {
15057
15055
  NetraInstruments2["ALL"] = "__all__";
15058
15056
  NetraInstruments2["OPENAI"] = "openai";
15059
- NetraInstruments2["GOOGLE_GENERATIVE_AI"] = "google_genai";
15057
+ NetraInstruments2["GOOGLE_GENAI"] = "google_genai";
15058
+ NetraInstruments2["GOOGLE_GENERATIVE_AI"] = "google_generative_ai";
15060
15059
  NetraInstruments2["MISTRAL"] = "mistral_ai";
15061
15060
  NetraInstruments2["GROQ"] = "groq";
15062
15061
  NetraInstruments2["VERTEX_AI"] = "vertexai";
@@ -15081,7 +15080,8 @@ var DEFAULT_INSTRUMENTS_FOR_ROOT = /* @__PURE__ */ new Set([
15081
15080
  "anthropic" /* ANTHROPIC */,
15082
15081
  "groq" /* GROQ */,
15083
15082
  "mistral_ai" /* MISTRAL */,
15084
- "google_genai" /* GOOGLE_GENERATIVE_AI */,
15083
+ "google_genai" /* GOOGLE_GENAI */,
15084
+ "google_generative_ai" /* GOOGLE_GENERATIVE_AI */,
15085
15085
  "vertexai" /* VERTEX_AI */,
15086
15086
  "together" /* TOGETHER */,
15087
15087
  // AI frameworks
@@ -15105,41 +15105,41 @@ var DEFAULT_INSTRUMENTS = /* @__PURE__ */ new Set([
15105
15105
  "express" /* EXPRESS */
15106
15106
  ]);
15107
15107
  var Config = class {
15108
- constructor(config2 = {}) {
15109
- this.appName = this._getAppName(config2.appName);
15108
+ constructor(config = {}) {
15109
+ this.appName = this._getAppName(config.appName);
15110
15110
  this.otlpEndpoint = this._getOtlpEndpoint();
15111
15111
  this.apiKey = process.env.NETRA_API_KEY;
15112
- this.headers = this._parseHeaders(config2.headers);
15112
+ this.headers = this._parseHeaders(config.headers);
15113
15113
  this.disableBatch = this._getBoolConfig(
15114
- config2.disableBatch,
15114
+ config.disableBatch,
15115
15115
  "NETRA_DISABLE_BATCH",
15116
15116
  false
15117
15117
  );
15118
15118
  this.traceContent = this._getBoolConfig(
15119
- config2.traceContent,
15119
+ config.traceContent,
15120
15120
  "NETRA_TRACE_CONTENT",
15121
15121
  true
15122
15122
  );
15123
15123
  this.debugMode = this._getBoolConfig(
15124
- config2.debugMode,
15124
+ config.debugMode,
15125
15125
  "NETRA_DEBUG",
15126
15126
  false
15127
15127
  );
15128
15128
  this.enableRootSpan = this._getBoolConfig(
15129
- config2.enableRootSpan,
15129
+ config.enableRootSpan,
15130
15130
  "NETRA_ENABLE_ROOT_SPAN",
15131
15131
  false
15132
15132
  );
15133
15133
  this.enableScrubbing = this._getBoolConfig(
15134
- config2.enableScrubbing,
15134
+ config.enableScrubbing,
15135
15135
  "NETRA_ENABLE_SCRUBBING",
15136
15136
  false
15137
15137
  );
15138
- this.environment = config2.environment || process.env.NETRA_ENV || "local";
15138
+ this.environment = config.environment || process.env.NETRA_ENV || "local";
15139
15139
  this.resourceAttributes = this._getResourceAttributes(
15140
- config2.resourceAttributes
15140
+ config.resourceAttributes
15141
15141
  );
15142
- this.blockedSpans = config2.blockedSpans;
15142
+ this.blockedSpans = config.blockedSpans;
15143
15143
  this._validateApiKey();
15144
15144
  this._setupAuthentication();
15145
15145
  this._setTraceContentEnv();
@@ -15568,6 +15568,9 @@ function safeStringify(value, maxLength) {
15568
15568
  let result;
15569
15569
  try {
15570
15570
  result = JSON.stringify(value, (_key, val) => {
15571
+ if (typeof val === "string" && maxLength && val.length > maxLength) {
15572
+ return truncate(val, maxLength);
15573
+ }
15571
15574
  if (typeof val === "function")
15572
15575
  return `[Function: ${val.name || "anonymous"}]`;
15573
15576
  if (typeof val === "symbol") return val.toString();
@@ -15723,8 +15726,8 @@ var SessionManager = class _SessionManager {
15723
15726
  }
15724
15727
  /**
15725
15728
  * Set input on the currently active span.
15726
- * Writes to `netra.user.input` so that SpanIOProcessor can promote it
15727
- * to `input` at span end, giving user-supplied values the highest priority.
15729
+ * Writes to `netra.user.input` which SpanIOProcessor intercepts inline
15730
+ * and writes directly to `input`, taking priority over decorator/instrumentation.
15728
15731
  */
15729
15732
  static setInput(value) {
15730
15733
  try {
@@ -15738,8 +15741,8 @@ var SessionManager = class _SessionManager {
15738
15741
  }
15739
15742
  /**
15740
15743
  * Set output on the currently active span.
15741
- * Writes to `netra.user.output` so that SpanIOProcessor can promote it
15742
- * to `output` at span end, giving user-supplied values the highest priority.
15744
+ * Writes to `netra.user.output` which SpanIOProcessor intercepts inline
15745
+ * and writes directly to `output`, taking priority over decorator/instrumentation.
15743
15746
  */
15744
15747
  static setOutput(value) {
15745
15748
  try {
@@ -15754,12 +15757,12 @@ var SessionManager = class _SessionManager {
15754
15757
  /**
15755
15758
  * Set input on the root span of the current trace.
15756
15759
  * Delegates to RootSpanProcessor which owns root span bookkeeping.
15757
- * Writes to `netra.user.input` so SpanIOProcessor promotes it at span end.
15760
+ * Uses `netra.root.input` for highest priority (overrides even setInput).
15758
15761
  */
15759
15762
  static setRootInput(value) {
15760
15763
  try {
15761
15764
  RootSpanProcessor.setAttributeOnRootSpan(
15762
- "netra.user.input",
15765
+ "netra.root.input",
15763
15766
  serializeValue(value, Config.ATTRIBUTE_MAX_LEN)
15764
15767
  );
15765
15768
  } catch (e) {
@@ -15769,12 +15772,12 @@ var SessionManager = class _SessionManager {
15769
15772
  /**
15770
15773
  * Set output on the root span of the current trace.
15771
15774
  * Delegates to RootSpanProcessor which owns root span bookkeeping.
15772
- * Writes to `netra.user.output` so SpanIOProcessor promotes it at span end.
15775
+ * Uses `netra.root.output` for highest priority (overrides even setOutput).
15773
15776
  */
15774
15777
  static setRootOutput(value) {
15775
15778
  try {
15776
15779
  RootSpanProcessor.setAttributeOnRootSpan(
15777
- "netra.user.output",
15780
+ "netra.root.output",
15778
15781
  serializeValue(value, Config.ATTRIBUTE_MAX_LEN)
15779
15782
  );
15780
15783
  } catch (e) {
@@ -16016,8 +16019,8 @@ var SpanWrapper = class {
16016
16019
 
16017
16020
  // src/api/evaluation/client.ts
16018
16021
  var EvaluationHttpClient = class extends NetraHttpClient {
16019
- constructor(config2) {
16020
- super(config2, "NETRA_EVALUATION_TIMEOUT", 10);
16022
+ constructor(config) {
16023
+ super(config, "NETRA_EVALUATION_TIMEOUT", 10);
16021
16024
  }
16022
16025
  /**
16023
16026
  * Fetch dataset items for a dataset id
@@ -16262,11 +16265,11 @@ function extractEvaluatorConfig(evaluator) {
16262
16265
  if (!evaluator || typeof evaluator !== "object" || !("config" in evaluator)) {
16263
16266
  return null;
16264
16267
  }
16265
- const config2 = evaluator.config;
16266
- if (!config2 || typeof config2 !== "object") {
16268
+ const config = evaluator.config;
16269
+ if (!config || typeof config !== "object") {
16267
16270
  return null;
16268
16271
  }
16269
- return config2;
16272
+ return config;
16270
16273
  }
16271
16274
  async function executeTask(task2, itemInput) {
16272
16275
  try {
@@ -16282,17 +16285,17 @@ async function runSingleEvaluator(params) {
16282
16285
  return null;
16283
16286
  }
16284
16287
  let expectedName = null;
16285
- const config2 = extractEvaluatorConfig(evaluator);
16286
- if (config2) {
16287
- expectedName = config2.name;
16288
+ const config = extractEvaluatorConfig(evaluator);
16289
+ if (config) {
16290
+ expectedName = config.name;
16288
16291
  }
16289
- const context17 = {
16292
+ const context18 = {
16290
16293
  input: itemInput,
16291
16294
  taskOutput,
16292
16295
  expectedOutput,
16293
16296
  metadata
16294
16297
  };
16295
- let result = evaluator.evaluate(context17);
16298
+ let result = evaluator.evaluate(context18);
16296
16299
  if (result instanceof Promise) {
16297
16300
  result = await result;
16298
16301
  }
@@ -16360,12 +16363,12 @@ function buildEvaluatorsConfig(evaluators) {
16360
16363
  return configs;
16361
16364
  }
16362
16365
  for (const evaluator of evaluators) {
16363
- const config2 = extractEvaluatorConfig(evaluator);
16364
- if (!config2) {
16366
+ const config = extractEvaluatorConfig(evaluator);
16367
+ if (!config) {
16365
16368
  continue;
16366
16369
  }
16367
16370
  try {
16368
- configs.push(config2);
16371
+ configs.push(config);
16369
16372
  } catch {
16370
16373
  continue;
16371
16374
  }
@@ -16375,8 +16378,8 @@ function buildEvaluatorsConfig(evaluators) {
16375
16378
 
16376
16379
  // src/api/evaluation/api.ts
16377
16380
  var Evaluation = class {
16378
- constructor(config2) {
16379
- this.config = config2;
16381
+ constructor(config) {
16382
+ this.config = config;
16380
16383
  this.client = new EvaluationHttpClient(this.config);
16381
16384
  }
16382
16385
  /**
@@ -16777,9 +16780,9 @@ var RunStatus = /* @__PURE__ */ ((RunStatus2) => {
16777
16780
 
16778
16781
  // src/api/evaluation/context.ts
16779
16782
  var RunEntryContext = class {
16780
- constructor(client, config2, run, entry) {
16783
+ constructor(client, config, run, entry) {
16781
16784
  this.client = client;
16782
- this.config = config2;
16785
+ this.config = config;
16783
16786
  this.evaluationRun = run;
16784
16787
  this.entry = entry;
16785
16788
  }
@@ -16862,8 +16865,8 @@ var RunEntryContext = class {
16862
16865
 
16863
16866
  // src/api/dashboard/client.ts
16864
16867
  var DashboardHttpClient = class extends NetraHttpClient {
16865
- constructor(config2) {
16866
- super(config2, "NETRA_DASHBOARD_TIMEOUT", 30);
16868
+ constructor(config) {
16869
+ super(config, "NETRA_DASHBOARD_TIMEOUT", 30);
16867
16870
  }
16868
16871
  /**
16869
16872
  * Execute a dynamic query for dashboards
@@ -17133,9 +17136,9 @@ function metadataField(key) {
17133
17136
 
17134
17137
  // src/api/dashboard/api.ts
17135
17138
  var Dashboard = class {
17136
- constructor(config2) {
17137
- this.config = config2;
17138
- this.client = new DashboardHttpClient(config2);
17139
+ constructor(config) {
17140
+ this.config = config;
17141
+ this.client = new DashboardHttpClient(config);
17139
17142
  }
17140
17143
  /**
17141
17144
  * Execute a dynamic query for dashboards to retrieve metrics and time-series data
@@ -17284,8 +17287,8 @@ var Dashboard = class {
17284
17287
 
17285
17288
  // src/api/prompts/client.ts
17286
17289
  var PromptsHttpClient = class extends NetraHttpClient {
17287
- constructor(config2) {
17288
- super(config2, "NETRA_PROMPTS_TIMEOUT", 30);
17290
+ constructor(config) {
17291
+ super(config, "NETRA_PROMPTS_TIMEOUT", 30);
17289
17292
  }
17290
17293
  /**
17291
17294
  * Fetch prompt version from backend
@@ -17319,9 +17322,9 @@ var PromptsHttpClient = class extends NetraHttpClient {
17319
17322
 
17320
17323
  // src/api/prompts/api.ts
17321
17324
  var Prompts = class {
17322
- constructor(config2) {
17323
- this.config = config2;
17324
- this.client = new PromptsHttpClient(config2);
17325
+ constructor(config) {
17326
+ this.config = config;
17327
+ this.client = new PromptsHttpClient(config);
17325
17328
  }
17326
17329
  /**
17327
17330
  * Fetch prompt version by name and label.
@@ -17403,6 +17406,7 @@ var ALLOWED_INSTRUMENTATION_NAMES = /* @__PURE__ */ new Set([
17403
17406
  "mistral_ai",
17404
17407
  "mistralai",
17405
17408
  "google_genai",
17409
+ "google_generative_ai",
17406
17410
  "langchain",
17407
17411
  "llama_index",
17408
17412
  "pinecone",
@@ -17811,7 +17815,6 @@ var SessionSpanProcessor = class {
17811
17815
  span2.setAttribute("library.name", Config.LIBRARY_NAME);
17812
17816
  span2.setAttribute("library.version", Config.LIBRARY_VERSION);
17813
17817
  span2.setAttribute("sdk.name", Config.SDK_NAME);
17814
- span2.setAttribute("deployment.environment", this.environment);
17815
17818
  const ctxToUse = parentContext || api.context.active();
17816
17819
  const baggage = api.propagation.getBaggage(ctxToUse);
17817
17820
  const sessionId = baggage?.getEntry("session_id")?.value ?? sessionValues.get("session_id");
@@ -18027,6 +18030,8 @@ var _USAGE_OUTPUT_TOKENS = "gen_ai.usage.output_tokens";
18027
18030
  var _USAGE_COMPLETION_TOKENS = "gen_ai.usage.completion_tokens";
18028
18031
  var NETRA_USER_INPUT = "netra.user.input";
18029
18032
  var NETRA_USER_OUTPUT = "netra.user.output";
18033
+ var NETRA_ROOT_INPUT = "netra.root.input";
18034
+ var NETRA_ROOT_OUTPUT = "netra.root.output";
18030
18035
  var NETRA_ENTITY_INPUT = "netra.entity.input";
18031
18036
  var NETRA_ENTITY_OUTPUT = "netra.entity.output";
18032
18037
  var MAX_PARSE_LEN = 1e6;
@@ -18069,54 +18074,15 @@ var SpanIOProcessor = class {
18069
18074
  if (!("output" in attrs)) {
18070
18075
  span2.setAttribute("output", "");
18071
18076
  }
18077
+ if (!("conversation" in attrs)) {
18078
+ span2.setAttribute("conversation", JSON.stringify([]));
18079
+ }
18072
18080
  this._wrapSetAttribute(span2);
18073
18081
  } catch (e) {
18074
18082
  Logger.error("SpanIOProcessor.onStart failed:", e);
18075
18083
  }
18076
18084
  }
18077
- onEnd(span2) {
18078
- try {
18079
- const attrs = span2._attributes ?? span2.attributes;
18080
- if (!attrs || typeof attrs !== "object") {
18081
- Logger.debug(
18082
- "SpanIOProcessor.onEnd: could not access span attributes \u2014 OTel SDK internal API may have changed"
18083
- );
18084
- return;
18085
- }
18086
- try {
18087
- if (NETRA_USER_INPUT in attrs) {
18088
- const userInput = attrs[NETRA_USER_INPUT];
18089
- if (!isEmpty(userInput)) {
18090
- attrs["input"] = userInput;
18091
- }
18092
- delete attrs[NETRA_USER_INPUT];
18093
- }
18094
- } catch (e) {
18095
- Logger.warn(
18096
- "SpanIOProcessor.onEnd: could not promote netra.user.input \u2192 input",
18097
- e
18098
- );
18099
- }
18100
- try {
18101
- if (NETRA_USER_OUTPUT in attrs) {
18102
- const userOutput = attrs[NETRA_USER_OUTPUT];
18103
- if (!isEmpty(userOutput)) {
18104
- attrs["output"] = userOutput;
18105
- }
18106
- delete attrs[NETRA_USER_OUTPUT];
18107
- }
18108
- } catch (e) {
18109
- Logger.warn(
18110
- "SpanIOProcessor.onEnd: could not promote netra.user.output \u2192 output",
18111
- e
18112
- );
18113
- }
18114
- } catch (e) {
18115
- Logger.error(
18116
- "SpanIOProcessor.onEnd: unexpected error during netra.user promotion",
18117
- e
18118
- );
18119
- }
18085
+ onEnd(_span) {
18120
18086
  }
18121
18087
  shutdown() {
18122
18088
  return Promise.resolve();
@@ -18130,10 +18096,50 @@ var SpanIOProcessor = class {
18130
18096
  let completions;
18131
18097
  let genAiOwnsInput = false;
18132
18098
  let genAiOwnsOutput = false;
18099
+ let userOwnsInput = false;
18100
+ let userOwnsOutput = false;
18101
+ let rootOwnsInput = false;
18102
+ let rootOwnsOutput = false;
18103
+ const inputLocked = () => rootOwnsInput || userOwnsInput;
18104
+ const outputLocked = () => rootOwnsOutput || userOwnsOutput;
18133
18105
  const inputIsEmpty = () => isEmpty((span2.attributes ?? {})["input"]);
18134
18106
  const outputIsEmpty = () => isEmpty((span2.attributes ?? {})["output"]);
18135
18107
  const patched = (key, value) => {
18136
18108
  try {
18109
+ if (key === NETRA_ROOT_INPUT) {
18110
+ rootOwnsInput = true;
18111
+ return original("input", value);
18112
+ }
18113
+ if (key === NETRA_ROOT_OUTPUT) {
18114
+ rootOwnsOutput = true;
18115
+ return original("output", value);
18116
+ }
18117
+ if (key === NETRA_USER_INPUT) {
18118
+ if (!rootOwnsInput) {
18119
+ userOwnsInput = true;
18120
+ return original("input", value);
18121
+ }
18122
+ return span2;
18123
+ }
18124
+ if (key === NETRA_USER_OUTPUT) {
18125
+ if (!rootOwnsOutput) {
18126
+ userOwnsOutput = true;
18127
+ return original("output", value);
18128
+ }
18129
+ return span2;
18130
+ }
18131
+ if (key === "input") {
18132
+ if (!inputLocked()) {
18133
+ return original("input", value);
18134
+ }
18135
+ return span2;
18136
+ }
18137
+ if (key === "output") {
18138
+ if (!outputLocked()) {
18139
+ return original("output", value);
18140
+ }
18141
+ return span2;
18142
+ }
18137
18143
  const promptMatch = _PROMPT_RE.exec(key);
18138
18144
  if (promptMatch) {
18139
18145
  original(key, value);
@@ -18146,7 +18152,7 @@ var SpanIOProcessor = class {
18146
18152
  prompts.set(idx, entry);
18147
18153
  }
18148
18154
  entry[field] = String(value);
18149
- if (inputIsEmpty() || genAiOwnsInput) {
18155
+ if (!inputLocked() && (inputIsEmpty() || genAiOwnsInput)) {
18150
18156
  original("input", buildMessages(prompts));
18151
18157
  genAiOwnsInput = true;
18152
18158
  }
@@ -18164,32 +18170,32 @@ var SpanIOProcessor = class {
18164
18170
  completions.set(idx, entry);
18165
18171
  }
18166
18172
  entry[field] = String(value);
18167
- if (outputIsEmpty() || genAiOwnsOutput) {
18173
+ if (!outputLocked() && (outputIsEmpty() || genAiOwnsOutput)) {
18168
18174
  original("output", buildMessages(completions));
18169
18175
  genAiOwnsOutput = true;
18170
18176
  }
18171
18177
  return span2;
18172
18178
  }
18173
18179
  if (key === "traceloop.entity.input") {
18174
- if (inputIsEmpty()) {
18180
+ if (!inputLocked() && inputIsEmpty()) {
18175
18181
  original("input", extractTraceloopInput(value));
18176
18182
  }
18177
18183
  return span2;
18178
18184
  }
18179
18185
  if (key === "traceloop.entity.output") {
18180
- if (outputIsEmpty()) {
18186
+ if (!outputLocked() && outputIsEmpty()) {
18181
18187
  original("output", extractTraceloopOutput(value));
18182
18188
  }
18183
18189
  return span2;
18184
18190
  }
18185
18191
  if (key === NETRA_ENTITY_INPUT) {
18186
- if (inputIsEmpty()) {
18192
+ if (!inputLocked() && inputIsEmpty()) {
18187
18193
  original("input", extractTraceloopInput(value));
18188
18194
  }
18189
18195
  return span2;
18190
18196
  }
18191
18197
  if (key === NETRA_ENTITY_OUTPUT) {
18192
- if (outputIsEmpty()) {
18198
+ if (!outputLocked() && outputIsEmpty()) {
18193
18199
  original("output", extractTraceloopOutput(value));
18194
18200
  }
18195
18201
  return span2;
@@ -18404,12 +18410,14 @@ var SpanAttributes2 = {
18404
18410
  LLM_REQUEST_MAX_TOKENS: "gen_ai.request.max_tokens",
18405
18411
  LLM_REQUEST_TEMPERATURE: "gen_ai.request.temperature",
18406
18412
  LLM_REQUEST_TOP_P: "gen_ai.request.top_p",
18413
+ LLM_REQUEST_TOP_K: "gen_ai.request.top_k",
18407
18414
  LLM_REQUEST_REASONING: "gen_ai.request.reasoning",
18408
18415
  LLM_REQUEST_REASONING_EFFORT: "gen_ai.request.reasoning_effort",
18409
18416
  LLM_REQUEST_TOOL_NAME: "gen_ai.request.tool.name",
18410
18417
  LLM_REQUEST_TOOL_ID: "gen_ai.request.tool.id",
18411
18418
  LLM_RESPONSE_MODEL: "gen_ai.response.model",
18412
18419
  LLM_RESPONSE_FINISH_REASON: "llm.response.finish_reason",
18420
+ LLM_RESPONSE_DURATION: "llm.response.duration",
18413
18421
  LLM_USAGE_PROMPT_TOKENS: "gen_ai.usage.prompt_tokens",
18414
18422
  LLM_USAGE_COMPLETION_TOKENS: "gen_ai.usage.completion_tokens",
18415
18423
  LLM_USAGE_CACHE_READ_INPUT_TOKENS: "gen_ai.usage.cache_read_input_tokens",
@@ -18435,6 +18443,9 @@ function shouldSuppressInstrumentation() {
18435
18443
  const ctx = api.context.active();
18436
18444
  return ctx.getValue(SUPPRESS_INSTRUMENTATION_KEY) === true;
18437
18445
  }
18446
+ function createSuppressedContext(ctx) {
18447
+ return (ctx ?? api.context.active()).setValue(SUPPRESS_INSTRUMENTATION_KEY, true);
18448
+ }
18438
18449
  function defineHidden(target, key, value) {
18439
18450
  Object.defineProperty(target, key, {
18440
18451
  value,
@@ -19795,35 +19806,803 @@ var NetraAnthropicInstrumentor = class {
19795
19806
  }
19796
19807
  };
19797
19808
  var anthropicInstrumentor = new NetraAnthropicInstrumentor();
19809
+ var BaseInstrumentor = class {
19810
+ constructor() {
19811
+ this._isInstrumented = false;
19812
+ this._instrumentPromise = null;
19813
+ this._resolvedClasses = [];
19814
+ this._generation = 0;
19815
+ this._tracer = null;
19816
+ }
19817
+ /**
19818
+ * Check whether two resolved class sets refer to the same module load.
19819
+ * Default: reference equality. Override for composite class objects.
19820
+ */
19821
+ isSameClasses(a, b) {
19822
+ return a === b;
19823
+ }
19824
+ /**
19825
+ * Optional hook called during uninstrument() after prototype unwrapping.
19826
+ * Use for extra cleanup (e.g. restoring patched instance methods).
19827
+ */
19828
+ onUninstrument() {
19829
+ }
19830
+ get tracer() {
19831
+ return this._tracer;
19832
+ }
19833
+ isInstrumented() {
19834
+ return this._isInstrumented;
19835
+ }
19836
+ get resolvedClasses() {
19837
+ return this._resolvedClasses;
19838
+ }
19839
+ async instrument(options = {}) {
19840
+ if (this._isInstrumented) {
19841
+ Logger.warn(`${this.displayName} is already instrumented`);
19842
+ return this;
19843
+ }
19844
+ if (this._instrumentPromise) {
19845
+ return this._instrumentPromise;
19846
+ }
19847
+ this._instrumentPromise = this._doInstrument(options);
19848
+ try {
19849
+ return await this._instrumentPromise;
19850
+ } finally {
19851
+ this._instrumentPromise = null;
19852
+ }
19853
+ }
19854
+ uninstrument() {
19855
+ this._generation++;
19856
+ this._instrumentPromise = null;
19857
+ if (!this._isInstrumented) {
19858
+ Logger.warn(`${this.displayName} is not instrumented`);
19859
+ return;
19860
+ }
19861
+ for (const classes of this._resolvedClasses) {
19862
+ try {
19863
+ this.removePatches(classes);
19864
+ } catch (error) {
19865
+ Logger.error(`${this.displayName}: failed to remove patches: ${error}`);
19866
+ }
19867
+ }
19868
+ try {
19869
+ this.onUninstrument();
19870
+ } catch (error) {
19871
+ Logger.error(`${this.displayName}: onUninstrument failed: ${error}`);
19872
+ } finally {
19873
+ this._resolvedClasses = [];
19874
+ this._isInstrumented = false;
19875
+ }
19876
+ }
19877
+ async _doInstrument(options) {
19878
+ const gen = this._generation;
19879
+ const classSets = await this.resolveClasses();
19880
+ if (classSets.length === 0) {
19881
+ return this;
19882
+ }
19883
+ if (this._isInstrumented || this._generation !== gen) {
19884
+ return this;
19885
+ }
19886
+ try {
19887
+ this._tracerProvider = options.tracerProvider;
19888
+ this._tracer = this._tracerProvider ? this._tracerProvider.getTracer(
19889
+ this.instrumentationName,
19890
+ this.instrumentationVersion
19891
+ ) : api.trace.getTracer(
19892
+ this.instrumentationName,
19893
+ this.instrumentationVersion
19894
+ );
19895
+ } catch (error) {
19896
+ Logger.error(`${this.displayName}: failed to initialize tracer: ${error}`);
19897
+ return this;
19898
+ }
19899
+ let anyWrapped = false;
19900
+ for (const classes of classSets) {
19901
+ try {
19902
+ if (this.applyPatches(classes, this._tracer)) {
19903
+ anyWrapped = true;
19904
+ }
19905
+ } catch (error) {
19906
+ Logger.error(`${this.displayName}: patch failed: ${error}`);
19907
+ try {
19908
+ this.removePatches(classes);
19909
+ } catch {
19910
+ Logger.error(`${this.displayName}: failed to remove patches: ${error}`);
19911
+ }
19912
+ }
19913
+ }
19914
+ if (anyWrapped) {
19915
+ this._isInstrumented = true;
19916
+ }
19917
+ return this;
19918
+ }
19919
+ /**
19920
+ * Resolve the target package via ESM import() and CJS createRequire().
19921
+ * Override this for non-standard resolution strategies.
19922
+ */
19923
+ async resolveClasses() {
19924
+ if (this._resolvedClasses.length > 0) return this._resolvedClasses;
19925
+ try {
19926
+ const mod = await import(this.packageName);
19927
+ const classes = this.extractClasses(mod);
19928
+ if (classes) {
19929
+ this._resolvedClasses.push(classes);
19930
+ }
19931
+ } catch {
19932
+ Logger.debug(`${this.displayName}: ESM import not available`);
19933
+ }
19934
+ try {
19935
+ const req = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
19936
+ const mod = req(this.packageName);
19937
+ const classes = this.extractClasses(mod);
19938
+ if (classes) {
19939
+ const isDuplicate = this._resolvedClasses.some(
19940
+ (existing) => this.isSameClasses(existing, classes)
19941
+ );
19942
+ if (!isDuplicate) {
19943
+ this._resolvedClasses.push(classes);
19944
+ }
19945
+ }
19946
+ } catch {
19947
+ Logger.debug(`${this.displayName}: CJS require not available`);
19948
+ }
19949
+ return this._resolvedClasses;
19950
+ }
19951
+ };
19798
19952
 
19799
19953
  // src/instrumentation/google-genai/version.ts
19800
19954
  var __version__2 = "1.0.0";
19801
- dotenv__namespace.config();
19802
- function safeStringify2(value) {
19955
+
19956
+ // src/instrumentation/google-genai/types.ts
19957
+ var SPAN_NAMES2 = {
19958
+ CHAT: "google_genai.chat",
19959
+ EMBEDDING: "google_genai.embedding"
19960
+ };
19961
+
19962
+ // src/instrumentation/google-genai/utils.ts
19963
+ var LOG_PREFIX = "netra.instrumentation.google_genai";
19964
+ function setRequestAttributes3(span2, params, requestType) {
19803
19965
  try {
19804
- if (typeof value === "string") return value;
19805
- return JSON.stringify(value);
19806
- } catch {
19807
- return String(value);
19966
+ if (!span2.isRecording()) return;
19967
+ span2.setAttribute(SpanAttributes2.LLM_REQUEST_TYPE, requestType);
19968
+ span2.setAttribute(SpanAttributes2.LLM_SYSTEM, "google_genai");
19969
+ if (params.model) {
19970
+ span2.setAttribute(
19971
+ SpanAttributes2.LLM_REQUEST_MODEL,
19972
+ extractModelName(String(params.model))
19973
+ );
19974
+ }
19975
+ const cfg = params.config ?? {};
19976
+ if (cfg.temperature !== void 0) {
19977
+ span2.setAttribute(
19978
+ SpanAttributes2.LLM_REQUEST_TEMPERATURE,
19979
+ Number(cfg.temperature)
19980
+ );
19981
+ }
19982
+ if (cfg.topP !== void 0) {
19983
+ span2.setAttribute(SpanAttributes2.LLM_REQUEST_TOP_P, Number(cfg.topP));
19984
+ }
19985
+ if (cfg.topK !== void 0) {
19986
+ span2.setAttribute(SpanAttributes2.LLM_REQUEST_TOP_K, Number(cfg.topK));
19987
+ }
19988
+ if (cfg.maxOutputTokens !== void 0) {
19989
+ span2.setAttribute(
19990
+ SpanAttributes2.LLM_REQUEST_MAX_TOKENS,
19991
+ Number(cfg.maxOutputTokens)
19992
+ );
19993
+ }
19994
+ if (cfg.frequencyPenalty !== void 0) {
19995
+ span2.setAttribute(
19996
+ SpanAttributes2.LLM_FREQUENCY_PENALTY,
19997
+ Number(cfg.frequencyPenalty)
19998
+ );
19999
+ }
20000
+ if (cfg.presencePenalty !== void 0) {
20001
+ span2.setAttribute(
20002
+ SpanAttributes2.LLM_PRESENCE_PENALTY,
20003
+ Number(cfg.presencePenalty)
20004
+ );
20005
+ }
20006
+ if (cfg.stopSequences !== void 0) {
20007
+ span2.setAttribute(
20008
+ SpanAttributes2.LLM_CHAT_STOP_SEQUENCES,
20009
+ safeStringify(cfg.stopSequences)
20010
+ );
20011
+ }
20012
+ if (isTraceContentEnabled()) {
20013
+ const messages = buildGoogleInputMessages(params, cfg);
20014
+ writePromptAttributes(span2, messages);
20015
+ }
20016
+ } catch (e) {
20017
+ Logger.error(`${LOG_PREFIX}: setRequestAttributes error`, e);
19808
20018
  }
19809
20019
  }
19810
20020
  function extractModelName(model) {
20021
+ const MODEL_PREFIX = "models/";
20022
+ const TUNED_MODELS_PREFIX = "tunedModels/";
20023
+ const PUBLISHERS_PREFIX = "publishers/";
20024
+ const PROJECTS_PREFIX = "projects/";
20025
+ const MODELS_SEGMENT = "/models/";
20026
+ if (model.startsWith(MODEL_PREFIX)) return model.slice(MODEL_PREFIX.length);
20027
+ if (model.startsWith(TUNED_MODELS_PREFIX)) return model;
20028
+ const publisherIdx = model.indexOf(PUBLISHERS_PREFIX);
20029
+ if (publisherIdx !== -1) {
20030
+ const modelsIdx = model.indexOf(MODELS_SEGMENT, publisherIdx);
20031
+ if (modelsIdx !== -1) return model.slice(modelsIdx + MODELS_SEGMENT.length);
20032
+ }
20033
+ const slashIdx = model.indexOf("/");
20034
+ if (slashIdx !== -1 && !model.startsWith(PROJECTS_PREFIX)) {
20035
+ return model.slice(slashIdx + 1);
20036
+ }
20037
+ return model;
20038
+ }
20039
+ function buildGoogleInputMessages(params, cfg) {
20040
+ const messages = [];
20041
+ if (hasContent(cfg.systemInstruction)) {
20042
+ const sysContent = typeof cfg.systemInstruction === "string" ? cfg.systemInstruction : safeStringify(cfg.systemInstruction, Config.CONVERSATION_MAX_LEN);
20043
+ messages.push({ role: "system", content: sysContent });
20044
+ }
20045
+ const history = params._history;
20046
+ if (Array.isArray(history)) {
20047
+ for (const turn of history) {
20048
+ const role = normalizeRole(String(turn.role ?? "user"));
20049
+ const parts = turn.parts;
20050
+ if (Array.isArray(parts)) {
20051
+ const text = extractTextFromParts(parts);
20052
+ if (text) messages.push({ role, content: text });
20053
+ }
20054
+ }
20055
+ }
20056
+ const contents = params.contents ?? params.message;
20057
+ if (!hasContent(contents)) return messages;
20058
+ if (typeof contents === "string") {
20059
+ messages.push({ role: "user", content: contents });
20060
+ return messages;
20061
+ }
20062
+ if (Array.isArray(contents)) {
20063
+ for (const item of contents) {
20064
+ if (typeof item === "string") {
20065
+ messages.push({ role: "user", content: item });
20066
+ } else if (isDict(item) && item.role && Array.isArray(item.parts)) {
20067
+ const role = normalizeRole(String(item.role));
20068
+ const text = extractTextFromParts(item.parts);
20069
+ if (text) messages.push({ role, content: text });
20070
+ } else if (isDict(item) && item.text !== void 0) {
20071
+ messages.push({ role: "user", content: String(item.text) });
20072
+ } else {
20073
+ messages.push({
20074
+ role: "user",
20075
+ content: safeStringify(item, Config.CONVERSATION_MAX_LEN)
20076
+ });
20077
+ }
20078
+ }
20079
+ } else if (isDict(contents) && Array.isArray(contents.parts)) {
20080
+ const role = normalizeRole(String(contents.role ?? "user"));
20081
+ const text = extractTextFromParts(contents.parts);
20082
+ if (text) messages.push({ role, content: text });
20083
+ } else if (isDict(contents) && contents.text !== void 0) {
20084
+ messages.push({ role: "user", content: String(contents.text) });
20085
+ } else {
20086
+ messages.push({
20087
+ role: "user",
20088
+ content: safeStringify(contents, Config.CONVERSATION_MAX_LEN)
20089
+ });
20090
+ }
20091
+ return messages;
20092
+ }
20093
+ function normalizeRole(role) {
20094
+ if (role === "model") return "assistant";
20095
+ return role;
20096
+ }
20097
+ function extractTextFromParts(parts) {
20098
+ const texts = [];
20099
+ for (const part of parts) {
20100
+ if (!isDict(part)) continue;
20101
+ if (typeof part.text === "string") {
20102
+ texts.push(part.text);
20103
+ } else if (part.functionCall) {
20104
+ texts.push(safeStringify(part.functionCall, Config.CONVERSATION_MAX_LEN));
20105
+ } else if (part.functionResponse) {
20106
+ texts.push(
20107
+ safeStringify(part.functionResponse, Config.CONVERSATION_MAX_LEN)
20108
+ );
20109
+ }
20110
+ }
20111
+ return texts.join("");
20112
+ }
20113
+ function setResponseAttributes3(span2, response) {
20114
+ try {
20115
+ if (!span2.isRecording()) return;
20116
+ if (response.responseId) {
20117
+ span2.setAttribute("llm.response.id", String(response.responseId));
20118
+ }
20119
+ if (response.modelVersion) {
20120
+ span2.setAttribute(
20121
+ SpanAttributes2.LLM_RESPONSE_MODEL,
20122
+ String(response.modelVersion)
20123
+ );
20124
+ }
20125
+ setUsageAttributes2(span2, response);
20126
+ setFinishReason2(span2, response);
20127
+ setEmbeddingMeta(span2, response);
20128
+ if (isTraceContentEnabled()) {
20129
+ const messages = buildGoogleOutputMessages(response);
20130
+ writeCompletionAttributes(span2, messages);
20131
+ }
20132
+ } catch (e) {
20133
+ Logger.error(`${LOG_PREFIX}: setResponseAttributes error`, e);
20134
+ }
20135
+ }
20136
+ function setUsageAttributes2(span2, response) {
20137
+ const usage = response.usageMetadata;
20138
+ if (!usage) return;
20139
+ if (usage.promptTokenCount !== void 0) {
20140
+ span2.setAttribute(
20141
+ SpanAttributes2.LLM_USAGE_PROMPT_TOKENS,
20142
+ Number(usage.promptTokenCount)
20143
+ );
20144
+ }
20145
+ if (usage.candidatesTokenCount !== void 0) {
20146
+ span2.setAttribute(
20147
+ SpanAttributes2.LLM_USAGE_COMPLETION_TOKENS,
20148
+ Number(usage.candidatesTokenCount)
20149
+ );
20150
+ }
20151
+ if (usage.totalTokenCount !== void 0) {
20152
+ span2.setAttribute(
20153
+ SpanAttributes2.LLM_USAGE_TOTAL_TOKENS,
20154
+ Number(usage.totalTokenCount)
20155
+ );
20156
+ }
20157
+ if (usage.cachedContentTokenCount !== void 0) {
20158
+ span2.setAttribute(
20159
+ SpanAttributes2.LLM_USAGE_CACHE_READ_INPUT_TOKENS,
20160
+ Number(usage.cachedContentTokenCount)
20161
+ );
20162
+ }
20163
+ if (usage.thoughtsTokenCount !== void 0) {
20164
+ span2.setAttribute(
20165
+ SpanAttributes2.LLM_USAGE_REASONING_TOKENS,
20166
+ Number(usage.thoughtsTokenCount)
20167
+ );
20168
+ }
20169
+ }
20170
+ function setFinishReason2(span2, response) {
20171
+ const candidates = response.candidates;
20172
+ if (!Array.isArray(candidates) || candidates.length === 0) return;
20173
+ const reason = candidates[0].finishReason;
20174
+ if (reason) {
20175
+ span2.setAttribute(
20176
+ SpanAttributes2.LLM_RESPONSE_FINISH_REASON,
20177
+ String(reason)
20178
+ );
20179
+ span2.setAttribute("gen_ai.response.finish_reason", String(reason));
20180
+ }
20181
+ }
20182
+ function setEmbeddingMeta(span2, response) {
20183
+ const singleEmbed = response.embedding;
20184
+ if (singleEmbed?.values !== void 0) {
20185
+ const values2 = singleEmbed.values;
20186
+ span2.setAttribute("gen_ai.response.embedding_dimensions", values2.length);
20187
+ const stats = singleEmbed.statistics;
20188
+ if (stats?.tokenCount !== void 0) {
20189
+ const tokenCount = Number(stats.tokenCount);
20190
+ span2.setAttribute(SpanAttributes2.LLM_USAGE_PROMPT_TOKENS, tokenCount);
20191
+ span2.setAttribute(SpanAttributes2.LLM_USAGE_TOTAL_TOKENS, tokenCount);
20192
+ }
20193
+ return;
20194
+ }
20195
+ const embeddings = response.embeddings;
20196
+ if (!Array.isArray(embeddings) || embeddings.length === 0) return;
20197
+ span2.setAttribute("gen_ai.response.embedding_count", embeddings.length);
20198
+ const first = embeddings[0];
20199
+ const values = first?.values;
20200
+ if (Array.isArray(values)) {
20201
+ span2.setAttribute("gen_ai.response.embedding_dimensions", values.length);
20202
+ }
20203
+ let totalTokens = 0;
20204
+ let hasTokenCount = false;
20205
+ for (const emb of embeddings) {
20206
+ const stats = emb.statistics;
20207
+ if (stats?.tokenCount !== void 0) {
20208
+ totalTokens += Number(stats.tokenCount);
20209
+ hasTokenCount = true;
20210
+ }
20211
+ }
20212
+ if (hasTokenCount) {
20213
+ span2.setAttribute(SpanAttributes2.LLM_USAGE_PROMPT_TOKENS, totalTokens);
20214
+ span2.setAttribute(SpanAttributes2.LLM_USAGE_TOTAL_TOKENS, totalTokens);
20215
+ }
20216
+ }
20217
+ function buildGoogleOutputMessages(response) {
20218
+ const messages = [];
20219
+ const text = response.text;
20220
+ if (typeof text === "string" && text.length > 0) {
20221
+ messages.push({ role: "assistant", content: text });
20222
+ }
20223
+ const functionCalls = response.functionCalls;
20224
+ if (Array.isArray(functionCalls)) {
20225
+ for (const fc of functionCalls) {
20226
+ messages.push({
20227
+ role: "tool",
20228
+ content: safeStringify(
20229
+ { name: fc.name, arguments: fc.args },
20230
+ Config.CONVERSATION_MAX_LEN
20231
+ )
20232
+ });
20233
+ }
20234
+ }
20235
+ if (messages.length === 0) {
20236
+ const candidates = response.candidates;
20237
+ if (Array.isArray(candidates)) {
20238
+ for (const candidate of candidates) {
20239
+ const content = candidate.content;
20240
+ if (!content || !Array.isArray(content.parts)) continue;
20241
+ for (const part of content.parts) {
20242
+ if (typeof part.text === "string" && part.text.length > 0) {
20243
+ messages.push({ role: "assistant", content: part.text });
20244
+ }
20245
+ if (part.functionCall && isDict(part.functionCall)) {
20246
+ const fc = part.functionCall;
20247
+ messages.push({
20248
+ role: "tool",
20249
+ content: safeStringify(
20250
+ { name: fc.name, arguments: fc.args },
20251
+ Config.CONVERSATION_MAX_LEN
20252
+ )
20253
+ });
20254
+ }
20255
+ }
20256
+ }
20257
+ }
20258
+ }
20259
+ if (messages.length === 0) {
20260
+ const singleEmbed = response.embedding;
20261
+ if (singleEmbed?.values !== void 0) {
20262
+ const values = singleEmbed.values;
20263
+ messages.push({
20264
+ role: "assistant",
20265
+ content: safeStringify({
20266
+ dimensions: values.length,
20267
+ preview: values.slice(0, 5)
20268
+ })
20269
+ });
20270
+ }
20271
+ const embeddings = response.embeddings;
20272
+ if (Array.isArray(embeddings) && embeddings.length > 0) {
20273
+ for (let i = 0; i < embeddings.length; i++) {
20274
+ const values = embeddings[i]?.values ?? [];
20275
+ messages.push({
20276
+ role: "assistant",
20277
+ content: safeStringify({
20278
+ index: i,
20279
+ dimensions: values.length,
20280
+ preview: values.slice(0, 5)
20281
+ })
20282
+ });
20283
+ }
20284
+ }
20285
+ }
20286
+ return messages;
20287
+ }
20288
+ function processStreamChunk2(accumulated, chunk, span2, startTime) {
20289
+ try {
20290
+ if (chunk.modelVersion) {
20291
+ accumulated.modelVersion = chunk.modelVersion;
20292
+ }
20293
+ if (chunk.responseId) {
20294
+ accumulated.responseId = chunk.responseId;
20295
+ }
20296
+ const chunkText = typeof chunk.text === "string" ? chunk.text : void 0;
20297
+ if (chunkText && chunkText.length > 0) {
20298
+ if (!accumulated._text) {
20299
+ accumulated._text = chunkText;
20300
+ span2.setAttribute(
20301
+ "gen_ai.performance.time_to_first_token",
20302
+ (Date.now() - startTime) / 1e3
20303
+ );
20304
+ } else {
20305
+ accumulated._text += chunkText;
20306
+ }
20307
+ }
20308
+ const fcs = chunk.functionCalls;
20309
+ if (Array.isArray(fcs) && fcs.length > 0) {
20310
+ if (!accumulated._functionCalls) accumulated._functionCalls = [];
20311
+ accumulated._functionCalls.push(...fcs);
20312
+ }
20313
+ if (chunk.usageMetadata) {
20314
+ accumulated.usageMetadata = chunk.usageMetadata;
20315
+ }
20316
+ if (Array.isArray(chunk.candidates) && chunk.candidates.length > 0) {
20317
+ const reason = chunk.candidates[0]?.finishReason;
20318
+ if (reason) {
20319
+ if (!accumulated.candidates) accumulated.candidates = [{}];
20320
+ accumulated.candidates[0].finishReason = reason;
20321
+ }
20322
+ }
20323
+ if (Logger.isDebugMode()) {
20324
+ span2.addEvent("llm.content.completion.chunk");
20325
+ }
20326
+ } catch (e) {
20327
+ Logger.error(`${LOG_PREFIX}: processStreamChunk error`, e);
20328
+ }
20329
+ }
20330
+ function buildAccumulatedResponse(accumulated) {
20331
+ const response = {
20332
+ responseId: accumulated.responseId,
20333
+ modelVersion: accumulated.modelVersion,
20334
+ usageMetadata: accumulated.usageMetadata,
20335
+ candidates: accumulated.candidates
20336
+ };
20337
+ if (accumulated._text) {
20338
+ response.text = accumulated._text;
20339
+ }
20340
+ if (accumulated._functionCalls) {
20341
+ response.functionCalls = accumulated._functionCalls;
20342
+ }
20343
+ return response;
20344
+ }
20345
+
20346
+ // src/instrumentation/google-genai/wrappers.ts
20347
+ var LOG_PREFIX2 = "netra.instrumentation.google_genai";
20348
+ function buildParams(args, self) {
20349
+ const raw = args[0];
20350
+ const params = typeof raw === "object" && raw !== null ? { ...raw } : { message: raw };
20351
+ if (!params.model && self.model) {
20352
+ params.model = self.model;
20353
+ }
20354
+ if (!params.config && self.config) {
20355
+ params.config = self.config;
20356
+ }
20357
+ try {
20358
+ const history = typeof self.getHistory === "function" ? self.getHistory(true) : self.history;
20359
+ if (Array.isArray(history)) {
20360
+ params._history = history;
20361
+ }
20362
+ } catch {
20363
+ }
20364
+ return params;
20365
+ }
20366
+ function genericWrapperFactory(tracer, spanName, requestType) {
20367
+ return function wrapper(original) {
20368
+ return function(...args) {
20369
+ if (shouldSuppressInstrumentation()) {
20370
+ return original.apply(this, args);
20371
+ }
20372
+ const self = this;
20373
+ const params = buildParams(args, self);
20374
+ const currentContext = api.context.active();
20375
+ return tracer.startActiveSpan(
20376
+ spanName,
20377
+ { kind: api.SpanKind.CLIENT },
20378
+ (span2) => {
20379
+ try {
20380
+ setRequestAttributes3(span2, params, requestType);
20381
+ const startTime = Date.now();
20382
+ const spanContext = api.trace.setSpan(currentContext, span2);
20383
+ const suppressedCtx = createSuppressedContext(spanContext);
20384
+ const response = api.context.with(
20385
+ suppressedCtx,
20386
+ () => original.apply(this, args)
20387
+ );
20388
+ return wrapResponse(
20389
+ response,
20390
+ {
20391
+ withContext: (fn) => api.context.with(spanContext, fn),
20392
+ onSuccess: (value) => {
20393
+ const endTime = Date.now();
20394
+ const responseDict = modelAsDict(value);
20395
+ if (typeof value?.text === "string") {
20396
+ responseDict.text = value.text;
20397
+ }
20398
+ if (Array.isArray(value?.functionCalls)) {
20399
+ responseDict.functionCalls = value.functionCalls;
20400
+ }
20401
+ setResponseAttributes3(span2, responseDict);
20402
+ span2.setAttribute(
20403
+ SpanAttributes2.LLM_RESPONSE_DURATION,
20404
+ (endTime - startTime) / 1e3
20405
+ );
20406
+ },
20407
+ onError: (error) => {
20408
+ span2.setStatus({
20409
+ code: api.SpanStatusCode.ERROR,
20410
+ message: error instanceof Error ? error.message : String(error)
20411
+ });
20412
+ span2.recordException(error);
20413
+ },
20414
+ finalize: (status) => {
20415
+ if (status === "ok") {
20416
+ span2.setStatus({ code: api.SpanStatusCode.OK });
20417
+ }
20418
+ span2.end();
20419
+ }
20420
+ },
20421
+ { preserveOriginal: response }
20422
+ );
20423
+ } catch (error) {
20424
+ span2.setStatus({
20425
+ code: api.SpanStatusCode.ERROR,
20426
+ message: error instanceof Error ? error.message : String(error)
20427
+ });
20428
+ span2.recordException(error);
20429
+ span2.end();
20430
+ throw error;
20431
+ }
20432
+ }
20433
+ );
20434
+ };
20435
+ };
20436
+ }
20437
+ function streamWrapperFactory(tracer, spanName, requestType) {
20438
+ return function wrapper(original) {
20439
+ return function(...args) {
20440
+ if (shouldSuppressInstrumentation()) {
20441
+ return original.apply(this, args);
20442
+ }
20443
+ const self = this;
20444
+ const params = buildParams(args, self);
20445
+ const currentContext = api.context.active();
20446
+ return tracer.startActiveSpan(
20447
+ spanName,
20448
+ {
20449
+ kind: api.SpanKind.CLIENT,
20450
+ attributes: { [SpanAttributes2.LLM_IS_STREAMING]: true }
20451
+ },
20452
+ (span2) => {
20453
+ const startTime = Date.now();
20454
+ const accumulated = {};
20455
+ try {
20456
+ setRequestAttributes3(span2, params, requestType);
20457
+ const spanContext = api.trace.setSpan(currentContext, span2);
20458
+ const suppressedCtx = createSuppressedContext(spanContext);
20459
+ const response = api.context.with(
20460
+ suppressedCtx,
20461
+ () => original.apply(this, args)
20462
+ );
20463
+ return wrapResponse(
20464
+ response,
20465
+ {
20466
+ withContext: (fn) => api.context.with(spanContext, fn),
20467
+ onChunk: (chunk) => {
20468
+ processStreamChunk2(accumulated, chunk, span2, startTime);
20469
+ },
20470
+ onError: (error) => {
20471
+ span2.setStatus({
20472
+ code: api.SpanStatusCode.ERROR,
20473
+ message: error instanceof Error ? error.message : String(error)
20474
+ });
20475
+ span2.recordException(error);
20476
+ },
20477
+ finalize: (status) => {
20478
+ try {
20479
+ const endTime = Date.now();
20480
+ const syntheticResponse = buildAccumulatedResponse(accumulated);
20481
+ setResponseAttributes3(span2, syntheticResponse);
20482
+ span2.setAttribute(
20483
+ SpanAttributes2.LLM_RESPONSE_DURATION,
20484
+ (endTime - startTime) / 1e3
20485
+ );
20486
+ } catch (e) {
20487
+ Logger.error(`${LOG_PREFIX2}: stream finalize error`, e);
20488
+ }
20489
+ if (status === "ok") {
20490
+ span2.setStatus({ code: api.SpanStatusCode.OK });
20491
+ }
20492
+ span2.end();
20493
+ }
20494
+ },
20495
+ { preserveOriginal: response }
20496
+ );
20497
+ } catch (error) {
20498
+ span2.setStatus({
20499
+ code: api.SpanStatusCode.ERROR,
20500
+ message: error instanceof Error ? error.message : String(error)
20501
+ });
20502
+ span2.recordException(error);
20503
+ span2.end();
20504
+ throw error;
20505
+ }
20506
+ }
20507
+ );
20508
+ };
20509
+ };
20510
+ }
20511
+ var chatWrapper2 = (tracer) => genericWrapperFactory(tracer, SPAN_NAMES2.CHAT, "chat");
20512
+ var chatStreamWrapper2 = (tracer) => streamWrapperFactory(tracer, SPAN_NAMES2.CHAT, "chat");
20513
+ var embeddingsWrapper = (tracer) => genericWrapperFactory(tracer, SPAN_NAMES2.EMBEDDING, "embedding");
20514
+
20515
+ // src/instrumentation/google-genai/index.ts
20516
+ var NetraGoogleGenAIInstrumentor = class extends BaseInstrumentor {
20517
+ constructor() {
20518
+ super(...arguments);
20519
+ this.instrumentationName = "netra.instrumentation.google_genai";
20520
+ this.instrumentationVersion = __version__2;
20521
+ this.packageName = "@google/genai";
20522
+ this.displayName = "Google GenAI";
20523
+ }
20524
+ extractClasses(mod) {
20525
+ const root = mod.default ?? mod;
20526
+ if (!root.Models) return null;
20527
+ return { Models: root.Models, Chat: root.Chat };
20528
+ }
20529
+ isSameClasses(a, b) {
20530
+ return a.Models === b.Models;
20531
+ }
20532
+ applyPatches(classes, tracer) {
20533
+ const modelsProto = classes.Models?.prototype;
20534
+ if (!modelsProto) {
20535
+ Logger.error("Google GenAI: Models.prototype not found");
20536
+ return false;
20537
+ }
20538
+ let wrapped = false;
20539
+ if (typeof modelsProto.generateContentInternal === "function") {
20540
+ shimmer__default.default.wrap(modelsProto, "generateContentInternal", chatWrapper2(tracer));
20541
+ wrapped = true;
20542
+ }
20543
+ if (typeof modelsProto.generateContentStreamInternal === "function") {
20544
+ shimmer__default.default.wrap(modelsProto, "generateContentStreamInternal", chatStreamWrapper2(tracer));
20545
+ wrapped = true;
20546
+ }
20547
+ if (typeof modelsProto.embedContentInternal === "function") {
20548
+ shimmer__default.default.wrap(modelsProto, "embedContentInternal", embeddingsWrapper(tracer));
20549
+ wrapped = true;
20550
+ }
20551
+ const chatProto = classes.Chat?.prototype;
20552
+ if (chatProto) {
20553
+ if (typeof chatProto.sendMessage === "function") {
20554
+ shimmer__default.default.wrap(chatProto, "sendMessage", chatWrapper2(tracer));
20555
+ wrapped = true;
20556
+ }
20557
+ if (typeof chatProto.sendMessageStream === "function") {
20558
+ shimmer__default.default.wrap(chatProto, "sendMessageStream", chatStreamWrapper2(tracer));
20559
+ wrapped = true;
20560
+ }
20561
+ }
20562
+ return wrapped;
20563
+ }
20564
+ removePatches(classes) {
20565
+ const modelsProto = classes.Models?.prototype;
20566
+ if (modelsProto) {
20567
+ if (typeof modelsProto.generateContentInternal === "function")
20568
+ shimmer__default.default.unwrap(modelsProto, "generateContentInternal");
20569
+ if (typeof modelsProto.generateContentStreamInternal === "function")
20570
+ shimmer__default.default.unwrap(modelsProto, "generateContentStreamInternal");
20571
+ if (typeof modelsProto.embedContentInternal === "function")
20572
+ shimmer__default.default.unwrap(modelsProto, "embedContentInternal");
20573
+ }
20574
+ const chatProto = classes.Chat?.prototype;
20575
+ if (chatProto) {
20576
+ if (typeof chatProto.sendMessage === "function")
20577
+ shimmer__default.default.unwrap(chatProto, "sendMessage");
20578
+ if (typeof chatProto.sendMessageStream === "function")
20579
+ shimmer__default.default.unwrap(chatProto, "sendMessageStream");
20580
+ }
20581
+ }
20582
+ };
20583
+ var googleGenAIInstrumentor = new NetraGoogleGenAIInstrumentor();
20584
+
20585
+ // src/instrumentation/google-generative-ai/version.ts
20586
+ var __version__3 = "1.0.0";
20587
+
20588
+ // src/instrumentation/google-generative-ai/utils.ts
20589
+ function extractModelName2(model) {
19811
20590
  if (model && model.startsWith("models/")) {
19812
20591
  return model.replace(/^models\//, "");
19813
20592
  }
19814
20593
  return model;
19815
20594
  }
19816
- function normalizeGenAIRole(raw) {
20595
+ function normalizeGenerativeAIRole(raw) {
19817
20596
  const rawLower = raw.toLowerCase();
19818
20597
  return rawLower === "model" ? "assistant" : rawLower;
19819
20598
  }
19820
- function setRequestAttributes3(span2, kwargs, requestType, args) {
20599
+ function setRequestAttributes4(span2, kwargs, requestType, args) {
19821
20600
  span2._netra_kwargs = kwargs;
19822
20601
  if (!span2.isRecording()) {
19823
20602
  return;
19824
20603
  }
19825
20604
  span2.setAttribute(SpanAttributes2.LLM_REQUEST_TYPE, requestType);
19826
- span2.setAttribute(SpanAttributes2.LLM_SYSTEM, "google_genai");
20605
+ span2.setAttribute(SpanAttributes2.LLM_SYSTEM, "google_generative_ai");
19827
20606
  if (kwargs.model !== void 0) {
19828
20607
  span2.setAttribute(SpanAttributes2.LLM_REQUEST_MODEL, String(kwargs.model));
19829
20608
  }
@@ -19852,7 +20631,7 @@ function setRequestAttributes3(span2, kwargs, requestType, args) {
19852
20631
  if (generationConfig.stopSequences !== void 0) {
19853
20632
  span2.setAttribute(
19854
20633
  SpanAttributes2.LLM_CHAT_STOP_SEQUENCES,
19855
- safeStringify2(generationConfig.stopSequences)
20634
+ safeStringify(generationConfig.stopSequences)
19856
20635
  );
19857
20636
  }
19858
20637
  if (generationConfig.candidateCount !== void 0) {
@@ -19882,7 +20661,7 @@ function setRequestAttributes3(span2, kwargs, requestType, args) {
19882
20661
  if (kwargs.toolConfig !== void 0) {
19883
20662
  span2.setAttribute(
19884
20663
  "gen_ai.request.tool_config",
19885
- safeStringify2(kwargs.toolConfig)
20664
+ safeStringify(kwargs.toolConfig)
19886
20665
  );
19887
20666
  }
19888
20667
  if (Array.isArray(kwargs.safetySettings) && kwargs.safetySettings.length > 0) {
@@ -19892,22 +20671,18 @@ function setRequestAttributes3(span2, kwargs, requestType, args) {
19892
20671
  );
19893
20672
  }
19894
20673
  if (kwargs.systemInstruction !== void 0) {
19895
- if (isTraceContentEnabled2()) {
20674
+ if (isTraceContentEnabled()) {
19896
20675
  span2.setAttribute(
19897
20676
  "gen_ai.request.system_instruction",
19898
- safeStringify2(kwargs.systemInstruction)
20677
+ safeStringify(kwargs.systemInstruction)
19899
20678
  );
19900
20679
  }
19901
20680
  span2.setAttribute("gen_ai.request.has_system_instruction", true);
19902
20681
  }
19903
- if (isTraceContentEnabled2()) {
20682
+ if (isTraceContentEnabled()) {
19904
20683
  _setPromptAttributes(span2, kwargs, args);
19905
20684
  }
19906
20685
  }
19907
- function isTraceContentEnabled2() {
19908
- const raw = process.env.TRACELOOP_TRACE_CONTENT ?? process.env.NETRA_TRACE_CONTENT ?? "";
19909
- return ["1", "true"].includes(String(raw).toLowerCase());
19910
- }
19911
20686
  function _setPromptAttributes(span2, kwargs, args) {
19912
20687
  let promptIndex = 0;
19913
20688
  if (kwargs.systemInstruction !== void 0) {
@@ -19920,7 +20695,7 @@ function _setPromptAttributes(span2, kwargs, args) {
19920
20695
  } else if (systemInstruction.text) {
19921
20696
  systemContent = String(systemInstruction.text);
19922
20697
  } else {
19923
- systemContent = JSON.stringify(systemInstruction);
20698
+ systemContent = safeStringify(systemInstruction);
19924
20699
  }
19925
20700
  if (systemContent) {
19926
20701
  span2.setAttribute(
@@ -19936,7 +20711,7 @@ function _setPromptAttributes(span2, kwargs, args) {
19936
20711
  }
19937
20712
  if (kwargs.history && Array.isArray(kwargs.history)) {
19938
20713
  for (const turn of kwargs.history) {
19939
- const role = normalizeGenAIRole(String(turn.role ?? "user"));
20714
+ const role = normalizeGenerativeAIRole(String(turn.role ?? "user"));
19940
20715
  const parts = turn.parts;
19941
20716
  if (Array.isArray(parts)) {
19942
20717
  const textContent = parts.filter((p) => p.text !== void 0).map((p) => String(p.text)).join("");
@@ -19989,29 +20764,32 @@ function _setPromptAttributes(span2, kwargs, args) {
19989
20764
  const contents = args.contents;
19990
20765
  if (Array.isArray(contents)) {
19991
20766
  for (const content of contents) {
19992
- const role = String(content.role ?? "user");
20767
+ const role = normalizeGenerativeAIRole(String(content.role ?? "user"));
19993
20768
  const parts = content.parts;
19994
20769
  if (Array.isArray(parts)) {
19995
20770
  const textParts = parts.filter((p) => p.text !== void 0).map((p) => String(p.text)).join("");
19996
- if (textParts) {
20771
+ const inlineDataParts = parts.filter((p) => p.inlineData !== void 0);
20772
+ const slotIndex = promptIndex;
20773
+ if (textParts || inlineDataParts.length > 0) {
19997
20774
  span2.setAttribute(
19998
- `${SpanAttributes2.LLM_PROMPTS}.${promptIndex}.role`,
20775
+ `${SpanAttributes2.LLM_PROMPTS}.${slotIndex}.role`,
19999
20776
  role
20000
20777
  );
20001
- span2.setAttribute(
20002
- `${SpanAttributes2.LLM_PROMPTS}.${promptIndex}.content`,
20003
- textParts
20004
- );
20778
+ if (textParts) {
20779
+ span2.setAttribute(
20780
+ `${SpanAttributes2.LLM_PROMPTS}.${slotIndex}.content`,
20781
+ textParts
20782
+ );
20783
+ }
20005
20784
  promptIndex++;
20006
20785
  }
20007
- const inlineDataParts = parts.filter((p) => p.inlineData !== void 0);
20008
20786
  if (inlineDataParts.length > 0) {
20009
20787
  span2.setAttribute(
20010
- `gen_ai.prompt.${promptIndex - 1}.has_inline_data`,
20788
+ `gen_ai.prompt.${slotIndex}.has_inline_data`,
20011
20789
  true
20012
20790
  );
20013
20791
  span2.setAttribute(
20014
- `gen_ai.prompt.${promptIndex - 1}.inline_data_count`,
20792
+ `gen_ai.prompt.${slotIndex}.inline_data_count`,
20015
20793
  inlineDataParts.length
20016
20794
  );
20017
20795
  }
@@ -20039,15 +20817,18 @@ function _setPromptAttributes(span2, kwargs, args) {
20039
20817
  }
20040
20818
  }
20041
20819
  }
20042
- function setResponseAttributes3(span2, response) {
20820
+ function setResponseAttributes4(span2, response) {
20043
20821
  if (!span2.isRecording()) {
20044
20822
  return;
20045
20823
  }
20046
20824
  const actualResponse = response.response ?? response;
20047
20825
  _setUsageAttributes(span2, actualResponse);
20826
+ if (!actualResponse.usageMetadata && response.usageMetadata) {
20827
+ _setUsageAttributes(span2, response);
20828
+ }
20048
20829
  _setCandidateAttributes(span2, actualResponse);
20049
20830
  _setPromptFeedbackAttributes(span2, actualResponse);
20050
- if (isTraceContentEnabled2()) {
20831
+ if (isTraceContentEnabled()) {
20051
20832
  _setCompletionAttributes(span2, actualResponse);
20052
20833
  }
20053
20834
  _setEmbeddingResponseAttributes(span2, actualResponse);
@@ -20158,7 +20939,7 @@ function _setCompletionAttributes(span2, response) {
20158
20939
  const candidate = candidates[i];
20159
20940
  const content = candidate.content;
20160
20941
  if (!content) continue;
20161
- const role = normalizeGenAIRole(String(content.role ?? "model"));
20942
+ const role = normalizeGenerativeAIRole(String(content.role ?? "model"));
20162
20943
  const parts = content.parts;
20163
20944
  if (!Array.isArray(parts)) continue;
20164
20945
  const textContent = parts.filter((p) => p.text !== void 0).map((p) => String(p.text)).join("");
@@ -20203,29 +20984,39 @@ function _setEmbeddingResponseAttributes(span2, response) {
20203
20984
  }
20204
20985
  }
20205
20986
 
20206
- // src/instrumentation/google-genai/wrappers.ts
20207
- var CHAT_SPAN_NAME = "google_genai.chat";
20208
- var EMBEDDING_SPAN_NAME = "google_genai.embedding";
20209
- function googleGenAIWrapper(tracer, spanName, requestType) {
20987
+ // src/instrumentation/google-generative-ai/wrappers.ts
20988
+ var LOG_PREFIX3 = "netra.instrumentation.google_generative_ai";
20989
+ var CHAT_SPAN_NAME = "google_generative_ai.chat";
20990
+ var EMBEDDING_SPAN_NAME = "google_generative_ai.embedding";
20991
+ function buildKwargs(instance) {
20992
+ const kwargs = {};
20993
+ const params = instance.params;
20994
+ const modelName = instance.model;
20995
+ if (modelName) {
20996
+ kwargs.model = extractModelName2(modelName);
20997
+ }
20998
+ const systemInstruction = instance.systemInstruction ?? params?.systemInstruction;
20999
+ if (systemInstruction) kwargs.systemInstruction = systemInstruction;
21000
+ const history = instance._history ?? instance.history;
21001
+ if (history) kwargs.history = history;
21002
+ const generationConfig = instance.generationConfig ?? params?.generationConfig;
21003
+ if (generationConfig) kwargs.generationConfig = generationConfig;
21004
+ const safetySettings = instance.safetySettings ?? params?.safetySettings;
21005
+ if (safetySettings) kwargs.safetySettings = safetySettings;
21006
+ const tools = instance.tools ?? params?.tools;
21007
+ if (tools) kwargs.tools = tools;
21008
+ const toolConfig = instance.toolConfig ?? params?.toolConfig;
21009
+ if (toolConfig) kwargs.toolConfig = toolConfig;
21010
+ return kwargs;
21011
+ }
21012
+ function googleGenerativeAIWrapper(tracer, spanName, requestType) {
20210
21013
  return function wrapper(original) {
20211
21014
  return function(...args) {
20212
21015
  if (shouldSuppressInstrumentation()) {
20213
- return original.apply(this, args);
20214
- }
20215
- let kwargs = {};
20216
- const modelInstance = this;
20217
- const modelName = modelInstance.model;
20218
- const systemInstruction = modelInstance.systemInstruction;
20219
- const history = modelInstance.history;
20220
- if (modelName) {
20221
- kwargs.model = extractModelName(modelName);
20222
- }
20223
- if (systemInstruction) {
20224
- kwargs.systemInstruction = systemInstruction;
20225
- }
20226
- if (history) {
20227
- kwargs.history = history;
21016
+ return original.apply(this, args);
20228
21017
  }
21018
+ const modelInstance = this;
21019
+ const kwargs = buildKwargs(modelInstance);
20229
21020
  const currentContext = api.context.active();
20230
21021
  return tracer.startActiveSpan(
20231
21022
  spanName,
@@ -20236,27 +21027,36 @@ function googleGenAIWrapper(tracer, spanName, requestType) {
20236
21027
  currentContext,
20237
21028
  (span2) => {
20238
21029
  try {
20239
- setRequestAttributes3(span2, kwargs, requestType, args[0]);
21030
+ try {
21031
+ setRequestAttributes4(span2, kwargs, requestType, args[0]);
21032
+ } catch (e) {
21033
+ Logger.error(`${LOG_PREFIX3}:`, e);
21034
+ }
20240
21035
  const startTime = Date.now();
20241
21036
  const response = original.apply(this, args);
20242
21037
  if (isPromise(response)) {
20243
21038
  return (async () => {
20244
21039
  try {
20245
21040
  const value = await response;
20246
- const endTime = Date.now();
20247
- const responseDict = modelAsDict(value);
20248
- setResponseAttributes3(span2, responseDict);
20249
- const duration = (endTime - startTime) / 1e3;
20250
- span2.setAttribute("llm.response.duration", duration);
20251
- span2.setAttribute(
20252
- "gen_ai.performance.time_to_first_token",
20253
- duration
20254
- );
21041
+ try {
21042
+ const endTime = Date.now();
21043
+ const responseDict = modelAsDict(value);
21044
+ setResponseAttributes4(span2, responseDict);
21045
+ const duration = (endTime - startTime) / 1e3;
21046
+ span2.setAttribute("llm.response.duration", duration);
21047
+ if (requestType !== "embedding") {
21048
+ span2.setAttribute(
21049
+ "gen_ai.performance.time_to_first_token",
21050
+ duration
21051
+ );
21052
+ }
21053
+ } catch (e) {
21054
+ Logger.error(`${LOG_PREFIX3}:`, e);
21055
+ }
20255
21056
  span2.setStatus({ code: api.SpanStatusCode.OK });
20256
21057
  span2.end();
20257
21058
  return value;
20258
21059
  } catch (error) {
20259
- Logger.error("netra.instrumentation.google-genai:", error);
20260
21060
  span2.setStatus({
20261
21061
  code: api.SpanStatusCode.ERROR,
20262
21062
  message: error instanceof Error ? error.message : String(error)
@@ -20267,19 +21067,22 @@ function googleGenAIWrapper(tracer, spanName, requestType) {
20267
21067
  }
20268
21068
  })();
20269
21069
  } else {
20270
- const endTime = Date.now();
20271
- const responseDict = modelAsDict(response);
20272
- setResponseAttributes3(span2, responseDict);
20273
- span2.setAttribute(
20274
- "llm.response.duration",
20275
- (endTime - startTime) / 1e3
20276
- );
21070
+ try {
21071
+ const endTime = Date.now();
21072
+ const responseDict = modelAsDict(response);
21073
+ setResponseAttributes4(span2, responseDict);
21074
+ span2.setAttribute(
21075
+ "llm.response.duration",
21076
+ (endTime - startTime) / 1e3
21077
+ );
21078
+ } catch (e) {
21079
+ Logger.error(`${LOG_PREFIX3}:`, e);
21080
+ }
20277
21081
  span2.setStatus({ code: api.SpanStatusCode.OK });
20278
21082
  span2.end();
20279
21083
  return response;
20280
21084
  }
20281
21085
  } catch (error) {
20282
- Logger.error("netra.instrumentation.google-genai:", error);
20283
21086
  span2.setStatus({
20284
21087
  code: api.SpanStatusCode.ERROR,
20285
21088
  message: error instanceof Error ? error.message : String(error)
@@ -20293,20 +21096,14 @@ function googleGenAIWrapper(tracer, spanName, requestType) {
20293
21096
  };
20294
21097
  };
20295
21098
  }
20296
- function googleGenAIStreamWrapper(tracer, spanName, requestType) {
21099
+ function googleGenerativeAIStreamWrapper(tracer, spanName, requestType) {
20297
21100
  return function wrapper(original) {
20298
21101
  return function(...args) {
20299
21102
  if (shouldSuppressInstrumentation()) {
20300
21103
  return original.apply(this, args);
20301
21104
  }
20302
- let kwargs = {};
20303
21105
  const modelInstance = this;
20304
- const modelName = modelInstance.model;
20305
- const systemInstruction = modelInstance.systemInstruction;
20306
- const history = modelInstance.history;
20307
- if (modelName) kwargs.model = extractModelName(modelName);
20308
- if (systemInstruction) kwargs.systemInstruction = systemInstruction;
20309
- if (history) kwargs.history = history;
21106
+ const kwargs = buildKwargs(modelInstance);
20310
21107
  const currentContext = api.context.active();
20311
21108
  return tracer.startActiveSpan(
20312
21109
  spanName,
@@ -20318,7 +21115,11 @@ function googleGenAIStreamWrapper(tracer, spanName, requestType) {
20318
21115
  (span2) => {
20319
21116
  const startTime = Date.now();
20320
21117
  try {
20321
- setRequestAttributes3(span2, kwargs, requestType, args[0]);
21118
+ try {
21119
+ setRequestAttributes4(span2, kwargs, requestType, args[0]);
21120
+ } catch (e) {
21121
+ Logger.error(`${LOG_PREFIX3}:`, e);
21122
+ }
20322
21123
  const response = original.apply(this, args);
20323
21124
  if (!isPromise(response)) {
20324
21125
  span2.setStatus({ code: api.SpanStatusCode.OK });
@@ -20330,21 +21131,23 @@ function googleGenAIStreamWrapper(tracer, spanName, requestType) {
20330
21131
  const streamResult = await response;
20331
21132
  const originalStream = streamResult.stream;
20332
21133
  if (!originalStream || typeof originalStream[Symbol.asyncIterator] !== "function") {
20333
- const endTime = Date.now();
20334
- const responseDict = modelAsDict(streamResult);
20335
- setResponseAttributes3(span2, responseDict);
20336
- const duration = (endTime - startTime) / 1e3;
20337
- span2.setAttribute("llm.response.duration", duration);
20338
- span2.setAttribute(
20339
- "gen_ai.performance.time_to_first_token",
20340
- duration
20341
- );
21134
+ try {
21135
+ const endTime = Date.now();
21136
+ const responseDict = modelAsDict(streamResult);
21137
+ setResponseAttributes4(span2, responseDict);
21138
+ const duration = (endTime - startTime) / 1e3;
21139
+ span2.setAttribute("llm.response.duration", duration);
21140
+ span2.setAttribute(
21141
+ "gen_ai.performance.time_to_first_token",
21142
+ duration
21143
+ );
21144
+ } catch (e) {
21145
+ Logger.error(`${LOG_PREFIX3}:`, e);
21146
+ }
20342
21147
  span2.setStatus({ code: api.SpanStatusCode.OK });
20343
21148
  span2.end();
20344
21149
  return streamResult;
20345
21150
  }
20346
- let chunkIndex = 0;
20347
- let finalText = "";
20348
21151
  let firstTokenRecorded = false;
20349
21152
  const wrappedStream = {
20350
21153
  [Symbol.asyncIterator]() {
@@ -20354,25 +21157,29 @@ function googleGenAIStreamWrapper(tracer, spanName, requestType) {
20354
21157
  try {
20355
21158
  const res = await iterator.next();
20356
21159
  if (res?.done) {
20357
- const endTime = Date.now();
20358
- if (streamResult.response && isPromise(streamResult.response)) {
20359
- try {
20360
- const finalResponse = await streamResult.response;
20361
- const responseDict = modelAsDict(finalResponse);
20362
- setResponseAttributes3(span2, responseDict);
20363
- } catch {
21160
+ try {
21161
+ const endTime = Date.now();
21162
+ if (streamResult.response && isPromise(streamResult.response)) {
21163
+ try {
21164
+ const finalResponse = await streamResult.response;
21165
+ const responseDict = modelAsDict(finalResponse);
21166
+ setResponseAttributes4(span2, responseDict);
21167
+ } catch {
21168
+ const responseDict = modelAsDict(streamResult);
21169
+ setResponseAttributes4(span2, responseDict);
21170
+ }
21171
+ } else {
20364
21172
  const responseDict = modelAsDict(streamResult);
20365
- setResponseAttributes3(span2, responseDict);
21173
+ setResponseAttributes4(span2, responseDict);
20366
21174
  }
20367
- } else {
20368
- const responseDict = modelAsDict(streamResult);
20369
- setResponseAttributes3(span2, responseDict);
21175
+ const duration = (endTime - startTime) / 1e3;
21176
+ span2.setAttribute(
21177
+ "llm.response.duration",
21178
+ duration
21179
+ );
21180
+ } catch (e) {
21181
+ Logger.error(`${LOG_PREFIX3}:`, e);
20370
21182
  }
20371
- const duration = (endTime - startTime) / 1e3;
20372
- span2.setAttribute(
20373
- "llm.response.duration",
20374
- duration
20375
- );
20376
21183
  span2.setStatus({ code: api.SpanStatusCode.OK });
20377
21184
  span2.end();
20378
21185
  return res;
@@ -20388,11 +21195,9 @@ function googleGenAIStreamWrapper(tracer, spanName, requestType) {
20388
21195
  );
20389
21196
  firstTokenRecorded = true;
20390
21197
  }
20391
- finalText += t;
20392
21198
  }
20393
21199
  } catch {
20394
21200
  }
20395
- chunkIndex += 1;
20396
21201
  return res;
20397
21202
  } catch (error) {
20398
21203
  span2.setStatus({
@@ -20404,13 +21209,23 @@ function googleGenAIStreamWrapper(tracer, spanName, requestType) {
20404
21209
  throw error;
20405
21210
  }
20406
21211
  },
20407
- async return() {
21212
+ async return(value) {
20408
21213
  const endTime = Date.now();
20409
21214
  const duration = (endTime - startTime) / 1e3;
20410
21215
  span2.setAttribute("llm.response.duration", duration);
20411
21216
  span2.setStatus({ code: api.SpanStatusCode.OK });
20412
21217
  span2.end();
20413
- return { value: void 0, done: true };
21218
+ return iterator.return?.(value) ?? { value: void 0, done: true };
21219
+ },
21220
+ async throw(e) {
21221
+ span2.setStatus({
21222
+ code: api.SpanStatusCode.ERROR,
21223
+ message: e instanceof Error ? e.message : String(e)
21224
+ });
21225
+ span2.recordException(e instanceof Error ? e : new Error(String(e)));
21226
+ span2.end();
21227
+ if (iterator.throw) return iterator.throw(e);
21228
+ throw e;
20414
21229
  }
20415
21230
  };
20416
21231
  }
@@ -20420,7 +21235,6 @@ function googleGenAIStreamWrapper(tracer, spanName, requestType) {
20420
21235
  stream: wrappedStream
20421
21236
  };
20422
21237
  } catch (error) {
20423
- Logger.error("netra.instrumentation.google-genai:", error);
20424
21238
  span2.setStatus({
20425
21239
  code: api.SpanStatusCode.ERROR,
20426
21240
  message: error instanceof Error ? error.message : String(error)
@@ -20431,7 +21245,6 @@ function googleGenAIStreamWrapper(tracer, spanName, requestType) {
20431
21245
  }
20432
21246
  })();
20433
21247
  } catch (error) {
20434
- Logger.error("netra.instrumentation.google-genai:", error);
20435
21248
  span2.setStatus({
20436
21249
  code: api.SpanStatusCode.ERROR,
20437
21250
  message: error instanceof Error ? error.message : String(error)
@@ -20445,227 +21258,100 @@ function googleGenAIStreamWrapper(tracer, spanName, requestType) {
20445
21258
  };
20446
21259
  };
20447
21260
  }
20448
- function googleGenAIStartChatWrapper(tracer, spanName, requestType) {
20449
- const sendMessageWrapperFn = googleGenAIWrapper(tracer, spanName, requestType);
20450
- const sendMessageStreamWrapperFn = googleGenAIStreamWrapper(tracer, spanName, requestType);
20451
- return function wrapper(original) {
20452
- return function(...args) {
20453
- const chatSession = original.apply(this, args);
20454
- if (!chatSession) return chatSession;
20455
- const modelInstance = this;
20456
- const modelName = modelInstance.model;
20457
- const systemInstruction = modelInstance.systemInstruction;
20458
- const chatHistory = args[0]?.history;
20459
- if (typeof chatSession.sendMessage === "function" && !chatSession.__netra_patched) {
20460
- const originalSendMessage = chatSession.sendMessage.bind(chatSession);
20461
- const wrappedSendMessage = sendMessageWrapperFn(originalSendMessage);
20462
- chatSession.sendMessage = function(...sendArgs) {
20463
- const ctx = this;
20464
- if (modelName) ctx.model = modelName;
20465
- if (systemInstruction) ctx.systemInstruction = systemInstruction;
20466
- if (chatHistory) ctx.history = chatHistory;
20467
- return wrappedSendMessage.apply(this, sendArgs);
20468
- };
20469
- if (typeof chatSession.sendMessageStream === "function") {
20470
- const originalSendStream = chatSession.sendMessageStream.bind(chatSession);
20471
- const wrappedSendStream = sendMessageStreamWrapperFn(originalSendStream);
20472
- chatSession.sendMessageStream = function(...sendArgs) {
20473
- const ctx = this;
20474
- if (modelName) ctx.model = modelName;
20475
- if (systemInstruction) ctx.systemInstruction = systemInstruction;
20476
- if (chatHistory) ctx.history = chatHistory;
20477
- return wrappedSendStream.apply(this, sendArgs);
20478
- };
20479
- }
20480
- chatSession.__netra_patched = true;
20481
- }
20482
- return chatSession;
20483
- };
20484
- };
20485
- }
20486
- var chatWrapper2 = (tracer) => googleGenAIWrapper(tracer, CHAT_SPAN_NAME, "chat");
20487
- var embeddingsWrapper = (tracer) => googleGenAIWrapper(tracer, EMBEDDING_SPAN_NAME, "embedding");
20488
- var chatStreamWrapper2 = (tracer) => googleGenAIStreamWrapper(tracer, CHAT_SPAN_NAME, "chat");
20489
- var startChatWrapper = (tracer) => googleGenAIStartChatWrapper(tracer, CHAT_SPAN_NAME, "chat");
20490
- var INSTRUMENTATION_NAME2 = "netra.instrumentation.google_genai";
20491
- var INSTRUMENTS2 = ["@google/genai >= 0.24.1"];
20492
- var isInstrumented2 = false;
20493
- var generativeModelClasses = [];
20494
- async function resolveGoogleGenerativeAIAsync() {
20495
- if (generativeModelClasses.length > 0) return generativeModelClasses;
20496
- try {
20497
- const googleGenAIModule = await import('@google/generative-ai');
20498
- const esmClass = googleGenAIModule.GenerativeModel || googleGenAIModule.default?.GenerativeModel || googleGenAIModule.default || googleGenAIModule;
20499
- generativeModelClasses.push(esmClass);
20500
- } catch {
20501
- Logger.warn("Failed to resolve Google GenAI ESM module");
20502
- }
20503
- try {
20504
- const req = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
20505
- const mod = req("@google/generative-ai");
20506
- const cjsClass = mod.GenerativeModel || mod.default?.GenerativeModel || mod.default || mod;
20507
- if (!generativeModelClasses.includes(cjsClass)) {
20508
- generativeModelClasses.push(cjsClass);
20509
- }
20510
- } catch {
20511
- Logger.warn("Failed to resolve Google GenAI CJS module");
20512
- }
20513
- return generativeModelClasses;
20514
- }
20515
- function resolveGoogleGenerativeAI() {
20516
- return generativeModelClasses;
20517
- }
20518
- var NetraGoogleGenerativeAIInstrumentor = class {
21261
+ var chatWrapper3 = (tracer) => googleGenerativeAIWrapper(tracer, CHAT_SPAN_NAME, "chat");
21262
+ var embeddingsWrapper2 = (tracer) => googleGenerativeAIWrapper(tracer, EMBEDDING_SPAN_NAME, "embedding");
21263
+ var chatStreamWrapper3 = (tracer) => googleGenerativeAIStreamWrapper(tracer, CHAT_SPAN_NAME, "chat");
21264
+
21265
+ // src/instrumentation/google-generative-ai/index.ts
21266
+ var NetraGoogleGenerativeAIInstrumentor = class extends BaseInstrumentor {
20519
21267
  constructor() {
20520
- this.tracer = null;
20521
- }
20522
- /**
20523
- * Returns the list of instrumentation dependencies
20524
- */
20525
- instrumentationDependencies() {
20526
- return [...INSTRUMENTS2];
20527
- }
20528
- /**
20529
- * Instrument Google GenAI client methods (async version)
20530
- * Tries both ESM and CJS resolution to cover dual-package setups.
20531
- */
20532
- async instrumentAsync(options = {}) {
20533
- if (isInstrumented2) {
20534
- Logger.warn("Google GenAI is already instrumented");
20535
- return this;
20536
- }
20537
- const classes = await resolveGoogleGenerativeAIAsync();
20538
- if (classes.length === 0) {
20539
- return this;
21268
+ super(...arguments);
21269
+ this.instrumentationName = "netra.instrumentation.google_generative_ai";
21270
+ this.instrumentationVersion = __version__3;
21271
+ this.packageName = "@google/generative-ai";
21272
+ this.displayName = "Google Generative AI";
21273
+ }
21274
+ extractClasses(mod) {
21275
+ const root = mod.default ?? mod;
21276
+ const GenerativeModel = root.GenerativeModel ?? root;
21277
+ if (!GenerativeModel?.prototype) return null;
21278
+ return { GenerativeModel, ChatSession: root.ChatSession };
21279
+ }
21280
+ isSameClasses(a, b) {
21281
+ return a.GenerativeModel === b.GenerativeModel;
21282
+ }
21283
+ applyPatches(classes, tracer) {
21284
+ const proto = classes.GenerativeModel?.prototype;
21285
+ if (!proto) {
21286
+ Logger.error("Google Generative AI: GenerativeModel.prototype not found");
21287
+ return false;
20540
21288
  }
20541
- try {
20542
- this.tracerProvider = options.tracerProvider;
20543
- this.tracer = this.tracerProvider ? this.tracerProvider.getTracer(INSTRUMENTATION_NAME2, __version__2) : api.trace.getTracer(INSTRUMENTATION_NAME2, __version__2);
20544
- } catch (error) {
20545
- Logger.error(`Failed to initialize tracer: ${error}`);
20546
- return this;
21289
+ let wrapped = false;
21290
+ if (typeof proto.generateContent === "function") {
21291
+ shimmer__default.default.wrap(proto, "generateContent", chatWrapper3(tracer));
21292
+ wrapped = true;
20547
21293
  }
20548
- classes.forEach((model) => this._instrumentGenerativeModel(model));
20549
- isInstrumented2 = true;
20550
- return this;
20551
- }
20552
- /**
20553
- * Instrument Google GenAI client methods (sync version)
20554
- */
20555
- instrument(options = {}) {
20556
- if (isInstrumented2) {
20557
- Logger.warn("Google GenAI is already instrumented");
20558
- return this;
21294
+ if (typeof proto.generateContentStream === "function") {
21295
+ shimmer__default.default.wrap(proto, "generateContentStream", chatStreamWrapper3(tracer));
21296
+ wrapped = true;
20559
21297
  }
20560
- const classes = resolveGoogleGenerativeAI();
20561
- if (classes.length === 0) {
20562
- this.instrumentAsync(options).catch((e) => {
20563
- Logger.error("Failed to instrument Google GenAI:", e);
20564
- });
20565
- return this;
21298
+ if (typeof proto.embedContent === "function") {
21299
+ shimmer__default.default.wrap(proto, "embedContent", embeddingsWrapper2(tracer));
21300
+ wrapped = true;
20566
21301
  }
20567
- try {
20568
- this.tracerProvider = options.tracerProvider;
20569
- this.tracer = this.tracerProvider ? this.tracerProvider.getTracer(INSTRUMENTATION_NAME2, __version__2) : api.trace.getTracer(INSTRUMENTATION_NAME2, __version__2);
20570
- } catch (error) {
20571
- Logger.error(`Failed to initialize tracer: ${error}`);
20572
- return this;
21302
+ const chatProto = classes.ChatSession?.prototype;
21303
+ if (chatProto) {
21304
+ if (typeof chatProto.sendMessage === "function") {
21305
+ shimmer__default.default.wrap(chatProto, "sendMessage", chatWrapper3(tracer));
21306
+ wrapped = true;
21307
+ }
21308
+ if (typeof chatProto.sendMessageStream === "function") {
21309
+ shimmer__default.default.wrap(chatProto, "sendMessageStream", chatStreamWrapper3(tracer));
21310
+ wrapped = true;
21311
+ }
20573
21312
  }
20574
- classes.forEach((model) => this._instrumentGenerativeModel(model));
20575
- isInstrumented2 = true;
20576
- return this;
21313
+ return wrapped;
20577
21314
  }
20578
- /**
20579
- * Uninstrument Google GenAI client methods
20580
- */
20581
- uninstrument() {
20582
- if (!isInstrumented2) {
20583
- Logger.warn("Google GenAI is not instrumented");
20584
- return;
21315
+ removePatches(classes) {
21316
+ const proto = classes.GenerativeModel?.prototype;
21317
+ if (proto) {
21318
+ if (typeof proto.generateContent === "function")
21319
+ shimmer__default.default.unwrap(proto, "generateContent");
21320
+ if (typeof proto.generateContentStream === "function")
21321
+ shimmer__default.default.unwrap(proto, "generateContentStream");
21322
+ if (typeof proto.embedContent === "function")
21323
+ shimmer__default.default.unwrap(proto, "embedContent");
21324
+ }
21325
+ const chatProto = classes.ChatSession?.prototype;
21326
+ if (chatProto) {
21327
+ if (typeof chatProto.sendMessage === "function")
21328
+ shimmer__default.default.unwrap(chatProto, "sendMessage");
21329
+ if (typeof chatProto.sendMessageStream === "function")
21330
+ shimmer__default.default.unwrap(chatProto, "sendMessageStream");
20585
21331
  }
20586
- const classes = resolveGoogleGenerativeAI();
20587
- classes.forEach((model) => this._uninstrumentGenerativeModel(model));
20588
- generativeModelClasses = [];
20589
- isInstrumented2 = false;
20590
21332
  }
20591
21333
  /**
20592
- * Check if Google GenAI is currently instrumented
21334
+ * @deprecated Use instrument() instead. Kept for backward compatibility
21335
+ * with orchestrator call sites that haven't been updated yet.
20593
21336
  */
20594
- isInstrumented() {
20595
- return isInstrumented2;
20596
- }
20597
- _instrumentGenerativeModel(GenerativeModel) {
20598
- if (!this.tracer) return;
20599
- try {
20600
- if (!GenerativeModel?.prototype) {
20601
- Logger.error(
20602
- "Failed to find Google GenAI GenerativeModel to instrument"
20603
- );
20604
- return;
20605
- }
20606
- const tracer = this.tracer;
20607
- shimmer__default.default.wrap(
20608
- GenerativeModel.prototype,
20609
- "generateContent",
20610
- chatWrapper2(tracer)
20611
- );
20612
- shimmer__default.default.wrap(
20613
- GenerativeModel.prototype,
20614
- "generateContentStream",
20615
- chatStreamWrapper2(tracer)
20616
- );
20617
- shimmer__default.default.wrap(
20618
- GenerativeModel.prototype,
20619
- "embedContent",
20620
- embeddingsWrapper(tracer)
20621
- );
20622
- if (typeof GenerativeModel.prototype.startChat === "function") {
20623
- shimmer__default.default.wrap(
20624
- GenerativeModel.prototype,
20625
- "startChat",
20626
- startChatWrapper(tracer)
20627
- );
20628
- }
20629
- } catch (error) {
20630
- Logger.debug(
20631
- `Google GenAI instrumentation: failed to instrument: ${error}`
20632
- );
20633
- }
20634
- }
20635
- _uninstrumentGenerativeModel(GenerativeModel) {
20636
- try {
20637
- if (!GenerativeModel?.prototype) return;
20638
- if (typeof GenerativeModel.prototype.generateContent === "function") {
20639
- shimmer__default.default.unwrap(GenerativeModel.prototype, "generateContent");
20640
- }
20641
- if (typeof GenerativeModel.prototype.generateContentStream === "function") {
20642
- shimmer__default.default.unwrap(GenerativeModel.prototype, "generateContentStream");
20643
- }
20644
- if (typeof GenerativeModel.prototype.embedContent === "function") {
20645
- shimmer__default.default.unwrap(GenerativeModel.prototype, "embedContent");
20646
- }
20647
- if (typeof GenerativeModel.prototype.startChat === "function") {
20648
- shimmer__default.default.unwrap(GenerativeModel.prototype, "startChat");
20649
- }
20650
- } catch (error) {
20651
- Logger.debug(`Failed to uninstrument Google GenAI: ${error}`);
20652
- }
21337
+ async instrumentAsync(options = {}) {
21338
+ return this.instrument(options);
20653
21339
  }
20654
21340
  };
20655
21341
  var googleGenerativeAIInstrumentor = new NetraGoogleGenerativeAIInstrumentor();
20656
21342
 
20657
21343
  // src/instrumentation/groq/version.ts
20658
- var __version__3 = "1.0.0";
21344
+ var __version__4 = "1.0.0";
20659
21345
 
20660
21346
  // src/instrumentation/groq/utils.ts
20661
- function setRequestAttributes4(span2, kwargs, requestType) {
21347
+ function setRequestAttributes5(span2, kwargs, requestType) {
20662
21348
  if (!span2.isRecording()) {
20663
21349
  Logger.log("Span is not recording");
20664
21350
  return;
20665
21351
  }
20666
21352
  setRequestAttributes(span2, kwargs, requestType, "groq");
20667
21353
  }
20668
- function setResponseAttributes4(span2, response) {
21354
+ function setResponseAttributes5(span2, response) {
20669
21355
  if (!span2.isRecording()) {
20670
21356
  Logger.log("Span is not recording");
20671
21357
  return;
@@ -20694,7 +21380,7 @@ function groqWrapper(tracer, spanName, requestType) {
20694
21380
  currentContext
20695
21381
  );
20696
21382
  try {
20697
- setRequestAttributes4(span2, kwargs, requestType);
21383
+ setRequestAttributes5(span2, kwargs, requestType);
20698
21384
  const startTime = Date.now();
20699
21385
  const response = wrapped.call(instance, ...args);
20700
21386
  if (isPromise(response)) {
@@ -20735,7 +21421,7 @@ function groqWrapper(tracer, spanName, requestType) {
20735
21421
  },
20736
21422
  (span2) => {
20737
21423
  try {
20738
- setRequestAttributes4(span2, kwargs, requestType);
21424
+ setRequestAttributes5(span2, kwargs, requestType);
20739
21425
  const startTime = Date.now();
20740
21426
  const response = wrapped.call(instance, ...args);
20741
21427
  if (isPromise(response)) {
@@ -20744,7 +21430,7 @@ function groqWrapper(tracer, spanName, requestType) {
20744
21430
  const value = await response;
20745
21431
  const endTime = Date.now();
20746
21432
  const responseDict = modelAsDict(value);
20747
- setResponseAttributes4(span2, responseDict);
21433
+ setResponseAttributes5(span2, responseDict);
20748
21434
  span2.setAttribute(
20749
21435
  "llm.response.duration",
20750
21436
  (endTime - startTime) / 1e3
@@ -20766,7 +21452,7 @@ function groqWrapper(tracer, spanName, requestType) {
20766
21452
  } else {
20767
21453
  const endTime = Date.now();
20768
21454
  const responseDict = modelAsDict(response);
20769
- setResponseAttributes4(span2, responseDict);
21455
+ setResponseAttributes5(span2, responseDict);
20770
21456
  span2.setAttribute(
20771
21457
  "llm.response.duration",
20772
21458
  (endTime - startTime) / 1e3
@@ -20790,7 +21476,7 @@ function groqWrapper(tracer, spanName, requestType) {
20790
21476
  }
20791
21477
  };
20792
21478
  }
20793
- var chatWrapper3 = (tracer) => groqWrapper(tracer, CHAT_SPAN_NAME2, "chat");
21479
+ var chatWrapper4 = (tracer) => groqWrapper(tracer, CHAT_SPAN_NAME2, "chat");
20794
21480
  var StreamingWrapper = class {
20795
21481
  constructor(span2, response, startTime, requestKwargs) {
20796
21482
  this.iterator = null;
@@ -20998,7 +21684,7 @@ var AsyncStreamingWrapper = class {
20998
21684
  finalizeSpan(code) {
20999
21685
  const endTime = Date.now();
21000
21686
  const duration = (endTime - this.startTime) / 1e3;
21001
- setResponseAttributes4(this.span, this.completeResponse);
21687
+ setResponseAttributes5(this.span, this.completeResponse);
21002
21688
  this.span.setAttribute("llm.response.duration", duration);
21003
21689
  this.span.setStatus({ code });
21004
21690
  this.span.end();
@@ -21006,10 +21692,10 @@ var AsyncStreamingWrapper = class {
21006
21692
  };
21007
21693
 
21008
21694
  // src/instrumentation/groq/index.ts
21009
- var INSTRUMENTATION_NAME3 = "netra.instrumentation.groq";
21010
- var INSTRUMENTS3 = ["groq-sdk >= 0.3.0"];
21695
+ var INSTRUMENTATION_NAME2 = "netra.instrumentation.groq";
21696
+ var INSTRUMENTS2 = ["groq-sdk >= 0.3.0"];
21011
21697
  var originalMethods = /* @__PURE__ */ new Map();
21012
- var isInstrumented3 = false;
21698
+ var isInstrumented2 = false;
21013
21699
  var groqClasses = [];
21014
21700
  async function resolveGroqAsync() {
21015
21701
  if (groqClasses.length > 0) return groqClasses;
@@ -21039,14 +21725,14 @@ var NetraGroqInstrumentor = class {
21039
21725
  this.tracer = null;
21040
21726
  }
21041
21727
  instrumentationDependencies() {
21042
- return INSTRUMENTS3;
21728
+ return INSTRUMENTS2;
21043
21729
  }
21044
21730
  /**
21045
21731
  * Instrument Groq client methods (async version)
21046
21732
  * Tries both ESM and CJS resolution to cover dual-package setups.
21047
21733
  */
21048
21734
  async instrumentAsync(options = {}) {
21049
- if (isInstrumented3) {
21735
+ if (isInstrumented2) {
21050
21736
  Logger.warn("Groq is already instrumented");
21051
21737
  return this;
21052
21738
  }
@@ -21058,11 +21744,11 @@ var NetraGroqInstrumentor = class {
21058
21744
  this.tracerProvider = options.tracerProvider;
21059
21745
  if (this.tracerProvider) {
21060
21746
  this.tracer = this.tracerProvider.getTracer(
21061
- INSTRUMENTATION_NAME3,
21062
- __version__3
21747
+ INSTRUMENTATION_NAME2,
21748
+ __version__4
21063
21749
  );
21064
21750
  } else {
21065
- this.tracer = api.trace.getTracer(INSTRUMENTATION_NAME3, __version__3);
21751
+ this.tracer = api.trace.getTracer(INSTRUMENTATION_NAME2, __version__4);
21066
21752
  }
21067
21753
  } catch (error) {
21068
21754
  Logger.error(`Failed to initialize tracer: ${error}`);
@@ -21071,7 +21757,7 @@ var NetraGroqInstrumentor = class {
21071
21757
  classes.forEach((Groq, index) => {
21072
21758
  this._instrumentChatCompletions(Groq, index);
21073
21759
  });
21074
- isInstrumented3 = true;
21760
+ isInstrumented2 = true;
21075
21761
  return this;
21076
21762
  }
21077
21763
  /**
@@ -21079,7 +21765,7 @@ var NetraGroqInstrumentor = class {
21079
21765
  * Note: This uses cached Groq classes. Call instrumentAsync() for proper initialization.
21080
21766
  */
21081
21767
  instrument(options = {}) {
21082
- if (isInstrumented3) {
21768
+ if (isInstrumented2) {
21083
21769
  Logger.warn("Groq is already instrumented");
21084
21770
  return this;
21085
21771
  }
@@ -21094,11 +21780,11 @@ var NetraGroqInstrumentor = class {
21094
21780
  this.tracerProvider = options.tracerProvider;
21095
21781
  if (this.tracerProvider) {
21096
21782
  this.tracer = this.tracerProvider.getTracer(
21097
- INSTRUMENTATION_NAME3,
21098
- __version__3
21783
+ INSTRUMENTATION_NAME2,
21784
+ __version__4
21099
21785
  );
21100
21786
  } else {
21101
- this.tracer = api.trace.getTracer(INSTRUMENTATION_NAME3, __version__3);
21787
+ this.tracer = api.trace.getTracer(INSTRUMENTATION_NAME2, __version__4);
21102
21788
  }
21103
21789
  } catch (error) {
21104
21790
  Logger.error(`Failed to initialize tracer: ${error}`);
@@ -21107,11 +21793,11 @@ var NetraGroqInstrumentor = class {
21107
21793
  classes.forEach((Groq, index) => {
21108
21794
  this._instrumentChatCompletions(Groq, index);
21109
21795
  });
21110
- isInstrumented3 = true;
21796
+ isInstrumented2 = true;
21111
21797
  return this;
21112
21798
  }
21113
21799
  uninstrument() {
21114
- if (!isInstrumented3) {
21800
+ if (!isInstrumented2) {
21115
21801
  Logger.warn("Groq is not instrumented");
21116
21802
  return;
21117
21803
  }
@@ -21121,10 +21807,10 @@ var NetraGroqInstrumentor = class {
21121
21807
  });
21122
21808
  originalMethods.clear();
21123
21809
  groqClasses = [];
21124
- isInstrumented3 = false;
21810
+ isInstrumented2 = false;
21125
21811
  }
21126
21812
  isInstrumented() {
21127
- return isInstrumented3;
21813
+ return isInstrumented2;
21128
21814
  }
21129
21815
  _instrumentChatCompletions(Groq, index) {
21130
21816
  if (!this.tracer) {
@@ -21142,7 +21828,7 @@ var NetraGroqInstrumentor = class {
21142
21828
  const originalCreate = CompletionsClass.prototype.create;
21143
21829
  originalMethods.set(`chat.completions.create-${index}`, originalCreate);
21144
21830
  const tracer = this.tracer;
21145
- const wrapper = chatWrapper3(tracer);
21831
+ const wrapper = chatWrapper4(tracer);
21146
21832
  CompletionsClass.prototype.create = function(...args) {
21147
21833
  const original = originalCreate.bind(this);
21148
21834
  const kwargs = args[0] || {};
@@ -21170,7 +21856,7 @@ var NetraGroqInstrumentor = class {
21170
21856
  var groqInstrumentor = new NetraGroqInstrumentor();
21171
21857
 
21172
21858
  // src/instrumentation/langgraph/version.ts
21173
- var __version__4 = "1.0.0";
21859
+ var __version__5 = "1.0.0";
21174
21860
 
21175
21861
  // node_modules/@langchain/core/dist/_virtual/rolldown_runtime.js
21176
21862
  var __defProp2 = Object.defineProperty;
@@ -21868,8 +22554,8 @@ var LanggraphStreamingWrapper = class {
21868
22554
  return {};
21869
22555
  }
21870
22556
  }
21871
- async startStream(originalFunc, instance, input, config2, ...rest) {
21872
- this.iterable = await originalFunc.call(instance, input, config2, ...rest);
22557
+ async startStream(originalFunc, instance, input, config, ...rest) {
22558
+ this.iterable = await originalFunc.call(instance, input, config, ...rest);
21873
22559
  return this;
21874
22560
  }
21875
22561
  async *[Symbol.asyncIterator]() {
@@ -21903,23 +22589,23 @@ var LanggraphWrapper = class {
21903
22589
  this.tracer = tracer;
21904
22590
  this.spanName = "Langgraph.workflow";
21905
22591
  }
21906
- getUpdatedConfig(config2, rootSpan) {
21907
- if (!rootSpan) return config2 || {};
22592
+ getUpdatedConfig(config, rootSpan) {
22593
+ if (!rootSpan) return config || {};
21908
22594
  const callbackHandler = new NetraLanggraphCallbackHandler(
21909
22595
  this.tracer,
21910
22596
  rootSpan
21911
22597
  );
21912
- const callbacks = config2?.callbacks;
22598
+ const callbacks = config?.callbacks;
21913
22599
  const normalizedCallbacks = callbacks ? Array.isArray(callbacks) ? callbacks : [callbacks] : [];
21914
22600
  const updatedConfig = {
21915
- ...config2,
22601
+ ...config,
21916
22602
  callbacks: [...normalizedCallbacks, callbackHandler]
21917
22603
  };
21918
22604
  return updatedConfig;
21919
22605
  }
21920
- async invoke(originalFunc, instance, input, config2, ...rest) {
22606
+ async invoke(originalFunc, instance, input, config, ...rest) {
21921
22607
  if (shouldSuppressInstrumentation() || api.context.active().getValue(LANGGRAPH_INSTRUMENTATION_ACTIVE)) {
21922
- return await originalFunc.call(instance, input, config2, ...rest);
22608
+ return await originalFunc.call(instance, input, config, ...rest);
21923
22609
  }
21924
22610
  const activeSpan = api.trace.getSpan(api.context.active());
21925
22611
  Logger.debug(`LangGraph invoke start. Active TraceId: ${activeSpan?.spanContext().traceId}, SpanId: ${activeSpan?.spanContext().spanId}`);
@@ -21941,7 +22627,7 @@ var LanggraphWrapper = class {
21941
22627
  }
21942
22628
  try {
21943
22629
  setGraphInputAttributes(span2, input);
21944
- const updatedConfig = this.getUpdatedConfig(config2, span2);
22630
+ const updatedConfig = this.getUpdatedConfig(config, span2);
21945
22631
  const output = await originalFunc.call(
21946
22632
  instance,
21947
22633
  input,
@@ -21958,10 +22644,10 @@ var LanggraphWrapper = class {
21958
22644
  }
21959
22645
  });
21960
22646
  }
21961
- async stream(originalFunc, instance, input, config2, ...rest) {
22647
+ async stream(originalFunc, instance, input, config, ...rest) {
21962
22648
  if (shouldSuppressInstrumentation() || api.context.active().getValue(LANGGRAPH_INSTRUMENTATION_ACTIVE)) {
21963
22649
  Logger.debug("LangGraph stream skipped (inside instrumented call)");
21964
- return await originalFunc.call(instance, input, config2, ...rest);
22650
+ return await originalFunc.call(instance, input, config, ...rest);
21965
22651
  }
21966
22652
  Logger.debug("LangGraph stream starting instrumentation");
21967
22653
  const span2 = this.tracer.startSpan(
@@ -21972,7 +22658,7 @@ var LanggraphWrapper = class {
21972
22658
  api.context.active()
21973
22659
  );
21974
22660
  setGraphInputAttributes(span2, input);
21975
- const updatedConfig = this.getUpdatedConfig(config2, span2);
22661
+ const updatedConfig = this.getUpdatedConfig(config, span2);
21976
22662
  try {
21977
22663
  const ctxWithSpan = api.trace.setSpan(api.context.active(), span2);
21978
22664
  const ctxWithFlag = ctxWithSpan.setValue(LANGGRAPH_INSTRUMENTATION_ACTIVE, true);
@@ -21993,9 +22679,9 @@ var LanggraphWrapper = class {
21993
22679
  };
21994
22680
 
21995
22681
  // src/instrumentation/langgraph/index.ts
21996
- var INSTRUMENTATION_NAME4 = "netra.instrumentation.langgraph";
21997
- var INSTRUMENTS4 = ["langgraph >= 1.1.1"];
21998
- var isInstrumented4 = false;
22682
+ var INSTRUMENTATION_NAME3 = "netra.instrumentation.langgraph";
22683
+ var INSTRUMENTS3 = ["langgraph >= 1.1.1"];
22684
+ var isInstrumented3 = false;
21999
22685
  var LanggraphClass = null;
22000
22686
  var originalMethods2 = /* @__PURE__ */ new Map();
22001
22687
  function findModuleInCache(moduleName) {
@@ -22056,13 +22742,13 @@ var NetraLanggraphInstrumentor = class {
22056
22742
  this.tracer = null;
22057
22743
  }
22058
22744
  isInstrumented() {
22059
- return isInstrumented4;
22745
+ return isInstrumented3;
22060
22746
  }
22061
22747
  instrumentationDependencies() {
22062
- return [...INSTRUMENTS4];
22748
+ return [...INSTRUMENTS3];
22063
22749
  }
22064
22750
  async instrument(options = {}) {
22065
- if (isInstrumented4) {
22751
+ if (isInstrumented3) {
22066
22752
  Logger.warn("Langgraph is already instrumented");
22067
22753
  return this;
22068
22754
  }
@@ -22073,18 +22759,18 @@ var NetraLanggraphInstrumentor = class {
22073
22759
  }
22074
22760
  try {
22075
22761
  this.tracerProvider = options.tracerProvider;
22076
- this.tracer = this.tracerProvider ? this.tracerProvider.getTracer(INSTRUMENTATION_NAME4, __version__4) : api.trace.getTracer(INSTRUMENTATION_NAME4, __version__4);
22762
+ this.tracer = this.tracerProvider ? this.tracerProvider.getTracer(INSTRUMENTATION_NAME3, __version__5) : api.trace.getTracer(INSTRUMENTATION_NAME3, __version__5);
22077
22763
  } catch (error) {
22078
22764
  Logger.error(`Failed to initialize tracer: ${error}`);
22079
22765
  return this;
22080
22766
  }
22081
22767
  this._instrumentInvoke(Langgraph);
22082
22768
  this._instrumentStream(Langgraph);
22083
- isInstrumented4 = true;
22769
+ isInstrumented3 = true;
22084
22770
  return this;
22085
22771
  }
22086
22772
  async uninstrument() {
22087
- if (!isInstrumented4) {
22773
+ if (!isInstrumented3) {
22088
22774
  Logger.warn("LangGraph is not instrumented");
22089
22775
  return;
22090
22776
  }
@@ -22095,7 +22781,7 @@ var NetraLanggraphInstrumentor = class {
22095
22781
  }
22096
22782
  originalMethods2.clear();
22097
22783
  LanggraphClass = null;
22098
- isInstrumented4 = false;
22784
+ isInstrumented3 = false;
22099
22785
  }
22100
22786
  _instrumentInvoke(Langgraph) {
22101
22787
  if (!this.tracer) return;
@@ -22114,13 +22800,13 @@ var NetraLanggraphInstrumentor = class {
22114
22800
  originalMethods2.set("langgraph.graph.invoke.proto", targetProto);
22115
22801
  const tracer = this.tracer;
22116
22802
  const wrapper = new LanggraphWrapper(tracer);
22117
- const patchedInvoke = async function(input, config2, ...rest) {
22803
+ const patchedInvoke = async function(input, config, ...rest) {
22118
22804
  Logger.debug("LangGraph invoke intercepted!");
22119
22805
  return await wrapper.invoke(
22120
22806
  originalInvoke,
22121
22807
  this,
22122
22808
  input,
22123
- config2,
22809
+ config,
22124
22810
  ...rest
22125
22811
  );
22126
22812
  };
@@ -22149,13 +22835,13 @@ var NetraLanggraphInstrumentor = class {
22149
22835
  originalMethods2.set("langgraph.graph.stream.proto", targetProto);
22150
22836
  const tracer = this.tracer;
22151
22837
  const wrapper = new LanggraphWrapper(tracer);
22152
- targetProto.stream = async function(input, config2, ...rest) {
22838
+ targetProto.stream = async function(input, config, ...rest) {
22153
22839
  Logger.debug("LangGraph stream intercepted!");
22154
22840
  return await wrapper.stream(
22155
22841
  originalStream,
22156
22842
  this,
22157
22843
  input,
22158
- config2,
22844
+ config,
22159
22845
  ...rest
22160
22846
  );
22161
22847
  };
@@ -22192,10 +22878,10 @@ var NetraLanggraphInstrumentor = class {
22192
22878
  var langgraphInstrumentor = new NetraLanggraphInstrumentor();
22193
22879
 
22194
22880
  // src/instrumentation/mistralai/version.ts
22195
- var __version__5 = "1.0.0";
22881
+ var __version__6 = "1.0.0";
22196
22882
 
22197
22883
  // src/instrumentation/mistralai/utils.ts
22198
- function setRequestAttributes5(span2, kwargs, requestType) {
22884
+ function setRequestAttributes6(span2, kwargs, requestType) {
22199
22885
  setRequestAttributes(span2, kwargs, requestType, "mistralai");
22200
22886
  if (kwargs.agentId) {
22201
22887
  span2.setAttribute("gen_ai.agent.id", String(kwargs.agentId));
@@ -22214,7 +22900,7 @@ function setRequestAttributes5(span2, kwargs, requestType) {
22214
22900
  span2.setAttribute("llm.request.has_suffix", true);
22215
22901
  }
22216
22902
  }
22217
- function setResponseAttributes5(span2, response) {
22903
+ function setResponseAttributes6(span2, response) {
22218
22904
  setResponseAttributes(span2, response);
22219
22905
  }
22220
22906
 
@@ -22240,7 +22926,7 @@ function mistralWrapper(tracer, spanName, requestType) {
22240
22926
  },
22241
22927
  (span2) => {
22242
22928
  try {
22243
- setRequestAttributes5(span2, kwargs, requestType);
22929
+ setRequestAttributes6(span2, kwargs, requestType);
22244
22930
  const startTime = Date.now();
22245
22931
  const response = wrapped.call(instance, ...args);
22246
22932
  if (isPromise(response)) {
@@ -22248,7 +22934,7 @@ function mistralWrapper(tracer, spanName, requestType) {
22248
22934
  try {
22249
22935
  const value = await response;
22250
22936
  const endTime2 = Date.now();
22251
- setResponseAttributes5(span2, modelAsDict(value));
22937
+ setResponseAttributes6(span2, modelAsDict(value));
22252
22938
  span2.setAttribute(
22253
22939
  "llm.response.duration",
22254
22940
  (endTime2 - startTime) / 1e3
@@ -22269,7 +22955,7 @@ function mistralWrapper(tracer, spanName, requestType) {
22269
22955
  })();
22270
22956
  }
22271
22957
  const endTime = Date.now();
22272
- setResponseAttributes5(span2, modelAsDict(response));
22958
+ setResponseAttributes6(span2, modelAsDict(response));
22273
22959
  span2.setAttribute(
22274
22960
  "llm.response.duration",
22275
22961
  (endTime - startTime) / 1e3
@@ -22310,7 +22996,7 @@ function mistralStreamWrapper(tracer, spanName, requestType) {
22310
22996
  currentContext
22311
22997
  );
22312
22998
  try {
22313
- setRequestAttributes5(span2, { ...kwargs, stream: true }, requestType);
22999
+ setRequestAttributes6(span2, { ...kwargs, stream: true }, requestType);
22314
23000
  const startTime = Date.now();
22315
23001
  const response = wrapped.call(instance, ...args);
22316
23002
  if (isPromise(response)) {
@@ -22349,9 +23035,9 @@ function mistralStreamWrapper(tracer, spanName, requestType) {
22349
23035
  }
22350
23036
  };
22351
23037
  }
22352
- var chatWrapper4 = (tracer) => mistralWrapper(tracer, CHAT_SPAN_NAME3, "chat");
22353
- var chatStreamWrapper3 = (tracer) => mistralStreamWrapper(tracer, CHAT_STREAM_SPAN_NAME, "chat");
22354
- var embeddingsWrapper2 = (tracer) => mistralWrapper(tracer, EMBEDDING_SPAN_NAME2, "embedding");
23038
+ var chatWrapper5 = (tracer) => mistralWrapper(tracer, CHAT_SPAN_NAME3, "chat");
23039
+ var chatStreamWrapper4 = (tracer) => mistralStreamWrapper(tracer, CHAT_STREAM_SPAN_NAME, "chat");
23040
+ var embeddingsWrapper3 = (tracer) => mistralWrapper(tracer, EMBEDDING_SPAN_NAME2, "embedding");
22355
23041
  var fimWrapper = (tracer) => mistralWrapper(tracer, FIM_SPAN_NAME, "fim");
22356
23042
  var fimStreamWrapper = (tracer) => mistralStreamWrapper(tracer, FIM_STREAM_SPAN_NAME, "fim");
22357
23043
  var agentsWrapper = (tracer) => mistralWrapper(tracer, AGENTS_SPAN_NAME, "agent");
@@ -22484,7 +23170,7 @@ var StreamingWrapper2 = class {
22484
23170
  finalizeSpan(error) {
22485
23171
  const endTime = Date.now();
22486
23172
  const duration = (endTime - this.startTime) / 1e3;
22487
- setResponseAttributes5(this.span, this.completeResponse);
23173
+ setResponseAttributes6(this.span, this.completeResponse);
22488
23174
  this.span.setAttribute("llm.response.duration", duration);
22489
23175
  if (error) {
22490
23176
  this.span.setStatus({
@@ -22630,7 +23316,7 @@ var AsyncStreamingWrapper2 = class {
22630
23316
  finalizeSpan(error) {
22631
23317
  const endTime = Date.now();
22632
23318
  const duration = (endTime - this.startTime) / 1e3;
22633
- setResponseAttributes5(this.span, this.completeResponse);
23319
+ setResponseAttributes6(this.span, this.completeResponse);
22634
23320
  this.span.setAttribute("llm.response.duration", duration);
22635
23321
  if (error) {
22636
23322
  this.span.setStatus({
@@ -22649,10 +23335,10 @@ var AsyncStreamingWrapper2 = class {
22649
23335
  };
22650
23336
 
22651
23337
  // src/instrumentation/mistralai/index.ts
22652
- var INSTRUMENTATION_NAME5 = "netra.instrumentation.mistral_ai";
22653
- var INSTRUMENTS5 = ["@mistralai/mistralai >= 1.0.0"];
23338
+ var INSTRUMENTATION_NAME4 = "netra.instrumentation.mistral_ai";
23339
+ var INSTRUMENTS4 = ["@mistralai/mistralai >= 1.0.0"];
22654
23340
  var originalMethods3 = /* @__PURE__ */ new Map();
22655
- var isInstrumented5 = false;
23341
+ var isInstrumented4 = false;
22656
23342
  var mistralClasses = [];
22657
23343
  async function resolveMistralAsync() {
22658
23344
  if (mistralClasses.length > 0) return mistralClasses;
@@ -22688,14 +23374,14 @@ var NetraMistralAIInstrumentor = class {
22688
23374
  * Returns the list of instrumentation dependencies
22689
23375
  */
22690
23376
  instrumentationDependencies() {
22691
- return INSTRUMENTS5;
23377
+ return INSTRUMENTS4;
22692
23378
  }
22693
23379
  /**
22694
23380
  * Instrument MistralAI client methods (async version)
22695
23381
  * Tries both ESM and CJS resolution to cover dual-package setups.
22696
23382
  */
22697
23383
  async instrumentAsync(options = {}) {
22698
- if (isInstrumented5) {
23384
+ if (isInstrumented4) {
22699
23385
  Logger.warn("MistralAI is already instrumented");
22700
23386
  return this;
22701
23387
  }
@@ -22707,11 +23393,11 @@ var NetraMistralAIInstrumentor = class {
22707
23393
  this.tracerProvider = options.tracerProvider;
22708
23394
  if (this.tracerProvider) {
22709
23395
  this.tracer = this.tracerProvider.getTracer(
22710
- INSTRUMENTATION_NAME5,
22711
- __version__5
23396
+ INSTRUMENTATION_NAME4,
23397
+ __version__6
22712
23398
  );
22713
23399
  } else {
22714
- this.tracer = api.trace.getTracer(INSTRUMENTATION_NAME5, __version__5);
23400
+ this.tracer = api.trace.getTracer(INSTRUMENTATION_NAME4, __version__6);
22715
23401
  }
22716
23402
  } catch (error) {
22717
23403
  Logger.error(`Failed to initialize tracer: ${error}`);
@@ -22733,7 +23419,7 @@ var NetraMistralAIInstrumentor = class {
22733
23419
  );
22734
23420
  return this;
22735
23421
  }
22736
- isInstrumented5 = true;
23422
+ isInstrumented4 = true;
22737
23423
  return this;
22738
23424
  }
22739
23425
  /**
@@ -22741,7 +23427,7 @@ var NetraMistralAIInstrumentor = class {
22741
23427
  * Note: This uses cached Mistral classes. Call instrumentAsync() for proper initialization.
22742
23428
  */
22743
23429
  instrument(options = {}) {
22744
- if (isInstrumented5) {
23430
+ if (isInstrumented4) {
22745
23431
  Logger.warn("MistralAI is already instrumented");
22746
23432
  return this;
22747
23433
  }
@@ -22756,11 +23442,11 @@ var NetraMistralAIInstrumentor = class {
22756
23442
  this.tracerProvider = options.tracerProvider;
22757
23443
  if (this.tracerProvider) {
22758
23444
  this.tracer = this.tracerProvider.getTracer(
22759
- INSTRUMENTATION_NAME5,
22760
- __version__5
23445
+ INSTRUMENTATION_NAME4,
23446
+ __version__6
22761
23447
  );
22762
23448
  } else {
22763
- this.tracer = api.trace.getTracer(INSTRUMENTATION_NAME5, __version__5);
23449
+ this.tracer = api.trace.getTracer(INSTRUMENTATION_NAME4, __version__6);
22764
23450
  }
22765
23451
  } catch (error) {
22766
23452
  Logger.error(`Failed to initialize tracer: ${error}`);
@@ -22782,14 +23468,14 @@ var NetraMistralAIInstrumentor = class {
22782
23468
  );
22783
23469
  return this;
22784
23470
  }
22785
- isInstrumented5 = true;
23471
+ isInstrumented4 = true;
22786
23472
  return this;
22787
23473
  }
22788
23474
  /**
22789
23475
  * Uninstrument MistralAI client methods
22790
23476
  */
22791
23477
  uninstrument() {
22792
- if (!isInstrumented5) {
23478
+ if (!isInstrumented4) {
22793
23479
  Logger.warn("MistralAI is not instrumented");
22794
23480
  return;
22795
23481
  }
@@ -22802,13 +23488,13 @@ var NetraMistralAIInstrumentor = class {
22802
23488
  });
22803
23489
  originalMethods3.clear();
22804
23490
  mistralClasses = [];
22805
- isInstrumented5 = false;
23491
+ isInstrumented4 = false;
22806
23492
  }
22807
23493
  /**
22808
23494
  * Check if MistralAI is currently instrumented
22809
23495
  */
22810
23496
  isInstrumented() {
22811
- return isInstrumented5;
23497
+ return isInstrumented4;
22812
23498
  }
22813
23499
  /**
22814
23500
  * Resolve public resource constructors from the exported Mistral client.
@@ -22848,7 +23534,7 @@ var NetraMistralAIInstrumentor = class {
22848
23534
  const originalComplete = ChatClass.prototype.complete;
22849
23535
  originalMethods3.set(`chat.complete-${index}`, originalComplete);
22850
23536
  const tracer = this.tracer;
22851
- const wrapper = chatWrapper4(tracer);
23537
+ const wrapper = chatWrapper5(tracer);
22852
23538
  ChatClass.prototype.complete = function(...args) {
22853
23539
  const original = originalComplete.bind(this);
22854
23540
  const kwargs = args[0] || {};
@@ -22865,7 +23551,7 @@ var NetraMistralAIInstrumentor = class {
22865
23551
  const originalStream = ChatClass.prototype.stream;
22866
23552
  originalMethods3.set(`chat.stream-${index}`, originalStream);
22867
23553
  const tracer = this.tracer;
22868
- const wrapper = chatStreamWrapper3(tracer);
23554
+ const wrapper = chatStreamWrapper4(tracer);
22869
23555
  ChatClass.prototype.stream = function(...args) {
22870
23556
  const original = originalStream.bind(this);
22871
23557
  const kwargs = args[0] || {};
@@ -22893,7 +23579,7 @@ var NetraMistralAIInstrumentor = class {
22893
23579
  const originalCreate = EmbeddingsClass.prototype.create;
22894
23580
  originalMethods3.set(`embeddings.create-${index}`, originalCreate);
22895
23581
  const tracer = this.tracer;
22896
- const wrapper = embeddingsWrapper2(tracer);
23582
+ const wrapper = embeddingsWrapper3(tracer);
22897
23583
  EmbeddingsClass.prototype.create = function(...args) {
22898
23584
  const original = originalCreate.bind(this);
22899
23585
  const kwargs = args[0] || {};
@@ -23062,23 +23748,23 @@ var NetraMistralAIInstrumentor = class {
23062
23748
  var mistralAIInstrumentor = new NetraMistralAIInstrumentor();
23063
23749
 
23064
23750
  // src/instrumentation/openai/version.ts
23065
- var __version__6 = "1.0.0";
23751
+ var __version__7 = "1.0.0";
23066
23752
 
23067
23753
  // src/instrumentation/openai/utils.ts
23068
- function setRequestAttributes6(span2, kwargs, requestType) {
23754
+ function setRequestAttributes7(span2, kwargs, requestType) {
23069
23755
  if (!span2.isRecording()) return;
23070
23756
  setRequestAttributes(span2, kwargs, requestType, "openai");
23071
23757
  if (kwargs.dimensions !== void 0) {
23072
23758
  span2.setAttribute("gen_ai.request.dimensions", Number(kwargs.dimensions));
23073
23759
  }
23074
23760
  }
23075
- function setResponseAttributes6(span2, response) {
23761
+ function setResponseAttributes7(span2, response) {
23076
23762
  if (!span2.isRecording()) return;
23077
23763
  setResponseAttributes(span2, response);
23078
23764
  }
23079
23765
 
23080
23766
  // src/instrumentation/openai/wrappers.ts
23081
- var SPAN_NAMES2 = {
23767
+ var SPAN_NAMES3 = {
23082
23768
  chat: "openai.chat",
23083
23769
  embedding: "openai.embedding",
23084
23770
  response: "openai.response"
@@ -23093,10 +23779,10 @@ function handleSpanError(span2, error) {
23093
23779
  span2.end();
23094
23780
  }
23095
23781
  function setSpanRequestContext(span2, kwargs, requestType) {
23096
- setRequestAttributes6(span2, kwargs, requestType);
23782
+ setRequestAttributes7(span2, kwargs, requestType);
23097
23783
  }
23098
23784
  function finalizeSpanSuccess(span2, response, startTime) {
23099
- setResponseAttributes6(span2, response);
23785
+ setResponseAttributes7(span2, response);
23100
23786
  span2.setAttribute("llm.response.duration", (Date.now() - startTime) / 1e3);
23101
23787
  span2.setStatus({ code: api.SpanStatusCode.OK });
23102
23788
  span2.end();
@@ -23313,7 +23999,7 @@ function executeNonStreaming(span2, kwargs, requestType, call) {
23313
23999
  }
23314
24000
  }
23315
24001
  function openAIWrapper(tracer, requestType) {
23316
- const spanName = SPAN_NAMES2[requestType];
24002
+ const spanName = SPAN_NAMES3[requestType];
23317
24003
  const spanOpts = { kind: api.SpanKind.CLIENT, attributes: { "llm.request.type": requestType } };
23318
24004
  return (wrapped, instance, args, kwargs) => {
23319
24005
  if (shouldSuppressInstrumentation()) {
@@ -23334,12 +24020,12 @@ function openAIWrapper(tracer, requestType) {
23334
24020
  );
23335
24021
  };
23336
24022
  }
23337
- var chatWrapper5 = (tracer) => openAIWrapper(tracer, "chat");
23338
- var embeddingsWrapper3 = (tracer) => openAIWrapper(tracer, "embedding");
24023
+ var chatWrapper6 = (tracer) => openAIWrapper(tracer, "chat");
24024
+ var embeddingsWrapper4 = (tracer) => openAIWrapper(tracer, "embedding");
23339
24025
  var responsesWrapper = (tracer) => openAIWrapper(tracer, "response");
23340
24026
 
23341
24027
  // src/instrumentation/openai/index.ts
23342
- var INSTRUMENTATION_NAME6 = "netra.instrumentation.openai";
24028
+ var INSTRUMENTATION_NAME5 = "netra.instrumentation.openai";
23343
24029
  var SUPPORTED_VERSIONS = ["openai >= 4.0.0"];
23344
24030
  var openAIClasses = [];
23345
24031
  async function resolveOpenAI() {
@@ -23366,12 +24052,12 @@ var PATCH_TARGETS = [
23366
24052
  {
23367
24053
  key: "chat.completions.create",
23368
24054
  getPrototype: (O) => O.Chat?.Completions?.prototype,
23369
- wrapperFactory: chatWrapper5
24055
+ wrapperFactory: chatWrapper6
23370
24056
  },
23371
24057
  {
23372
24058
  key: "embeddings.create",
23373
24059
  getPrototype: (O) => O.Embeddings?.prototype,
23374
- wrapperFactory: embeddingsWrapper3
24060
+ wrapperFactory: embeddingsWrapper4
23375
24061
  },
23376
24062
  {
23377
24063
  key: "responses.create",
@@ -23398,7 +24084,7 @@ var _NetraOpenAIInstrumentor = class _NetraOpenAIInstrumentor {
23398
24084
  }
23399
24085
  try {
23400
24086
  const provider = options.tracerProvider;
23401
- this.tracer = provider ? provider.getTracer(INSTRUMENTATION_NAME6, __version__6) : api.trace.getTracer(INSTRUMENTATION_NAME6, __version__6);
24087
+ this.tracer = provider ? provider.getTracer(INSTRUMENTATION_NAME5, __version__7) : api.trace.getTracer(INSTRUMENTATION_NAME5, __version__7);
23402
24088
  } catch (error) {
23403
24089
  Logger.error(`Failed to initialize tracer: ${error}`);
23404
24090
  return this;
@@ -23470,7 +24156,7 @@ var NetraOpenAIInstrumentor = _NetraOpenAIInstrumentor;
23470
24156
  var openAIInstrumentor = new NetraOpenAIInstrumentor();
23471
24157
 
23472
24158
  // src/instrumentation/openai-agents/constants.ts
23473
- var INSTRUMENTATION_NAME7 = "netra.instrumentation.openai_agents";
24159
+ var INSTRUMENTATION_NAME6 = "netra.instrumentation.openai_agents";
23474
24160
  var DEFAULT_LLM_SYSTEM = "openai";
23475
24161
  var MAX_INDEXED_MESSAGES = 128;
23476
24162
  var MAX_STRINGIFY_LENGTH = 65536;
@@ -23569,7 +24255,7 @@ function setSpanDataAttributes(otelSpan, agentSpan, systemName = DEFAULT_LLM_SYS
23569
24255
  setGenerationAttributes(otelSpan, data, systemName);
23570
24256
  break;
23571
24257
  case "response":
23572
- setResponseAttributes7(otelSpan, agentSpan, systemName);
24258
+ setResponseAttributes8(otelSpan, agentSpan, systemName);
23573
24259
  break;
23574
24260
  case "function":
23575
24261
  setFunctionAttributes(otelSpan, data);
@@ -23603,6 +24289,10 @@ function setAgentAttributes(span2, data) {
23603
24289
  span2.setAttribute(NETRA_AGENT_OUTPUT_TYPE, data.output_type);
23604
24290
  }
23605
24291
  }
24292
+ function unwrapGenerationOutput(output) {
24293
+ const isSingleWrappedResponse = Array.isArray(output) && output.length === 1 && output[0] && typeof output[0] === "object" && ("choices" in output[0] || "usage" in output[0]);
24294
+ return isSingleWrappedResponse ? output[0] : output;
24295
+ }
23606
24296
  function setGenerationAttributes(span2, data, systemName) {
23607
24297
  span2.setAttribute(SpanAttributes2.LLM_SYSTEM, systemName);
23608
24298
  span2.setAttribute(SpanAttributes2.LLM_REQUEST_TYPE, "chat");
@@ -23611,42 +24301,48 @@ function setGenerationAttributes(span2, data, systemName) {
23611
24301
  span2.setAttribute(SpanAttributes2.LLM_RESPONSE_MODEL, data.model);
23612
24302
  }
23613
24303
  if (data.model_config) {
23614
- const config2 = data.model_config;
23615
- if (config2.temperature !== void 0) {
23616
- span2.setAttribute(SpanAttributes2.LLM_REQUEST_TEMPERATURE, Number(config2.temperature));
24304
+ const config = data.model_config;
24305
+ if (config.temperature !== void 0) {
24306
+ span2.setAttribute(SpanAttributes2.LLM_REQUEST_TEMPERATURE, Number(config.temperature));
23617
24307
  }
23618
- if (config2.max_tokens !== void 0) {
23619
- span2.setAttribute(SpanAttributes2.LLM_REQUEST_MAX_TOKENS, Number(config2.max_tokens));
24308
+ if (config.max_tokens !== void 0) {
24309
+ span2.setAttribute(SpanAttributes2.LLM_REQUEST_MAX_TOKENS, Number(config.max_tokens));
23620
24310
  }
23621
- if (config2.top_p !== void 0) {
23622
- span2.setAttribute(SpanAttributes2.LLM_REQUEST_TOP_P, Number(config2.top_p));
24311
+ if (config.top_p !== void 0) {
24312
+ span2.setAttribute(SpanAttributes2.LLM_REQUEST_TOP_P, Number(config.top_p));
23623
24313
  }
23624
- if (config2.frequency_penalty !== void 0) {
23625
- span2.setAttribute(SpanAttributes2.LLM_FREQUENCY_PENALTY, Number(config2.frequency_penalty));
24314
+ if (config.frequency_penalty !== void 0) {
24315
+ span2.setAttribute(SpanAttributes2.LLM_FREQUENCY_PENALTY, Number(config.frequency_penalty));
23626
24316
  }
23627
- if (config2.presence_penalty !== void 0) {
23628
- span2.setAttribute(SpanAttributes2.LLM_PRESENCE_PENALTY, Number(config2.presence_penalty));
24317
+ if (config.presence_penalty !== void 0) {
24318
+ span2.setAttribute(SpanAttributes2.LLM_PRESENCE_PENALTY, Number(config.presence_penalty));
23629
24319
  }
23630
- if (config2.stop !== void 0) {
23631
- span2.setAttribute(SpanAttributes2.LLM_CHAT_STOP_SEQUENCES, safeJsonStringify(config2.stop));
24320
+ if (config.stop !== void 0) {
24321
+ span2.setAttribute(SpanAttributes2.LLM_CHAT_STOP_SEQUENCES, safeJsonStringify(config.stop));
23632
24322
  }
23633
- if (config2.reasoning_effort !== void 0) {
23634
- span2.setAttribute(SpanAttributes2.LLM_REQUEST_REASONING_EFFORT, String(config2.reasoning_effort));
23635
- } else if (config2.reasoning !== void 0) {
23636
- span2.setAttribute(SpanAttributes2.LLM_REQUEST_REASONING_EFFORT, safeJsonStringify(config2.reasoning));
24323
+ if (config.reasoning_effort !== void 0) {
24324
+ span2.setAttribute(SpanAttributes2.LLM_REQUEST_REASONING_EFFORT, String(config.reasoning_effort));
24325
+ } else if (config.reasoning !== void 0) {
24326
+ span2.setAttribute(SpanAttributes2.LLM_REQUEST_REASONING_EFFORT, safeJsonStringify(config.reasoning));
23637
24327
  }
23638
24328
  }
24329
+ const effectiveOutput = unwrapGenerationOutput(data.output);
23639
24330
  if (data.usage) {
23640
- setUsageAttributes2(span2, data.usage);
24331
+ setUsageAttributes3(span2, data.usage);
24332
+ } else if (effectiveOutput && typeof effectiveOutput === "object" && !Array.isArray(effectiveOutput)) {
24333
+ const respUsage = effectiveOutput.usage;
24334
+ if (respUsage && typeof respUsage === "object") {
24335
+ setUsageAttributes3(span2, respUsage);
24336
+ }
23641
24337
  }
23642
24338
  if (data.input !== void 0) {
23643
24339
  setIndexedPromptAttributes(span2, data.input);
23644
24340
  }
23645
- if (data.output !== void 0) {
23646
- setIndexedCompletionAttributes(span2, data.output);
24341
+ if (effectiveOutput !== void 0) {
24342
+ setIndexedCompletionAttributes(span2, effectiveOutput);
23647
24343
  }
23648
24344
  }
23649
- function setResponseAttributes7(span2, agentSpan, systemName) {
24345
+ function setResponseAttributes8(span2, agentSpan, systemName) {
23650
24346
  const data = agentSpan.spanData;
23651
24347
  span2.setAttribute(SpanAttributes2.LLM_SYSTEM, systemName);
23652
24348
  span2.setAttribute(SpanAttributes2.LLM_REQUEST_TYPE, "response");
@@ -23675,7 +24371,7 @@ function setResponseAttributes7(span2, agentSpan, systemName) {
23675
24371
  }
23676
24372
  const resp = data._response;
23677
24373
  if (data.usage && !(resp && typeof resp === "object" && resp.usage)) {
23678
- setUsageAttributes2(span2, data.usage);
24374
+ setUsageAttributes3(span2, data.usage);
23679
24375
  }
23680
24376
  }
23681
24377
  function setFunctionAttributes(span2, data) {
@@ -23724,17 +24420,22 @@ function setCustomAttributes(span2, data) {
23724
24420
  span2.setAttribute(NETRA_CUSTOM_DATA, safeJsonStringify(data.data));
23725
24421
  }
23726
24422
  }
23727
- function setUsageAttributes2(span2, usage) {
23728
- if (usage.input_tokens !== void 0) {
23729
- span2.setAttribute(SpanAttributes2.LLM_USAGE_PROMPT_TOKENS, usage.input_tokens);
24423
+ function setUsageAttributes3(span2, usage) {
24424
+ const promptTokens = usage.input_tokens ?? usage.prompt_tokens;
24425
+ const completionTokens = usage.output_tokens ?? usage.completion_tokens;
24426
+ const totalTokens = usage.total_tokens;
24427
+ if (promptTokens !== void 0) {
24428
+ span2.setAttribute(SpanAttributes2.LLM_USAGE_PROMPT_TOKENS, promptTokens);
23730
24429
  }
23731
- if (usage.output_tokens !== void 0) {
23732
- span2.setAttribute(SpanAttributes2.LLM_USAGE_COMPLETION_TOKENS, usage.output_tokens);
24430
+ if (completionTokens !== void 0) {
24431
+ span2.setAttribute(SpanAttributes2.LLM_USAGE_COMPLETION_TOKENS, completionTokens);
23733
24432
  }
23734
- if (usage.input_tokens !== void 0 && usage.output_tokens !== void 0) {
24433
+ if (totalTokens !== void 0) {
24434
+ span2.setAttribute(SpanAttributes2.LLM_USAGE_TOTAL_TOKENS, totalTokens);
24435
+ } else if (promptTokens !== void 0 && completionTokens !== void 0) {
23735
24436
  span2.setAttribute(
23736
24437
  SpanAttributes2.LLM_USAGE_TOTAL_TOKENS,
23737
- usage.input_tokens + usage.output_tokens
24438
+ promptTokens + completionTokens
23738
24439
  );
23739
24440
  }
23740
24441
  if (usage.details) {
@@ -23746,6 +24447,21 @@ function setUsageAttributes2(span2, usage) {
23746
24447
  span2.setAttribute(SpanAttributes2.LLM_USAGE_REASONING_TOKENS, Number(details.reasoning_tokens));
23747
24448
  }
23748
24449
  }
24450
+ const inputDetails = usage.input_tokens_details ?? usage.prompt_tokens_details;
24451
+ if (inputDetails) {
24452
+ if (inputDetails.cached_tokens !== void 0) {
24453
+ span2.setAttribute(SpanAttributes2.LLM_USAGE_CACHE_READ_INPUT_TOKENS, Number(inputDetails.cached_tokens));
24454
+ }
24455
+ if (inputDetails.cache_write_tokens !== void 0) {
24456
+ span2.setAttribute(SpanAttributes2.LLM_USAGE_CACHE_CREATION_INPUT_TOKENS, Number(inputDetails.cache_write_tokens));
24457
+ }
24458
+ }
24459
+ const outputDetails = usage.output_tokens_details ?? usage.completion_tokens_details;
24460
+ if (outputDetails) {
24461
+ if (outputDetails.reasoning_tokens !== void 0) {
24462
+ span2.setAttribute(SpanAttributes2.LLM_USAGE_REASONING_TOKENS, Number(outputDetails.reasoning_tokens));
24463
+ }
24464
+ }
23749
24465
  }
23750
24466
  function setResponseObjectAttributes(span2, response) {
23751
24467
  if (!response || typeof response !== "object") return;
@@ -23788,6 +24504,9 @@ function setResponseObjectUsageAttributes(span2, usage) {
23788
24504
  if (usage.input_tokens_details?.cached_tokens !== void 0) {
23789
24505
  span2.setAttribute(SpanAttributes2.LLM_USAGE_CACHE_READ_INPUT_TOKENS, usage.input_tokens_details.cached_tokens);
23790
24506
  }
24507
+ if (usage.input_tokens_details?.cache_write_tokens !== void 0) {
24508
+ span2.setAttribute(SpanAttributes2.LLM_USAGE_CACHE_CREATION_INPUT_TOKENS, usage.input_tokens_details.cache_write_tokens);
24509
+ }
23791
24510
  if (usage.output_tokens_details?.reasoning_tokens !== void 0) {
23792
24511
  span2.setAttribute(SpanAttributes2.LLM_USAGE_REASONING_TOKENS, usage.output_tokens_details.reasoning_tokens);
23793
24512
  }
@@ -23827,8 +24546,14 @@ function setIndexedPromptAttributes(span2, input, startIndex = 0) {
23827
24546
  }
23828
24547
  }
23829
24548
  function setIndexedCompletionAttributes(span2, responseData) {
23830
- if (!responseData || typeof responseData !== "object") return;
23831
- const resp = responseData;
24549
+ if (!responseData) return;
24550
+ if (typeof responseData === "string") {
24551
+ span2.setAttribute(`${SpanAttributes2.LLM_COMPLETIONS}.0.role`, "assistant");
24552
+ span2.setAttribute(`${SpanAttributes2.LLM_COMPLETIONS}.0.content`, responseData);
24553
+ return;
24554
+ }
24555
+ if (typeof responseData !== "object") return;
24556
+ const resp = Array.isArray(responseData) ? { output: responseData } : responseData;
23832
24557
  if (Array.isArray(resp.output)) {
23833
24558
  let index = 0;
23834
24559
  for (const item of resp.output) {
@@ -24135,11 +24860,11 @@ try {
24135
24860
  if (pkg?.version) _version = pkg.version;
24136
24861
  } catch {
24137
24862
  }
24138
- var __version__7 = _version;
24863
+ var __version__8 = _version;
24139
24864
 
24140
24865
  // src/instrumentation/openai-agents/index.ts
24141
24866
  var cachedAgentsModule = null;
24142
- var isInstrumented6 = false;
24867
+ var isInstrumented5 = false;
24143
24868
  var activeTracer = null;
24144
24869
  var activeProcessor = null;
24145
24870
  var originalProcessors = null;
@@ -24165,7 +24890,7 @@ async function resolveAgentsModule() {
24165
24890
  }
24166
24891
  var NetraOpenAIAgentsInstrumentor = class {
24167
24892
  isInstrumented() {
24168
- return isInstrumented6;
24893
+ return isInstrumented5;
24169
24894
  }
24170
24895
  /**
24171
24896
  * Register the Netra tracing processor with the OpenAI Agents SDK.
@@ -24175,13 +24900,13 @@ var NetraOpenAIAgentsInstrumentor = class {
24175
24900
  * was registered successfully.
24176
24901
  */
24177
24902
  async instrument(options = {}) {
24178
- if (isInstrumented6) {
24903
+ if (isInstrumented5) {
24179
24904
  Logger.warn("OpenAI Agents SDK is already instrumented");
24180
24905
  return this;
24181
24906
  }
24182
24907
  try {
24183
24908
  const provider = options.tracerProvider;
24184
- activeTracer = provider ? provider.getTracer(INSTRUMENTATION_NAME7, __version__7) : api.trace.getTracer(INSTRUMENTATION_NAME7, __version__7);
24909
+ activeTracer = provider ? provider.getTracer(INSTRUMENTATION_NAME6, __version__8) : api.trace.getTracer(INSTRUMENTATION_NAME6, __version__8);
24185
24910
  } catch (error) {
24186
24911
  Logger.error(`Failed to initialize tracer for OpenAI Agents: ${error}`);
24187
24912
  return this;
@@ -24248,11 +24973,11 @@ var NetraOpenAIAgentsInstrumentor = class {
24248
24973
  activeTracer = null;
24249
24974
  return this;
24250
24975
  }
24251
- isInstrumented6 = true;
24976
+ isInstrumented5 = true;
24252
24977
  return this;
24253
24978
  }
24254
24979
  uninstrument() {
24255
- if (!isInstrumented6) {
24980
+ if (!isInstrumented5) {
24256
24981
  Logger.warn("OpenAI Agents SDK is not instrumented");
24257
24982
  return;
24258
24983
  }
@@ -24277,7 +25002,7 @@ var NetraOpenAIAgentsInstrumentor = class {
24277
25002
  didReplaceProcessors = false;
24278
25003
  activeTracer = null;
24279
25004
  cachedAgentsModule = null;
24280
- isInstrumented6 = false;
25005
+ isInstrumented5 = false;
24281
25006
  }
24282
25007
  };
24283
25008
  var openaiAgentsInstrumentor = new NetraOpenAIAgentsInstrumentor();
@@ -24536,22 +25261,22 @@ function repositoryQueryWrapper(tracer) {
24536
25261
  }
24537
25262
 
24538
25263
  // src/instrumentation/typeorm/version.ts
24539
- var __version__8 = "1.0.0";
25264
+ var __version__9 = "1.0.0";
24540
25265
  var require2 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
24541
- var INSTRUMENTATION_NAME8 = "netra.instrumentation.typeorm";
25266
+ var INSTRUMENTATION_NAME7 = "netra.instrumentation.typeorm";
24542
25267
  var originalMethods4 = /* @__PURE__ */ new Map();
24543
- var isInstrumented7 = false;
25268
+ var isInstrumented6 = false;
24544
25269
  var NetraTypeORMInstrumentor = class {
24545
25270
  constructor() {
24546
25271
  }
24547
25272
  async instrument(options = {}) {
24548
- if (isInstrumented7) {
25273
+ if (isInstrumented6) {
24549
25274
  Logger.warn("TypeORM is already instrumented");
24550
25275
  return this;
24551
25276
  }
24552
25277
  try {
24553
25278
  this.tracerProvider = options.tracerProvider;
24554
- this.tracer = this.tracerProvider ? this.tracerProvider.getTracer(INSTRUMENTATION_NAME8, __version__8) : api.trace.getTracer(INSTRUMENTATION_NAME8, __version__8);
25279
+ this.tracer = this.tracerProvider ? this.tracerProvider.getTracer(INSTRUMENTATION_NAME7, __version__9) : api.trace.getTracer(INSTRUMENTATION_NAME7, __version__9);
24555
25280
  } catch (error) {
24556
25281
  Logger.error(`Failed to initialize tracer: ${error}`);
24557
25282
  return this;
@@ -24559,11 +25284,11 @@ var NetraTypeORMInstrumentor = class {
24559
25284
  await this._instrumentDataSource();
24560
25285
  await this._instrumentEntityManager();
24561
25286
  await this._instrumentRepository();
24562
- isInstrumented7 = true;
25287
+ isInstrumented6 = true;
24563
25288
  return this;
24564
25289
  }
24565
25290
  uninstrument() {
24566
- if (!isInstrumented7) {
25291
+ if (!isInstrumented6) {
24567
25292
  Logger.warn("TypeORM is not instrumented");
24568
25293
  return;
24569
25294
  }
@@ -24574,10 +25299,10 @@ var NetraTypeORMInstrumentor = class {
24574
25299
  this._uninstrumentRepository().catch(() => {
24575
25300
  });
24576
25301
  originalMethods4.clear();
24577
- isInstrumented7 = false;
25302
+ isInstrumented6 = false;
24578
25303
  }
24579
25304
  isInstrumented() {
24580
- return isInstrumented7;
25305
+ return isInstrumented6;
24581
25306
  }
24582
25307
  async _instrumentDataSource() {
24583
25308
  if (!this.tracer) return;
@@ -24923,10 +25648,10 @@ _FilteringSpanExporter.MAX_REMEMBERED_ENTRIES = 1e4;
24923
25648
  _FilteringSpanExporter.MAX_LOCAL_PATTERN_CACHE = 100;
24924
25649
  var FilteringSpanExporter = _FilteringSpanExporter;
24925
25650
  var TrialAwareOTLPExporter = class {
24926
- constructor(config2) {
25651
+ constructor(config) {
24927
25652
  this._isShutdown = false;
24928
- this._url = config2.url;
24929
- this._headers = config2.headers || {};
25653
+ this._url = config.url;
25654
+ this._headers = config.headers || {};
24930
25655
  }
24931
25656
  export(spans, resultCallback) {
24932
25657
  if (this._isShutdown || isTrialBlocked()) {
@@ -25144,7 +25869,7 @@ function resolveRootInstrumentNames(rootInstruments, blockInstruments) {
25144
25869
  }
25145
25870
  return resolved;
25146
25871
  }
25147
- function initInstrumentations(config2, instruments, blockInstruments, rootInstruments) {
25872
+ function initInstrumentations(config, instruments, blockInstruments, rootInstruments) {
25148
25873
  const enableAll = instruments != null && instruments.has("__all__" /* ALL */);
25149
25874
  const resolvedRootNames = resolveRootInstrumentNames(
25150
25875
  rootInstruments,
@@ -25157,6 +25882,7 @@ function initInstrumentations(config2, instruments, blockInstruments, rootInstru
25157
25882
  mistral: false,
25158
25883
  langgraph: false,
25159
25884
  googleGenAI: false,
25885
+ googleGenerativeAI: false,
25160
25886
  anthropic: false,
25161
25887
  openAiAgents: false
25162
25888
  };
@@ -25177,9 +25903,12 @@ function initInstrumentations(config2, instruments, blockInstruments, rootInstru
25177
25903
  if (resolved.has("groq" /* GROQ */)) {
25178
25904
  customInstrumentModules.groq = true;
25179
25905
  }
25180
- if (resolved.has("google_genai" /* GOOGLE_GENERATIVE_AI */)) {
25906
+ if (resolved.has("google_genai" /* GOOGLE_GENAI */)) {
25181
25907
  customInstrumentModules.googleGenAI = true;
25182
25908
  }
25909
+ if (resolved.has("google_generative_ai" /* GOOGLE_GENERATIVE_AI */)) {
25910
+ customInstrumentModules.googleGenerativeAI = true;
25911
+ }
25183
25912
  if (resolved.has("vertexai" /* VERTEX_AI */) && isPackageInstalled("@google-cloud/vertexai")) {
25184
25913
  instrumentModules.google_vertexai = require3("@google-cloud/vertexai");
25185
25914
  }
@@ -25216,7 +25945,8 @@ function initInstrumentations(config2, instruments, blockInstruments, rootInstru
25216
25945
  if (blockAll || blockInstruments.has("groq" /* GROQ */)) customInstrumentModules.groq = false;
25217
25946
  if (blockAll || blockInstruments.has("mistral_ai" /* MISTRAL */)) customInstrumentModules.mistral = false;
25218
25947
  if (blockAll || blockInstruments.has("langgraph" /* LANGGRAPH */)) customInstrumentModules.langgraph = false;
25219
- if (blockAll || blockInstruments.has("google_genai" /* GOOGLE_GENERATIVE_AI */)) customInstrumentModules.googleGenAI = false;
25948
+ if (blockAll || blockInstruments.has("google_genai" /* GOOGLE_GENAI */)) customInstrumentModules.googleGenAI = false;
25949
+ if (blockAll || blockInstruments.has("google_generative_ai" /* GOOGLE_GENERATIVE_AI */)) customInstrumentModules.googleGenerativeAI = false;
25220
25950
  if (blockAll || blockInstruments.has("anthropic" /* ANTHROPIC */)) customInstrumentModules.anthropic = false;
25221
25951
  if (blockAll || blockInstruments.has("openai_agents" /* OPENAI_AGENTS */)) customInstrumentModules.openAiAgents = false;
25222
25952
  if (blockAll || blockInstruments.has("vertexai" /* VERTEX_AI */)) instrumentModules.google_vertexai = false;
@@ -25227,34 +25957,34 @@ function initInstrumentations(config2, instruments, blockInstruments, rootInstru
25227
25957
  if (blockAll || blockInstruments.has("chromadb" /* CHROMADB */)) instrumentModules.chromadb = false;
25228
25958
  if (blockAll || blockInstruments.has("together" /* TOGETHER */)) instrumentModules.together = false;
25229
25959
  }
25230
- config2.setTraceloopEnv();
25960
+ config.setTraceloopEnv();
25231
25961
  Logger.debug("Netra SDK Configuration:");
25232
- Logger.debug(` App Name: ${config2.appName}`);
25233
- Logger.debug(` OTLP Endpoint: ${config2.otlpEndpoint || "(default - localhost:3002)"}`);
25234
- Logger.debug(` API Key: ${config2.apiKey ? "***" + config2.apiKey.slice(-4) : "(not set)"}`);
25235
- Logger.debug(` Trace Content: ${config2.traceContent}`);
25236
- Logger.debug(` Enable Scrubbing: ${config2.enableScrubbing}`);
25962
+ Logger.debug(` App Name: ${config.appName}`);
25963
+ Logger.debug(` OTLP Endpoint: ${config.otlpEndpoint || "(default - localhost:3002)"}`);
25964
+ Logger.debug(` API Key: ${config.apiKey ? "***" + config.apiKey.slice(-4) : "(not set)"}`);
25965
+ Logger.debug(` Trace Content: ${config.traceContent}`);
25966
+ Logger.debug(` Enable Scrubbing: ${config.enableScrubbing}`);
25237
25967
  const traceloopOptions = {
25238
- appName: config2.appName,
25239
- apiKey: config2.apiKey,
25240
- baseUrl: config2.otlpEndpoint,
25241
- disableBatch: config2.disableBatch,
25242
- traceContent: config2.traceContent,
25243
- headers: config2.headers,
25968
+ appName: config.appName,
25969
+ apiKey: config.apiKey,
25970
+ baseUrl: config.otlpEndpoint,
25971
+ disableBatch: config.disableBatch,
25972
+ traceContent: config.traceContent,
25973
+ headers: config.headers,
25244
25974
  instrumentModules,
25245
- silenceInitializationMessage: !config2.debugMode
25975
+ silenceInitializationMessage: !config.debugMode
25246
25976
  };
25247
25977
  let exporter;
25248
25978
  if (!traceloopOptions.baseUrl || traceloopOptions.baseUrl == void 0) {
25249
25979
  exporter = new sdkTraceBase.ConsoleSpanExporter();
25250
25980
  } else {
25251
- const formattedEndpoint = config2.formatOtlpEndpoint();
25981
+ const formattedEndpoint = config.formatOtlpEndpoint();
25252
25982
  exporter = new TrialAwareOTLPExporter({
25253
25983
  url: formattedEndpoint,
25254
- headers: config2.headers
25984
+ headers: config.headers
25255
25985
  });
25256
25986
  }
25257
- const globalBlockedPatterns = config2.blockedSpans ?? [];
25987
+ const globalBlockedPatterns = config.blockedSpans ?? [];
25258
25988
  const localFilteringSpanProcessor = new LocalFilteringSpanProcessor(globalBlockedPatterns);
25259
25989
  const originalExporter = exporter;
25260
25990
  try {
@@ -25276,23 +26006,23 @@ function initInstrumentations(config2, instruments, blockInstruments, rootInstru
25276
26006
  const tracerProvider = api.trace.getTracerProvider();
25277
26007
  const effectiveProvider = addCustomSpanProcessors(
25278
26008
  tracerProvider,
25279
- config2,
26009
+ config,
25280
26010
  resolvedRootNames
25281
26011
  );
25282
26012
  instrumentationsReady = initCustomInstrumentationsAsync(
25283
- config2,
26013
+ config,
25284
26014
  tracerProvider,
25285
26015
  customInstrumentModules,
25286
26016
  blockInstruments
25287
26017
  );
25288
- initOpenTelemetryInstrumentations(config2, resolved, blockInstruments);
26018
+ initOpenTelemetryInstrumentations(config, resolved, blockInstruments);
25289
26019
  return effectiveProvider;
25290
26020
  }
25291
26021
  function isBlocked(instrument, blockInstruments) {
25292
26022
  if (!blockInstruments || blockInstruments.size === 0) return false;
25293
26023
  return blockInstruments.has("__all__" /* ALL */) || blockInstruments.has(instrument);
25294
26024
  }
25295
- async function initCustomInstrumentationsAsync(config2, tracerProvider, customInstrumentModules, blockInstruments) {
26025
+ async function initCustomInstrumentationsAsync(config, tracerProvider, customInstrumentModules, blockInstruments) {
25296
26026
  if (customInstrumentModules.mistral) {
25297
26027
  try {
25298
26028
  await mistralAIInstrumentor.instrumentAsync({ tracerProvider });
@@ -25319,10 +26049,21 @@ async function initCustomInstrumentationsAsync(config2, tracerProvider, customIn
25319
26049
  }
25320
26050
  if (customInstrumentModules.googleGenAI) {
25321
26051
  try {
25322
- await googleGenerativeAIInstrumentor.instrumentAsync({ tracerProvider });
26052
+ await googleGenAIInstrumentor.instrument({ tracerProvider });
25323
26053
  Logger.debug("Custom Google GenAI instrumentation enabled");
25324
26054
  } catch (e) {
25325
- Logger.debug("Failed to initialize custom Google GenAI instrumentation:", e);
26055
+ Logger.debug(
26056
+ "Failed to initialize custom Google GenAI instrumentation:",
26057
+ e
26058
+ );
26059
+ }
26060
+ }
26061
+ if (customInstrumentModules.googleGenerativeAI) {
26062
+ try {
26063
+ await googleGenerativeAIInstrumentor.instrument({ tracerProvider });
26064
+ Logger.debug("Custom Google Generative AI instrumentation enabled");
26065
+ } catch (e) {
26066
+ Logger.debug("Failed to initialize custom Google Generative AI instrumentation:", e);
25326
26067
  }
25327
26068
  }
25328
26069
  if (customInstrumentModules.langgraph) {
@@ -25350,20 +26091,20 @@ async function initCustomInstrumentationsAsync(config2, tracerProvider, customIn
25350
26091
  }
25351
26092
  }
25352
26093
  }
25353
- function initOpenTelemetryInstrumentations(config2, resolved, blockInstruments) {
26094
+ function initOpenTelemetryInstrumentations(config, resolved, blockInstruments) {
25354
26095
  let netraHost = "";
25355
26096
  try {
25356
- if (config2.otlpEndpoint) {
25357
- netraHost = new URL(config2.otlpEndpoint).host;
26097
+ if (config.otlpEndpoint) {
26098
+ netraHost = new URL(config.otlpEndpoint).host;
25358
26099
  }
25359
26100
  } catch {
25360
- Logger.debug(`OTEL_NODE_EXCLUDED_URLS: malformed otlpEndpoint '${config2.otlpEndpoint}', skipping host-based exclusion`);
26101
+ Logger.debug(`OTEL_NODE_EXCLUDED_URLS: malformed otlpEndpoint '${config.otlpEndpoint}', skipping host-based exclusion`);
25361
26102
  }
25362
26103
  const excludeRegexes = (process.env.OTEL_NODE_EXCLUDED_URLS || "").split(",").map((s) => s.trim()).filter(Boolean).map((pattern) => {
25363
26104
  try {
25364
26105
  return new RegExp(pattern);
25365
26106
  } catch {
25366
- if (config2.debugMode) {
26107
+ if (config.debugMode) {
25367
26108
  Logger.debug(
25368
26109
  `Invalid OTEL_NODE_EXCLUDED_URLS pattern skipped: ${pattern}`
25369
26110
  );
@@ -25386,7 +26127,7 @@ function initOpenTelemetryInstrumentations(config2, resolved, blockInstruments)
25386
26127
  }
25387
26128
  });
25388
26129
  registerInstrumentations({ instrumentations: [_httpInstrumentation] });
25389
- if (config2.debugMode) {
26130
+ if (config.debugMode) {
25390
26131
  Logger.debug("HTTP instrumentation enabled");
25391
26132
  }
25392
26133
  } catch (e) {
@@ -25405,11 +26146,11 @@ function initOpenTelemetryInstrumentations(config2, resolved, blockInstruments)
25405
26146
  }
25406
26147
  });
25407
26148
  registerInstrumentations({ instrumentations: [_undiciInstrumentation] });
25408
- if (config2.debugMode) {
26149
+ if (config.debugMode) {
25409
26150
  Logger.debug("Undici/fetch instrumentation enabled");
25410
26151
  }
25411
26152
  } catch (e) {
25412
- if (config2.debugMode) {
26153
+ if (config.debugMode) {
25413
26154
  Logger.debug("Undici/fetch instrumentation not available:", e);
25414
26155
  }
25415
26156
  }
@@ -25433,7 +26174,7 @@ function initOpenTelemetryInstrumentations(config2, resolved, blockInstruments)
25433
26174
  const { ExpressInstrumentation } = require3("@opentelemetry/instrumentation-express");
25434
26175
  const { registerInstrumentations } = require3("@opentelemetry/instrumentation");
25435
26176
  registerInstrumentations({ instrumentations: [new ExpressInstrumentation()] });
25436
- if (config2.debugMode) {
26177
+ if (config.debugMode) {
25437
26178
  Logger.debug("Express instrumentation enabled");
25438
26179
  }
25439
26180
  } catch (e) {
@@ -25441,7 +26182,7 @@ function initOpenTelemetryInstrumentations(config2, resolved, blockInstruments)
25441
26182
  }
25442
26183
  }
25443
26184
  }
25444
- function addCustomSpanProcessors(tracerProvider, config2, rootInstrumentNames) {
26185
+ function addCustomSpanProcessors(tracerProvider, config, rootInstrumentNames) {
25445
26186
  try {
25446
26187
  let provider = null;
25447
26188
  const providerAny = tracerProvider;
@@ -25487,7 +26228,7 @@ function addCustomSpanProcessors(tracerProvider, config2, rootInstrumentNames) {
25487
26228
  }
25488
26229
  const instrumentationProcessor = new InstrumentationSpanProcessor();
25489
26230
  provider.addSpanProcessor(instrumentationProcessor);
25490
- const sessionProcessor = new SessionSpanProcessor(config2.environment);
26231
+ const sessionProcessor = new SessionSpanProcessor(config.environment);
25491
26232
  provider.addSpanProcessor(sessionProcessor);
25492
26233
  const spanIOProcessor = new SpanIOProcessor();
25493
26234
  provider.addSpanProcessor(spanIOProcessor);
@@ -25495,7 +26236,7 @@ function addCustomSpanProcessors(tracerProvider, config2, rootInstrumentNames) {
25495
26236
  provider.addSpanProcessor(llmTraceProcessor);
25496
26237
  const rootSpanProcessor = new RootSpanProcessor();
25497
26238
  provider.addSpanProcessor(rootSpanProcessor);
25498
- if (config2.enableScrubbing) {
26239
+ if (config.enableScrubbing) {
25499
26240
  const scrubbingProcessor = new ScrubbingSpanProcessor();
25500
26241
  provider.addSpanProcessor(scrubbingProcessor);
25501
26242
  }
@@ -25544,13 +26285,21 @@ async function uninstrumentAll() {
25544
26285
  Logger.debug("Failed to uninstrument Anthropic:", e);
25545
26286
  }
25546
26287
  try {
25547
- if (googleGenerativeAIInstrumentor.isInstrumented()) {
25548
- googleGenerativeAIInstrumentor.uninstrument();
26288
+ if (googleGenAIInstrumentor.isInstrumented()) {
26289
+ googleGenAIInstrumentor.uninstrument();
25549
26290
  Logger.debug("Custom Google GenAI instrumentation disabled");
25550
26291
  }
25551
26292
  } catch (e) {
25552
26293
  Logger.debug("Failed to uninstrument Google GenAI:", e);
25553
26294
  }
26295
+ try {
26296
+ if (googleGenerativeAIInstrumentor.isInstrumented()) {
26297
+ googleGenerativeAIInstrumentor.uninstrument();
26298
+ Logger.debug("Custom Google Generative AI instrumentation disabled");
26299
+ }
26300
+ } catch (e) {
26301
+ Logger.debug("Failed to uninstrument Google Generative AI:", e);
26302
+ }
25554
26303
  try {
25555
26304
  if (langgraphInstrumentor.isInstrumented()) {
25556
26305
  await langgraphInstrumentor.uninstrument();
@@ -25600,17 +26349,17 @@ var BaseTask = class {
25600
26349
  };
25601
26350
 
25602
26351
  // src/simulation/utils.ts
25603
- var LOG_PREFIX = "netra.simulation";
26352
+ var LOG_PREFIX4 = "netra.simulation";
25604
26353
  var DEFAULT_FILE_DOWNLOAD_TIMEOUT_S = 30;
25605
26354
  var MAX_FILE_DOWNLOAD_WORKERS = 8;
25606
26355
  var _cachedFileDownloadTimeoutMs = null;
25607
26356
  function validateSimulationInputs(datasetId, task2) {
25608
26357
  if (!datasetId) {
25609
- Logger.error(`${LOG_PREFIX}: dataset_id is required`);
26358
+ Logger.error(`${LOG_PREFIX4}: dataset_id is required`);
25610
26359
  return false;
25611
26360
  }
25612
26361
  if (!(task2 instanceof BaseTask)) {
25613
- Logger.error(`${LOG_PREFIX}: task must be a BaseTask instance`);
26362
+ Logger.error(`${LOG_PREFIX4}: task must be a BaseTask instance`);
25614
26363
  return false;
25615
26364
  }
25616
26365
  return true;
@@ -25627,7 +26376,7 @@ function _getFileDownloadTimeout() {
25627
26376
  return _cachedFileDownloadTimeoutMs;
25628
26377
  }
25629
26378
  Logger.warn(
25630
- `${LOG_PREFIX}: Invalid file download timeout '${envVal}', using default ${DEFAULT_FILE_DOWNLOAD_TIMEOUT_S}s`
26379
+ `${LOG_PREFIX4}: Invalid file download timeout '${envVal}', using default ${DEFAULT_FILE_DOWNLOAD_TIMEOUT_S}s`
25631
26380
  );
25632
26381
  }
25633
26382
  _cachedFileDownloadTimeoutMs = DEFAULT_FILE_DOWNLOAD_TIMEOUT_S * 1e3;
@@ -25656,7 +26405,7 @@ async function _downloadSingleFile(fileData, timeoutMs, signal) {
25656
26405
  const status = axios__default.default.isAxiosError(error) ? error.response?.status : void 0;
25657
26406
  const reason = status ? `HTTP ${status}` : error instanceof Error ? error.message : String(error);
25658
26407
  Logger.error(
25659
- `${LOG_PREFIX}: Failed to download file '${fileData.fileName}': ${reason}`
26408
+ `${LOG_PREFIX4}: Failed to download file '${fileData.fileName}': ${reason}`
25660
26409
  );
25661
26410
  throw new Error(
25662
26411
  `Failed to download file '${fileData.fileName}': ${reason}`
@@ -25673,7 +26422,7 @@ function parseFiles(rawFiles) {
25673
26422
  const downloadUrl = entry.downloadUrl || "";
25674
26423
  if (!fileName || !downloadUrl) {
25675
26424
  Logger.warn(
25676
- `${LOG_PREFIX}: Skipping malformed file attachment (missing fileName or downloadUrl)`
26425
+ `${LOG_PREFIX4}: Skipping malformed file attachment (missing fileName or downloadUrl)`
25677
26426
  );
25678
26427
  continue;
25679
26428
  }
@@ -25717,24 +26466,24 @@ async function executeTask2(task2, message, sessionId, rawFiles) {
25717
26466
  }
25718
26467
 
25719
26468
  // src/simulation/client.ts
25720
- var LOG_PREFIX2 = "netra.simulation";
26469
+ var LOG_PREFIX5 = "netra.simulation";
25721
26470
  var DEFAULT_TIMEOUT = 1e4;
25722
26471
  var SimulationHttpClient = class {
25723
- constructor(config2) {
26472
+ constructor(config) {
25724
26473
  this.client = null;
25725
- this.client = this._createClient(config2);
26474
+ this.client = this._createClient(config);
25726
26475
  }
25727
26476
  /**
25728
26477
  * Create and configure the HTTP client.
25729
26478
  */
25730
- _createClient(config2) {
25731
- const endpoint = (config2.otlpEndpoint || "").trim();
26479
+ _createClient(config) {
26480
+ const endpoint = (config.otlpEndpoint || "").trim();
25732
26481
  if (!endpoint) {
25733
- Logger.error(`${LOG_PREFIX2}: NETRA_OTLP_ENDPOINT is required`);
26482
+ Logger.error(`${LOG_PREFIX5}: NETRA_OTLP_ENDPOINT is required`);
25734
26483
  return null;
25735
26484
  }
25736
26485
  const baseURL = this._resolveBaseUrl(endpoint);
25737
- const headers = this._buildHeaders(config2);
26486
+ const headers = this._buildHeaders(config);
25738
26487
  const timeout = this._getTimeout();
25739
26488
  try {
25740
26489
  const instance = axios__default.default.create({
@@ -25743,16 +26492,16 @@ var SimulationHttpClient = class {
25743
26492
  timeout
25744
26493
  });
25745
26494
  instance.interceptors.request.use(
25746
- (config3) => {
26495
+ (config2) => {
25747
26496
  const traceHeaders = injectTraceContextHeaders({});
25748
- Object.assign(config3.headers, traceHeaders);
25749
- return config3;
26497
+ Object.assign(config2.headers, traceHeaders);
26498
+ return config2;
25750
26499
  },
25751
26500
  (error) => Promise.reject(error)
25752
26501
  );
25753
26502
  return instance;
25754
26503
  } catch (error) {
25755
- Logger.error(`${LOG_PREFIX2}: Failed to create HTTP client:`, error);
26504
+ Logger.error(`${LOG_PREFIX5}: Failed to create HTTP client:`, error);
25756
26505
  return null;
25757
26506
  }
25758
26507
  }
@@ -25769,10 +26518,10 @@ var SimulationHttpClient = class {
25769
26518
  /**
25770
26519
  * Build request headers from configuration.
25771
26520
  */
25772
- _buildHeaders(config2) {
25773
- const headers = { ...config2.headers };
25774
- if (config2.apiKey) {
25775
- headers["x-api-key"] = config2.apiKey;
26521
+ _buildHeaders(config) {
26522
+ const headers = { ...config.headers };
26523
+ if (config.apiKey) {
26524
+ headers["x-api-key"] = config.apiKey;
25776
26525
  }
25777
26526
  return headers;
25778
26527
  }
@@ -25787,7 +26536,7 @@ var SimulationHttpClient = class {
25787
26536
  const timeout = parseFloat(timeoutStr);
25788
26537
  if (isNaN(timeout)) {
25789
26538
  Logger.warn(
25790
- `${LOG_PREFIX2}: Invalid timeout '${timeoutStr}', using default ${DEFAULT_TIMEOUT}ms`
26539
+ `${LOG_PREFIX5}: Invalid timeout '${timeoutStr}', using default ${DEFAULT_TIMEOUT}ms`
25791
26540
  );
25792
26541
  return DEFAULT_TIMEOUT;
25793
26542
  }
@@ -25796,9 +26545,9 @@ var SimulationHttpClient = class {
25796
26545
  /**
25797
26546
  * Create a new simulation run for the specified dataset.
25798
26547
  */
25799
- async createRun(name, datasetId, context17) {
26548
+ async createRun(name, datasetId, context18) {
25800
26549
  if (!this.client) {
25801
- Logger.error(`${LOG_PREFIX2}: Client not initialized`);
26550
+ Logger.error(`${LOG_PREFIX5}: Client not initialized`);
25802
26551
  return null;
25803
26552
  }
25804
26553
  try {
@@ -25806,14 +26555,14 @@ var SimulationHttpClient = class {
25806
26555
  const payload = {
25807
26556
  name,
25808
26557
  datasetId,
25809
- context: context17 || {}
26558
+ context: context18 || {}
25810
26559
  };
25811
26560
  const response = await this.client.post(url, payload);
25812
26561
  const data = response.data;
25813
26562
  const responseData = data.data || {};
25814
26563
  const userMessages = responseData.userMessages || [];
25815
26564
  if (userMessages.length === 0) {
25816
- Logger.warn(`${LOG_PREFIX2}: No user messages returned from create_run`);
26565
+ Logger.warn(`${LOG_PREFIX5}: No user messages returned from create_run`);
25817
26566
  return null;
25818
26567
  }
25819
26568
  const runId = responseData.id || "";
@@ -25831,7 +26580,7 @@ var SimulationHttpClient = class {
25831
26580
  };
25832
26581
  } catch (error) {
25833
26582
  const errorMsg = this._extractErrorMessage(error);
25834
- Logger.error(`${LOG_PREFIX2}: Failed to create simulation run:`, errorMsg);
26583
+ Logger.error(`${LOG_PREFIX5}: Failed to create simulation run:`, errorMsg);
25835
26584
  return null;
25836
26585
  }
25837
26586
  }
@@ -25840,7 +26589,7 @@ var SimulationHttpClient = class {
25840
26589
  */
25841
26590
  async triggerConversation(message, turnId, sessionId, traceId) {
25842
26591
  if (!this.client) {
25843
- Logger.error(`${LOG_PREFIX2}: Client not initialized`);
26592
+ Logger.error(`${LOG_PREFIX5}: Client not initialized`);
25844
26593
  return null;
25845
26594
  }
25846
26595
  try {
@@ -25863,7 +26612,7 @@ var SimulationHttpClient = class {
25863
26612
  }
25864
26613
  const userMessages = responseData.userMessages || [];
25865
26614
  if (userMessages.length === 0) {
25866
- Logger.warn(`${LOG_PREFIX2}: No user messages in continue response`);
26615
+ Logger.warn(`${LOG_PREFIX5}: No user messages in continue response`);
25867
26616
  return null;
25868
26617
  }
25869
26618
  const nextMsg = userMessages[0];
@@ -25876,7 +26625,7 @@ var SimulationHttpClient = class {
25876
26625
  };
25877
26626
  } catch (error) {
25878
26627
  const errorMsg = this._extractErrorMessage(error);
25879
- Logger.error(`${LOG_PREFIX2}: Failed to trigger conversation:`, errorMsg);
26628
+ Logger.error(`${LOG_PREFIX5}: Failed to trigger conversation:`, errorMsg);
25880
26629
  return null;
25881
26630
  }
25882
26631
  }
@@ -25885,17 +26634,17 @@ var SimulationHttpClient = class {
25885
26634
  */
25886
26635
  async reportFailure(runId, runItemId, error) {
25887
26636
  if (!this.client) {
25888
- Logger.error(`${LOG_PREFIX2}: Client not initialized`);
26637
+ Logger.error(`${LOG_PREFIX5}: Client not initialized`);
25889
26638
  return;
25890
26639
  }
25891
26640
  try {
25892
26641
  const url = `/evaluations/run/${runId}/item/${runItemId}/status`;
25893
26642
  const payload = { status: "failed", failureReason: error };
25894
26643
  await this.client.patch(url, payload);
25895
- Logger.info(`${LOG_PREFIX2}: Reported failure - ${error}`);
26644
+ Logger.info(`${LOG_PREFIX5}: Reported failure - ${error}`);
25896
26645
  } catch (err) {
25897
26646
  const errorMsg = this._extractErrorMessage(err);
25898
- Logger.error(`${LOG_PREFIX2}: Failed to report failure:`, errorMsg);
26647
+ Logger.error(`${LOG_PREFIX5}: Failed to report failure:`, errorMsg);
25899
26648
  }
25900
26649
  }
25901
26650
  /**
@@ -25904,7 +26653,7 @@ var SimulationHttpClient = class {
25904
26653
  async postRunStatus(runId, status) {
25905
26654
  if (!this.client) {
25906
26655
  Logger.error(
25907
- `${LOG_PREFIX2}: Client not initialized; cannot post run status`
26656
+ `${LOG_PREFIX5}: Client not initialized; cannot post run status`
25908
26657
  );
25909
26658
  return { success: false };
25910
26659
  }
@@ -25914,14 +26663,14 @@ var SimulationHttpClient = class {
25914
26663
  const response = await this.client.post(url, payload);
25915
26664
  const data = response.data;
25916
26665
  if (data && typeof data === "object" && "data" in data) {
25917
- Logger.info(`${LOG_PREFIX2}: Completed test run successfully`);
26666
+ Logger.info(`${LOG_PREFIX5}: Completed test run successfully`);
25918
26667
  return data.data || {};
25919
26668
  }
25920
26669
  return data;
25921
26670
  } catch (error) {
25922
26671
  const errorMsg = this._extractErrorMessage(error);
25923
26672
  Logger.error(
25924
- `${LOG_PREFIX2}: Failed to post run status for run '${runId}':`,
26673
+ `${LOG_PREFIX5}: Failed to post run status for run '${runId}':`,
25925
26674
  errorMsg
25926
26675
  );
25927
26676
  return { success: false };
@@ -25946,12 +26695,12 @@ var SimulationHttpClient = class {
25946
26695
  };
25947
26696
 
25948
26697
  // src/simulation/api.ts
25949
- var LOG_PREFIX3 = "netra.simulation";
26698
+ var LOG_PREFIX6 = "netra.simulation";
25950
26699
  var SPAN_NAME = "Netra.Simulation.TestRun";
25951
26700
  var Simulation = class {
25952
- constructor(config2) {
25953
- this._config = config2;
25954
- this._client = new SimulationHttpClient(config2);
26701
+ constructor(config) {
26702
+ this._config = config;
26703
+ this._client = new SimulationHttpClient(config);
25955
26704
  }
25956
26705
  /**
25957
26706
  * Run a multi-turn conversation simulation.
@@ -25964,20 +26713,20 @@ var Simulation = class {
25964
26713
  name,
25965
26714
  datasetId,
25966
26715
  task: task2,
25967
- context: context17,
26716
+ context: context18,
25968
26717
  maxConcurrency = 5
25969
26718
  } = options;
25970
26719
  if (!validateSimulationInputs(datasetId, task2)) {
25971
26720
  return null;
25972
26721
  }
25973
26722
  const startTime = Date.now();
25974
- const runResult = await this._client.createRun(name, datasetId, context17);
26723
+ const runResult = await this._client.createRun(name, datasetId, context18);
25975
26724
  if (!runResult) {
25976
26725
  return null;
25977
26726
  }
25978
26727
  const { runId, simulationItems } = runResult;
25979
26728
  if (!simulationItems || simulationItems.length === 0) {
25980
- Logger.error(`${LOG_PREFIX3}: No items returned from create_run`);
26729
+ Logger.error(`${LOG_PREFIX6}: No items returned from create_run`);
25981
26730
  return null;
25982
26731
  }
25983
26732
  let interrupted = false;
@@ -26013,7 +26762,7 @@ var Simulation = class {
26013
26762
  proc.once("unhandledRejection", handleRejection);
26014
26763
  }
26015
26764
  Logger.info(
26016
- `${LOG_PREFIX3}: Starting simulation with ${simulationItems.length} items`
26765
+ `${LOG_PREFIX6}: Starting simulation with ${simulationItems.length} items`
26017
26766
  );
26018
26767
  try {
26019
26768
  const result = await this._runSimulationAsync(
@@ -26024,11 +26773,11 @@ var Simulation = class {
26024
26773
  );
26025
26774
  const elapsedTime = ((Date.now() - startTime) / 1e3).toFixed(2);
26026
26775
  Logger.info(
26027
- `${LOG_PREFIX3}: Simulation completed in ${elapsedTime} seconds`
26776
+ `${LOG_PREFIX6}: Simulation completed in ${elapsedTime} seconds`
26028
26777
  );
26029
26778
  return result;
26030
26779
  } catch (error) {
26031
- Logger.error(`${LOG_PREFIX3}: Run simulation failed`);
26780
+ Logger.error(`${LOG_PREFIX6}: Run simulation failed`);
26032
26781
  await this._client.postRunStatus(runId, "failed");
26033
26782
  throw error;
26034
26783
  } finally {
@@ -26062,14 +26811,14 @@ var Simulation = class {
26062
26811
  }
26063
26812
  processedCount++;
26064
26813
  Logger.info(
26065
- `${LOG_PREFIX3}: ${processedCount}/${runItems.length} processed (run_item_id=${runItem.runItemId})`
26814
+ `${LOG_PREFIX6}: ${processedCount}/${runItems.length} processed (run_item_id=${runItem.runItemId})`
26066
26815
  );
26067
26816
  return result;
26068
26817
  })
26069
26818
  );
26070
26819
  await Promise.all(promises);
26071
26820
  Logger.info(
26072
- `${LOG_PREFIX3}: Completed=${results.completed.length}, Failed=${results.failed.length}`
26821
+ `${LOG_PREFIX6}: Completed=${results.completed.length}, Failed=${results.failed.length}`
26073
26822
  );
26074
26823
  await this._client.postRunStatus(runId, "completed");
26075
26824
  return results;
@@ -26084,7 +26833,7 @@ var Simulation = class {
26084
26833
  let sessionId = null;
26085
26834
  let rawFiles = initialFiles ?? [];
26086
26835
  while (true) {
26087
- const span2 = new SpanWrapper(SPAN_NAME, {}, LOG_PREFIX3);
26836
+ const span2 = new SpanWrapper(SPAN_NAME, {}, LOG_PREFIX6);
26088
26837
  span2.start();
26089
26838
  try {
26090
26839
  const traceId = span2.getCurrentSpan()?.spanContext().traceId ?? "";
@@ -26113,7 +26862,7 @@ var Simulation = class {
26113
26862
  }
26114
26863
  if (response.decision === "stop") {
26115
26864
  Logger.info(
26116
- `${LOG_PREFIX3}: Completed run_item_id=${runItemId} reason=${response.reason}`
26865
+ `${LOG_PREFIX6}: Completed run_item_id=${runItemId} reason=${response.reason}`
26117
26866
  );
26118
26867
  return {
26119
26868
  runItemId,
@@ -26127,7 +26876,7 @@ var Simulation = class {
26127
26876
  } catch (error) {
26128
26877
  const errorMsg = error instanceof Error ? error.message : String(error);
26129
26878
  Logger.error(
26130
- `${LOG_PREFIX3}: Task failed run_item_id=${runItemId}, turn_id=${turnId}: ${errorMsg}`
26879
+ `${LOG_PREFIX6}: Task failed run_item_id=${runItemId}, turn_id=${turnId}: ${errorMsg}`
26131
26880
  );
26132
26881
  await this._client.reportFailure(runId, runItemId, errorMsg);
26133
26882
  return {
@@ -26142,7 +26891,7 @@ var Simulation = class {
26142
26891
  }
26143
26892
  }
26144
26893
  };
26145
- var Tracer17 = class {
26894
+ var Tracer18 = class {
26146
26895
  constructor(cfg, effectiveProvider) {
26147
26896
  if (effectiveProvider && typeof effectiveProvider.getTracer === "function") {
26148
26897
  this.tracer = effectiveProvider.getTracer(Config.LIBRARY_NAME, Config.LIBRARY_VERSION);
@@ -26169,7 +26918,7 @@ function addInputAttributes(span2, args, entityType) {
26169
26918
  }
26170
26919
  }
26171
26920
  function addOutputAttributes(span2, result) {
26172
- if (spanHasOutput(span2)) return;
26921
+ if (result === void 0 || spanHasOutput(span2)) return;
26173
26922
  try {
26174
26923
  span2.setAttribute("output", serializeValue(result, Config.ATTRIBUTE_MAX_LEN));
26175
26924
  } catch (e) {
@@ -26340,21 +27089,21 @@ var Netra = class {
26340
27089
  static isInitialized() {
26341
27090
  return this._initialized;
26342
27091
  }
26343
- static async init(config2 = {}) {
27092
+ static async init(config = {}) {
26344
27093
  if (this._initialized) {
26345
27094
  Logger.warn("Netra.init() called more than once; ignoring subsequent calls.");
26346
27095
  return;
26347
27096
  }
26348
- const cfg = new Config(config2);
27097
+ const cfg = new Config(config);
26349
27098
  this._config = cfg;
26350
27099
  Logger.setDebugMode(cfg.debugMode);
26351
27100
  const effectiveProvider = initInstrumentations(
26352
27101
  cfg,
26353
- config2.instruments,
26354
- config2.blockInstruments,
26355
- config2.rootInstruments
27102
+ config.instruments,
27103
+ config.blockInstruments,
27104
+ config.rootInstruments
26356
27105
  );
26357
- const tracer = new Tracer17(cfg, effectiveProvider);
27106
+ const tracer = new Tracer18(cfg, effectiveProvider);
26358
27107
  this._tracer = tracer.tracer;
26359
27108
  try {
26360
27109
  this.usage = new Usage(cfg);