netra-sdk 1.8.0 → 1.9.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
@@ -2461,14 +2461,14 @@ var require_otel = __commonJS({
2461
2461
  getActiveSpan() {
2462
2462
  return void 0;
2463
2463
  }
2464
- setSpan(context18, _span) {
2465
- return context18;
2464
+ setSpan(context17, _span) {
2465
+ return context17;
2466
2466
  }
2467
2467
  getSpan(_context) {
2468
2468
  return void 0;
2469
2469
  }
2470
- setSpanContext(context18, _spanContext) {
2471
- return context18;
2470
+ setSpanContext(context17, _spanContext) {
2471
+ return context17;
2472
2472
  }
2473
2473
  getTracerProvider() {
2474
2474
  return void 0;
@@ -3035,17 +3035,17 @@ var require_p_retry = __commonJS({
3035
3035
  }
3036
3036
  const retriesLeft = Number.isFinite(options.retries) ? Math.max(0, options.retries - retriesConsumed) : options.retries;
3037
3037
  const maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY;
3038
- const context18 = Object.freeze({
3038
+ const context17 = Object.freeze({
3039
3039
  error: normalizedError,
3040
3040
  attemptNumber,
3041
3041
  retriesLeft,
3042
3042
  retriesConsumed
3043
3043
  });
3044
- await options.onFailedAttempt(context18);
3044
+ await options.onFailedAttempt(context17);
3045
3045
  if (calculateRemainingTime(startTime, maxRetryTime) <= 0) {
3046
3046
  throw normalizedError;
3047
3047
  }
3048
- const consumeRetry = await options.shouldConsumeRetry(context18);
3048
+ const consumeRetry = await options.shouldConsumeRetry(context17);
3049
3049
  const remainingTime = calculateRemainingTime(startTime, maxRetryTime);
3050
3050
  if (remainingTime <= 0 || retriesLeft <= 0) {
3051
3051
  throw normalizedError;
@@ -3057,7 +3057,7 @@ var require_p_retry = __commonJS({
3057
3057
  options.signal?.throwIfAborted();
3058
3058
  return false;
3059
3059
  }
3060
- if (!await options.shouldRetry(context18)) {
3060
+ if (!await options.shouldRetry(context17)) {
3061
3061
  throw normalizedError;
3062
3062
  }
3063
3063
  if (!consumeRetry) {
@@ -3165,16 +3165,16 @@ var require_eventemitter3 = __commonJS({
3165
3165
  Events.prototype = /* @__PURE__ */ Object.create(null);
3166
3166
  if (!new Events().__proto__) prefix = false;
3167
3167
  }
3168
- function EE(fn, context18, once) {
3168
+ function EE(fn, context17, once) {
3169
3169
  this.fn = fn;
3170
- this.context = context18;
3170
+ this.context = context17;
3171
3171
  this.once = once || false;
3172
3172
  }
3173
- function addListener(emitter, event, fn, context18, once) {
3173
+ function addListener(emitter, event, fn, context17, once) {
3174
3174
  if (typeof fn !== "function") {
3175
3175
  throw new TypeError("The listener must be a function");
3176
3176
  }
3177
- var listener = new EE(fn, context18 || emitter, once), evt = prefix ? prefix + event : event;
3177
+ var listener = new EE(fn, context17 || emitter, once), evt = prefix ? prefix + event : event;
3178
3178
  if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
3179
3179
  else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
3180
3180
  else emitter._events[evt] = [emitter._events[evt], listener];
@@ -3265,13 +3265,13 @@ var require_eventemitter3 = __commonJS({
3265
3265
  }
3266
3266
  return true;
3267
3267
  };
3268
- EventEmitter.prototype.on = function on(event, fn, context18) {
3269
- return addListener(this, event, fn, context18, false);
3268
+ EventEmitter.prototype.on = function on(event, fn, context17) {
3269
+ return addListener(this, event, fn, context17, false);
3270
3270
  };
3271
- EventEmitter.prototype.once = function once(event, fn, context18) {
3272
- return addListener(this, event, fn, context18, true);
3271
+ EventEmitter.prototype.once = function once(event, fn, context17) {
3272
+ return addListener(this, event, fn, context17, true);
3273
3273
  };
3274
- EventEmitter.prototype.removeListener = function removeListener(event, fn, context18, once) {
3274
+ EventEmitter.prototype.removeListener = function removeListener(event, fn, context17, once) {
3275
3275
  var evt = prefix ? prefix + event : event;
3276
3276
  if (!this._events[evt]) return this;
3277
3277
  if (!fn) {
@@ -3280,12 +3280,12 @@ var require_eventemitter3 = __commonJS({
3280
3280
  }
3281
3281
  var listeners = this._events[evt];
3282
3282
  if (listeners.fn) {
3283
- if (listeners.fn === fn && (!once || listeners.once) && (!context18 || listeners.context === context18)) {
3283
+ if (listeners.fn === fn && (!once || listeners.once) && (!context17 || listeners.context === context17)) {
3284
3284
  clearEvent(this, evt);
3285
3285
  }
3286
3286
  } else {
3287
3287
  for (var i = 0, events = [], length = listeners.length; i < length; i++) {
3288
- if (listeners[i].fn !== fn || once && !listeners[i].once || context18 && listeners[i].context !== context18) {
3288
+ if (listeners[i].fn !== fn || once && !listeners[i].once || context17 && listeners[i].context !== context17) {
3289
3289
  events.push(listeners[i]);
3290
3290
  }
3291
3291
  }
@@ -5844,7 +5844,7 @@ var require_error = __commonJS({
5844
5844
  }
5845
5845
  };
5846
5846
  exports$1.LangSmithConflictError = LangSmithConflictError;
5847
- async function raiseForStatus(response, context18, consumeOnSuccess) {
5847
+ async function raiseForStatus(response, context17, consumeOnSuccess) {
5848
5848
  let errorBody;
5849
5849
  if (response.ok) {
5850
5850
  if (consumeOnSuccess) {
@@ -5872,7 +5872,7 @@ var require_error = __commonJS({
5872
5872
  errorBody = "";
5873
5873
  }
5874
5874
  }
5875
- const fullMessage = `Failed to ${context18}. Received status [${response.status}]: ${response.statusText}. Message: ${errorBody}`;
5875
+ const fullMessage = `Failed to ${context17}. Received status [${response.status}]: ${response.statusText}. Message: ${errorBody}`;
5876
5876
  if (response.status === 409) {
5877
5877
  throw new LangSmithConflictError(fullMessage);
5878
5878
  }
@@ -7225,7 +7225,7 @@ var require_client = __commonJS({
7225
7225
  });
7226
7226
  return stream;
7227
7227
  }
7228
- async _sendMultipartRequest(parts, context18, options) {
7228
+ async _sendMultipartRequest(parts, context17, options) {
7229
7229
  const boundary = "----LangSmithFormBoundary" + Math.random().toString(36).slice(2);
7230
7230
  const isNodeFetch = (0, fetch_js_1._globalFetchImplementationIsNodeFetch)();
7231
7231
  const buildBuffered = () => this._createNodeFetchBody(parts, boundary);
@@ -7267,14 +7267,14 @@ var require_client = __commonJS({
7267
7267
  res = await sendWithRetry(buildBuffered);
7268
7268
  }
7269
7269
  if ((!this.multipartStreamingDisabled || streamedAttempt) && res.status === 422 && (options?.apiUrl ?? this.apiUrl) !== DEFAULT_API_URL) {
7270
- 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}".`);
7270
+ 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}".`);
7271
7271
  this.multipartStreamingDisabled = true;
7272
7272
  res = await sendWithRetry(buildBuffered);
7273
7273
  }
7274
7274
  } catch (e) {
7275
7275
  console.warn(`${e.message.trim()}
7276
7276
 
7277
- Context: ${context18}`);
7277
+ Context: ${context17}`);
7278
7278
  }
7279
7279
  }
7280
7280
  async updateRun(runId, run, options) {
@@ -15139,11 +15139,6 @@ var _Config = class _Config {
15139
15139
  "NETRA_DEBUG",
15140
15140
  false
15141
15141
  );
15142
- this.enableRootSpan = this._getBoolConfig(
15143
- config.enableRootSpan,
15144
- "NETRA_ENABLE_ROOT_SPAN",
15145
- false
15146
- );
15147
15142
  this.enableScrubbing = this._getBoolConfig(
15148
15143
  config.enableScrubbing,
15149
15144
  "NETRA_ENABLE_SCRUBBING",
@@ -15293,6 +15288,11 @@ _Config.SDK_NAME = "netra";
15293
15288
  _Config.LIBRARY_NAME = "netra";
15294
15289
  _Config.LIBRARY_VERSION = SDK_VERSION;
15295
15290
  _Config.TRIAL_BLOCK_DURATION_SECONDS = 900;
15291
+ // 15 minutes
15292
+ // Root-span attribute marking traces produced by evaluation/simulation runs
15293
+ // so the FE/BE can distinguish them from normal workflow invocations.
15294
+ _Config.TRACE_ORIGIN_KEY = "netra.trace.origin";
15295
+ _Config.TRACE_ORIGIN_EVALUATION = "evaluation";
15296
15296
  var Config = _Config;
15297
15297
 
15298
15298
  // src/utils/pattern-matching.ts
@@ -16413,13 +16413,13 @@ async function runSingleEvaluator(params) {
16413
16413
  if (config) {
16414
16414
  expectedName = config.name;
16415
16415
  }
16416
- const context18 = {
16416
+ const context17 = {
16417
16417
  input: itemInput,
16418
16418
  taskOutput,
16419
16419
  expectedOutput,
16420
16420
  metadata
16421
16421
  };
16422
- let result = evaluator.evaluate(context18);
16422
+ let result = evaluator.evaluate(context17);
16423
16423
  if (result instanceof Promise) {
16424
16424
  result = await result;
16425
16425
  }
@@ -16763,7 +16763,11 @@ var Evaluation = class {
16763
16763
  */
16764
16764
  async executeItemPipeline(runId, runName, ctx, task2, evaluators, results, bgEvalTasks) {
16765
16765
  const spanName = `TestRun.${runName}`;
16766
- const span2 = new SpanWrapper(spanName, {}, "netra.evaluation");
16766
+ const span2 = new SpanWrapper(
16767
+ spanName,
16768
+ { [Config.TRACE_ORIGIN_KEY]: Config.TRACE_ORIGIN_EVALUATION },
16769
+ "netra.evaluation"
16770
+ );
16767
16771
  span2.start();
16768
16772
  try {
16769
16773
  const otelSpan = span2.getCurrentSpan();
@@ -17166,6 +17170,42 @@ var DashboardHttpClient = class extends NetraHttpClient {
17166
17170
  return null;
17167
17171
  }
17168
17172
  }
17173
+ /**
17174
+ * Get detailed information for a specific session including all its traces.
17175
+ *
17176
+ * Args:
17177
+ * sessionId: The session ID to retrieve details for.
17178
+ *
17179
+ * Returns:
17180
+ * The session details response data or null on error.
17181
+ */
17182
+ async getSessionDetails(sessionId) {
17183
+ if (!this.isInitialized()) {
17184
+ Logger.error(
17185
+ "netra.dashboard: Dashboard client is not initialized; cannot get session details"
17186
+ );
17187
+ return null;
17188
+ }
17189
+ try {
17190
+ const url = `/public/dashboard/session/${encodeURIComponent(sessionId)}`;
17191
+ const response = await this.get(url);
17192
+ if (!response.ok) {
17193
+ const errorMessage = response.data?.error?.message ?? "Unknown error";
17194
+ Logger.error(
17195
+ `netra.dashboard: Failed to fetch session details: ${errorMessage}`
17196
+ );
17197
+ return null;
17198
+ }
17199
+ return response.data;
17200
+ } catch (err) {
17201
+ const message = err?.response?.data?.error?.message ?? "";
17202
+ Logger.error(
17203
+ "netra.dashboard: Failed to fetch session details:",
17204
+ message
17205
+ );
17206
+ return null;
17207
+ }
17208
+ }
17169
17209
  };
17170
17210
 
17171
17211
  // src/api/dashboard/models.ts
@@ -17389,6 +17429,19 @@ var Dashboard = class {
17389
17429
  }
17390
17430
  return result.data ?? {};
17391
17431
  }
17432
+ async getSessionDetails(sessionId) {
17433
+ if (!sessionId) {
17434
+ Logger.error(
17435
+ "netra.dashboard: session_id is required to fetch session details"
17436
+ );
17437
+ return null;
17438
+ }
17439
+ const result = await this.client.getSessionDetails(sessionId);
17440
+ if (!result) {
17441
+ return null;
17442
+ }
17443
+ return result.data ?? result;
17444
+ }
17392
17445
  isValidScope(scope) {
17393
17446
  return Object.values(Scope).includes(scope);
17394
17447
  }
@@ -18304,6 +18357,13 @@ var SpanIOProcessor = class {
18304
18357
  if (key === _USAGE_OUTPUT_TOKENS) {
18305
18358
  return original(_USAGE_COMPLETION_TOKENS, value);
18306
18359
  }
18360
+ if (key === "db.statement") {
18361
+ original(key, value);
18362
+ if (!inputLocked() && inputIsEmpty() && !isEmpty(value)) {
18363
+ original("input", typeof value === "string" ? value : String(value));
18364
+ }
18365
+ return span2;
18366
+ }
18307
18367
  return original(key, value);
18308
18368
  } catch (e) {
18309
18369
  Logger.debug(`SpanIOProcessor: error processing key=${key}`, e);
@@ -18884,7 +18944,7 @@ function setUsageAttributes(span2, response) {
18884
18944
  Number(cacheReadTokens)
18885
18945
  );
18886
18946
  }
18887
- const cacheCreationTokens = usage.cache_creation_input_tokens;
18947
+ const cacheCreationTokens = usage.cache_creation_input_tokens ?? (usage.prompt_tokens_details ?? usage.input_tokens_details)?.cache_write_tokens;
18888
18948
  if (cacheCreationTokens !== void 0) {
18889
18949
  span2.setAttribute(
18890
18950
  SpanAttributes2.LLM_USAGE_CACHE_CREATION_INPUT_TOKENS,
@@ -26829,7 +26889,7 @@ var SimulationHttpClient = class {
26829
26889
  * Used in the two-phase flow so that beforeAll/before hooks can run
26830
26890
  * before any LLM spend.
26831
26891
  */
26832
- async initializeRun(name, datasetId, context18, hooksMeta) {
26892
+ async initializeRun(name, datasetId, context17, hooksMeta) {
26833
26893
  if (!this.client) {
26834
26894
  Logger.error(`${LOG_PREFIX5}: Client not initialized`);
26835
26895
  return null;
@@ -26839,7 +26899,7 @@ var SimulationHttpClient = class {
26839
26899
  const payload = {
26840
26900
  name,
26841
26901
  datasetId,
26842
- context: context18 || {}
26902
+ context: context17 || {}
26843
26903
  };
26844
26904
  if (hooksMeta) {
26845
26905
  payload.lifecycleHooks = hooksMeta;
@@ -27157,7 +27217,7 @@ var Simulation = class {
27157
27217
  name,
27158
27218
  datasetId,
27159
27219
  task: task2,
27160
- context: context18,
27220
+ context: context17,
27161
27221
  maxConcurrency = 5,
27162
27222
  hooks
27163
27223
  } = options;
@@ -27169,7 +27229,7 @@ var Simulation = class {
27169
27229
  const initResult = await this._client.initializeRun(
27170
27230
  name,
27171
27231
  datasetId,
27172
- context18,
27232
+ context17,
27173
27233
  hooksMeta && Object.keys(hooksMeta).length > 0 ? hooksMeta : null
27174
27234
  );
27175
27235
  if (!initResult) {
@@ -27470,7 +27530,11 @@ var Simulation = class {
27470
27530
  let sessionId = null;
27471
27531
  let rawFiles = initialFiles ?? [];
27472
27532
  while (true) {
27473
- const span2 = new SpanWrapper(SPAN_NAME, {}, LOG_PREFIX7);
27533
+ const span2 = new SpanWrapper(
27534
+ SPAN_NAME,
27535
+ { [Config.TRACE_ORIGIN_KEY]: Config.TRACE_ORIGIN_EVALUATION },
27536
+ LOG_PREFIX7
27537
+ );
27474
27538
  span2.start();
27475
27539
  try {
27476
27540
  const traceId = span2.getCurrentSpan()?.spanContext().traceId ?? "";
@@ -27810,26 +27874,6 @@ Received ${signal}. Shutting down Netra SDK...`);
27810
27874
  process.once("SIGINT", () => handleSignal("SIGINT"));
27811
27875
  process.once("SIGTERM", () => handleSignal("SIGTERM"));
27812
27876
  process.once("uncaughtException", handleUncaughtException);
27813
- if (cfg.enableRootSpan) {
27814
- const tracer2 = this._tracer || api.trace.getTracer("netra.root.span");
27815
- const rootName = `${Config.LIBRARY_NAME}.root.span`;
27816
- this._rootSpan = tracer2.startSpan(rootName, {
27817
- kind: api.SpanKind.INTERNAL
27818
- });
27819
- if (this._rootSpan) {
27820
- if (cfg.appName) {
27821
- this._rootSpan.setAttribute("service.name", cfg.appName);
27822
- }
27823
- this._rootSpan.setAttribute("netra.environment", cfg.environment);
27824
- this._rootSpan.setAttribute(
27825
- "netra.library.version",
27826
- Config.LIBRARY_VERSION
27827
- );
27828
- Logger.info(
27829
- "Netra root span created. Use Netra.runWithRootSpan() to parent spans under it."
27830
- );
27831
- }
27832
- }
27833
27877
  await instrumentationsReady;
27834
27878
  }
27835
27879
  static async shutdown() {
@@ -27841,14 +27885,6 @@ Received ${signal}. Shutting down Netra SDK...`);
27841
27885
  } catch (e) {
27842
27886
  Logger.error("Error during uninstrumentAll:", e);
27843
27887
  }
27844
- if (this._rootSpan) {
27845
- try {
27846
- this._rootSpan.end();
27847
- } catch (e) {
27848
- } finally {
27849
- this._rootSpan = void 0;
27850
- }
27851
- }
27852
27888
  const FLUSH_TIMEOUT_MS = 5e3;
27853
27889
  try {
27854
27890
  const traceProvider = api.trace.getTracerProvider();
@@ -27885,20 +27921,6 @@ Received ${signal}. Shutting down Netra SDK...`);
27885
27921
  static setRootOutput(value) {
27886
27922
  SessionManager.setRootOutput(value);
27887
27923
  }
27888
- /**
27889
- * Run a function with the root span as the active parent context.
27890
- * All spans created within this function will be children of the root span.
27891
- * Note: required in JS because OTel JS has no persistent context.attach()
27892
- */
27893
- static runWithRootSpan(fn) {
27894
- if (!this._rootSpan) {
27895
- Logger.warn(
27896
- "runWithRootSpan: No root span available. Running function without parent context."
27897
- );
27898
- return fn();
27899
- }
27900
- return api.context.with(api.trace.setSpan(api.context.active(), this._rootSpan), fn);
27901
- }
27902
27924
  static setSessionId(sessionId) {
27903
27925
  if (typeof sessionId !== "string") {
27904
27926
  Logger.error(`setSessionId: sessionId must be a string, got ${typeof sessionId}`);