netra-sdk 1.7.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) {
@@ -15049,7 +15049,7 @@ var Usage = class {
15049
15049
  };
15050
15050
 
15051
15051
  // src/version.ts
15052
- var SDK_VERSION = "1.6.0";
15052
+ var SDK_VERSION = "1.8.0";
15053
15053
 
15054
15054
  // src/config.ts
15055
15055
  var NetraInstruments = /* @__PURE__ */ ((NetraInstruments2) => {
@@ -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;
@@ -26944,6 +27004,16 @@ var SimulationHttpClient = class {
26944
27004
  }
26945
27005
  /**
26946
27006
  * Report a task execution failure to the backend.
27007
+ *
27008
+ * @param runId - Identifier of the run.
27009
+ * @param runItemId - Identifier of the run item.
27010
+ * @param error - Error message describing the failure.
27011
+ * @param status - The run status to set on the item. Use `"prescript_failed"`
27012
+ * when the failure originated from a beforeAll or before hook, or
27013
+ * `"postscript_failed"` when an after/afterEach/afterAll hook failed on an
27014
+ * otherwise successful item. Callers must not overwrite an existing real
27015
+ * failure (e.g. `failed` / `prescript_failed`) with `postscript_failed`.
27016
+ * Defaults to `"failed"`.
26947
27017
  */
26948
27018
  async reportFailure(runId, runItemId, error, status = "failed") {
26949
27019
  if (!this.client) {
@@ -27106,14 +27176,7 @@ async function runAfter(hooks, datasetItemId, itemResult, setupContext) {
27106
27176
  Logger.info(
27107
27177
  `${LOG_PREFIX6}: running after hook for datasetItemId=${datasetItemId}`
27108
27178
  );
27109
- try {
27110
- await hooks.after[datasetItemId](itemResult, setupContext);
27111
- } catch (error) {
27112
- Logger.warn(
27113
- `${LOG_PREFIX6}: after hook raised an exception for datasetItemId=${datasetItemId} (ignored):`,
27114
- error
27115
- );
27116
- }
27179
+ await hooks.after[datasetItemId](itemResult, setupContext);
27117
27180
  }
27118
27181
  }
27119
27182
  async function runAfterEach(hooks, datasetItemId, itemResult, setupContext) {
@@ -27121,26 +27184,12 @@ async function runAfterEach(hooks, datasetItemId, itemResult, setupContext) {
27121
27184
  Logger.info(
27122
27185
  `${LOG_PREFIX6}: running afterEach hook for datasetItemId=${datasetItemId}`
27123
27186
  );
27124
- try {
27125
- await hooks.afterEach(itemResult, setupContext);
27126
- } catch (error) {
27127
- Logger.warn(
27128
- `${LOG_PREFIX6}: afterEach hook raised an exception for datasetItemId=${datasetItemId} (ignored):`,
27129
- error
27130
- );
27131
- }
27187
+ await hooks.afterEach(itemResult, setupContext);
27132
27188
  }
27133
27189
  async function runAfterAll(hooks, results, sharedContext) {
27134
27190
  if (!hooks?.afterAll) return;
27135
27191
  Logger.info(`${LOG_PREFIX6}: running afterAll hook`);
27136
- try {
27137
- await hooks.afterAll(results, sharedContext);
27138
- } catch (error) {
27139
- Logger.warn(
27140
- `${LOG_PREFIX6}: afterAll hook raised an exception (ignored):`,
27141
- error
27142
- );
27143
- }
27192
+ await hooks.afterAll(results, sharedContext);
27144
27193
  }
27145
27194
 
27146
27195
  // src/simulation/api.ts
@@ -27168,7 +27217,7 @@ var Simulation = class {
27168
27217
  name,
27169
27218
  datasetId,
27170
27219
  task: task2,
27171
- context: context18,
27220
+ context: context17,
27172
27221
  maxConcurrency = 5,
27173
27222
  hooks
27174
27223
  } = options;
@@ -27180,7 +27229,7 @@ var Simulation = class {
27180
27229
  const initResult = await this._client.initializeRun(
27181
27230
  name,
27182
27231
  datasetId,
27183
- context18,
27232
+ context17,
27184
27233
  hooksMeta && Object.keys(hooksMeta).length > 0 ? hooksMeta : null
27185
27234
  );
27186
27235
  if (!initResult) {
@@ -27231,14 +27280,13 @@ var Simulation = class {
27231
27280
  } catch (error) {
27232
27281
  const errorMsg = `beforeAll hook failed: ${error instanceof Error ? error.message : String(error)}`;
27233
27282
  Logger.error(`${LOG_PREFIX7}: ${errorMsg} \u2014 aborting run (no LLM spent)`);
27234
- for (const item of items) {
27235
- await this._client.reportFailure(
27236
- runId,
27237
- item.runItemId,
27238
- errorMsg,
27239
- "prescript_failed"
27240
- );
27241
- }
27283
+ await this._reportFailures(
27284
+ runId,
27285
+ items.map((item) => item.runItemId),
27286
+ errorMsg,
27287
+ "prescript_failed",
27288
+ maxConcurrency
27289
+ );
27242
27290
  const results = {
27243
27291
  success: false,
27244
27292
  completed: [],
@@ -27249,7 +27297,12 @@ var Simulation = class {
27249
27297
  })),
27250
27298
  totalItems: items.length
27251
27299
  };
27252
- await runAfterAll(hooks, results, null);
27300
+ try {
27301
+ await runAfterAll(hooks, results, null);
27302
+ } catch (afterAllError) {
27303
+ const afterAllMsg = `afterAll hook failed: ${afterAllError instanceof Error ? afterAllError.message : String(afterAllError)}`;
27304
+ Logger.error(`${LOG_PREFIX7}: ${afterAllMsg}`);
27305
+ }
27253
27306
  await this._client.postRunStatus(runId, "completed");
27254
27307
  return results;
27255
27308
  }
@@ -27279,8 +27332,7 @@ var Simulation = class {
27279
27332
  error: errorMsg
27280
27333
  };
27281
27334
  failedItems.push(itemResult);
27282
- await runAfter(hooks, datasetItemId, itemResult, setupContext);
27283
- await runAfterEach(hooks, datasetItemId, itemResult, setupContext);
27335
+ await this._runAfterHooks(runId, runItemId, datasetItemId, hooks, itemResult, setupContext);
27284
27336
  return;
27285
27337
  }
27286
27338
  } else {
@@ -27296,8 +27348,7 @@ var Simulation = class {
27296
27348
  error: "Failed to generate first user message"
27297
27349
  };
27298
27350
  failedItems.push(itemResult);
27299
- await runAfter(hooks, datasetItemId, itemResult, setupContexts.get(runItemId) ?? null);
27300
- await runAfterEach(hooks, datasetItemId, itemResult, setupContexts.get(runItemId) ?? null);
27351
+ await this._runAfterHooks(runId, runItemId, datasetItemId, hooks, itemResult, setupContexts.get(runItemId) ?? null);
27301
27352
  return;
27302
27353
  }
27303
27354
  simulationItems.push(simItem);
@@ -27312,7 +27363,12 @@ var Simulation = class {
27312
27363
  failed: failedItems,
27313
27364
  totalItems: items.length
27314
27365
  };
27315
- await runAfterAll(hooks, results, sharedContext);
27366
+ try {
27367
+ await runAfterAll(hooks, results, sharedContext);
27368
+ } catch (afterAllError) {
27369
+ const afterAllMsg = `afterAll hook failed: ${afterAllError instanceof Error ? afterAllError.message : String(afterAllError)}`;
27370
+ Logger.error(`${LOG_PREFIX7}: ${afterAllMsg}`);
27371
+ }
27316
27372
  await this._client.postRunStatus(runId, "completed");
27317
27373
  return results;
27318
27374
  }
@@ -27382,12 +27438,84 @@ var Simulation = class {
27382
27438
  );
27383
27439
  await Promise.all(promises);
27384
27440
  results.failed.push(...setupFailedItems);
27385
- await runAfterAll(hooks, results, sharedContext);
27441
+ try {
27442
+ await runAfterAll(hooks, results, sharedContext);
27443
+ } catch (error) {
27444
+ const errorMsg = `afterAll hook failed: ${error instanceof Error ? error.message : String(error)}`;
27445
+ Logger.error(`${LOG_PREFIX7}: ${errorMsg}`);
27446
+ const completed = results.completed;
27447
+ const successfulIds = completed.map((item) => item.runItemId);
27448
+ await this._reportFailures(
27449
+ runId,
27450
+ successfulIds,
27451
+ errorMsg,
27452
+ "postscript_failed",
27453
+ maxConcurrency
27454
+ );
27455
+ for (const item of completed) {
27456
+ item.success = false;
27457
+ item.error = errorMsg;
27458
+ item.status = "postscript_failed";
27459
+ }
27460
+ results.failed.push(...completed);
27461
+ results.completed = [];
27462
+ }
27463
+ results.success = results.failed.length === 0;
27386
27464
  Logger.info(
27387
27465
  `${LOG_PREFIX7}: Completed=${results.completed.length}, Failed=${results.failed.length}`
27388
27466
  );
27389
27467
  return results;
27390
27468
  }
27469
+ /**
27470
+ * Report failures for many items concurrently, capped like other paths.
27471
+ */
27472
+ async _reportFailures(runId, runItemIds, error, status, maxConcurrency = 5) {
27473
+ if (runItemIds.length === 0) {
27474
+ return;
27475
+ }
27476
+ const limit = pLimit2__default.default(Math.min(5, maxConcurrency));
27477
+ await Promise.all(
27478
+ runItemIds.map(
27479
+ (runItemId) => limit(() => this._client.reportFailure(runId, runItemId, error, status))
27480
+ )
27481
+ );
27482
+ }
27483
+ /**
27484
+ * Run after/afterEach hooks independently.
27485
+ *
27486
+ * Both hooks always attempt to run. `postscript_failed` is reported only
27487
+ * when the item otherwise succeeded — an existing failure status/reason is
27488
+ * never overwritten.
27489
+ */
27490
+ async _runAfterHooks(runId, runItemId, datasetItemId, hooks, itemResult, setupContext) {
27491
+ const errors = [];
27492
+ try {
27493
+ await runAfter(hooks, datasetItemId, itemResult, setupContext);
27494
+ } catch (error) {
27495
+ const errorMsg = `after hook failed: ${error instanceof Error ? error.message : String(error)}`;
27496
+ Logger.error(`${LOG_PREFIX7}: ${errorMsg} for runItemId=${runItemId}`);
27497
+ errors.push(errorMsg);
27498
+ }
27499
+ try {
27500
+ await runAfterEach(hooks, datasetItemId, itemResult, setupContext);
27501
+ } catch (error) {
27502
+ const errorMsg = `afterEach hook failed: ${error instanceof Error ? error.message : String(error)}`;
27503
+ Logger.error(`${LOG_PREFIX7}: ${errorMsg} for runItemId=${runItemId}`);
27504
+ errors.push(errorMsg);
27505
+ }
27506
+ if (errors.length > 0 && itemResult.success) {
27507
+ const error = errors.join("; ");
27508
+ await this._client.reportFailure(
27509
+ runId,
27510
+ runItemId,
27511
+ error,
27512
+ "postscript_failed"
27513
+ );
27514
+ itemResult.success = false;
27515
+ itemResult.error = error;
27516
+ itemResult.status = "postscript_failed";
27517
+ }
27518
+ }
27391
27519
  /**
27392
27520
  * Execute a multi-turn conversation for a single simulation item.
27393
27521
  *
@@ -27402,7 +27530,11 @@ var Simulation = class {
27402
27530
  let sessionId = null;
27403
27531
  let rawFiles = initialFiles ?? [];
27404
27532
  while (true) {
27405
- 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
+ );
27406
27538
  span2.start();
27407
27539
  try {
27408
27540
  const traceId = span2.getCurrentSpan()?.spanContext().traceId ?? "";
@@ -27427,8 +27559,7 @@ var Simulation = class {
27427
27559
  error: "Failed to get conversation response",
27428
27560
  turnId
27429
27561
  };
27430
- await runAfter(hooks, datasetItemId, itemResult, setupContext);
27431
- await runAfterEach(hooks, datasetItemId, itemResult, setupContext);
27562
+ await this._runAfterHooks(runId, runItemId, datasetItemId, hooks, itemResult, setupContext);
27432
27563
  return itemResult;
27433
27564
  }
27434
27565
  if (response.decision === "stop") {
@@ -27440,8 +27571,7 @@ var Simulation = class {
27440
27571
  success: true,
27441
27572
  finalTurnId: turnId
27442
27573
  };
27443
- await runAfter(hooks, datasetItemId, itemResult, setupContext);
27444
- await runAfterEach(hooks, datasetItemId, itemResult, setupContext);
27574
+ await this._runAfterHooks(runId, runItemId, datasetItemId, hooks, itemResult, setupContext);
27445
27575
  return itemResult;
27446
27576
  }
27447
27577
  message = response.nextUserMessage;
@@ -27459,8 +27589,7 @@ var Simulation = class {
27459
27589
  error: errorMsg,
27460
27590
  turnId
27461
27591
  };
27462
- await runAfter(hooks, datasetItemId, itemResult, setupContext);
27463
- await runAfterEach(hooks, datasetItemId, itemResult, setupContext);
27592
+ await this._runAfterHooks(runId, runItemId, datasetItemId, hooks, itemResult, setupContext);
27464
27593
  return itemResult;
27465
27594
  } finally {
27466
27595
  span2.end();
@@ -27745,26 +27874,6 @@ Received ${signal}. Shutting down Netra SDK...`);
27745
27874
  process.once("SIGINT", () => handleSignal("SIGINT"));
27746
27875
  process.once("SIGTERM", () => handleSignal("SIGTERM"));
27747
27876
  process.once("uncaughtException", handleUncaughtException);
27748
- if (cfg.enableRootSpan) {
27749
- const tracer2 = this._tracer || api.trace.getTracer("netra.root.span");
27750
- const rootName = `${Config.LIBRARY_NAME}.root.span`;
27751
- this._rootSpan = tracer2.startSpan(rootName, {
27752
- kind: api.SpanKind.INTERNAL
27753
- });
27754
- if (this._rootSpan) {
27755
- if (cfg.appName) {
27756
- this._rootSpan.setAttribute("service.name", cfg.appName);
27757
- }
27758
- this._rootSpan.setAttribute("netra.environment", cfg.environment);
27759
- this._rootSpan.setAttribute(
27760
- "netra.library.version",
27761
- Config.LIBRARY_VERSION
27762
- );
27763
- Logger.info(
27764
- "Netra root span created. Use Netra.runWithRootSpan() to parent spans under it."
27765
- );
27766
- }
27767
- }
27768
27877
  await instrumentationsReady;
27769
27878
  }
27770
27879
  static async shutdown() {
@@ -27776,14 +27885,6 @@ Received ${signal}. Shutting down Netra SDK...`);
27776
27885
  } catch (e) {
27777
27886
  Logger.error("Error during uninstrumentAll:", e);
27778
27887
  }
27779
- if (this._rootSpan) {
27780
- try {
27781
- this._rootSpan.end();
27782
- } catch (e) {
27783
- } finally {
27784
- this._rootSpan = void 0;
27785
- }
27786
- }
27787
27888
  const FLUSH_TIMEOUT_MS = 5e3;
27788
27889
  try {
27789
27890
  const traceProvider = api.trace.getTracerProvider();
@@ -27820,20 +27921,6 @@ Received ${signal}. Shutting down Netra SDK...`);
27820
27921
  static setRootOutput(value) {
27821
27922
  SessionManager.setRootOutput(value);
27822
27923
  }
27823
- /**
27824
- * Run a function with the root span as the active parent context.
27825
- * All spans created within this function will be children of the root span.
27826
- * Note: required in JS because OTel JS has no persistent context.attach()
27827
- */
27828
- static runWithRootSpan(fn) {
27829
- if (!this._rootSpan) {
27830
- Logger.warn(
27831
- "runWithRootSpan: No root span available. Running function without parent context."
27832
- );
27833
- return fn();
27834
- }
27835
- return api.context.with(api.trace.setSpan(api.context.active(), this._rootSpan), fn);
27836
- }
27837
27924
  static setSessionId(sessionId) {
27838
27925
  if (typeof sessionId !== "string") {
27839
27926
  Logger.error(`setSessionId: sessionId must be a string, got ${typeof sessionId}`);