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.js CHANGED
@@ -579,7 +579,7 @@ var Usage = class {
579
579
  };
580
580
 
581
581
  // src/version.ts
582
- var SDK_VERSION = "1.6.0";
582
+ var SDK_VERSION = "1.8.0";
583
583
 
584
584
  // src/config.ts
585
585
  var NetraInstruments = /* @__PURE__ */ ((NetraInstruments2) => {
@@ -669,11 +669,6 @@ var _Config = class _Config {
669
669
  "NETRA_DEBUG",
670
670
  false
671
671
  );
672
- this.enableRootSpan = this._getBoolConfig(
673
- config.enableRootSpan,
674
- "NETRA_ENABLE_ROOT_SPAN",
675
- false
676
- );
677
672
  this.enableScrubbing = this._getBoolConfig(
678
673
  config.enableScrubbing,
679
674
  "NETRA_ENABLE_SCRUBBING",
@@ -823,6 +818,11 @@ _Config.SDK_NAME = "netra";
823
818
  _Config.LIBRARY_NAME = "netra";
824
819
  _Config.LIBRARY_VERSION = SDK_VERSION;
825
820
  _Config.TRIAL_BLOCK_DURATION_SECONDS = 900;
821
+ // 15 minutes
822
+ // Root-span attribute marking traces produced by evaluation/simulation runs
823
+ // so the FE/BE can distinguish them from normal workflow invocations.
824
+ _Config.TRACE_ORIGIN_KEY = "netra.trace.origin";
825
+ _Config.TRACE_ORIGIN_EVALUATION = "evaluation";
826
826
  var Config = _Config;
827
827
 
828
828
  // src/utils/pattern-matching.ts
@@ -1943,13 +1943,13 @@ async function runSingleEvaluator(params) {
1943
1943
  if (config) {
1944
1944
  expectedName = config.name;
1945
1945
  }
1946
- const context17 = {
1946
+ const context16 = {
1947
1947
  input: itemInput,
1948
1948
  taskOutput,
1949
1949
  expectedOutput,
1950
1950
  metadata
1951
1951
  };
1952
- let result = evaluator.evaluate(context17);
1952
+ let result = evaluator.evaluate(context16);
1953
1953
  if (result instanceof Promise) {
1954
1954
  result = await result;
1955
1955
  }
@@ -2293,7 +2293,11 @@ var Evaluation = class {
2293
2293
  */
2294
2294
  async executeItemPipeline(runId, runName, ctx, task2, evaluators, results, bgEvalTasks) {
2295
2295
  const spanName = `TestRun.${runName}`;
2296
- const span2 = new SpanWrapper(spanName, {}, "netra.evaluation");
2296
+ const span2 = new SpanWrapper(
2297
+ spanName,
2298
+ { [Config.TRACE_ORIGIN_KEY]: Config.TRACE_ORIGIN_EVALUATION },
2299
+ "netra.evaluation"
2300
+ );
2297
2301
  span2.start();
2298
2302
  try {
2299
2303
  const otelSpan = span2.getCurrentSpan();
@@ -2696,6 +2700,42 @@ var DashboardHttpClient = class extends NetraHttpClient {
2696
2700
  return null;
2697
2701
  }
2698
2702
  }
2703
+ /**
2704
+ * Get detailed information for a specific session including all its traces.
2705
+ *
2706
+ * Args:
2707
+ * sessionId: The session ID to retrieve details for.
2708
+ *
2709
+ * Returns:
2710
+ * The session details response data or null on error.
2711
+ */
2712
+ async getSessionDetails(sessionId) {
2713
+ if (!this.isInitialized()) {
2714
+ Logger.error(
2715
+ "netra.dashboard: Dashboard client is not initialized; cannot get session details"
2716
+ );
2717
+ return null;
2718
+ }
2719
+ try {
2720
+ const url = `/public/dashboard/session/${encodeURIComponent(sessionId)}`;
2721
+ const response = await this.get(url);
2722
+ if (!response.ok) {
2723
+ const errorMessage = response.data?.error?.message ?? "Unknown error";
2724
+ Logger.error(
2725
+ `netra.dashboard: Failed to fetch session details: ${errorMessage}`
2726
+ );
2727
+ return null;
2728
+ }
2729
+ return response.data;
2730
+ } catch (err) {
2731
+ const message = err?.response?.data?.error?.message ?? "";
2732
+ Logger.error(
2733
+ "netra.dashboard: Failed to fetch session details:",
2734
+ message
2735
+ );
2736
+ return null;
2737
+ }
2738
+ }
2699
2739
  };
2700
2740
 
2701
2741
  // src/api/dashboard/models.ts
@@ -2919,6 +2959,19 @@ var Dashboard = class {
2919
2959
  }
2920
2960
  return result.data ?? {};
2921
2961
  }
2962
+ async getSessionDetails(sessionId) {
2963
+ if (!sessionId) {
2964
+ Logger.error(
2965
+ "netra.dashboard: session_id is required to fetch session details"
2966
+ );
2967
+ return null;
2968
+ }
2969
+ const result = await this.client.getSessionDetails(sessionId);
2970
+ if (!result) {
2971
+ return null;
2972
+ }
2973
+ return result.data ?? result;
2974
+ }
2922
2975
  isValidScope(scope) {
2923
2976
  return Object.values(Scope).includes(scope);
2924
2977
  }
@@ -3834,6 +3887,13 @@ var SpanIOProcessor = class {
3834
3887
  if (key === _USAGE_OUTPUT_TOKENS) {
3835
3888
  return original(_USAGE_COMPLETION_TOKENS, value);
3836
3889
  }
3890
+ if (key === "db.statement") {
3891
+ original(key, value);
3892
+ if (!inputLocked() && inputIsEmpty() && !isEmpty(value)) {
3893
+ original("input", typeof value === "string" ? value : String(value));
3894
+ }
3895
+ return span2;
3896
+ }
3837
3897
  return original(key, value);
3838
3898
  } catch (e) {
3839
3899
  Logger.debug(`SpanIOProcessor: error processing key=${key}`, e);
@@ -4414,7 +4474,7 @@ function setUsageAttributes(span2, response) {
4414
4474
  Number(cacheReadTokens)
4415
4475
  );
4416
4476
  }
4417
- const cacheCreationTokens = usage.cache_creation_input_tokens;
4477
+ const cacheCreationTokens = usage.cache_creation_input_tokens ?? (usage.prompt_tokens_details ?? usage.input_tokens_details)?.cache_write_tokens;
4418
4478
  if (cacheCreationTokens !== void 0) {
4419
4479
  span2.setAttribute(
4420
4480
  SpanAttributes2.LLM_USAGE_CACHE_CREATION_INPUT_TOKENS,
@@ -12359,7 +12419,7 @@ var SimulationHttpClient = class {
12359
12419
  * Used in the two-phase flow so that beforeAll/before hooks can run
12360
12420
  * before any LLM spend.
12361
12421
  */
12362
- async initializeRun(name, datasetId, context17, hooksMeta) {
12422
+ async initializeRun(name, datasetId, context16, hooksMeta) {
12363
12423
  if (!this.client) {
12364
12424
  Logger.error(`${LOG_PREFIX5}: Client not initialized`);
12365
12425
  return null;
@@ -12369,7 +12429,7 @@ var SimulationHttpClient = class {
12369
12429
  const payload = {
12370
12430
  name,
12371
12431
  datasetId,
12372
- context: context17 || {}
12432
+ context: context16 || {}
12373
12433
  };
12374
12434
  if (hooksMeta) {
12375
12435
  payload.lifecycleHooks = hooksMeta;
@@ -12474,6 +12534,16 @@ var SimulationHttpClient = class {
12474
12534
  }
12475
12535
  /**
12476
12536
  * Report a task execution failure to the backend.
12537
+ *
12538
+ * @param runId - Identifier of the run.
12539
+ * @param runItemId - Identifier of the run item.
12540
+ * @param error - Error message describing the failure.
12541
+ * @param status - The run status to set on the item. Use `"prescript_failed"`
12542
+ * when the failure originated from a beforeAll or before hook, or
12543
+ * `"postscript_failed"` when an after/afterEach/afterAll hook failed on an
12544
+ * otherwise successful item. Callers must not overwrite an existing real
12545
+ * failure (e.g. `failed` / `prescript_failed`) with `postscript_failed`.
12546
+ * Defaults to `"failed"`.
12477
12547
  */
12478
12548
  async reportFailure(runId, runItemId, error, status = "failed") {
12479
12549
  if (!this.client) {
@@ -12636,14 +12706,7 @@ async function runAfter(hooks, datasetItemId, itemResult, setupContext) {
12636
12706
  Logger.info(
12637
12707
  `${LOG_PREFIX6}: running after hook for datasetItemId=${datasetItemId}`
12638
12708
  );
12639
- try {
12640
- await hooks.after[datasetItemId](itemResult, setupContext);
12641
- } catch (error) {
12642
- Logger.warn(
12643
- `${LOG_PREFIX6}: after hook raised an exception for datasetItemId=${datasetItemId} (ignored):`,
12644
- error
12645
- );
12646
- }
12709
+ await hooks.after[datasetItemId](itemResult, setupContext);
12647
12710
  }
12648
12711
  }
12649
12712
  async function runAfterEach(hooks, datasetItemId, itemResult, setupContext) {
@@ -12651,26 +12714,12 @@ async function runAfterEach(hooks, datasetItemId, itemResult, setupContext) {
12651
12714
  Logger.info(
12652
12715
  `${LOG_PREFIX6}: running afterEach hook for datasetItemId=${datasetItemId}`
12653
12716
  );
12654
- try {
12655
- await hooks.afterEach(itemResult, setupContext);
12656
- } catch (error) {
12657
- Logger.warn(
12658
- `${LOG_PREFIX6}: afterEach hook raised an exception for datasetItemId=${datasetItemId} (ignored):`,
12659
- error
12660
- );
12661
- }
12717
+ await hooks.afterEach(itemResult, setupContext);
12662
12718
  }
12663
12719
  async function runAfterAll(hooks, results, sharedContext) {
12664
12720
  if (!hooks?.afterAll) return;
12665
12721
  Logger.info(`${LOG_PREFIX6}: running afterAll hook`);
12666
- try {
12667
- await hooks.afterAll(results, sharedContext);
12668
- } catch (error) {
12669
- Logger.warn(
12670
- `${LOG_PREFIX6}: afterAll hook raised an exception (ignored):`,
12671
- error
12672
- );
12673
- }
12722
+ await hooks.afterAll(results, sharedContext);
12674
12723
  }
12675
12724
 
12676
12725
  // src/simulation/api.ts
@@ -12698,7 +12747,7 @@ var Simulation = class {
12698
12747
  name,
12699
12748
  datasetId,
12700
12749
  task: task2,
12701
- context: context17,
12750
+ context: context16,
12702
12751
  maxConcurrency = 5,
12703
12752
  hooks
12704
12753
  } = options;
@@ -12710,7 +12759,7 @@ var Simulation = class {
12710
12759
  const initResult = await this._client.initializeRun(
12711
12760
  name,
12712
12761
  datasetId,
12713
- context17,
12762
+ context16,
12714
12763
  hooksMeta && Object.keys(hooksMeta).length > 0 ? hooksMeta : null
12715
12764
  );
12716
12765
  if (!initResult) {
@@ -12761,14 +12810,13 @@ var Simulation = class {
12761
12810
  } catch (error) {
12762
12811
  const errorMsg = `beforeAll hook failed: ${error instanceof Error ? error.message : String(error)}`;
12763
12812
  Logger.error(`${LOG_PREFIX7}: ${errorMsg} \u2014 aborting run (no LLM spent)`);
12764
- for (const item of items) {
12765
- await this._client.reportFailure(
12766
- runId,
12767
- item.runItemId,
12768
- errorMsg,
12769
- "prescript_failed"
12770
- );
12771
- }
12813
+ await this._reportFailures(
12814
+ runId,
12815
+ items.map((item) => item.runItemId),
12816
+ errorMsg,
12817
+ "prescript_failed",
12818
+ maxConcurrency
12819
+ );
12772
12820
  const results = {
12773
12821
  success: false,
12774
12822
  completed: [],
@@ -12779,7 +12827,12 @@ var Simulation = class {
12779
12827
  })),
12780
12828
  totalItems: items.length
12781
12829
  };
12782
- await runAfterAll(hooks, results, null);
12830
+ try {
12831
+ await runAfterAll(hooks, results, null);
12832
+ } catch (afterAllError) {
12833
+ const afterAllMsg = `afterAll hook failed: ${afterAllError instanceof Error ? afterAllError.message : String(afterAllError)}`;
12834
+ Logger.error(`${LOG_PREFIX7}: ${afterAllMsg}`);
12835
+ }
12783
12836
  await this._client.postRunStatus(runId, "completed");
12784
12837
  return results;
12785
12838
  }
@@ -12809,8 +12862,7 @@ var Simulation = class {
12809
12862
  error: errorMsg
12810
12863
  };
12811
12864
  failedItems.push(itemResult);
12812
- await runAfter(hooks, datasetItemId, itemResult, setupContext);
12813
- await runAfterEach(hooks, datasetItemId, itemResult, setupContext);
12865
+ await this._runAfterHooks(runId, runItemId, datasetItemId, hooks, itemResult, setupContext);
12814
12866
  return;
12815
12867
  }
12816
12868
  } else {
@@ -12826,8 +12878,7 @@ var Simulation = class {
12826
12878
  error: "Failed to generate first user message"
12827
12879
  };
12828
12880
  failedItems.push(itemResult);
12829
- await runAfter(hooks, datasetItemId, itemResult, setupContexts.get(runItemId) ?? null);
12830
- await runAfterEach(hooks, datasetItemId, itemResult, setupContexts.get(runItemId) ?? null);
12881
+ await this._runAfterHooks(runId, runItemId, datasetItemId, hooks, itemResult, setupContexts.get(runItemId) ?? null);
12831
12882
  return;
12832
12883
  }
12833
12884
  simulationItems.push(simItem);
@@ -12842,7 +12893,12 @@ var Simulation = class {
12842
12893
  failed: failedItems,
12843
12894
  totalItems: items.length
12844
12895
  };
12845
- await runAfterAll(hooks, results, sharedContext);
12896
+ try {
12897
+ await runAfterAll(hooks, results, sharedContext);
12898
+ } catch (afterAllError) {
12899
+ const afterAllMsg = `afterAll hook failed: ${afterAllError instanceof Error ? afterAllError.message : String(afterAllError)}`;
12900
+ Logger.error(`${LOG_PREFIX7}: ${afterAllMsg}`);
12901
+ }
12846
12902
  await this._client.postRunStatus(runId, "completed");
12847
12903
  return results;
12848
12904
  }
@@ -12912,12 +12968,84 @@ var Simulation = class {
12912
12968
  );
12913
12969
  await Promise.all(promises);
12914
12970
  results.failed.push(...setupFailedItems);
12915
- await runAfterAll(hooks, results, sharedContext);
12971
+ try {
12972
+ await runAfterAll(hooks, results, sharedContext);
12973
+ } catch (error) {
12974
+ const errorMsg = `afterAll hook failed: ${error instanceof Error ? error.message : String(error)}`;
12975
+ Logger.error(`${LOG_PREFIX7}: ${errorMsg}`);
12976
+ const completed = results.completed;
12977
+ const successfulIds = completed.map((item) => item.runItemId);
12978
+ await this._reportFailures(
12979
+ runId,
12980
+ successfulIds,
12981
+ errorMsg,
12982
+ "postscript_failed",
12983
+ maxConcurrency
12984
+ );
12985
+ for (const item of completed) {
12986
+ item.success = false;
12987
+ item.error = errorMsg;
12988
+ item.status = "postscript_failed";
12989
+ }
12990
+ results.failed.push(...completed);
12991
+ results.completed = [];
12992
+ }
12993
+ results.success = results.failed.length === 0;
12916
12994
  Logger.info(
12917
12995
  `${LOG_PREFIX7}: Completed=${results.completed.length}, Failed=${results.failed.length}`
12918
12996
  );
12919
12997
  return results;
12920
12998
  }
12999
+ /**
13000
+ * Report failures for many items concurrently, capped like other paths.
13001
+ */
13002
+ async _reportFailures(runId, runItemIds, error, status, maxConcurrency = 5) {
13003
+ if (runItemIds.length === 0) {
13004
+ return;
13005
+ }
13006
+ const limit = pLimit2(Math.min(5, maxConcurrency));
13007
+ await Promise.all(
13008
+ runItemIds.map(
13009
+ (runItemId) => limit(() => this._client.reportFailure(runId, runItemId, error, status))
13010
+ )
13011
+ );
13012
+ }
13013
+ /**
13014
+ * Run after/afterEach hooks independently.
13015
+ *
13016
+ * Both hooks always attempt to run. `postscript_failed` is reported only
13017
+ * when the item otherwise succeeded — an existing failure status/reason is
13018
+ * never overwritten.
13019
+ */
13020
+ async _runAfterHooks(runId, runItemId, datasetItemId, hooks, itemResult, setupContext) {
13021
+ const errors = [];
13022
+ try {
13023
+ await runAfter(hooks, datasetItemId, itemResult, setupContext);
13024
+ } catch (error) {
13025
+ const errorMsg = `after hook failed: ${error instanceof Error ? error.message : String(error)}`;
13026
+ Logger.error(`${LOG_PREFIX7}: ${errorMsg} for runItemId=${runItemId}`);
13027
+ errors.push(errorMsg);
13028
+ }
13029
+ try {
13030
+ await runAfterEach(hooks, datasetItemId, itemResult, setupContext);
13031
+ } catch (error) {
13032
+ const errorMsg = `afterEach hook failed: ${error instanceof Error ? error.message : String(error)}`;
13033
+ Logger.error(`${LOG_PREFIX7}: ${errorMsg} for runItemId=${runItemId}`);
13034
+ errors.push(errorMsg);
13035
+ }
13036
+ if (errors.length > 0 && itemResult.success) {
13037
+ const error = errors.join("; ");
13038
+ await this._client.reportFailure(
13039
+ runId,
13040
+ runItemId,
13041
+ error,
13042
+ "postscript_failed"
13043
+ );
13044
+ itemResult.success = false;
13045
+ itemResult.error = error;
13046
+ itemResult.status = "postscript_failed";
13047
+ }
13048
+ }
12921
13049
  /**
12922
13050
  * Execute a multi-turn conversation for a single simulation item.
12923
13051
  *
@@ -12932,7 +13060,11 @@ var Simulation = class {
12932
13060
  let sessionId = null;
12933
13061
  let rawFiles = initialFiles ?? [];
12934
13062
  while (true) {
12935
- const span2 = new SpanWrapper(SPAN_NAME, {}, LOG_PREFIX7);
13063
+ const span2 = new SpanWrapper(
13064
+ SPAN_NAME,
13065
+ { [Config.TRACE_ORIGIN_KEY]: Config.TRACE_ORIGIN_EVALUATION },
13066
+ LOG_PREFIX7
13067
+ );
12936
13068
  span2.start();
12937
13069
  try {
12938
13070
  const traceId = span2.getCurrentSpan()?.spanContext().traceId ?? "";
@@ -12957,8 +13089,7 @@ var Simulation = class {
12957
13089
  error: "Failed to get conversation response",
12958
13090
  turnId
12959
13091
  };
12960
- await runAfter(hooks, datasetItemId, itemResult, setupContext);
12961
- await runAfterEach(hooks, datasetItemId, itemResult, setupContext);
13092
+ await this._runAfterHooks(runId, runItemId, datasetItemId, hooks, itemResult, setupContext);
12962
13093
  return itemResult;
12963
13094
  }
12964
13095
  if (response.decision === "stop") {
@@ -12970,8 +13101,7 @@ var Simulation = class {
12970
13101
  success: true,
12971
13102
  finalTurnId: turnId
12972
13103
  };
12973
- await runAfter(hooks, datasetItemId, itemResult, setupContext);
12974
- await runAfterEach(hooks, datasetItemId, itemResult, setupContext);
13104
+ await this._runAfterHooks(runId, runItemId, datasetItemId, hooks, itemResult, setupContext);
12975
13105
  return itemResult;
12976
13106
  }
12977
13107
  message = response.nextUserMessage;
@@ -12989,8 +13119,7 @@ var Simulation = class {
12989
13119
  error: errorMsg,
12990
13120
  turnId
12991
13121
  };
12992
- await runAfter(hooks, datasetItemId, itemResult, setupContext);
12993
- await runAfterEach(hooks, datasetItemId, itemResult, setupContext);
13122
+ await this._runAfterHooks(runId, runItemId, datasetItemId, hooks, itemResult, setupContext);
12994
13123
  return itemResult;
12995
13124
  } finally {
12996
13125
  span2.end();
@@ -13275,26 +13404,6 @@ Received ${signal}. Shutting down Netra SDK...`);
13275
13404
  process.once("SIGINT", () => handleSignal("SIGINT"));
13276
13405
  process.once("SIGTERM", () => handleSignal("SIGTERM"));
13277
13406
  process.once("uncaughtException", handleUncaughtException);
13278
- if (cfg.enableRootSpan) {
13279
- const tracer2 = this._tracer || trace.getTracer("netra.root.span");
13280
- const rootName = `${Config.LIBRARY_NAME}.root.span`;
13281
- this._rootSpan = tracer2.startSpan(rootName, {
13282
- kind: SpanKind.INTERNAL
13283
- });
13284
- if (this._rootSpan) {
13285
- if (cfg.appName) {
13286
- this._rootSpan.setAttribute("service.name", cfg.appName);
13287
- }
13288
- this._rootSpan.setAttribute("netra.environment", cfg.environment);
13289
- this._rootSpan.setAttribute(
13290
- "netra.library.version",
13291
- Config.LIBRARY_VERSION
13292
- );
13293
- Logger.info(
13294
- "Netra root span created. Use Netra.runWithRootSpan() to parent spans under it."
13295
- );
13296
- }
13297
- }
13298
13407
  await instrumentationsReady;
13299
13408
  }
13300
13409
  static async shutdown() {
@@ -13306,14 +13415,6 @@ Received ${signal}. Shutting down Netra SDK...`);
13306
13415
  } catch (e) {
13307
13416
  Logger.error("Error during uninstrumentAll:", e);
13308
13417
  }
13309
- if (this._rootSpan) {
13310
- try {
13311
- this._rootSpan.end();
13312
- } catch (e) {
13313
- } finally {
13314
- this._rootSpan = void 0;
13315
- }
13316
- }
13317
13418
  const FLUSH_TIMEOUT_MS = 5e3;
13318
13419
  try {
13319
13420
  const traceProvider = trace.getTracerProvider();
@@ -13350,20 +13451,6 @@ Received ${signal}. Shutting down Netra SDK...`);
13350
13451
  static setRootOutput(value) {
13351
13452
  SessionManager.setRootOutput(value);
13352
13453
  }
13353
- /**
13354
- * Run a function with the root span as the active parent context.
13355
- * All spans created within this function will be children of the root span.
13356
- * Note: required in JS because OTel JS has no persistent context.attach()
13357
- */
13358
- static runWithRootSpan(fn) {
13359
- if (!this._rootSpan) {
13360
- Logger.warn(
13361
- "runWithRootSpan: No root span available. Running function without parent context."
13362
- );
13363
- return fn();
13364
- }
13365
- return context.with(trace.setSpan(context.active(), this._rootSpan), fn);
13366
- }
13367
13454
  static setSessionId(sessionId) {
13368
13455
  if (typeof sessionId !== "string") {
13369
13456
  Logger.error(`setSessionId: sessionId must be a string, got ${typeof sessionId}`);