netra-sdk 1.11.0 → 1.12.1

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';
@@ -9,10 +8,17 @@ import shimmer from 'shimmer';
9
8
  import { CompositePropagator, W3CTraceContextPropagator, W3CBaggagePropagator, ExportResultCode } from '@opentelemetry/core';
10
9
  import * as http from 'http';
11
10
  import * as https from 'https';
12
- import { JsonTraceSerializer } from '@opentelemetry/otlp-transformer';
11
+ import { ProtobufTraceSerializer } 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.1";
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);
@@ -11322,6 +11392,27 @@ var _FilteringSpanExporter = class _FilteringSpanExporter {
11322
11392
  _FilteringSpanExporter.MAX_REMEMBERED_ENTRIES = 1e4;
11323
11393
  _FilteringSpanExporter.MAX_LOCAL_PATTERN_CACHE = 100;
11324
11394
  var FilteringSpanExporter = _FilteringSpanExporter;
11395
+ var HTTP_STATUS_PAYLOAD_TOO_LARGE = 413;
11396
+ var RESPONSE_EXCERPT_MAX_CHARS = 200;
11397
+ var PAYLOAD_TOO_LARGE_HINT = "Lower OTEL_BSP_MAX_EXPORT_BATCH_SIZE or reduce large span attributes such as prompts and completions.";
11398
+ function describeServerMessage(responseBody) {
11399
+ try {
11400
+ const parsed = JSON.parse(responseBody);
11401
+ const message = parsed?.error?.message;
11402
+ if (typeof message === "string") return `"${message}"`;
11403
+ if (Array.isArray(message) && message.every((m) => typeof m === "string")) {
11404
+ return `"${message.join("; ")}"`;
11405
+ }
11406
+ } catch {
11407
+ }
11408
+ const excerpt = responseBody.trim().slice(0, RESPONSE_EXCERPT_MAX_CHARS);
11409
+ return excerpt ? `"${excerpt}"` : "(empty response body)";
11410
+ }
11411
+ function formatExportFailure(statusCode, statusMessage, responseBody, spanCount, requestBytes) {
11412
+ const status = [statusCode ?? "unknown", statusMessage].filter(Boolean).join(" ");
11413
+ const hint = statusCode === HTTP_STATUS_PAYLOAD_TOO_LARGE ? ` ${PAYLOAD_TOO_LARGE_HINT}` : "";
11414
+ return `Span export failed with HTTP ${status}: ${describeServerMessage(responseBody)}. Dropped a batch of ${spanCount} spans (${requestBytes} bytes).${hint}`;
11415
+ }
11325
11416
  var TrialAwareOTLPExporter = class {
11326
11417
  constructor(config) {
11327
11418
  this._isShutdown = false;
@@ -11334,7 +11425,7 @@ var TrialAwareOTLPExporter = class {
11334
11425
  }
11335
11426
  let data;
11336
11427
  try {
11337
- const serialized = JsonTraceSerializer.serializeRequest(spans);
11428
+ const serialized = ProtobufTraceSerializer.serializeRequest(spans);
11338
11429
  if (!serialized) throw new Error("Serialization failed");
11339
11430
  data = serialized;
11340
11431
  } catch (err) {
@@ -11343,6 +11434,7 @@ var TrialAwareOTLPExporter = class {
11343
11434
  error: err instanceof Error ? err : new Error("Serialization failed")
11344
11435
  });
11345
11436
  }
11437
+ const requestBytes = typeof data === "string" ? Buffer.byteLength(data) : data.byteLength;
11346
11438
  const url = new URL(this._url);
11347
11439
  const options = {
11348
11440
  hostname: url.hostname,
@@ -11352,8 +11444,8 @@ var TrialAwareOTLPExporter = class {
11352
11444
  headers: {
11353
11445
  ...this._headers,
11354
11446
  host: url.host,
11355
- "Content-Type": "application/json",
11356
- "Content-Length": typeof data === "string" ? Buffer.byteLength(data) : data.byteLength
11447
+ "Content-Type": "application/x-protobuf",
11448
+ "Content-Length": requestBytes
11357
11449
  }
11358
11450
  };
11359
11451
  const lib = url.protocol === "https:" ? https : http;
@@ -11364,6 +11456,15 @@ var TrialAwareOTLPExporter = class {
11364
11456
  if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
11365
11457
  resultCallback({ code: ExportResultCode.SUCCESS });
11366
11458
  } else {
11459
+ Logger.warn(
11460
+ formatExportFailure(
11461
+ res.statusCode,
11462
+ res.statusMessage,
11463
+ body,
11464
+ spans.length,
11465
+ requestBytes
11466
+ )
11467
+ );
11367
11468
  this.checkErrorBody(body, res.statusCode);
11368
11469
  resultCallback({
11369
11470
  code: ExportResultCode.FAILED,
@@ -11372,10 +11473,12 @@ var TrialAwareOTLPExporter = class {
11372
11473
  }
11373
11474
  });
11374
11475
  });
11375
- req.on(
11376
- "error",
11377
- (err) => resultCallback({ code: ExportResultCode.FAILED, error: err })
11378
- );
11476
+ req.on("error", (err) => {
11477
+ Logger.warn(
11478
+ `Span export failed: ${err.message}. Dropped a batch of ${spans.length} spans (${requestBytes} bytes).`
11479
+ );
11480
+ resultCallback({ code: ExportResultCode.FAILED, error: err });
11481
+ });
11379
11482
  req.write(data);
11380
11483
  req.end();
11381
11484
  }
@@ -11451,7 +11554,7 @@ function patchTraceloopLangchainCallbackHandler() {
11451
11554
  } catch (e) {
11452
11555
  Logger.debug("require() for traceloop langchain failed, falling back to import().");
11453
11556
  }
11454
- import('./dist-4UBY6Q6Z.js').then((mod) => {
11557
+ import('@traceloop/instrumentation-langchain').then((mod) => {
11455
11558
  applyPatch(mod, "import");
11456
11559
  }).catch(() => {
11457
11560
  });
@@ -12017,6 +12120,262 @@ async function uninstrumentAll() {
12017
12120
  }
12018
12121
  }
12019
12122
 
12123
+ // src/shutdown-registry.ts
12124
+ var FLUSH_TIMEOUT_MS = 5e3;
12125
+ var EXIT_BUDGET_MS = FLUSH_TIMEOUT_MS + 2e3;
12126
+ var SIGNALS = ["SIGINT", "SIGTERM"];
12127
+ var entries = /* @__PURE__ */ new Set();
12128
+ var ours = /* @__PURE__ */ new Set();
12129
+ var appHadListener = /* @__PURE__ */ new Map();
12130
+ var inFlight = [];
12131
+ var installed = false;
12132
+ var rejectionInstalled = false;
12133
+ var firing = false;
12134
+ var rethrowing = false;
12135
+ var appOwnedSignal;
12136
+ var handedBack;
12137
+ var generation = 0;
12138
+ function registerExitTask(task2, options = {}) {
12139
+ const entry = {
12140
+ task: task2,
12141
+ unhandledRejection: options.unhandledRejection === true
12142
+ };
12143
+ entries.add(entry);
12144
+ install();
12145
+ return () => {
12146
+ entries.delete(entry);
12147
+ if (entries.size === 0 && !firing) {
12148
+ uninstall();
12149
+ } else {
12150
+ syncRejectionListener();
12151
+ }
12152
+ };
12153
+ }
12154
+ function install() {
12155
+ if (firing) {
12156
+ return;
12157
+ }
12158
+ if (!installed) {
12159
+ installed = true;
12160
+ for (const sig of SIGNALS) {
12161
+ appHadListener.set(sig, process.listenerCount(sig) > 0);
12162
+ process.on(sig, onSignal);
12163
+ }
12164
+ process.on("uncaughtException", onUncaughtException);
12165
+ process.on("removeListener", onRemoveListener);
12166
+ ours.add(onSignal);
12167
+ ours.add(onUncaughtException);
12168
+ }
12169
+ syncRejectionListener();
12170
+ }
12171
+ var onRemoveListener = (event, listener) => {
12172
+ if (!SIGNALS.includes(event) || ours.has(listener)) {
12173
+ return;
12174
+ }
12175
+ const sig = event;
12176
+ queueMicrotask(() => {
12177
+ if (installed) {
12178
+ appHadListener.set(
12179
+ sig,
12180
+ process.listeners(sig).some((l) => !ours.has(l))
12181
+ );
12182
+ }
12183
+ });
12184
+ };
12185
+ function syncRejectionListener() {
12186
+ if (!installed) {
12187
+ return;
12188
+ }
12189
+ const wanted = [...entries].some((e) => e.unhandledRejection);
12190
+ if (wanted && !rejectionInstalled) {
12191
+ rejectionInstalled = true;
12192
+ process.on("unhandledRejection", onUnhandledRejection);
12193
+ ours.add(onUnhandledRejection);
12194
+ } else if (!wanted && rejectionInstalled) {
12195
+ rejectionInstalled = false;
12196
+ process.removeListener("unhandledRejection", onUnhandledRejection);
12197
+ ours.delete(onUnhandledRejection);
12198
+ }
12199
+ }
12200
+ function uninstall() {
12201
+ if (rejectionInstalled) {
12202
+ rejectionInstalled = false;
12203
+ process.removeListener("unhandledRejection", onUnhandledRejection);
12204
+ }
12205
+ if (!installed) {
12206
+ return;
12207
+ }
12208
+ installed = false;
12209
+ for (const sig of SIGNALS) {
12210
+ process.removeListener(sig, onSignal);
12211
+ }
12212
+ process.removeListener("uncaughtException", onUncaughtException);
12213
+ process.removeListener("removeListener", onRemoveListener);
12214
+ ours.clear();
12215
+ appHadListener.clear();
12216
+ }
12217
+ function appHandles(event) {
12218
+ const live = process.listeners(event).some((l) => !ours.has(l));
12219
+ if (live) {
12220
+ return true;
12221
+ }
12222
+ return event !== "uncaughtException" && appHadListener.get(event) === true;
12223
+ }
12224
+ async function runTasks(reason) {
12225
+ const pending = [...entries];
12226
+ pending.forEach((e) => entries.delete(e));
12227
+ let timer;
12228
+ const budget = new Promise((resolve) => {
12229
+ timer = setTimeout(resolve, EXIT_BUDGET_MS);
12230
+ timer.unref?.();
12231
+ });
12232
+ const running = pending.map((e) => ({
12233
+ task: e.task,
12234
+ promise: Promise.resolve().then(() => e.task(reason))
12235
+ }));
12236
+ running.forEach((r) => r.promise.catch(() => {
12237
+ }));
12238
+ inFlight = running;
12239
+ try {
12240
+ await Promise.race([
12241
+ Promise.allSettled(running.map((r) => r.promise)),
12242
+ budget
12243
+ ]);
12244
+ } finally {
12245
+ clearTimeout(timer);
12246
+ inFlight = inFlight.filter((r) => !running.includes(r));
12247
+ }
12248
+ }
12249
+ async function settleOtherExitTasks(exclude) {
12250
+ const others = inFlight.filter((r) => r.task !== exclude).map((r) => r.promise);
12251
+ const notYetRun = [...entries].filter((e) => e.task !== exclude);
12252
+ notYetRun.forEach((e) => entries.delete(e));
12253
+ const started = notYetRun.map((e) => {
12254
+ const p = Promise.resolve().then(() => e.task({ kind: "shutdown" }));
12255
+ p.catch(() => {
12256
+ });
12257
+ return p;
12258
+ });
12259
+ const all = [...others, ...started];
12260
+ if (all.length === 0) {
12261
+ return;
12262
+ }
12263
+ let timer;
12264
+ const budget = new Promise((resolve) => {
12265
+ timer = setTimeout(resolve, EXIT_BUDGET_MS);
12266
+ timer.unref?.();
12267
+ });
12268
+ try {
12269
+ await Promise.race([Promise.allSettled(all), budget]);
12270
+ } finally {
12271
+ clearTimeout(timer);
12272
+ }
12273
+ }
12274
+ function startFire(appOwned) {
12275
+ firing = true;
12276
+ appOwnedSignal = appOwned;
12277
+ handedBack = void 0;
12278
+ return ++generation;
12279
+ }
12280
+ var onSignal = (sig) => {
12281
+ if (firing) {
12282
+ const handled2 = process.listeners(sig).some((l) => !ours.has(l));
12283
+ if (!handled2 && sig === appOwnedSignal && !handedBack) {
12284
+ Logger.debug(`netra: ${sig} handed back by the app; exiting after flush`);
12285
+ handedBack = sig;
12286
+ return;
12287
+ }
12288
+ Logger.debug(`netra: second ${sig} during shutdown; exiting now`);
12289
+ generation++;
12290
+ firing = false;
12291
+ uninstall();
12292
+ if (!handled2) {
12293
+ try {
12294
+ process.kill(process.pid, sig);
12295
+ } catch {
12296
+ }
12297
+ }
12298
+ return;
12299
+ }
12300
+ const handled = appHandles(sig);
12301
+ const gen = startFire(handled ? sig : void 0);
12302
+ Logger.log(`
12303
+ Received ${sig}. Flushing Netra SDK...`);
12304
+ void runTasks({ kind: "signal", signal: sig }).catch((err) => Logger.error("netra: error during shutdown:", err)).finally(() => {
12305
+ if (gen !== generation) {
12306
+ return;
12307
+ }
12308
+ uninstall();
12309
+ firing = false;
12310
+ const reraise = handled ? handedBack : sig;
12311
+ if (reraise) {
12312
+ try {
12313
+ process.kill(process.pid, reraise);
12314
+ } catch {
12315
+ }
12316
+ }
12317
+ });
12318
+ };
12319
+ var onUncaughtException = (error) => {
12320
+ if (rethrowing) {
12321
+ rethrowing = false;
12322
+ return;
12323
+ }
12324
+ if (firing) {
12325
+ if (appHandles("uncaughtException")) {
12326
+ return;
12327
+ }
12328
+ uninstall();
12329
+ console.error(error);
12330
+ process.exitCode = 1;
12331
+ setImmediate(() => process.exit(1));
12332
+ return;
12333
+ }
12334
+ if (appHandles("uncaughtException")) {
12335
+ return;
12336
+ }
12337
+ const gen = startFire();
12338
+ Logger.error("Uncaught exception; flushing Netra SDK before exit...");
12339
+ void runTasks({ kind: "uncaughtException", error }).catch((err) => Logger.error("netra: error during crash shutdown:", err)).finally(() => {
12340
+ if (gen !== generation) {
12341
+ return;
12342
+ }
12343
+ uninstall();
12344
+ firing = false;
12345
+ console.error(error);
12346
+ process.exitCode = 1;
12347
+ setImmediate(() => process.exit(1));
12348
+ });
12349
+ };
12350
+ var onUnhandledRejection = (reason) => {
12351
+ if (firing) {
12352
+ return;
12353
+ }
12354
+ const rejHandled = process.listeners("unhandledRejection").some((l) => !ours.has(l));
12355
+ if (rejHandled) {
12356
+ return;
12357
+ }
12358
+ if (!appHandles("uncaughtException")) {
12359
+ const gen = startFire();
12360
+ void runTasks({ kind: "unhandledRejection", error: reason }).catch((err) => Logger.error("netra: error during shutdown:", err)).finally(() => {
12361
+ if (gen !== generation) {
12362
+ return;
12363
+ }
12364
+ firing = false;
12365
+ uninstall();
12366
+ rethrow(reason);
12367
+ });
12368
+ return;
12369
+ }
12370
+ rethrow(reason);
12371
+ };
12372
+ function rethrow(reason) {
12373
+ rethrowing = true;
12374
+ setImmediate(() => {
12375
+ throw reason;
12376
+ });
12377
+ }
12378
+
12020
12379
  // src/simulation/task.ts
12021
12380
  var BaseTask = class {
12022
12381
  };
@@ -12269,7 +12628,7 @@ var SimulationHttpClient = class {
12269
12628
  return null;
12270
12629
  }
12271
12630
  try {
12272
- const url = `/evaluations/run/${runId}/item/${runItemId}/first-turn`;
12631
+ const url = apiPath`/evaluations/run/${runId}/item/${runItemId}/first-turn`;
12273
12632
  const response = await this.client.post(url, {});
12274
12633
  const data = response.data;
12275
12634
  const responseData = data.data || {};
@@ -12353,7 +12712,7 @@ var SimulationHttpClient = class {
12353
12712
  return;
12354
12713
  }
12355
12714
  try {
12356
- const url = `/evaluations/run/${runId}/item/${runItemId}/status`;
12715
+ const url = apiPath`/evaluations/run/${runId}/item/${runItemId}/status`;
12357
12716
  const payload = { status, failureReason: error };
12358
12717
  await this.client.patch(url, payload);
12359
12718
  Logger.info(`${LOG_PREFIX5}: Reported failure - ${error}`);
@@ -12373,7 +12732,7 @@ var SimulationHttpClient = class {
12373
12732
  return { success: false };
12374
12733
  }
12375
12734
  try {
12376
- const url = `/evaluations/run/${runId}/status`;
12735
+ const url = apiPath`/evaluations/run/${runId}/status`;
12377
12736
  const payload = { status };
12378
12737
  const response = await this.client.post(url, payload);
12379
12738
  const data = response.data;
@@ -12572,38 +12931,10 @@ var Simulation = class {
12572
12931
  Logger.error(`${LOG_PREFIX7}: No items returned from initialize_run`);
12573
12932
  return null;
12574
12933
  }
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
- }
12934
+ const unregisterExitTask = registerExitTask(
12935
+ () => this._client.postRunStatus(runId, "failed"),
12936
+ { unhandledRejection: true }
12937
+ );
12607
12938
  try {
12608
12939
  let sharedContext = null;
12609
12940
  if (hooks?.beforeAll) {
@@ -12726,12 +13057,7 @@ var Simulation = class {
12726
13057
  throw error;
12727
13058
  }
12728
13059
  } 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
- }
13060
+ unregisterExitTask();
12735
13061
  }
12736
13062
  }
12737
13063
  /**
@@ -13117,7 +13443,7 @@ function span(targetOrOptions, options) {
13117
13443
  }
13118
13444
 
13119
13445
  // src/index.ts
13120
- var Netra = class {
13446
+ var _Netra = class _Netra {
13121
13447
  static getConfig() {
13122
13448
  if (!this._config) {
13123
13449
  throw new Error("Netra SDK not initialized. Call Netra.init() first.");
@@ -13131,6 +13457,9 @@ var Netra = class {
13131
13457
  * Initialize the Netra SDK.
13132
13458
  */
13133
13459
  static async init(config = {}) {
13460
+ if (this._shutdownPromise) {
13461
+ await this._shutdownPromise;
13462
+ }
13134
13463
  if (this._initialized) {
13135
13464
  Logger.warn("Netra.init() called more than once; ignoring subsequent calls.");
13136
13465
  return;
@@ -13192,56 +13521,82 @@ var Netra = class {
13192
13521
  `SDK version=${pkgVersion} libraryVersion=${Config.LIBRARY_VERSION} build=langgraph-parenting-v3 packageJson=${pkgPath}`
13193
13522
  );
13194
13523
  }
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);
13524
+ if (config.registerShutdownHooks !== false) {
13525
+ this._registerShutdownHooks();
13526
+ }
13217
13527
  await instrumentationsReady;
13218
13528
  }
13219
- static async shutdown() {
13220
- if (!this._initialized) {
13529
+ /**
13530
+ * Flush spans when the host process is going away, without taking over
13531
+ * the process lifecycle: the SDK never decides when (or with which code)
13532
+ * the process exits. Once flushed, if no other listener is handling the
13533
+ * event, Node's default behaviour is restored (the signal is re-raised so
13534
+ * the exit code is 128+n; an uncaught exception exits with code 1).
13535
+ */
13536
+ static _registerShutdownHooks() {
13537
+ if (this._unregisterFlush) {
13221
13538
  return;
13222
13539
  }
13540
+ this._unregisterFlush = registerExitTask(this._flushTask);
13541
+ const beforeExit = () => {
13542
+ void this.shutdown();
13543
+ };
13544
+ this._beforeExit = beforeExit;
13545
+ process.once("beforeExit", beforeExit);
13546
+ }
13547
+ static _removeShutdownHooks() {
13548
+ this._unregisterFlush?.();
13549
+ this._unregisterFlush = void 0;
13550
+ if (this._beforeExit) {
13551
+ process.removeListener("beforeExit", this._beforeExit);
13552
+ this._beforeExit = void 0;
13553
+ }
13554
+ }
13555
+ /**
13556
+ * Flush pending spans and release SDK resources. Safe to call more than
13557
+ * once and from several places at the same time (e.g. the app's own SIGTERM
13558
+ * handler while the SDK's hook is also flushing): concurrent callers share
13559
+ * the same in-flight shutdown and all resolve once it has finished.
13560
+ */
13561
+ static shutdown() {
13562
+ if (this._shutdownPromise) {
13563
+ return this._shutdownPromise;
13564
+ }
13565
+ if (!this._initialized) {
13566
+ return Promise.resolve();
13567
+ }
13568
+ this._shutdownPromise = this._shutdown().finally(() => {
13569
+ this._shutdownPromise = void 0;
13570
+ });
13571
+ return this._shutdownPromise;
13572
+ }
13573
+ static async _shutdown() {
13574
+ this._removeShutdownHooks();
13223
13575
  try {
13224
13576
  await uninstrumentAll();
13225
13577
  } catch (e) {
13226
13578
  Logger.error("Error during uninstrumentAll:", e);
13227
13579
  }
13228
- const FLUSH_TIMEOUT_MS = 5e3;
13580
+ let flushTimer;
13229
13581
  try {
13230
- const traceProvider = trace.getTracerProvider();
13582
+ const globalProvider = trace.getTracerProvider();
13583
+ const traceProvider = typeof globalProvider.getDelegate === "function" ? globalProvider.getDelegate() : globalProvider;
13231
13584
  const flushPromise = (async () => {
13232
- if ("forceFlush" in traceProvider && typeof traceProvider.forceFlush === "function") {
13585
+ if (typeof traceProvider?.forceFlush === "function") {
13233
13586
  await traceProvider.forceFlush();
13234
13587
  }
13235
- if ("shutdown" in traceProvider && typeof traceProvider.shutdown === "function") {
13236
- await traceProvider.shutdown();
13237
- }
13238
13588
  })();
13239
13589
  await Promise.race([
13240
13590
  flushPromise,
13241
- new Promise((resolve) => setTimeout(resolve, FLUSH_TIMEOUT_MS))
13591
+ new Promise((resolve) => {
13592
+ flushTimer = setTimeout(resolve, FLUSH_TIMEOUT_MS);
13593
+ flushTimer.unref?.();
13594
+ })
13242
13595
  ]);
13243
13596
  } catch (e) {
13244
13597
  Logger.error("Error during Netra trace shutdown:", e);
13598
+ } finally {
13599
+ clearTimeout(flushTimer);
13245
13600
  }
13246
13601
  try {
13247
13602
  this.prompts?.clearCache();
@@ -13249,6 +13604,11 @@ Received ${signal}. Shutting down Netra SDK...`);
13249
13604
  } catch (e) {
13250
13605
  Logger.error("Error clearing SDK API caches:", e);
13251
13606
  }
13607
+ try {
13608
+ await settleOtherExitTasks(this._flushTask);
13609
+ } catch (e) {
13610
+ Logger.error("Error awaiting pending shutdown tasks:", e);
13611
+ }
13252
13612
  this._initialized = false;
13253
13613
  this._tracer = void 0;
13254
13614
  }
@@ -13401,10 +13761,12 @@ Received ${signal}. Shutting down Netra SDK...`);
13401
13761
  });
13402
13762
  }
13403
13763
  };
13404
- Netra._SDK_NAME = "netra_sdk";
13405
- Netra._initialized = false;
13406
- Netra._metricsEnabled = false;
13407
- Netra.withBlockedSpansLocal = withBlockedSpansLocal;
13764
+ _Netra._SDK_NAME = "netra_sdk";
13765
+ _Netra._initialized = false;
13766
+ _Netra._metricsEnabled = false;
13767
+ _Netra._flushTask = () => _Netra.shutdown();
13768
+ _Netra.withBlockedSpansLocal = withBlockedSpansLocal;
13769
+ var Netra = _Netra;
13408
13770
  var index_default = Netra;
13409
13771
 
13410
13772
  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 };