netra-sdk 1.11.0 → 1.12.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
@@ -1,4 +1,3 @@
1
- import { __require, BaseCallbackHandler } from './chunk-LRCHNZDG.js';
2
1
  import { createContextKey, propagation, trace, context, SpanKind, SpanStatusCode, ROOT_CONTEXT } from '@opentelemetry/api';
3
2
  import { createRequire } from 'module';
4
3
  import { AsyncLocalStorage } from 'async_hooks';
@@ -13,6 +12,13 @@ import { JsonTraceSerializer } from '@opentelemetry/otlp-transformer';
13
12
  import pLimit2 from 'p-limit';
14
13
  import axios from 'axios';
15
14
 
15
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
16
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
17
+ }) : x)(function(x) {
18
+ if (typeof require !== "undefined") return require.apply(this, arguments);
19
+ throw Error('Dynamic require of "' + x + '" is not supported');
20
+ });
21
+
16
22
  // src/logger.ts
17
23
  var PREFIX = "[Netra]";
18
24
  var Logger = class {
@@ -42,6 +48,19 @@ var Logger = class {
42
48
  }
43
49
  };
44
50
  Logger._debugMode = false;
51
+
52
+ // src/utils/api-path.ts
53
+ function apiPath(strings, ...values) {
54
+ let result = strings[0];
55
+ values.forEach((value, i) => {
56
+ const segment = String(value ?? "");
57
+ if (segment === "" || segment === "." || segment === "..") {
58
+ throw new Error(`Invalid path segment '${segment}' in ${strings.join("{}")}`);
59
+ }
60
+ result += encodeURIComponent(segment) + strings[i + 1];
61
+ });
62
+ return result;
63
+ }
45
64
  function injectTraceContextHeaders(headers) {
46
65
  const carrier = { ...headers };
47
66
  try {
@@ -125,11 +144,27 @@ var NetraHttpClient = class {
125
144
  isInitialized() {
126
145
  return this.initialized;
127
146
  }
147
+ /**
148
+ * Build an API path, percent-encoding every interpolated value.
149
+ * Returns null (and logs) if a value is not a valid path segment;
150
+ * `get`/`post` treat a null path as a failed request.
151
+ */
152
+ path(strings, ...values) {
153
+ try {
154
+ return apiPath(strings, ...values);
155
+ } catch (error) {
156
+ Logger.error(`netra: ${error instanceof Error ? error.message : error}`);
157
+ return null;
158
+ }
159
+ }
128
160
  async get(path, params) {
129
161
  if (!this.initialized) {
130
162
  Logger.error("netra: HTTP client is not initialized");
131
163
  return { data: {}, status: 0, ok: false };
132
164
  }
165
+ if (path === null) {
166
+ return { data: {}, status: 0, ok: false };
167
+ }
133
168
  const url = new URL(path, this.baseUrl);
134
169
  if (params) {
135
170
  Object.entries(params).forEach(([key, value]) => {
@@ -166,6 +201,9 @@ var NetraHttpClient = class {
166
201
  Logger.error("netra: HTTP client is not initialized");
167
202
  return { data: {}, status: 0, ok: false };
168
203
  }
204
+ if (path === null) {
205
+ return { data: {}, status: 0, ok: false };
206
+ }
169
207
  const url = new URL(path, this.baseUrl);
170
208
  try {
171
209
  const controller = new AbortController();
@@ -222,7 +260,7 @@ var UsageHttpClient = class extends NetraHttpClient {
222
260
  const params = {};
223
261
  if (startTime) params.startTime = startTime;
224
262
  if (endTime) params.endTime = endTime;
225
- const response = await this.get(`/usage/sessions/${sessionId}`, params);
263
+ const response = await this.get(this.path`/usage/sessions/${sessionId}`, params);
226
264
  return this.extractData(response, {});
227
265
  }
228
266
  async getTenantUsage(tenantId, startTime, endTime) {
@@ -235,7 +273,7 @@ var UsageHttpClient = class extends NetraHttpClient {
235
273
  const params = {};
236
274
  if (startTime) params.startTime = startTime;
237
275
  if (endTime) params.endTime = endTime;
238
- const response = await this.get(`/usage/tenants/${tenantId}`, params);
276
+ const response = await this.get(this.path`/usage/tenants/${tenantId}`, params);
239
277
  return this.extractData(response, {});
240
278
  }
241
279
  async listTraces(params) {
@@ -289,7 +327,7 @@ var UsageHttpClient = class extends NetraHttpClient {
289
327
  if (params.limit !== void 0) queryParams.limit = params.limit;
290
328
  if (params.spanName !== void 0) queryParams.spanName = params.spanName;
291
329
  const response = await this.get(
292
- `/sdk/traces/${params.traceId}/spans`,
330
+ this.path`/sdk/traces/${params.traceId}/spans`,
293
331
  queryParams
294
332
  );
295
333
  return response.ok ? response.data : {};
@@ -579,7 +617,7 @@ var Usage = class {
579
617
  };
580
618
 
581
619
  // src/version.ts
582
- var SDK_VERSION = "1.11.0";
620
+ var SDK_VERSION = "1.12.0";
583
621
 
584
622
  // src/config.ts
585
623
  var NetraInstruments = /* @__PURE__ */ ((NetraInstruments2) => {
@@ -1686,7 +1724,7 @@ var EvaluationHttpClient = class extends NetraHttpClient {
1686
1724
  );
1687
1725
  return [];
1688
1726
  }
1689
- const response = await this.get(`/evaluations/dataset/${datasetId}`);
1727
+ const response = await this.get(this.path`/evaluations/dataset/${datasetId}`);
1690
1728
  return this.extractData(response, []);
1691
1729
  }
1692
1730
  /**
@@ -1741,7 +1779,7 @@ var EvaluationHttpClient = class extends NetraHttpClient {
1741
1779
  return { success: false };
1742
1780
  }
1743
1781
  const response = await this.post(
1744
- `/evaluations/dataset/${datasetId}/items`,
1782
+ this.path`/evaluations/dataset/${datasetId}/items`,
1745
1783
  itemPayload
1746
1784
  );
1747
1785
  if (!response.ok) {
@@ -1762,7 +1800,7 @@ var EvaluationHttpClient = class extends NetraHttpClient {
1762
1800
  return { success: false };
1763
1801
  }
1764
1802
  try {
1765
- const response = await this.get(`/evaluations/run/${runId}`);
1803
+ const response = await this.get(this.path`/evaluations/run/${runId}`);
1766
1804
  if (!response.ok) {
1767
1805
  const errorMessage = response.data?.error?.message ?? "Unknown error";
1768
1806
  Logger.error(
@@ -1792,7 +1830,7 @@ var EvaluationHttpClient = class extends NetraHttpClient {
1792
1830
  );
1793
1831
  return { success: false };
1794
1832
  }
1795
- const response = await this.post(`/evaluations/run/${runId}/item`, payload);
1833
+ const response = await this.post(this.path`/evaluations/run/${runId}/item`, payload);
1796
1834
  if (!response.ok) {
1797
1835
  return { success: false };
1798
1836
  }
@@ -1817,7 +1855,7 @@ var EvaluationHttpClient = class extends NetraHttpClient {
1817
1855
  }
1818
1856
  const payload = { evaluatorResults };
1819
1857
  const response = await this.post(
1820
- `/evaluations/run/${runId}/item/${testRunItemId}/local-evaluations`,
1858
+ this.path`/evaluations/run/${runId}/item/${testRunItemId}/local-evaluations`,
1821
1859
  payload
1822
1860
  );
1823
1861
  if (!response.ok) {
@@ -1837,7 +1875,7 @@ var EvaluationHttpClient = class extends NetraHttpClient {
1837
1875
  }
1838
1876
  const payload = { status };
1839
1877
  const response = await this.post(
1840
- `/evaluations/run/${runId}/status`,
1878
+ this.path`/evaluations/run/${runId}/status`,
1841
1879
  payload
1842
1880
  );
1843
1881
  if (!response.ok) {
@@ -1860,7 +1898,7 @@ var EvaluationHttpClient = class extends NetraHttpClient {
1860
1898
  return null;
1861
1899
  }
1862
1900
  try {
1863
- const response = await this.get(`sdk/traces/spans/${spanId}`);
1901
+ const response = await this.get(this.path`sdk/traces/spans/${spanId}`);
1864
1902
  if (!response.ok) {
1865
1903
  return null;
1866
1904
  }
@@ -2717,7 +2755,7 @@ var DashboardHttpClient = class extends NetraHttpClient {
2717
2755
  return null;
2718
2756
  }
2719
2757
  try {
2720
- const url = `/public/dashboard/session/${encodeURIComponent(sessionId)}`;
2758
+ const url = this.path`/public/dashboard/session/${sessionId}`;
2721
2759
  const response = await this.get(url);
2722
2760
  if (!response.ok) {
2723
2761
  const errorMessage = response.data?.error?.message ?? "Unknown error";
@@ -3005,11 +3043,14 @@ var TTLCache = class {
3005
3043
  this.store.delete(key);
3006
3044
  return void 0;
3007
3045
  }
3008
- return entry.value;
3046
+ return structuredClone(entry.value);
3009
3047
  }
3010
3048
  set(key, value, ttl) {
3011
3049
  const ttlMs = (ttl ?? this.defaultTtl) * 1e3;
3012
- this.store.set(key, { value, expiresAt: performance.now() + ttlMs });
3050
+ this.store.set(key, {
3051
+ value: structuredClone(value),
3052
+ expiresAt: performance.now() + ttlMs
3053
+ });
3013
3054
  }
3014
3055
  invalidate(key) {
3015
3056
  this.store.delete(key);
@@ -7838,184 +7879,209 @@ function enterWithContext(newContext) {
7838
7879
  contextManager._asyncLocalStorage.enterWith(newContext);
7839
7880
  }
7840
7881
  }
7841
- var NetraLanggraphCallbackHandler = class extends BaseCallbackHandler {
7842
- constructor(tracer, rootSpan) {
7843
- super();
7844
- this.tracer = tracer;
7845
- this.rootSpan = rootSpan;
7846
- this.name = "netra-langgraph-callback-handler";
7847
- // Map runId -> Span for explicit parenting
7848
- this.spans = /* @__PURE__ */ new Map();
7849
- this.nodeAttributes = /* @__PURE__ */ new Map();
7850
- this.runStack = [];
7851
- this.inferredParents = /* @__PURE__ */ new Map();
7852
- }
7853
- getParentSpan(parentRunId) {
7854
- if (parentRunId && this.spans.has(parentRunId)) {
7855
- return this.spans.get(parentRunId);
7856
- }
7857
- return this.rootSpan;
7858
- }
7859
- addNodeAttributes(runId, attributes) {
7860
- const current = this.nodeAttributes.get(runId) || {};
7861
- this.nodeAttributes.set(runId, { ...current, ...attributes });
7862
- }
7863
- inferParentRunId(parentRunId) {
7864
- if (parentRunId) return parentRunId;
7865
- return this.runStack.length > 0 ? this.runStack[this.runStack.length - 1] : void 0;
7866
- }
7867
- pushRun(runId) {
7868
- this.runStack.push(runId);
7869
- }
7870
- popRun(runId) {
7871
- const last = this.runStack[this.runStack.length - 1];
7872
- if (last === runId) {
7873
- this.runStack.pop();
7874
- return;
7875
- }
7876
- const idx = this.runStack.lastIndexOf(runId);
7877
- if (idx >= 0) {
7878
- this.runStack.splice(idx, 1);
7879
- }
7880
- }
7881
- async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runName, runType) {
7882
- const metadataNodeName = typeof metadata?.langgraph_node === "string" ? metadata.langgraph_node : "";
7883
- const runNameValue = typeof runName === "string" ? runName : "";
7884
- const chainIdName = Array.isArray(chain.id) && chain.id.length > 0 ? chain.id[chain.id.length - 1] : "";
7885
- const nodeName = metadataNodeName || runNameValue || chainIdName || "Chain";
7886
- const nodeType = chainIdName || "Unknown";
7887
- const metadataKeys = metadata && typeof metadata === "object" ? Object.keys(metadata).join(",") : "n/a";
7888
- Logger.debug(
7889
- `NetraLanggraph handleChainStart: runId=${runId} parentRunId=${parentRunId} nodeName=${nodeName} nodeType=${nodeType} runName=${runNameValue || "n/a"} metadataKeys=${metadataKeys}`
7890
- );
7891
- if (["__start__"].includes(nodeName.toLowerCase())) {
7892
- return;
7893
- }
7894
- const effectiveParentRunId = this.inferParentRunId(parentRunId);
7895
- if (!parentRunId && effectiveParentRunId && effectiveParentRunId !== runId) {
7896
- this.inferredParents.set(runId, effectiveParentRunId);
7897
- Logger.debug(`NetraLanggraph inferred parent: runId=${runId} parentRunId=${effectiveParentRunId}`);
7898
- }
7899
- const parentSpan = this.getParentSpan(effectiveParentRunId);
7900
- const ctx = trace.setSpan(context.active(), parentSpan);
7901
- const span2 = this.tracer.startSpan(`${nodeName}.task`, void 0, ctx);
7902
- setChainInputAttributes(span2, inputs, tags, metadata);
7903
- this.spans.set(runId, span2);
7904
- this.pushRun(runId);
7905
- }
7906
- async handleChainEnd(outputs, runId, parentRunId, tags, kwargs) {
7907
- const span2 = this.spans.get(runId);
7908
- if (!span2) return;
7909
- setChainOutputAttributes(span2, outputs, tags);
7910
- span2.end();
7911
- this.spans.delete(runId);
7912
- this.nodeAttributes.delete(runId);
7913
- this.inferredParents.delete(runId);
7914
- this.popRun(runId);
7915
- }
7916
- async handleChainError(err, runId, parentRunId, tags, kwargs) {
7917
- const span2 = this.spans.get(runId);
7918
- if (!span2) return;
7919
- span2.recordException(err);
7920
- span2.end();
7921
- this.spans.delete(runId);
7922
- this.nodeAttributes.delete(runId);
7923
- this.inferredParents.delete(runId);
7924
- this.popRun(runId);
7925
- }
7926
- async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, runName) {
7927
- const effectiveParentRunId = parentRunId ?? this.inferParentRunId(parentRunId);
7928
- {
7929
- const llmId = llm.id?.[llm.id.length - 1] || "llm";
7930
- Logger.debug(`NetraLanggraph handleLLMStart: runId=${runId} parentRunId=${effectiveParentRunId} llmId=${llmId}`);
7931
- }
7932
- this.addNodeAttributes(runId, {
7933
- llmIds: llm.id,
7934
- metadata,
7935
- prompts,
7936
- extraParams,
7937
- parentRunId: effectiveParentRunId
7938
- // Store parent ID to link back
7939
- });
7940
- }
7941
- async handleLLMEnd(output, runId, parentRunId) {
7942
- const attributes = this.nodeAttributes.get(runId);
7943
- if (!attributes) return;
7944
- const response = output?.generations?.[0]?.[0]?.message;
7945
- const llmIds = attributes.llmIds ?? [];
7946
- const llmId = llmIds?.length > 0 ? llmIds[llmIds.length - 1] : "llm";
7947
- const effectiveParentRunId = parentRunId ?? attributes.parentRunId ?? this.inferredParents.get(runId);
7948
- const parentSpan = this.getParentSpan(effectiveParentRunId);
7949
- const ctx = trace.setSpan(context.active(), parentSpan);
7950
- const span2 = this.tracer.startSpan(`${llmId}.task`, void 0, ctx);
7951
- setLlmRequestAttributes(
7952
- span2,
7953
- attributes.metadata,
7954
- attributes.prompts,
7955
- attributes.extraParams
7956
- );
7957
- setResponseAttributes(span2, response);
7958
- span2.end();
7959
- this.nodeAttributes.delete(runId);
7960
- }
7961
- async handleLLMError(err, runId, parentRunId, tags, extraParams) {
7962
- const attributes = this.nodeAttributes.get(runId);
7963
- if (!attributes) return;
7964
- const llmIds = attributes.llmIds ?? [];
7965
- const llmId = llmIds?.length > 0 ? llmIds[llmIds.length - 1] : "llm";
7966
- const effectiveParentRunId = parentRunId ?? attributes.parentRunId ?? this.inferredParents.get(runId);
7967
- const parentSpan = this.getParentSpan(effectiveParentRunId);
7968
- const ctx = trace.setSpan(context.active(), parentSpan);
7969
- const span2 = this.tracer.startSpan(`${llmId}.task`, void 0, ctx);
7970
- span2.recordException(err);
7971
- span2.end();
7972
- this.nodeAttributes.delete(runId);
7882
+ var NetraLanggraphCallbackHandler = null;
7883
+ async function loadLanggraphCallbackHandler() {
7884
+ if (NetraLanggraphCallbackHandler) return true;
7885
+ let Base;
7886
+ try {
7887
+ Base = (await import('@langchain/core/callbacks/base')).BaseCallbackHandler;
7888
+ } catch {
7889
+ Logger.debug("@langchain/core: ESM import not available");
7973
7890
  }
7974
- async handleToolStart(tool, input, runId, parentRunId, tags, metadata, runName) {
7975
- let parsedInput;
7891
+ if (!Base) {
7976
7892
  try {
7977
- parsedInput = JSON.parse(input);
7893
+ const req = createRequire(import.meta.url);
7894
+ Base = req("@langchain/core/callbacks/base").BaseCallbackHandler;
7978
7895
  } catch {
7979
- parsedInput = {};
7896
+ Logger.debug("@langchain/core: CJS require not available");
7980
7897
  }
7981
- const effectiveParentRunId = parentRunId ?? this.inferParentRunId(parentRunId);
7982
- {
7983
- const toolName = tool.id?.[tool.id.length - 1] || "tool";
7984
- Logger.debug(`NetraLanggraph handleToolStart: runId=${runId} parentRunId=${effectiveParentRunId} tool=${toolName}`);
7985
- }
7986
- this.addNodeAttributes(runId, {
7987
- input: parsedInput,
7988
- metadata,
7989
- tags,
7990
- parentRunId: effectiveParentRunId
7991
- });
7992
7898
  }
7993
- async handleToolEnd(output, runId, parentRunId, tags) {
7994
- const attributes = this.nodeAttributes.get(runId);
7995
- if (!attributes) return;
7996
- const toolName = attributes?.input?.name ?? "custom";
7997
- const { input, metadata } = attributes;
7998
- const effectiveParentRunId = parentRunId ?? attributes.parentRunId ?? this.inferredParents.get(runId);
7999
- const parentSpan = this.getParentSpan(effectiveParentRunId);
8000
- const ctx = trace.setSpan(context.active(), parentSpan);
8001
- const span2 = this.tracer.startSpan(`${toolName}.tool`, void 0, ctx);
8002
- setToolAttributes(span2, toolName, input ?? {}, output, metadata, tags);
8003
- span2.end();
8004
- this.nodeAttributes.delete(runId);
8005
- }
8006
- async handleToolError(err, runId, parentRunId, tags) {
8007
- const attributes = this.nodeAttributes.get(runId);
8008
- if (!attributes) return;
8009
- const toolName = attributes?.input?.name ?? "custom";
8010
- const effectiveParentRunId = parentRunId ?? attributes.parentRunId ?? this.inferredParents.get(runId);
8011
- const parentSpan = this.getParentSpan(effectiveParentRunId);
8012
- const ctx = trace.setSpan(context.active(), parentSpan);
8013
- const span2 = this.tracer.startSpan(`${toolName}.tool`, void 0, ctx);
8014
- span2.recordException(err);
8015
- span2.end();
8016
- this.nodeAttributes.delete(runId);
7899
+ if (!Base) {
7900
+ return false;
8017
7901
  }
8018
- };
7902
+ NetraLanggraphCallbackHandler = createCallbackHandlerClass(Base);
7903
+ return true;
7904
+ }
7905
+ function createCallbackHandlerClass(Base) {
7906
+ return class NetraLanggraphCallbackHandler extends Base {
7907
+ constructor(tracer, rootSpan) {
7908
+ super();
7909
+ this.tracer = tracer;
7910
+ this.rootSpan = rootSpan;
7911
+ this.name = "netra-langgraph-callback-handler";
7912
+ // Map runId -> Span for explicit parenting
7913
+ this.spans = /* @__PURE__ */ new Map();
7914
+ this.nodeAttributes = /* @__PURE__ */ new Map();
7915
+ this.runStack = [];
7916
+ this.inferredParents = /* @__PURE__ */ new Map();
7917
+ }
7918
+ getParentSpan(parentRunId) {
7919
+ if (parentRunId && this.spans.has(parentRunId)) {
7920
+ return this.spans.get(parentRunId);
7921
+ }
7922
+ return this.rootSpan;
7923
+ }
7924
+ addNodeAttributes(runId, attributes) {
7925
+ const current = this.nodeAttributes.get(runId) || {};
7926
+ this.nodeAttributes.set(runId, { ...current, ...attributes });
7927
+ }
7928
+ inferParentRunId(parentRunId) {
7929
+ if (parentRunId) return parentRunId;
7930
+ return this.runStack.length > 0 ? this.runStack[this.runStack.length - 1] : void 0;
7931
+ }
7932
+ pushRun(runId) {
7933
+ this.runStack.push(runId);
7934
+ }
7935
+ popRun(runId) {
7936
+ const last = this.runStack[this.runStack.length - 1];
7937
+ if (last === runId) {
7938
+ this.runStack.pop();
7939
+ return;
7940
+ }
7941
+ const idx = this.runStack.lastIndexOf(runId);
7942
+ if (idx >= 0) {
7943
+ this.runStack.splice(idx, 1);
7944
+ }
7945
+ }
7946
+ async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runName, runType) {
7947
+ const metadataNodeName = typeof metadata?.langgraph_node === "string" ? metadata.langgraph_node : "";
7948
+ const runNameValue = typeof runName === "string" ? runName : "";
7949
+ const chainIdName = Array.isArray(chain.id) && chain.id.length > 0 ? chain.id[chain.id.length - 1] : "";
7950
+ const nodeName = metadataNodeName || runNameValue || chainIdName || "Chain";
7951
+ const nodeType = chainIdName || "Unknown";
7952
+ const metadataKeys = metadata && typeof metadata === "object" ? Object.keys(metadata).join(",") : "n/a";
7953
+ Logger.debug(
7954
+ `NetraLanggraph handleChainStart: runId=${runId} parentRunId=${parentRunId} nodeName=${nodeName} nodeType=${nodeType} runName=${runNameValue || "n/a"} metadataKeys=${metadataKeys}`
7955
+ );
7956
+ if (["__start__"].includes(nodeName.toLowerCase())) {
7957
+ return;
7958
+ }
7959
+ const effectiveParentRunId = this.inferParentRunId(parentRunId);
7960
+ if (!parentRunId && effectiveParentRunId && effectiveParentRunId !== runId) {
7961
+ this.inferredParents.set(runId, effectiveParentRunId);
7962
+ Logger.debug(`NetraLanggraph inferred parent: runId=${runId} parentRunId=${effectiveParentRunId}`);
7963
+ }
7964
+ const parentSpan = this.getParentSpan(effectiveParentRunId);
7965
+ const ctx = trace.setSpan(context.active(), parentSpan);
7966
+ const span2 = this.tracer.startSpan(`${nodeName}.task`, void 0, ctx);
7967
+ setChainInputAttributes(span2, inputs, tags, metadata);
7968
+ this.spans.set(runId, span2);
7969
+ this.pushRun(runId);
7970
+ }
7971
+ async handleChainEnd(outputs, runId, parentRunId, tags, kwargs) {
7972
+ const span2 = this.spans.get(runId);
7973
+ if (!span2) return;
7974
+ setChainOutputAttributes(span2, outputs, tags);
7975
+ span2.end();
7976
+ this.spans.delete(runId);
7977
+ this.nodeAttributes.delete(runId);
7978
+ this.inferredParents.delete(runId);
7979
+ this.popRun(runId);
7980
+ }
7981
+ async handleChainError(err, runId, parentRunId, tags, kwargs) {
7982
+ const span2 = this.spans.get(runId);
7983
+ if (!span2) return;
7984
+ span2.recordException(err);
7985
+ span2.end();
7986
+ this.spans.delete(runId);
7987
+ this.nodeAttributes.delete(runId);
7988
+ this.inferredParents.delete(runId);
7989
+ this.popRun(runId);
7990
+ }
7991
+ async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, runName) {
7992
+ const effectiveParentRunId = parentRunId ?? this.inferParentRunId(parentRunId);
7993
+ {
7994
+ const llmId = llm.id?.[llm.id.length - 1] || "llm";
7995
+ Logger.debug(`NetraLanggraph handleLLMStart: runId=${runId} parentRunId=${effectiveParentRunId} llmId=${llmId}`);
7996
+ }
7997
+ this.addNodeAttributes(runId, {
7998
+ llmIds: llm.id,
7999
+ metadata,
8000
+ prompts,
8001
+ extraParams,
8002
+ parentRunId: effectiveParentRunId
8003
+ // Store parent ID to link back
8004
+ });
8005
+ }
8006
+ async handleLLMEnd(output, runId, parentRunId) {
8007
+ const attributes = this.nodeAttributes.get(runId);
8008
+ if (!attributes) return;
8009
+ const response = output?.generations?.[0]?.[0]?.message;
8010
+ const llmIds = attributes.llmIds ?? [];
8011
+ const llmId = llmIds?.length > 0 ? llmIds[llmIds.length - 1] : "llm";
8012
+ const effectiveParentRunId = parentRunId ?? attributes.parentRunId ?? this.inferredParents.get(runId);
8013
+ const parentSpan = this.getParentSpan(effectiveParentRunId);
8014
+ const ctx = trace.setSpan(context.active(), parentSpan);
8015
+ const span2 = this.tracer.startSpan(`${llmId}.task`, void 0, ctx);
8016
+ setLlmRequestAttributes(
8017
+ span2,
8018
+ attributes.metadata,
8019
+ attributes.prompts,
8020
+ attributes.extraParams
8021
+ );
8022
+ setResponseAttributes(span2, response);
8023
+ span2.end();
8024
+ this.nodeAttributes.delete(runId);
8025
+ }
8026
+ async handleLLMError(err, runId, parentRunId, tags, extraParams) {
8027
+ const attributes = this.nodeAttributes.get(runId);
8028
+ if (!attributes) return;
8029
+ const llmIds = attributes.llmIds ?? [];
8030
+ const llmId = llmIds?.length > 0 ? llmIds[llmIds.length - 1] : "llm";
8031
+ const effectiveParentRunId = parentRunId ?? attributes.parentRunId ?? this.inferredParents.get(runId);
8032
+ const parentSpan = this.getParentSpan(effectiveParentRunId);
8033
+ const ctx = trace.setSpan(context.active(), parentSpan);
8034
+ const span2 = this.tracer.startSpan(`${llmId}.task`, void 0, ctx);
8035
+ span2.recordException(err);
8036
+ span2.end();
8037
+ this.nodeAttributes.delete(runId);
8038
+ }
8039
+ async handleToolStart(tool, input, runId, parentRunId, tags, metadata, runName) {
8040
+ let parsedInput;
8041
+ try {
8042
+ parsedInput = JSON.parse(input);
8043
+ } catch {
8044
+ parsedInput = {};
8045
+ }
8046
+ const effectiveParentRunId = parentRunId ?? this.inferParentRunId(parentRunId);
8047
+ {
8048
+ const toolName = tool.id?.[tool.id.length - 1] || "tool";
8049
+ Logger.debug(`NetraLanggraph handleToolStart: runId=${runId} parentRunId=${effectiveParentRunId} tool=${toolName}`);
8050
+ }
8051
+ this.addNodeAttributes(runId, {
8052
+ input: parsedInput,
8053
+ metadata,
8054
+ tags,
8055
+ parentRunId: effectiveParentRunId
8056
+ });
8057
+ }
8058
+ async handleToolEnd(output, runId, parentRunId, tags) {
8059
+ const attributes = this.nodeAttributes.get(runId);
8060
+ if (!attributes) return;
8061
+ const toolName = attributes?.input?.name ?? "custom";
8062
+ const { input, metadata } = attributes;
8063
+ const effectiveParentRunId = parentRunId ?? attributes.parentRunId ?? this.inferredParents.get(runId);
8064
+ const parentSpan = this.getParentSpan(effectiveParentRunId);
8065
+ const ctx = trace.setSpan(context.active(), parentSpan);
8066
+ const span2 = this.tracer.startSpan(`${toolName}.tool`, void 0, ctx);
8067
+ setToolAttributes(span2, toolName, input ?? {}, output, metadata, tags);
8068
+ span2.end();
8069
+ this.nodeAttributes.delete(runId);
8070
+ }
8071
+ async handleToolError(err, runId, parentRunId, tags) {
8072
+ const attributes = this.nodeAttributes.get(runId);
8073
+ if (!attributes) return;
8074
+ const toolName = attributes?.input?.name ?? "custom";
8075
+ const effectiveParentRunId = parentRunId ?? attributes.parentRunId ?? this.inferredParents.get(runId);
8076
+ const parentSpan = this.getParentSpan(effectiveParentRunId);
8077
+ const ctx = trace.setSpan(context.active(), parentSpan);
8078
+ const span2 = this.tracer.startSpan(`${toolName}.tool`, void 0, ctx);
8079
+ span2.recordException(err);
8080
+ span2.end();
8081
+ this.nodeAttributes.delete(runId);
8082
+ }
8083
+ };
8084
+ }
8019
8085
  var LanggraphStreamingWrapper = class {
8020
8086
  constructor(rootSpan, rootContext) {
8021
8087
  this.output = {};
@@ -8065,7 +8131,7 @@ var LanggraphWrapper = class {
8065
8131
  this.spanName = "Langgraph.workflow";
8066
8132
  }
8067
8133
  getUpdatedConfig(config, rootSpan) {
8068
- if (!rootSpan) return config || {};
8134
+ if (!rootSpan || !NetraLanggraphCallbackHandler) return config || {};
8069
8135
  const callbackHandler = new NetraLanggraphCallbackHandler(
8070
8136
  this.tracer,
8071
8137
  rootSpan
@@ -8232,6 +8298,10 @@ var NetraLanggraphInstrumentor = class {
8232
8298
  Logger.warn("LangGraph class not found, skipping instrumentation");
8233
8299
  return this;
8234
8300
  }
8301
+ if (!await loadLanggraphCallbackHandler()) {
8302
+ Logger.warn("@langchain/core not found, skipping LangGraph instrumentation");
8303
+ return this;
8304
+ }
8235
8305
  try {
8236
8306
  this.tracerProvider = options.tracerProvider;
8237
8307
  this.tracer = this.tracerProvider ? this.tracerProvider.getTracer(INSTRUMENTATION_NAME3, __version__5) : trace.getTracer(INSTRUMENTATION_NAME3, __version__5);
@@ -11451,7 +11521,7 @@ function patchTraceloopLangchainCallbackHandler() {
11451
11521
  } catch (e) {
11452
11522
  Logger.debug("require() for traceloop langchain failed, falling back to import().");
11453
11523
  }
11454
- import('./dist-4UBY6Q6Z.js').then((mod) => {
11524
+ import('@traceloop/instrumentation-langchain').then((mod) => {
11455
11525
  applyPatch(mod, "import");
11456
11526
  }).catch(() => {
11457
11527
  });
@@ -12017,6 +12087,262 @@ async function uninstrumentAll() {
12017
12087
  }
12018
12088
  }
12019
12089
 
12090
+ // src/shutdown-registry.ts
12091
+ var FLUSH_TIMEOUT_MS = 5e3;
12092
+ var EXIT_BUDGET_MS = FLUSH_TIMEOUT_MS + 2e3;
12093
+ var SIGNALS = ["SIGINT", "SIGTERM"];
12094
+ var entries = /* @__PURE__ */ new Set();
12095
+ var ours = /* @__PURE__ */ new Set();
12096
+ var appHadListener = /* @__PURE__ */ new Map();
12097
+ var inFlight = [];
12098
+ var installed = false;
12099
+ var rejectionInstalled = false;
12100
+ var firing = false;
12101
+ var rethrowing = false;
12102
+ var appOwnedSignal;
12103
+ var handedBack;
12104
+ var generation = 0;
12105
+ function registerExitTask(task2, options = {}) {
12106
+ const entry = {
12107
+ task: task2,
12108
+ unhandledRejection: options.unhandledRejection === true
12109
+ };
12110
+ entries.add(entry);
12111
+ install();
12112
+ return () => {
12113
+ entries.delete(entry);
12114
+ if (entries.size === 0 && !firing) {
12115
+ uninstall();
12116
+ } else {
12117
+ syncRejectionListener();
12118
+ }
12119
+ };
12120
+ }
12121
+ function install() {
12122
+ if (firing) {
12123
+ return;
12124
+ }
12125
+ if (!installed) {
12126
+ installed = true;
12127
+ for (const sig of SIGNALS) {
12128
+ appHadListener.set(sig, process.listenerCount(sig) > 0);
12129
+ process.on(sig, onSignal);
12130
+ }
12131
+ process.on("uncaughtException", onUncaughtException);
12132
+ process.on("removeListener", onRemoveListener);
12133
+ ours.add(onSignal);
12134
+ ours.add(onUncaughtException);
12135
+ }
12136
+ syncRejectionListener();
12137
+ }
12138
+ var onRemoveListener = (event, listener) => {
12139
+ if (!SIGNALS.includes(event) || ours.has(listener)) {
12140
+ return;
12141
+ }
12142
+ const sig = event;
12143
+ queueMicrotask(() => {
12144
+ if (installed) {
12145
+ appHadListener.set(
12146
+ sig,
12147
+ process.listeners(sig).some((l) => !ours.has(l))
12148
+ );
12149
+ }
12150
+ });
12151
+ };
12152
+ function syncRejectionListener() {
12153
+ if (!installed) {
12154
+ return;
12155
+ }
12156
+ const wanted = [...entries].some((e) => e.unhandledRejection);
12157
+ if (wanted && !rejectionInstalled) {
12158
+ rejectionInstalled = true;
12159
+ process.on("unhandledRejection", onUnhandledRejection);
12160
+ ours.add(onUnhandledRejection);
12161
+ } else if (!wanted && rejectionInstalled) {
12162
+ rejectionInstalled = false;
12163
+ process.removeListener("unhandledRejection", onUnhandledRejection);
12164
+ ours.delete(onUnhandledRejection);
12165
+ }
12166
+ }
12167
+ function uninstall() {
12168
+ if (rejectionInstalled) {
12169
+ rejectionInstalled = false;
12170
+ process.removeListener("unhandledRejection", onUnhandledRejection);
12171
+ }
12172
+ if (!installed) {
12173
+ return;
12174
+ }
12175
+ installed = false;
12176
+ for (const sig of SIGNALS) {
12177
+ process.removeListener(sig, onSignal);
12178
+ }
12179
+ process.removeListener("uncaughtException", onUncaughtException);
12180
+ process.removeListener("removeListener", onRemoveListener);
12181
+ ours.clear();
12182
+ appHadListener.clear();
12183
+ }
12184
+ function appHandles(event) {
12185
+ const live = process.listeners(event).some((l) => !ours.has(l));
12186
+ if (live) {
12187
+ return true;
12188
+ }
12189
+ return event !== "uncaughtException" && appHadListener.get(event) === true;
12190
+ }
12191
+ async function runTasks(reason) {
12192
+ const pending = [...entries];
12193
+ pending.forEach((e) => entries.delete(e));
12194
+ let timer;
12195
+ const budget = new Promise((resolve) => {
12196
+ timer = setTimeout(resolve, EXIT_BUDGET_MS);
12197
+ timer.unref?.();
12198
+ });
12199
+ const running = pending.map((e) => ({
12200
+ task: e.task,
12201
+ promise: Promise.resolve().then(() => e.task(reason))
12202
+ }));
12203
+ running.forEach((r) => r.promise.catch(() => {
12204
+ }));
12205
+ inFlight = running;
12206
+ try {
12207
+ await Promise.race([
12208
+ Promise.allSettled(running.map((r) => r.promise)),
12209
+ budget
12210
+ ]);
12211
+ } finally {
12212
+ clearTimeout(timer);
12213
+ inFlight = inFlight.filter((r) => !running.includes(r));
12214
+ }
12215
+ }
12216
+ async function settleOtherExitTasks(exclude) {
12217
+ const others = inFlight.filter((r) => r.task !== exclude).map((r) => r.promise);
12218
+ const notYetRun = [...entries].filter((e) => e.task !== exclude);
12219
+ notYetRun.forEach((e) => entries.delete(e));
12220
+ const started = notYetRun.map((e) => {
12221
+ const p = Promise.resolve().then(() => e.task({ kind: "shutdown" }));
12222
+ p.catch(() => {
12223
+ });
12224
+ return p;
12225
+ });
12226
+ const all = [...others, ...started];
12227
+ if (all.length === 0) {
12228
+ return;
12229
+ }
12230
+ let timer;
12231
+ const budget = new Promise((resolve) => {
12232
+ timer = setTimeout(resolve, EXIT_BUDGET_MS);
12233
+ timer.unref?.();
12234
+ });
12235
+ try {
12236
+ await Promise.race([Promise.allSettled(all), budget]);
12237
+ } finally {
12238
+ clearTimeout(timer);
12239
+ }
12240
+ }
12241
+ function startFire(appOwned) {
12242
+ firing = true;
12243
+ appOwnedSignal = appOwned;
12244
+ handedBack = void 0;
12245
+ return ++generation;
12246
+ }
12247
+ var onSignal = (sig) => {
12248
+ if (firing) {
12249
+ const handled2 = process.listeners(sig).some((l) => !ours.has(l));
12250
+ if (!handled2 && sig === appOwnedSignal && !handedBack) {
12251
+ Logger.debug(`netra: ${sig} handed back by the app; exiting after flush`);
12252
+ handedBack = sig;
12253
+ return;
12254
+ }
12255
+ Logger.debug(`netra: second ${sig} during shutdown; exiting now`);
12256
+ generation++;
12257
+ firing = false;
12258
+ uninstall();
12259
+ if (!handled2) {
12260
+ try {
12261
+ process.kill(process.pid, sig);
12262
+ } catch {
12263
+ }
12264
+ }
12265
+ return;
12266
+ }
12267
+ const handled = appHandles(sig);
12268
+ const gen = startFire(handled ? sig : void 0);
12269
+ Logger.log(`
12270
+ Received ${sig}. Flushing Netra SDK...`);
12271
+ void runTasks({ kind: "signal", signal: sig }).catch((err) => Logger.error("netra: error during shutdown:", err)).finally(() => {
12272
+ if (gen !== generation) {
12273
+ return;
12274
+ }
12275
+ uninstall();
12276
+ firing = false;
12277
+ const reraise = handled ? handedBack : sig;
12278
+ if (reraise) {
12279
+ try {
12280
+ process.kill(process.pid, reraise);
12281
+ } catch {
12282
+ }
12283
+ }
12284
+ });
12285
+ };
12286
+ var onUncaughtException = (error) => {
12287
+ if (rethrowing) {
12288
+ rethrowing = false;
12289
+ return;
12290
+ }
12291
+ if (firing) {
12292
+ if (appHandles("uncaughtException")) {
12293
+ return;
12294
+ }
12295
+ uninstall();
12296
+ console.error(error);
12297
+ process.exitCode = 1;
12298
+ setImmediate(() => process.exit(1));
12299
+ return;
12300
+ }
12301
+ if (appHandles("uncaughtException")) {
12302
+ return;
12303
+ }
12304
+ const gen = startFire();
12305
+ Logger.error("Uncaught exception; flushing Netra SDK before exit...");
12306
+ void runTasks({ kind: "uncaughtException", error }).catch((err) => Logger.error("netra: error during crash shutdown:", err)).finally(() => {
12307
+ if (gen !== generation) {
12308
+ return;
12309
+ }
12310
+ uninstall();
12311
+ firing = false;
12312
+ console.error(error);
12313
+ process.exitCode = 1;
12314
+ setImmediate(() => process.exit(1));
12315
+ });
12316
+ };
12317
+ var onUnhandledRejection = (reason) => {
12318
+ if (firing) {
12319
+ return;
12320
+ }
12321
+ const rejHandled = process.listeners("unhandledRejection").some((l) => !ours.has(l));
12322
+ if (rejHandled) {
12323
+ return;
12324
+ }
12325
+ if (!appHandles("uncaughtException")) {
12326
+ const gen = startFire();
12327
+ void runTasks({ kind: "unhandledRejection", error: reason }).catch((err) => Logger.error("netra: error during shutdown:", err)).finally(() => {
12328
+ if (gen !== generation) {
12329
+ return;
12330
+ }
12331
+ firing = false;
12332
+ uninstall();
12333
+ rethrow(reason);
12334
+ });
12335
+ return;
12336
+ }
12337
+ rethrow(reason);
12338
+ };
12339
+ function rethrow(reason) {
12340
+ rethrowing = true;
12341
+ setImmediate(() => {
12342
+ throw reason;
12343
+ });
12344
+ }
12345
+
12020
12346
  // src/simulation/task.ts
12021
12347
  var BaseTask = class {
12022
12348
  };
@@ -12269,7 +12595,7 @@ var SimulationHttpClient = class {
12269
12595
  return null;
12270
12596
  }
12271
12597
  try {
12272
- const url = `/evaluations/run/${runId}/item/${runItemId}/first-turn`;
12598
+ const url = apiPath`/evaluations/run/${runId}/item/${runItemId}/first-turn`;
12273
12599
  const response = await this.client.post(url, {});
12274
12600
  const data = response.data;
12275
12601
  const responseData = data.data || {};
@@ -12353,7 +12679,7 @@ var SimulationHttpClient = class {
12353
12679
  return;
12354
12680
  }
12355
12681
  try {
12356
- const url = `/evaluations/run/${runId}/item/${runItemId}/status`;
12682
+ const url = apiPath`/evaluations/run/${runId}/item/${runItemId}/status`;
12357
12683
  const payload = { status, failureReason: error };
12358
12684
  await this.client.patch(url, payload);
12359
12685
  Logger.info(`${LOG_PREFIX5}: Reported failure - ${error}`);
@@ -12373,7 +12699,7 @@ var SimulationHttpClient = class {
12373
12699
  return { success: false };
12374
12700
  }
12375
12701
  try {
12376
- const url = `/evaluations/run/${runId}/status`;
12702
+ const url = apiPath`/evaluations/run/${runId}/status`;
12377
12703
  const payload = { status };
12378
12704
  const response = await this.client.post(url, payload);
12379
12705
  const data = response.data;
@@ -12572,38 +12898,10 @@ var Simulation = class {
12572
12898
  Logger.error(`${LOG_PREFIX7}: No items returned from initialize_run`);
12573
12899
  return null;
12574
12900
  }
12575
- let interrupted = false;
12576
- const proc = typeof process !== "undefined" ? process : void 0;
12577
- const finalizeFailure = (signal) => {
12578
- if (interrupted) {
12579
- return;
12580
- }
12581
- interrupted = true;
12582
- proc?.removeListener("SIGINT", handleSignal);
12583
- proc?.removeListener("SIGTERM", handleSignal);
12584
- proc?.removeListener("uncaughtException", handleException);
12585
- proc?.removeListener("unhandledRejection", handleRejection);
12586
- void this._client.postRunStatus(runId, "failed").finally(() => {
12587
- if (signal) {
12588
- proc?.kill(proc.pid, signal);
12589
- }
12590
- });
12591
- };
12592
- const handleSignal = (signal) => {
12593
- finalizeFailure(signal);
12594
- };
12595
- const handleException = () => {
12596
- finalizeFailure();
12597
- };
12598
- const handleRejection = () => {
12599
- finalizeFailure();
12600
- };
12601
- if (proc && typeof proc.once === "function") {
12602
- proc.once("SIGINT", handleSignal);
12603
- proc.once("SIGTERM", handleSignal);
12604
- proc.once("uncaughtException", handleException);
12605
- proc.once("unhandledRejection", handleRejection);
12606
- }
12901
+ const unregisterExitTask = registerExitTask(
12902
+ () => this._client.postRunStatus(runId, "failed"),
12903
+ { unhandledRejection: true }
12904
+ );
12607
12905
  try {
12608
12906
  let sharedContext = null;
12609
12907
  if (hooks?.beforeAll) {
@@ -12726,12 +13024,7 @@ var Simulation = class {
12726
13024
  throw error;
12727
13025
  }
12728
13026
  } finally {
12729
- if (proc && typeof proc.removeListener === "function") {
12730
- proc.removeListener("SIGINT", handleSignal);
12731
- proc.removeListener("SIGTERM", handleSignal);
12732
- proc.removeListener("uncaughtException", handleException);
12733
- proc.removeListener("unhandledRejection", handleRejection);
12734
- }
13027
+ unregisterExitTask();
12735
13028
  }
12736
13029
  }
12737
13030
  /**
@@ -13117,7 +13410,7 @@ function span(targetOrOptions, options) {
13117
13410
  }
13118
13411
 
13119
13412
  // src/index.ts
13120
- var Netra = class {
13413
+ var _Netra = class _Netra {
13121
13414
  static getConfig() {
13122
13415
  if (!this._config) {
13123
13416
  throw new Error("Netra SDK not initialized. Call Netra.init() first.");
@@ -13131,6 +13424,9 @@ var Netra = class {
13131
13424
  * Initialize the Netra SDK.
13132
13425
  */
13133
13426
  static async init(config = {}) {
13427
+ if (this._shutdownPromise) {
13428
+ await this._shutdownPromise;
13429
+ }
13134
13430
  if (this._initialized) {
13135
13431
  Logger.warn("Netra.init() called more than once; ignoring subsequent calls.");
13136
13432
  return;
@@ -13192,56 +13488,82 @@ var Netra = class {
13192
13488
  `SDK version=${pkgVersion} libraryVersion=${Config.LIBRARY_VERSION} build=langgraph-parenting-v3 packageJson=${pkgPath}`
13193
13489
  );
13194
13490
  }
13195
- const handleSignal = async (signal) => {
13196
- Logger.log(`
13197
- Received ${signal}. Shutting down Netra SDK...`);
13198
- await this.shutdown();
13199
- process.exit(0);
13200
- };
13201
- const handleUncaughtException = async (error) => {
13202
- Logger.error("Uncaught exception:", error);
13203
- Logger.error("Shutting down Netra SDK due to crash...");
13204
- try {
13205
- await this.shutdown();
13206
- } catch (err) {
13207
- Logger.error("Error during crash shutdown:", err);
13208
- }
13209
- process.exit(1);
13210
- };
13211
- process.once("beforeExit", async () => {
13212
- await this.shutdown();
13213
- });
13214
- process.once("SIGINT", () => handleSignal("SIGINT"));
13215
- process.once("SIGTERM", () => handleSignal("SIGTERM"));
13216
- process.once("uncaughtException", handleUncaughtException);
13491
+ if (config.registerShutdownHooks !== false) {
13492
+ this._registerShutdownHooks();
13493
+ }
13217
13494
  await instrumentationsReady;
13218
13495
  }
13219
- static async shutdown() {
13220
- if (!this._initialized) {
13496
+ /**
13497
+ * Flush spans when the host process is going away, without taking over
13498
+ * the process lifecycle: the SDK never decides when (or with which code)
13499
+ * the process exits. Once flushed, if no other listener is handling the
13500
+ * event, Node's default behaviour is restored (the signal is re-raised so
13501
+ * the exit code is 128+n; an uncaught exception exits with code 1).
13502
+ */
13503
+ static _registerShutdownHooks() {
13504
+ if (this._unregisterFlush) {
13221
13505
  return;
13222
13506
  }
13507
+ this._unregisterFlush = registerExitTask(this._flushTask);
13508
+ const beforeExit = () => {
13509
+ void this.shutdown();
13510
+ };
13511
+ this._beforeExit = beforeExit;
13512
+ process.once("beforeExit", beforeExit);
13513
+ }
13514
+ static _removeShutdownHooks() {
13515
+ this._unregisterFlush?.();
13516
+ this._unregisterFlush = void 0;
13517
+ if (this._beforeExit) {
13518
+ process.removeListener("beforeExit", this._beforeExit);
13519
+ this._beforeExit = void 0;
13520
+ }
13521
+ }
13522
+ /**
13523
+ * Flush pending spans and release SDK resources. Safe to call more than
13524
+ * once and from several places at the same time (e.g. the app's own SIGTERM
13525
+ * handler while the SDK's hook is also flushing): concurrent callers share
13526
+ * the same in-flight shutdown and all resolve once it has finished.
13527
+ */
13528
+ static shutdown() {
13529
+ if (this._shutdownPromise) {
13530
+ return this._shutdownPromise;
13531
+ }
13532
+ if (!this._initialized) {
13533
+ return Promise.resolve();
13534
+ }
13535
+ this._shutdownPromise = this._shutdown().finally(() => {
13536
+ this._shutdownPromise = void 0;
13537
+ });
13538
+ return this._shutdownPromise;
13539
+ }
13540
+ static async _shutdown() {
13541
+ this._removeShutdownHooks();
13223
13542
  try {
13224
13543
  await uninstrumentAll();
13225
13544
  } catch (e) {
13226
13545
  Logger.error("Error during uninstrumentAll:", e);
13227
13546
  }
13228
- const FLUSH_TIMEOUT_MS = 5e3;
13547
+ let flushTimer;
13229
13548
  try {
13230
- const traceProvider = trace.getTracerProvider();
13549
+ const globalProvider = trace.getTracerProvider();
13550
+ const traceProvider = typeof globalProvider.getDelegate === "function" ? globalProvider.getDelegate() : globalProvider;
13231
13551
  const flushPromise = (async () => {
13232
- if ("forceFlush" in traceProvider && typeof traceProvider.forceFlush === "function") {
13552
+ if (typeof traceProvider?.forceFlush === "function") {
13233
13553
  await traceProvider.forceFlush();
13234
13554
  }
13235
- if ("shutdown" in traceProvider && typeof traceProvider.shutdown === "function") {
13236
- await traceProvider.shutdown();
13237
- }
13238
13555
  })();
13239
13556
  await Promise.race([
13240
13557
  flushPromise,
13241
- new Promise((resolve) => setTimeout(resolve, FLUSH_TIMEOUT_MS))
13558
+ new Promise((resolve) => {
13559
+ flushTimer = setTimeout(resolve, FLUSH_TIMEOUT_MS);
13560
+ flushTimer.unref?.();
13561
+ })
13242
13562
  ]);
13243
13563
  } catch (e) {
13244
13564
  Logger.error("Error during Netra trace shutdown:", e);
13565
+ } finally {
13566
+ clearTimeout(flushTimer);
13245
13567
  }
13246
13568
  try {
13247
13569
  this.prompts?.clearCache();
@@ -13249,6 +13571,11 @@ Received ${signal}. Shutting down Netra SDK...`);
13249
13571
  } catch (e) {
13250
13572
  Logger.error("Error clearing SDK API caches:", e);
13251
13573
  }
13574
+ try {
13575
+ await settleOtherExitTasks(this._flushTask);
13576
+ } catch (e) {
13577
+ Logger.error("Error awaiting pending shutdown tasks:", e);
13578
+ }
13252
13579
  this._initialized = false;
13253
13580
  this._tracer = void 0;
13254
13581
  }
@@ -13401,10 +13728,12 @@ Received ${signal}. Shutting down Netra SDK...`);
13401
13728
  });
13402
13729
  }
13403
13730
  };
13404
- Netra._SDK_NAME = "netra_sdk";
13405
- Netra._initialized = false;
13406
- Netra._metricsEnabled = false;
13407
- Netra.withBlockedSpansLocal = withBlockedSpansLocal;
13731
+ _Netra._SDK_NAME = "netra_sdk";
13732
+ _Netra._initialized = false;
13733
+ _Netra._metricsEnabled = false;
13734
+ _Netra._flushTask = () => _Netra.shutdown();
13735
+ _Netra.withBlockedSpansLocal = withBlockedSpansLocal;
13736
+ var Netra = _Netra;
13408
13737
  var index_default = Netra;
13409
13738
 
13410
13739
  export { Aggregation, BaseTask, ChartType, Config, ConversationType, DEFAULT_INSTRUMENTS, DEFAULT_INSTRUMENTS_FOR_ROOT, Dashboard, DimensionField, EntryStatus, Evaluation, FilterField, FilterType, FilteringSpanExporter, GroupBy, InstrumentationSpanProcessor, MODEL_PRICING_CACHE_TTL_SECONDS, Measure, Models, Netra, NetraAgentsTracingProcessor, NetraInstruments, NetraOpenAIAgentsInstrumentor, Operator, PROMPT_CACHE_TTL_SECONDS, Prompts, RunEntryContext, RunStatus, Scope, ScrubbingSpanProcessor, SerializationSpanProcessor, SessionSpanProcessor, Simulation, SpanIOProcessor, SpanType, TrialAwareOTLPExporter, TruncatingSerializer, Usage, agent, index_default as default, metadataField, mistralAIInstrumentor, netraExpressMiddleware, openaiAgentsInstrumentor, runWithExtractedContext, safeStringify, span, task, workflow };