netra-sdk 1.6.0 → 1.8.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
@@ -15,7 +15,7 @@ var core = require('@opentelemetry/core');
15
15
  var http = require('http');
16
16
  var https = require('https');
17
17
  var otlpTransformer = require('@opentelemetry/otlp-transformer');
18
- var pLimit = require('p-limit');
18
+ var pLimit2 = require('p-limit');
19
19
  var axios = require('axios');
20
20
 
21
21
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
@@ -43,7 +43,7 @@ var crypto__default = /*#__PURE__*/_interopDefault(crypto);
43
43
  var shimmer__default = /*#__PURE__*/_interopDefault(shimmer);
44
44
  var http__namespace = /*#__PURE__*/_interopNamespace(http);
45
45
  var https__namespace = /*#__PURE__*/_interopNamespace(https);
46
- var pLimit__default = /*#__PURE__*/_interopDefault(pLimit);
46
+ var pLimit2__default = /*#__PURE__*/_interopDefault(pLimit2);
47
47
  var axios__default = /*#__PURE__*/_interopDefault(axios);
48
48
 
49
49
  var __create = Object.create;
@@ -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) => {
@@ -26721,7 +26721,7 @@ async function processFiles(files) {
26721
26721
  return null;
26722
26722
  }
26723
26723
  const timeoutMs = _getFileDownloadTimeout();
26724
- const limit = pLimit__default.default(MAX_FILE_DOWNLOAD_WORKERS);
26724
+ const limit = pLimit2__default.default(MAX_FILE_DOWNLOAD_WORKERS);
26725
26725
  const controller = new AbortController();
26726
26726
  const downloadPromises = files.map(
26727
26727
  (file) => limit(() => _downloadSingleFile(file, timeoutMs, controller.signal))
@@ -26734,9 +26734,9 @@ async function processFiles(files) {
26734
26734
  throw error;
26735
26735
  }
26736
26736
  }
26737
- async function executeTask2(task2, message, sessionId, rawFiles) {
26737
+ async function executeTask2(task2, message, sessionId, rawFiles, setupContext) {
26738
26738
  const processedFiles = rawFiles && rawFiles.length > 0 ? await processFiles(rawFiles) : null;
26739
- const result = task2.run(message, sessionId, processedFiles);
26739
+ const result = task2.run(message, sessionId, processedFiles, setupContext);
26740
26740
  const resolvedResult = result instanceof Promise ? await result : result;
26741
26741
  if (typeof resolvedResult === "object" && resolvedResult !== null && "message" in resolvedResult && "sessionId" in resolvedResult) {
26742
26742
  return [resolvedResult.message, resolvedResult.sessionId];
@@ -26824,44 +26824,76 @@ var SimulationHttpClient = class {
26824
26824
  return timeout * 1e3;
26825
26825
  }
26826
26826
  /**
26827
- * Create a new simulation run for the specified dataset.
26827
+ * Initialize a simulation run without generating first user messages.
26828
+ *
26829
+ * Used in the two-phase flow so that beforeAll/before hooks can run
26830
+ * before any LLM spend.
26828
26831
  */
26829
- async createRun(name, datasetId, context18) {
26832
+ async initializeRun(name, datasetId, context18, hooksMeta) {
26830
26833
  if (!this.client) {
26831
26834
  Logger.error(`${LOG_PREFIX5}: Client not initialized`);
26832
26835
  return null;
26833
26836
  }
26834
26837
  try {
26835
- const url = "/evaluations/test_run/multi-turn";
26838
+ const url = "/evaluations/test_run/multi-turn/initialize";
26836
26839
  const payload = {
26837
26840
  name,
26838
26841
  datasetId,
26839
26842
  context: context18 || {}
26840
26843
  };
26844
+ if (hooksMeta) {
26845
+ payload.lifecycleHooks = hooksMeta;
26846
+ }
26841
26847
  const response = await this.client.post(url, payload);
26842
26848
  const data = response.data;
26843
26849
  const responseData = data.data || {};
26844
- const userMessages = responseData.userMessages || [];
26845
- if (userMessages.length === 0) {
26846
- Logger.warn(`${LOG_PREFIX5}: No user messages returned from create_run`);
26850
+ const items = responseData.items || [];
26851
+ if (items.length === 0) {
26852
+ Logger.warn(`${LOG_PREFIX5}: No items returned from initialize_run`);
26847
26853
  return null;
26848
26854
  }
26849
26855
  const runId = responseData.id || "";
26850
- const simulationItems = userMessages.map(
26851
- (msg) => ({
26852
- runItemId: msg.testRunItemId || "",
26853
- message: msg.userMessage || "",
26854
- turnId: msg.turnId || "",
26855
- files: parseFiles(msg.attachments)
26856
- })
26857
- );
26858
26856
  return {
26859
26857
  runId,
26860
- simulationItems
26858
+ items: items.map((item) => ({
26859
+ runItemId: item.testRunItemId || "",
26860
+ datasetItemId: item.datasetItemId || ""
26861
+ }))
26862
+ };
26863
+ } catch (error) {
26864
+ const errorMsg = this._extractErrorMessage(error);
26865
+ Logger.error(`${LOG_PREFIX5}: Failed to initialize run:`, errorMsg);
26866
+ return null;
26867
+ }
26868
+ }
26869
+ /**
26870
+ * Generate the first user message for a single test run item.
26871
+ *
26872
+ * Used in the two-phase flow after hooks have been executed.
26873
+ */
26874
+ async generateFirstTurn(runId, runItemId) {
26875
+ if (!this.client) {
26876
+ Logger.error(`${LOG_PREFIX5}: Client not initialized`);
26877
+ return null;
26878
+ }
26879
+ try {
26880
+ const url = `/evaluations/run/${runId}/item/${runItemId}/first-turn`;
26881
+ const response = await this.client.post(url, {});
26882
+ const data = response.data;
26883
+ const responseData = data.data || {};
26884
+ return {
26885
+ runItemId,
26886
+ datasetItemId: responseData.datasetItemId || "",
26887
+ message: responseData.userMessage || "",
26888
+ turnId: responseData.turnId || "",
26889
+ files: parseFiles(responseData.attachments)
26861
26890
  };
26862
26891
  } catch (error) {
26863
26892
  const errorMsg = this._extractErrorMessage(error);
26864
- Logger.error(`${LOG_PREFIX5}: Failed to create simulation run:`, errorMsg);
26893
+ Logger.error(
26894
+ `${LOG_PREFIX5}: Failed to generate first turn for item ${runItemId}:`,
26895
+ errorMsg
26896
+ );
26865
26897
  return null;
26866
26898
  }
26867
26899
  }
@@ -26912,15 +26944,25 @@ var SimulationHttpClient = class {
26912
26944
  }
26913
26945
  /**
26914
26946
  * Report a task execution failure to the backend.
26947
+ *
26948
+ * @param runId - Identifier of the run.
26949
+ * @param runItemId - Identifier of the run item.
26950
+ * @param error - Error message describing the failure.
26951
+ * @param status - The run status to set on the item. Use `"prescript_failed"`
26952
+ * when the failure originated from a beforeAll or before hook, or
26953
+ * `"postscript_failed"` when an after/afterEach/afterAll hook failed on an
26954
+ * otherwise successful item. Callers must not overwrite an existing real
26955
+ * failure (e.g. `failed` / `prescript_failed`) with `postscript_failed`.
26956
+ * Defaults to `"failed"`.
26915
26957
  */
26916
- async reportFailure(runId, runItemId, error) {
26958
+ async reportFailure(runId, runItemId, error, status = "failed") {
26917
26959
  if (!this.client) {
26918
26960
  Logger.error(`${LOG_PREFIX5}: Client not initialized`);
26919
26961
  return;
26920
26962
  }
26921
26963
  try {
26922
26964
  const url = `/evaluations/run/${runId}/item/${runItemId}/status`;
26923
- const payload = { status: "failed", failureReason: error };
26965
+ const payload = { status, failureReason: error };
26924
26966
  await this.client.patch(url, payload);
26925
26967
  Logger.info(`${LOG_PREFIX5}: Reported failure - ${error}`);
26926
26968
  } catch (err) {
@@ -26975,8 +27017,123 @@ var SimulationHttpClient = class {
26975
27017
  }
26976
27018
  };
26977
27019
 
26978
- // src/simulation/api.ts
27020
+ // src/simulation/hooks.ts
26979
27021
  var LOG_PREFIX6 = "netra.simulation";
27022
+ function describeHooks(hooks) {
27023
+ const descFn = (fn) => {
27024
+ if (!fn) return null;
27025
+ const description = typeof fn.description === "string" ? String(fn.description).slice(0, 200) : null;
27026
+ return {
27027
+ configured: true,
27028
+ name: fn.name || null,
27029
+ description
27030
+ };
27031
+ };
27032
+ const payload = {};
27033
+ const beforeAllDesc = descFn(hooks.beforeAll);
27034
+ const beforeEachDesc = descFn(hooks.beforeEach);
27035
+ const afterEachDesc = descFn(hooks.afterEach);
27036
+ const afterAllDesc = descFn(hooks.afterAll);
27037
+ if (beforeAllDesc) payload.beforeAll = beforeAllDesc;
27038
+ if (beforeEachDesc) payload.beforeEach = beforeEachDesc;
27039
+ if (afterEachDesc) payload.afterEach = afterEachDesc;
27040
+ if (afterAllDesc) payload.afterAll = afterAllDesc;
27041
+ const itemIds = /* @__PURE__ */ new Set([
27042
+ ...Object.keys(hooks.before || {}),
27043
+ ...Object.keys(hooks.after || {})
27044
+ ]);
27045
+ if (itemIds.size > 0) {
27046
+ const items = [];
27047
+ for (const itemId of itemIds) {
27048
+ const entry = { datasetItemId: itemId };
27049
+ const beforeDesc = descFn(hooks.before?.[itemId]);
27050
+ const afterDesc = descFn(hooks.after?.[itemId]);
27051
+ if (beforeDesc) entry.before = beforeDesc;
27052
+ if (afterDesc) entry.after = afterDesc;
27053
+ if (entry.before || entry.after) {
27054
+ items.push(entry);
27055
+ }
27056
+ }
27057
+ if (items.length > 0) {
27058
+ payload.items = items;
27059
+ }
27060
+ }
27061
+ return payload;
27062
+ }
27063
+ async function runBeforeAll(hooks) {
27064
+ if (!hooks?.beforeAll) return null;
27065
+ Logger.info(`${LOG_PREFIX6}: running beforeAll hook`);
27066
+ const result = await hooks.beforeAll();
27067
+ if (result !== null && result !== void 0 && typeof result !== "object") {
27068
+ Logger.warn(
27069
+ `${LOG_PREFIX6}: beforeAll returned ${typeof result} (expected object or null); ignoring value`
27070
+ );
27071
+ return null;
27072
+ }
27073
+ return result ?? null;
27074
+ }
27075
+ async function runBefore(hooks, datasetItemId, sharedContext) {
27076
+ if (hooks?.before && datasetItemId in hooks.before) {
27077
+ Logger.info(
27078
+ `${LOG_PREFIX6}: running before hook for datasetItemId=${datasetItemId}`
27079
+ );
27080
+ const itemHook = hooks.before[datasetItemId];
27081
+ const result = await itemHook(sharedContext);
27082
+ const base = { ...sharedContext || {} };
27083
+ if (result !== null && result !== void 0) {
27084
+ if (typeof result === "object") {
27085
+ Object.assign(base, result);
27086
+ } else {
27087
+ Logger.warn(
27088
+ `${LOG_PREFIX6}: before hook returned ${typeof result} (expected object or null); ignoring value`
27089
+ );
27090
+ }
27091
+ }
27092
+ return Object.keys(base).length > 0 ? base : null;
27093
+ }
27094
+ return sharedContext;
27095
+ }
27096
+ async function runBeforeEach(hooks, datasetItemId, sharedContext) {
27097
+ if (!hooks?.beforeEach) return sharedContext;
27098
+ Logger.info(
27099
+ `${LOG_PREFIX6}: running beforeEach hook for datasetItemId=${datasetItemId}`
27100
+ );
27101
+ const result = await hooks.beforeEach(sharedContext);
27102
+ const base = { ...sharedContext || {} };
27103
+ if (result !== null && result !== void 0) {
27104
+ if (typeof result === "object") {
27105
+ Object.assign(base, result);
27106
+ } else {
27107
+ Logger.warn(
27108
+ `${LOG_PREFIX6}: beforeEach hook returned ${typeof result} (expected object or null); ignoring value`
27109
+ );
27110
+ }
27111
+ }
27112
+ return Object.keys(base).length > 0 ? base : null;
27113
+ }
27114
+ async function runAfter(hooks, datasetItemId, itemResult, setupContext) {
27115
+ if (hooks?.after && datasetItemId in hooks.after) {
27116
+ Logger.info(
27117
+ `${LOG_PREFIX6}: running after hook for datasetItemId=${datasetItemId}`
27118
+ );
27119
+ await hooks.after[datasetItemId](itemResult, setupContext);
27120
+ }
27121
+ }
27122
+ async function runAfterEach(hooks, datasetItemId, itemResult, setupContext) {
27123
+ if (!hooks?.afterEach) return;
27124
+ Logger.info(
27125
+ `${LOG_PREFIX6}: running afterEach hook for datasetItemId=${datasetItemId}`
27126
+ );
27127
+ await hooks.afterEach(itemResult, setupContext);
27128
+ }
27129
+ async function runAfterAll(hooks, results, sharedContext) {
27130
+ if (!hooks?.afterAll) return;
27131
+ Logger.info(`${LOG_PREFIX6}: running afterAll hook`);
27132
+ await hooks.afterAll(results, sharedContext);
27133
+ }
27134
+
27135
+ // src/simulation/api.ts
27136
+ var LOG_PREFIX7 = "netra.simulation";
26980
27137
  var SPAN_NAME = "Netra.Simulation.TestRun";
26981
27138
  var Simulation = class {
26982
27139
  constructor(config) {
@@ -26986,6 +27143,12 @@ var Simulation = class {
26986
27143
  /**
26987
27144
  * Run a multi-turn conversation simulation.
26988
27145
  *
27146
+ * Uses the two-phase API flow:
27147
+ * 1. initializeRun (no LLM cost) — with optional lifecycle hooks metadata
27148
+ * 2. beforeAll hook (if configured)
27149
+ * 3. Per-item: before hook -> generateFirstTurn -> conversation loop -> after hook
27150
+ * 4. afterAll hook (if configured)
27151
+ *
26989
27152
  * @param options - Simulation configuration options
26990
27153
  * @returns Dictionary with simulation results, or null on failure
26991
27154
  */
@@ -26995,19 +27158,26 @@ var Simulation = class {
26995
27158
  datasetId,
26996
27159
  task: task2,
26997
27160
  context: context18,
26998
- maxConcurrency = 5
27161
+ maxConcurrency = 5,
27162
+ hooks
26999
27163
  } = options;
27000
27164
  if (!validateSimulationInputs(datasetId, task2)) {
27001
27165
  return null;
27002
27166
  }
27003
27167
  const startTime = Date.now();
27004
- const runResult = await this._client.createRun(name, datasetId, context18);
27005
- if (!runResult) {
27168
+ const hooksMeta = hooks ? describeHooks(hooks) : null;
27169
+ const initResult = await this._client.initializeRun(
27170
+ name,
27171
+ datasetId,
27172
+ context18,
27173
+ hooksMeta && Object.keys(hooksMeta).length > 0 ? hooksMeta : null
27174
+ );
27175
+ if (!initResult) {
27006
27176
  return null;
27007
27177
  }
27008
- const { runId, simulationItems } = runResult;
27009
- if (!simulationItems || simulationItems.length === 0) {
27010
- Logger.error(`${LOG_PREFIX6}: No items returned from create_run`);
27178
+ const { runId, items } = initResult;
27179
+ if (!items || items.length === 0) {
27180
+ Logger.error(`${LOG_PREFIX7}: No items returned from initialize_run`);
27011
27181
  return null;
27012
27182
  }
27013
27183
  let interrupted = false;
@@ -27042,25 +27212,127 @@ var Simulation = class {
27042
27212
  proc.once("uncaughtException", handleException);
27043
27213
  proc.once("unhandledRejection", handleRejection);
27044
27214
  }
27045
- Logger.info(
27046
- `${LOG_PREFIX6}: Starting simulation with ${simulationItems.length} items`
27047
- );
27048
27215
  try {
27049
- const result = await this._runSimulationAsync(
27050
- runId,
27051
- simulationItems,
27052
- task2,
27053
- maxConcurrency
27054
- );
27055
- const elapsedTime = ((Date.now() - startTime) / 1e3).toFixed(2);
27056
- Logger.info(
27057
- `${LOG_PREFIX6}: Simulation completed in ${elapsedTime} seconds`
27216
+ let sharedContext = null;
27217
+ if (hooks?.beforeAll) {
27218
+ try {
27219
+ sharedContext = await runBeforeAll(hooks);
27220
+ } catch (error) {
27221
+ const errorMsg = `beforeAll hook failed: ${error instanceof Error ? error.message : String(error)}`;
27222
+ Logger.error(`${LOG_PREFIX7}: ${errorMsg} \u2014 aborting run (no LLM spent)`);
27223
+ await this._reportFailures(
27224
+ runId,
27225
+ items.map((item) => item.runItemId),
27226
+ errorMsg,
27227
+ "prescript_failed",
27228
+ maxConcurrency
27229
+ );
27230
+ const results = {
27231
+ success: false,
27232
+ completed: [],
27233
+ failed: items.map((item) => ({
27234
+ runItemId: item.runItemId,
27235
+ success: false,
27236
+ error: errorMsg
27237
+ })),
27238
+ totalItems: items.length
27239
+ };
27240
+ try {
27241
+ await runAfterAll(hooks, results, null);
27242
+ } catch (afterAllError) {
27243
+ const afterAllMsg = `afterAll hook failed: ${afterAllError instanceof Error ? afterAllError.message : String(afterAllError)}`;
27244
+ Logger.error(`${LOG_PREFIX7}: ${afterAllMsg}`);
27245
+ }
27246
+ await this._client.postRunStatus(runId, "completed");
27247
+ return results;
27248
+ }
27249
+ }
27250
+ const setupContexts = /* @__PURE__ */ new Map();
27251
+ const simulationItems = [];
27252
+ const failedItems = [];
27253
+ const limit = pLimit2__default.default(Math.min(5, maxConcurrency));
27254
+ const setupPromises = items.map(
27255
+ (item) => limit(async () => {
27256
+ const { runItemId, datasetItemId } = item;
27257
+ const hasBeforeHook = hooks?.before && datasetItemId in hooks.before;
27258
+ const hasBeforeEachHook = !!hooks?.beforeEach;
27259
+ let setupContext = sharedContext;
27260
+ if (hasBeforeEachHook || hasBeforeHook) {
27261
+ try {
27262
+ setupContext = await runBeforeEach(hooks, datasetItemId, setupContext);
27263
+ setupContext = await runBefore(hooks, datasetItemId, setupContext);
27264
+ setupContexts.set(runItemId, setupContext);
27265
+ } catch (error) {
27266
+ const errorMsg = `before hook failed: ${error instanceof Error ? error.message : String(error)}`;
27267
+ Logger.error(`${LOG_PREFIX7}: ${errorMsg} for runItemId=${runItemId}`);
27268
+ await this._client.reportFailure(runId, runItemId, errorMsg, "prescript_failed");
27269
+ const itemResult = {
27270
+ runItemId,
27271
+ success: false,
27272
+ error: errorMsg
27273
+ };
27274
+ failedItems.push(itemResult);
27275
+ await this._runAfterHooks(runId, runItemId, datasetItemId, hooks, itemResult, setupContext);
27276
+ return;
27277
+ }
27278
+ } else {
27279
+ setupContexts.set(runItemId, setupContext);
27280
+ }
27281
+ const simItem = await this._client.generateFirstTurn(runId, runItemId);
27282
+ if (!simItem) {
27283
+ Logger.warn(`${LOG_PREFIX7}: Failed to generate first turn for item ${runItemId}, marking failed`);
27284
+ await this._client.reportFailure(runId, runItemId, "Failed to generate first user message");
27285
+ const itemResult = {
27286
+ runItemId,
27287
+ success: false,
27288
+ error: "Failed to generate first user message"
27289
+ };
27290
+ failedItems.push(itemResult);
27291
+ await this._runAfterHooks(runId, runItemId, datasetItemId, hooks, itemResult, setupContexts.get(runItemId) ?? null);
27292
+ return;
27293
+ }
27294
+ simulationItems.push(simItem);
27295
+ })
27058
27296
  );
27059
- return result;
27060
- } catch (error) {
27061
- Logger.error(`${LOG_PREFIX6}: Run simulation failed`);
27062
- await this._client.postRunStatus(runId, "failed");
27063
- throw error;
27297
+ await Promise.all(setupPromises);
27298
+ if (simulationItems.length === 0) {
27299
+ Logger.error(`${LOG_PREFIX7}: All items failed during setup/generation`);
27300
+ const results = {
27301
+ success: false,
27302
+ completed: [],
27303
+ failed: failedItems,
27304
+ totalItems: items.length
27305
+ };
27306
+ try {
27307
+ await runAfterAll(hooks, results, sharedContext);
27308
+ } catch (afterAllError) {
27309
+ const afterAllMsg = `afterAll hook failed: ${afterAllError instanceof Error ? afterAllError.message : String(afterAllError)}`;
27310
+ Logger.error(`${LOG_PREFIX7}: ${afterAllMsg}`);
27311
+ }
27312
+ await this._client.postRunStatus(runId, "completed");
27313
+ return results;
27314
+ }
27315
+ Logger.info(`${LOG_PREFIX7}: Starting simulation with ${simulationItems.length} items`);
27316
+ try {
27317
+ const result = await this._runSimulationAsync(
27318
+ runId,
27319
+ simulationItems,
27320
+ task2,
27321
+ maxConcurrency,
27322
+ hooks,
27323
+ sharedContext,
27324
+ setupContexts,
27325
+ failedItems
27326
+ );
27327
+ const elapsedTime = ((Date.now() - startTime) / 1e3).toFixed(2);
27328
+ Logger.info(`${LOG_PREFIX7}: Simulation completed in ${elapsedTime} seconds`);
27329
+ await this._client.postRunStatus(runId, "completed");
27330
+ return result;
27331
+ } catch (error) {
27332
+ Logger.error(`${LOG_PREFIX7}: Run simulation failed`);
27333
+ await this._client.postRunStatus(runId, "failed");
27334
+ throw error;
27335
+ }
27064
27336
  } finally {
27065
27337
  if (proc && typeof proc.removeListener === "function") {
27066
27338
  proc.removeListener("SIGINT", handleSignal);
@@ -27071,20 +27343,27 @@ var Simulation = class {
27071
27343
  }
27072
27344
  }
27073
27345
  /**
27074
- * Async implementation of run_simulation with concurrency control.
27346
+ * Orchestrate concurrent simulation execution with hooks support.
27075
27347
  */
27076
- async _runSimulationAsync(runId, runItems, task2, maxConcurrency) {
27348
+ async _runSimulationAsync(runId, runItems, task2, maxConcurrency, hooks, sharedContext, setupContexts, setupFailedItems) {
27077
27349
  const results = {
27078
27350
  success: true,
27079
27351
  completed: [],
27080
27352
  failed: [],
27081
- totalItems: runItems.length
27353
+ totalItems: runItems.length + setupFailedItems.length
27082
27354
  };
27083
27355
  let processedCount = 0;
27084
- const limit = pLimit__default.default(Math.min(5, maxConcurrency));
27356
+ const limit = pLimit2__default.default(Math.min(5, maxConcurrency));
27085
27357
  const promises = runItems.map(
27086
27358
  (runItem) => limit(async () => {
27087
- const result = await this._executeConversation(runId, runItem, task2);
27359
+ const setupContext = setupContexts.get(runItem.runItemId) ?? null;
27360
+ const result = await this._executeConversation(
27361
+ runId,
27362
+ runItem,
27363
+ task2,
27364
+ hooks,
27365
+ setupContext
27366
+ );
27088
27367
  if (result.success) {
27089
27368
  results.completed.push(result);
27090
27369
  } else {
@@ -27092,34 +27371,111 @@ var Simulation = class {
27092
27371
  }
27093
27372
  processedCount++;
27094
27373
  Logger.info(
27095
- `${LOG_PREFIX6}: ${processedCount}/${runItems.length} processed (run_item_id=${runItem.runItemId})`
27374
+ `${LOG_PREFIX7}: ${processedCount}/${runItems.length} processed (run_item_id=${runItem.runItemId})`
27096
27375
  );
27097
27376
  return result;
27098
27377
  })
27099
27378
  );
27100
27379
  await Promise.all(promises);
27380
+ results.failed.push(...setupFailedItems);
27381
+ try {
27382
+ await runAfterAll(hooks, results, sharedContext);
27383
+ } catch (error) {
27384
+ const errorMsg = `afterAll hook failed: ${error instanceof Error ? error.message : String(error)}`;
27385
+ Logger.error(`${LOG_PREFIX7}: ${errorMsg}`);
27386
+ const completed = results.completed;
27387
+ const successfulIds = completed.map((item) => item.runItemId);
27388
+ await this._reportFailures(
27389
+ runId,
27390
+ successfulIds,
27391
+ errorMsg,
27392
+ "postscript_failed",
27393
+ maxConcurrency
27394
+ );
27395
+ for (const item of completed) {
27396
+ item.success = false;
27397
+ item.error = errorMsg;
27398
+ item.status = "postscript_failed";
27399
+ }
27400
+ results.failed.push(...completed);
27401
+ results.completed = [];
27402
+ }
27403
+ results.success = results.failed.length === 0;
27101
27404
  Logger.info(
27102
- `${LOG_PREFIX6}: Completed=${results.completed.length}, Failed=${results.failed.length}`
27405
+ `${LOG_PREFIX7}: Completed=${results.completed.length}, Failed=${results.failed.length}`
27103
27406
  );
27104
- await this._client.postRunStatus(runId, "completed");
27105
27407
  return results;
27106
27408
  }
27409
+ /**
27410
+ * Report failures for many items concurrently, capped like other paths.
27411
+ */
27412
+ async _reportFailures(runId, runItemIds, error, status, maxConcurrency = 5) {
27413
+ if (runItemIds.length === 0) {
27414
+ return;
27415
+ }
27416
+ const limit = pLimit2__default.default(Math.min(5, maxConcurrency));
27417
+ await Promise.all(
27418
+ runItemIds.map(
27419
+ (runItemId) => limit(() => this._client.reportFailure(runId, runItemId, error, status))
27420
+ )
27421
+ );
27422
+ }
27423
+ /**
27424
+ * Run after/afterEach hooks independently.
27425
+ *
27426
+ * Both hooks always attempt to run. `postscript_failed` is reported only
27427
+ * when the item otherwise succeeded — an existing failure status/reason is
27428
+ * never overwritten.
27429
+ */
27430
+ async _runAfterHooks(runId, runItemId, datasetItemId, hooks, itemResult, setupContext) {
27431
+ const errors = [];
27432
+ try {
27433
+ await runAfter(hooks, datasetItemId, itemResult, setupContext);
27434
+ } catch (error) {
27435
+ const errorMsg = `after hook failed: ${error instanceof Error ? error.message : String(error)}`;
27436
+ Logger.error(`${LOG_PREFIX7}: ${errorMsg} for runItemId=${runItemId}`);
27437
+ errors.push(errorMsg);
27438
+ }
27439
+ try {
27440
+ await runAfterEach(hooks, datasetItemId, itemResult, setupContext);
27441
+ } catch (error) {
27442
+ const errorMsg = `afterEach hook failed: ${error instanceof Error ? error.message : String(error)}`;
27443
+ Logger.error(`${LOG_PREFIX7}: ${errorMsg} for runItemId=${runItemId}`);
27444
+ errors.push(errorMsg);
27445
+ }
27446
+ if (errors.length > 0 && itemResult.success) {
27447
+ const error = errors.join("; ");
27448
+ await this._client.reportFailure(
27449
+ runId,
27450
+ runItemId,
27451
+ error,
27452
+ "postscript_failed"
27453
+ );
27454
+ itemResult.success = false;
27455
+ itemResult.error = error;
27456
+ itemResult.status = "postscript_failed";
27457
+ }
27458
+ }
27107
27459
  /**
27108
27460
  * Execute a multi-turn conversation for a single simulation item.
27461
+ *
27462
+ * The per-item before hook has already been executed by the caller;
27463
+ * the merged setupContext is passed directly to executeTask.
27464
+ * The after hook runs when the conversation ends (success or failure).
27109
27465
  */
27110
- async _executeConversation(runId, runItem, task2) {
27111
- const { runItemId, message: initialMessage, turnId: initialTurnId, files: initialFiles } = runItem;
27466
+ async _executeConversation(runId, runItem, task2, hooks, setupContext) {
27467
+ const { runItemId, datasetItemId, message: initialMessage, turnId: initialTurnId, files: initialFiles } = runItem;
27112
27468
  let message = initialMessage;
27113
27469
  let turnId = initialTurnId;
27114
27470
  let sessionId = null;
27115
27471
  let rawFiles = initialFiles ?? [];
27116
27472
  while (true) {
27117
- const span2 = new SpanWrapper(SPAN_NAME, {}, LOG_PREFIX6);
27473
+ const span2 = new SpanWrapper(SPAN_NAME, {}, LOG_PREFIX7);
27118
27474
  span2.start();
27119
27475
  try {
27120
27476
  const traceId = span2.getCurrentSpan()?.spanContext().traceId ?? "";
27121
27477
  const [responseMessage, taskSessionId] = await span2.withActive(
27122
- () => executeTask2(task2, message, sessionId, rawFiles)
27478
+ () => executeTask2(task2, message, sessionId, rawFiles, setupContext)
27123
27479
  );
27124
27480
  if (taskSessionId) {
27125
27481
  sessionId = taskSessionId;
@@ -27133,23 +27489,26 @@ var Simulation = class {
27133
27489
  )
27134
27490
  );
27135
27491
  if (response === null) {
27136
- const errorMsg = "Failed to get conversation response";
27137
- return {
27492
+ const itemResult = {
27138
27493
  runItemId,
27139
27494
  success: false,
27140
- error: errorMsg,
27495
+ error: "Failed to get conversation response",
27141
27496
  turnId
27142
27497
  };
27498
+ await this._runAfterHooks(runId, runItemId, datasetItemId, hooks, itemResult, setupContext);
27499
+ return itemResult;
27143
27500
  }
27144
27501
  if (response.decision === "stop") {
27145
27502
  Logger.info(
27146
- `${LOG_PREFIX6}: Completed run_item_id=${runItemId} reason=${response.reason}`
27503
+ `${LOG_PREFIX7}: Completed run_item_id=${runItemId} reason=${response.reason}`
27147
27504
  );
27148
- return {
27505
+ const itemResult = {
27149
27506
  runItemId,
27150
27507
  success: true,
27151
27508
  finalTurnId: turnId
27152
27509
  };
27510
+ await this._runAfterHooks(runId, runItemId, datasetItemId, hooks, itemResult, setupContext);
27511
+ return itemResult;
27153
27512
  }
27154
27513
  message = response.nextUserMessage;
27155
27514
  turnId = response.nextTurnId;
@@ -27157,15 +27516,17 @@ var Simulation = class {
27157
27516
  } catch (error) {
27158
27517
  const errorMsg = error instanceof Error ? error.message : String(error);
27159
27518
  Logger.error(
27160
- `${LOG_PREFIX6}: Task failed run_item_id=${runItemId}, turn_id=${turnId}: ${errorMsg}`
27519
+ `${LOG_PREFIX7}: Task failed run_item_id=${runItemId}, turn_id=${turnId}: ${errorMsg}`
27161
27520
  );
27162
27521
  await this._client.reportFailure(runId, runItemId, errorMsg);
27163
- return {
27522
+ const itemResult = {
27164
27523
  runItemId,
27165
27524
  success: false,
27166
27525
  error: errorMsg,
27167
27526
  turnId
27168
27527
  };
27528
+ await this._runAfterHooks(runId, runItemId, datasetItemId, hooks, itemResult, setupContext);
27529
+ return itemResult;
27169
27530
  } finally {
27170
27531
  span2.end();
27171
27532
  }