netra-sdk 1.10.1 → 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) {
@@ -253,10 +291,10 @@ var UsageHttpClient = class extends NetraHttpClient {
253
291
  user_id: params.userId,
254
292
  tenant_id: params.tenantId
255
293
  };
256
- for (const [field3, value] of Object.entries(filterMapping)) {
294
+ for (const [field, value] of Object.entries(filterMapping)) {
257
295
  if (value !== void 0) {
258
296
  filters.push({
259
- field: field3,
297
+ field,
260
298
  operator: "equals",
261
299
  type: "string",
262
300
  value
@@ -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 : {};
@@ -465,8 +503,8 @@ var Usage = class {
465
503
  if (!page) {
466
504
  break;
467
505
  }
468
- for (const trace25 of page.traces) {
469
- yield trace25;
506
+ for (const trace24 of page.traces) {
507
+ yield trace24;
470
508
  }
471
509
  if (!page.hasNextPage || !page.nextCursor) {
472
510
  break;
@@ -579,7 +617,7 @@ var Usage = class {
579
617
  };
580
618
 
581
619
  // src/version.ts
582
- var SDK_VERSION = "1.10.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
  }
@@ -1943,13 +1981,13 @@ async function runSingleEvaluator(params) {
1943
1981
  if (config) {
1944
1982
  expectedName = config.name;
1945
1983
  }
1946
- const context17 = {
1984
+ const context16 = {
1947
1985
  input: itemInput,
1948
1986
  taskOutput,
1949
1987
  expectedOutput,
1950
1988
  metadata
1951
1989
  };
1952
- let result = evaluator.evaluate(context17);
1990
+ let result = evaluator.evaluate(context16);
1953
1991
  if (result instanceof Promise) {
1954
1992
  result = await result;
1955
1993
  }
@@ -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);
@@ -3946,14 +3987,14 @@ var SpanIOProcessor = class {
3946
3987
  if (promptMatch) {
3947
3988
  original(key, value);
3948
3989
  const idx = parseInt(promptMatch[1], 10);
3949
- const field3 = promptMatch[2];
3990
+ const field = promptMatch[2];
3950
3991
  if (!prompts) prompts = /* @__PURE__ */ new Map();
3951
3992
  let entry = prompts.get(idx);
3952
3993
  if (!entry) {
3953
3994
  entry = {};
3954
3995
  prompts.set(idx, entry);
3955
3996
  }
3956
- entry[field3] = String(value);
3997
+ entry[field] = String(value);
3957
3998
  if (!inputLocked() && (inputIsEmpty() || genAiOwnsInput)) {
3958
3999
  original("input", buildMessages(prompts));
3959
4000
  genAiOwnsInput = true;
@@ -3964,14 +4005,14 @@ var SpanIOProcessor = class {
3964
4005
  if (completionMatch) {
3965
4006
  original(key, value);
3966
4007
  const idx = parseInt(completionMatch[1], 10);
3967
- const field3 = completionMatch[2];
4008
+ const field = completionMatch[2];
3968
4009
  if (!completions) completions = /* @__PURE__ */ new Map();
3969
4010
  let entry = completions.get(idx);
3970
4011
  if (!entry) {
3971
4012
  entry = {};
3972
4013
  completions.set(idx, entry);
3973
4014
  }
3974
- entry[field3] = String(value);
4015
+ entry[field] = String(value);
3975
4016
  if (!outputLocked() && (outputIsEmpty() || genAiOwnsOutput)) {
3976
4017
  original("output", buildMessages(completions));
3977
4018
  genAiOwnsOutput = true;
@@ -4231,6 +4272,8 @@ var SpanAttributes2 = {
4231
4272
  LLM_USAGE_COMPLETION_TOKENS: "gen_ai.usage.completion_tokens",
4232
4273
  LLM_USAGE_CACHE_READ_INPUT_TOKENS: "gen_ai.usage.cache_read_input_tokens",
4233
4274
  LLM_USAGE_CACHE_CREATION_INPUT_TOKENS: "gen_ai.usage.cache_creation_input_tokens",
4275
+ LLM_USAGE_CACHE_CREATION_INPUT_TOKENS_30M: "gen_ai.usage.cache_creation_input_tokens_30m",
4276
+ LLM_USAGE_CACHE_CREATION_INPUT_TOKENS_12H: "gen_ai.usage.cache_creation_input_tokens_12h",
4234
4277
  LLM_USAGE_REASONING_TOKENS: "gen_ai.usage.reasoning_tokens",
4235
4278
  LLM_USAGE_TOTAL_TOKENS: "llm.usage.total_tokens",
4236
4279
  LLM_FREQUENCY_PENALTY: "llm.frequency_penalty",
@@ -4238,33 +4281,7 @@ var SpanAttributes2 = {
4238
4281
  LLM_CHAT_STOP_SEQUENCES: "llm.chat.stop_sequences",
4239
4282
  LLM_IS_STREAMING: "llm.is_streaming",
4240
4283
  LLM_COMPLETIONS: "gen_ai.completion",
4241
- LLM_PROMPTS: "gen_ai.prompt",
4242
- // Google GenAI Interactions API. Its request is flat snake_case and its
4243
- // response is a multi-step Interaction, so it needs names the chat/embedding
4244
- // surfaces have no equivalent for.
4245
- LLM_REQUEST_AGENT: "gen_ai.request.agent",
4246
- LLM_REQUEST_AGENT_CONFIG: "gen_ai.request.agent_config",
4247
- LLM_REQUEST_SEED: "gen_ai.request.seed",
4248
- LLM_REQUEST_THINKING_SUMMARIES: "gen_ai.request.thinking_summaries",
4249
- LLM_REQUEST_TOOL_CHOICE: "llm.request.tool_choice",
4250
- LLM_REQUEST_TOOLS: "llm.request.functions",
4251
- LLM_REQUEST_STORE: "gen_ai.request.store",
4252
- LLM_REQUEST_BACKGROUND: "gen_ai.request.background",
4253
- LLM_REQUEST_PREVIOUS_INTERACTION_ID: "gen_ai.request.previous_interaction_id",
4254
- LLM_REQUEST_RESPONSE_FORMAT: "gen_ai.request.response_format",
4255
- LLM_REQUEST_RESPONSE_MIME_TYPE: "gen_ai.request.response_mime_type",
4256
- LLM_REQUEST_RESPONSE_MODALITIES: "gen_ai.request.response_modalities",
4257
- LLM_REQUEST_SERVICE_TIER: "gen_ai.request.service_tier",
4258
- LLM_RESPONSE_ID: "gen_ai.response.id",
4259
- LLM_RESPONSE_STATUS: "gen_ai.response.status",
4260
- LLM_RESPONSE_PREVIOUS_INTERACTION_ID: "gen_ai.response.previous_interaction_id",
4261
- LLM_RESPONSE_REASONING: "llm.response.reasoning",
4262
- LLM_INTERACTION_STEP_COUNT: "gen_ai.interaction.step_count",
4263
- LLM_USAGE_TOOL_USE_TOKENS: "gen_ai.usage.tool_use_tokens",
4264
- LLM_USAGE_GROUNDING_TOOL_COUNT: "gen_ai.usage.grounding_tool_count",
4265
- // Set when a stream is consumed through a path we cannot observe
4266
- // (getReader/pipeTo/pipeThrough/tee), so the span closes instead of leaking.
4267
- STREAM_UNOBSERVED: "netra.stream.unobserved"
4284
+ LLM_PROMPTS: "gen_ai.prompt"
4268
4285
  };
4269
4286
  var VALID_NATIVE_TRACING_MODES = /* @__PURE__ */ new Set(["both", "netra", "netra-strict"]);
4270
4287
  function parseNativeTracingEnv(name) {
@@ -4594,6 +4611,19 @@ function setFinishReason(span2, response) {
4594
4611
  }
4595
4612
  }
4596
4613
  }
4614
+ var CACHE_WRITE_TTL_ATTRIBUTES = {
4615
+ ttl_30m_tokens: SpanAttributes2.LLM_USAGE_CACHE_CREATION_INPUT_TOKENS_30M,
4616
+ ttl_12h_tokens: SpanAttributes2.LLM_USAGE_CACHE_CREATION_INPUT_TOKENS_12H
4617
+ };
4618
+ function setCacheWriteTtlAttributes(span2, inputTokensDetails) {
4619
+ if (!isDict(inputTokensDetails)) return;
4620
+ const breakdown = inputTokensDetails.cache_write_tokens_details;
4621
+ if (!isDict(breakdown)) return;
4622
+ for (const [field, attribute] of Object.entries(CACHE_WRITE_TTL_ATTRIBUTES)) {
4623
+ const tokens = breakdown[field];
4624
+ if (typeof tokens === "number") span2.setAttribute(attribute, tokens);
4625
+ }
4626
+ }
4597
4627
  function setUsageAttributes(span2, response) {
4598
4628
  const usage = response.usage ?? response.usage_metadata;
4599
4629
  if (!usage) return;
@@ -4632,6 +4662,10 @@ function setUsageAttributes(span2, response) {
4632
4662
  Number(cacheCreationTokens)
4633
4663
  );
4634
4664
  }
4665
+ setCacheWriteTtlAttributes(
4666
+ span2,
4667
+ usage.prompt_tokens_details ?? usage.input_tokens_details
4668
+ );
4635
4669
  const reasoningTokens = (usage.completion_tokens_details ?? usage.output_tokens_details)?.reasoning_tokens;
4636
4670
  if (reasoningTokens !== void 0) {
4637
4671
  span2.setAttribute(
@@ -5781,6 +5815,15 @@ var BaseInstrumentor = class {
5781
5815
  }
5782
5816
  };
5783
5817
 
5818
+ // src/instrumentation/google-genai/version.ts
5819
+ var __version__2 = "1.0.0";
5820
+
5821
+ // src/instrumentation/google-genai/types.ts
5822
+ var SPAN_NAMES2 = {
5823
+ CHAT: "google_genai.chat",
5824
+ EMBEDDING: "google_genai.embedding"
5825
+ };
5826
+
5784
5827
  // src/instrumentation/google-genai/utils.ts
5785
5828
  var LOG_PREFIX = "netra.instrumentation.google_genai";
5786
5829
  function setRequestAttributes3(span2, params, requestType) {
@@ -6129,914 +6172,42 @@ function processStreamChunk2(accumulated, chunk, span2, startTime) {
6129
6172
  if (Array.isArray(fcs) && fcs.length > 0) {
6130
6173
  if (!accumulated._functionCalls) accumulated._functionCalls = [];
6131
6174
  accumulated._functionCalls.push(...fcs);
6132
- }
6133
- if (chunk.usageMetadata) {
6134
- accumulated.usageMetadata = chunk.usageMetadata;
6135
- }
6136
- if (Array.isArray(chunk.candidates) && chunk.candidates.length > 0) {
6137
- const reason = chunk.candidates[0]?.finishReason;
6138
- if (reason) {
6139
- if (!accumulated.candidates) accumulated.candidates = [{}];
6140
- accumulated.candidates[0].finishReason = reason;
6141
- }
6142
- }
6143
- if (Logger.isDebugMode()) {
6144
- span2.addEvent("llm.content.completion.chunk");
6145
- }
6146
- } catch (e) {
6147
- Logger.error(`${LOG_PREFIX}: processStreamChunk error`, e);
6148
- }
6149
- }
6150
- function buildAccumulatedResponse(accumulated) {
6151
- const response = {
6152
- responseId: accumulated.responseId,
6153
- modelVersion: accumulated.modelVersion,
6154
- usageMetadata: accumulated.usageMetadata,
6155
- candidates: accumulated.candidates
6156
- };
6157
- if (accumulated._text) {
6158
- response.text = accumulated._text;
6159
- }
6160
- if (accumulated._functionCalls) {
6161
- response.functionCalls = accumulated._functionCalls;
6162
- }
6163
- return response;
6164
- }
6165
-
6166
- // src/instrumentation/google-genai/interactions-utils.ts
6167
- var LOG_PREFIX2 = "netra.instrumentation.google_genai";
6168
- var CONTENT_TYPES = /* @__PURE__ */ new Set([
6169
- "text",
6170
- "image",
6171
- "audio",
6172
- "document",
6173
- "video"
6174
- ]);
6175
- var SERVER_TOOL_CALL_STEPS = /* @__PURE__ */ new Set([
6176
- "code_execution_call",
6177
- "url_context_call",
6178
- "google_search_call",
6179
- "google_maps_call",
6180
- "file_search_call",
6181
- "mcp_server_tool_call"
6182
- ]);
6183
- var SERVER_TOOL_RESULT_STEPS = /* @__PURE__ */ new Set([
6184
- "code_execution_result",
6185
- "url_context_result",
6186
- "google_search_result",
6187
- "google_maps_result",
6188
- "file_search_result",
6189
- "mcp_server_tool_result"
6190
- ]);
6191
- var STEP_TYPES = /* @__PURE__ */ new Set([
6192
- "user_input",
6193
- "model_output",
6194
- "thought",
6195
- "function_call",
6196
- "function_result",
6197
- ...SERVER_TOOL_CALL_STEPS,
6198
- ...SERVER_TOOL_RESULT_STEPS
6199
- ]);
6200
- function field(obj, name) {
6201
- if (!isDict(obj)) return void 0;
6202
- return obj[name];
6203
- }
6204
- function asArray(value) {
6205
- if (value === null || value === void 0) return [];
6206
- return Array.isArray(value) ? value : [value];
6207
- }
6208
- function contentText(items) {
6209
- const parts = [];
6210
- for (const item of asArray(items)) {
6211
- const itemType = field(item, "type");
6212
- if (itemType === "text") {
6213
- const text = field(item, "text");
6214
- if (typeof text === "string") parts.push(text);
6215
- } else if (typeof itemType === "string" && CONTENT_TYPES.has(itemType)) {
6216
- parts.push(`<${itemType}>`);
6217
- }
6218
- }
6219
- return parts.join("");
6220
- }
6221
- function contentModalities(items) {
6222
- const modalities = [];
6223
- for (const item of asArray(items)) {
6224
- const itemType = field(item, "type");
6225
- if (typeof itemType === "string" && CONTENT_TYPES.has(itemType) && itemType !== "text" && !modalities.includes(itemType)) {
6226
- modalities.push(itemType);
6227
- }
6228
- }
6229
- return modalities;
6230
- }
6231
- function stepMessage(step) {
6232
- const stepType = field(step, "type");
6233
- if (typeof stepType !== "string") return null;
6234
- if (stepType === "user_input") {
6235
- return {
6236
- role: "user",
6237
- content: contentText(field(step, "content")),
6238
- stepType
6239
- };
6240
- }
6241
- if (stepType === "model_output") {
6242
- const content = field(step, "content");
6243
- return {
6244
- role: "assistant",
6245
- content: contentText(content),
6246
- stepType,
6247
- modalities: contentModalities(content)
6248
- };
6249
- }
6250
- if (stepType === "thought") {
6251
- return {
6252
- role: "assistant",
6253
- content: contentText(field(step, "summary")),
6254
- stepType
6255
- };
6256
- }
6257
- if (stepType === "function_call") {
6258
- const toolCall = {
6259
- name: field(step, "name"),
6260
- id: field(step, "id"),
6261
- arguments: field(step, "arguments")
6262
- };
6263
- return {
6264
- role: "assistant",
6265
- content: safeStringify(toolCall),
6266
- stepType,
6267
- toolCall
6268
- };
6269
- }
6270
- if (stepType === "function_result") {
6271
- const name = field(step, "name");
6272
- return {
6273
- role: "tool",
6274
- content: safeStringify({
6275
- call_id: field(step, "call_id"),
6276
- name,
6277
- result: field(step, "result"),
6278
- is_error: field(step, "is_error")
6279
- }),
6280
- stepType,
6281
- toolCall: { name }
6282
- };
6283
- }
6284
- if (SERVER_TOOL_CALL_STEPS.has(stepType)) {
6285
- return {
6286
- role: "tool",
6287
- content: safeStringify({
6288
- name: stepType,
6289
- arguments: field(step, "arguments")
6290
- }),
6291
- stepType,
6292
- toolCall: { name: stepType }
6293
- };
6294
- }
6295
- if (SERVER_TOOL_RESULT_STEPS.has(stepType)) {
6296
- return {
6297
- role: "tool",
6298
- content: safeStringify({ name: stepType, result: field(step, "result") }),
6299
- stepType,
6300
- toolCall: { name: stepType }
6301
- };
6302
- }
6303
- return { role: "assistant", content: safeStringify(step), stepType };
6304
- }
6305
- function inputMessages(value) {
6306
- if (value === null || value === void 0) return [];
6307
- if (typeof value === "string") {
6308
- return [{ role: "user", content: value }];
6309
- }
6310
- if (Array.isArray(value)) {
6311
- if (value.length === 0) return [];
6312
- const types = value.map((item) => field(item, "type"));
6313
- if (types.every((t) => typeof t === "string" && STEP_TYPES.has(t))) {
6314
- const messages = [];
6315
- for (const item of value) {
6316
- const message = stepMessage(item);
6317
- if (message && message.stepType !== "thought" && message.content) {
6318
- messages.push(message);
6319
- }
6320
- }
6321
- return messages;
6322
- }
6323
- if (types.every((t) => typeof t === "string" && CONTENT_TYPES.has(t))) {
6324
- return [{ role: "user", content: contentText(value) }];
6325
- }
6326
- return [{ role: "user", content: safeStringify(value) }];
6327
- }
6328
- const valueType = field(value, "type");
6329
- if (typeof valueType === "string" && CONTENT_TYPES.has(valueType)) {
6330
- return [{ role: "user", content: contentText([value]) }];
6331
- }
6332
- if (typeof valueType === "string" && STEP_TYPES.has(valueType)) {
6333
- const message = stepMessage(value);
6334
- return message && message.content ? [message] : [];
6335
- }
6336
- return [{ role: "user", content: safeStringify(value) }];
6337
- }
6338
- function setToolDefinitions(span2, tools) {
6339
- if (!Array.isArray(tools)) return;
6340
- tools.forEach((tool, index) => {
6341
- const toolType = field(tool, "type");
6342
- const prefix = `${SpanAttributes2.LLM_REQUEST_TOOLS}.${index}`;
6343
- if (toolType === "function") {
6344
- const fn = field(tool, "function") ?? tool;
6345
- span2.setAttribute(`${prefix}.name`, String(field(fn, "name") ?? ""));
6346
- const description = field(fn, "description");
6347
- if (description !== void 0) {
6348
- span2.setAttribute(`${prefix}.description`, String(description));
6349
- }
6350
- const parameters = field(fn, "parameters");
6351
- if (parameters !== void 0) {
6352
- span2.setAttribute(`${prefix}.parameters`, safeStringify(parameters));
6353
- }
6354
- } else if (typeof toolType === "string") {
6355
- span2.setAttribute(`${prefix}.name`, toolType);
6356
- }
6357
- });
6358
- }
6359
- function setInteractionRequestAttributes(span2, params) {
6360
- try {
6361
- if (!span2.isRecording()) return;
6362
- span2.setAttribute(SpanAttributes2.LLM_REQUEST_TYPE, "chat");
6363
- span2.setAttribute(SpanAttributes2.LLM_SYSTEM, "google_genai");
6364
- if (params.model) {
6365
- span2.setAttribute(
6366
- SpanAttributes2.LLM_REQUEST_MODEL,
6367
- extractModelName(String(params.model))
6368
- );
6369
- }
6370
- if (params.agent !== void 0) {
6371
- span2.setAttribute(SpanAttributes2.LLM_REQUEST_AGENT, String(params.agent));
6372
- }
6373
- if (params.agent_config !== void 0) {
6374
- span2.setAttribute(
6375
- SpanAttributes2.LLM_REQUEST_AGENT_CONFIG,
6376
- safeStringify(params.agent_config)
6377
- );
6378
- }
6379
- const cfg = params.generation_config;
6380
- if (isDict(cfg)) {
6381
- if (cfg.temperature !== void 0) {
6382
- span2.setAttribute(
6383
- SpanAttributes2.LLM_REQUEST_TEMPERATURE,
6384
- Number(cfg.temperature)
6385
- );
6386
- }
6387
- if (cfg.top_p !== void 0) {
6388
- span2.setAttribute(SpanAttributes2.LLM_REQUEST_TOP_P, Number(cfg.top_p));
6389
- }
6390
- if (cfg.max_output_tokens !== void 0) {
6391
- span2.setAttribute(
6392
- SpanAttributes2.LLM_REQUEST_MAX_TOKENS,
6393
- Number(cfg.max_output_tokens)
6394
- );
6395
- }
6396
- if (cfg.seed !== void 0) {
6397
- span2.setAttribute(SpanAttributes2.LLM_REQUEST_SEED, Number(cfg.seed));
6398
- }
6399
- if (cfg.stop_sequences !== void 0) {
6400
- span2.setAttribute(
6401
- SpanAttributes2.LLM_CHAT_STOP_SEQUENCES,
6402
- safeStringify(cfg.stop_sequences)
6403
- );
6404
- }
6405
- if (cfg.thinking_level !== void 0) {
6406
- span2.setAttribute(
6407
- SpanAttributes2.LLM_REQUEST_REASONING_EFFORT,
6408
- String(cfg.thinking_level)
6409
- );
6410
- }
6411
- if (cfg.thinking_summaries !== void 0) {
6412
- span2.setAttribute(
6413
- SpanAttributes2.LLM_REQUEST_THINKING_SUMMARIES,
6414
- String(cfg.thinking_summaries)
6415
- );
6416
- }
6417
- if (cfg.tool_choice !== void 0) {
6418
- span2.setAttribute(
6419
- SpanAttributes2.LLM_REQUEST_TOOL_CHOICE,
6420
- safeStringify(cfg.tool_choice)
6421
- );
6422
- }
6423
- }
6424
- setToolDefinitions(span2, params.tools);
6425
- if (typeof params.store === "boolean") {
6426
- span2.setAttribute(SpanAttributes2.LLM_REQUEST_STORE, params.store);
6427
- }
6428
- if (typeof params.background === "boolean") {
6429
- span2.setAttribute(
6430
- SpanAttributes2.LLM_REQUEST_BACKGROUND,
6431
- params.background
6432
- );
6433
- }
6434
- if (params.previous_interaction_id !== void 0) {
6435
- span2.setAttribute(
6436
- SpanAttributes2.LLM_REQUEST_PREVIOUS_INTERACTION_ID,
6437
- String(params.previous_interaction_id)
6438
- );
6439
- }
6440
- if (params.response_mime_type !== void 0) {
6441
- span2.setAttribute(
6442
- SpanAttributes2.LLM_REQUEST_RESPONSE_MIME_TYPE,
6443
- String(params.response_mime_type)
6444
- );
6445
- }
6446
- if (params.service_tier !== void 0) {
6447
- span2.setAttribute(
6448
- SpanAttributes2.LLM_REQUEST_SERVICE_TIER,
6449
- String(params.service_tier)
6450
- );
6451
- }
6452
- if (params.response_format !== void 0) {
6453
- span2.setAttribute(
6454
- SpanAttributes2.LLM_REQUEST_RESPONSE_FORMAT,
6455
- safeStringify(params.response_format)
6456
- );
6457
- }
6458
- if (Array.isArray(params.response_modalities)) {
6459
- span2.setAttribute(
6460
- SpanAttributes2.LLM_REQUEST_RESPONSE_MODALITIES,
6461
- params.response_modalities.map((m) => String(m))
6462
- );
6463
- }
6464
- if (!isTraceContentEnabled()) return;
6465
- const messages = [];
6466
- if (params.system_instruction !== void 0) {
6467
- messages.push({
6468
- role: "system",
6469
- content: String(params.system_instruction)
6470
- });
6471
- }
6472
- messages.push(...inputMessages(params.input));
6473
- writePromptAttributes(
6474
- span2,
6475
- messages.filter((m) => m.content)
6476
- );
6477
- } catch (e) {
6478
- Logger.error(`${LOG_PREFIX2}: setInteractionRequestAttributes error`, e);
6479
- }
6480
- }
6481
- var MODALITY_USAGE_PREFIXES = {
6482
- input_tokens_by_modality: "gen_ai.usage.input_tokens_by_modality",
6483
- output_tokens_by_modality: "gen_ai.usage.output_tokens_by_modality",
6484
- cached_tokens_by_modality: "gen_ai.usage.cached_tokens_by_modality",
6485
- tool_use_tokens_by_modality: "gen_ai.usage.tool_use_tokens_by_modality"
6486
- };
6487
- function setUsageAttributes3(span2, usage) {
6488
- if (!isDict(usage)) return;
6489
- const totals = [
6490
- ["total_input_tokens", SpanAttributes2.LLM_USAGE_PROMPT_TOKENS],
6491
- ["total_tokens", SpanAttributes2.LLM_USAGE_TOTAL_TOKENS],
6492
- ["total_cached_tokens", SpanAttributes2.LLM_USAGE_CACHE_READ_INPUT_TOKENS],
6493
- ["total_thought_tokens", SpanAttributes2.LLM_USAGE_REASONING_TOKENS],
6494
- ["total_tool_use_tokens", SpanAttributes2.LLM_USAGE_TOOL_USE_TOKENS]
6495
- ];
6496
- for (const [field_, attribute] of totals) {
6497
- const value = usage[field_];
6498
- if (typeof value === "number") span2.setAttribute(attribute, value);
6499
- }
6500
- let completion = 0;
6501
- let hasCompletion = false;
6502
- for (const field_ of ["total_output_tokens", "total_thought_tokens"]) {
6503
- const value = usage[field_];
6504
- if (typeof value === "number") {
6505
- completion += value;
6506
- hasCompletion = true;
6507
- }
6508
- }
6509
- if (hasCompletion) {
6510
- span2.setAttribute(SpanAttributes2.LLM_USAGE_COMPLETION_TOKENS, completion);
6511
- }
6512
- for (const [field_, prefix] of Object.entries(MODALITY_USAGE_PREFIXES)) {
6513
- const entries = usage[field_];
6514
- if (!Array.isArray(entries)) continue;
6515
- for (const entry of entries) {
6516
- const modality = field(entry, "modality");
6517
- const tokens = field(entry, "tokens");
6518
- if (modality && typeof tokens === "number") {
6519
- span2.setAttribute(`${prefix}.${String(modality)}`, tokens);
6520
- }
6521
- }
6522
- }
6523
- const grounding = usage.grounding_tool_count;
6524
- if (Array.isArray(grounding)) {
6525
- for (const entry of grounding) {
6526
- const toolType = field(entry, "type");
6527
- const count = field(entry, "count");
6528
- if (toolType && typeof count === "number") {
6529
- span2.setAttribute(
6530
- `${SpanAttributes2.LLM_USAGE_GROUNDING_TOOL_COUNT}.${String(toolType)}`,
6531
- count
6532
- );
6533
- }
6534
- }
6535
- }
6536
- }
6537
- function outputSteps(steps) {
6538
- if (!Array.isArray(steps)) return [];
6539
- let firstOutput = 0;
6540
- steps.forEach((step, index) => {
6541
- if (field(step, "type") === "user_input") firstOutput = index + 1;
6542
- });
6543
- return steps.slice(firstOutput);
6544
- }
6545
- function interactionOutputText(steps) {
6546
- return outputSteps(steps).filter((step) => field(step, "type") === "model_output").map((step) => contentText(field(step, "content"))).join("");
6547
- }
6548
- function setInteractionResponseAttributes(span2, interaction) {
6549
- try {
6550
- if (!span2.isRecording() || !isDict(interaction)) return;
6551
- if (interaction.id !== void 0 && interaction.id !== null) {
6552
- const id = String(interaction.id);
6553
- span2.setAttribute(SpanAttributes2.LLM_RESPONSE_ID, id);
6554
- span2.setAttribute("llm.response.id", id);
6555
- }
6556
- if (interaction.model !== void 0 && interaction.model !== null) {
6557
- span2.setAttribute(
6558
- SpanAttributes2.LLM_RESPONSE_MODEL,
6559
- String(interaction.model)
6560
- );
6561
- }
6562
- if (interaction.status !== void 0 && interaction.status !== null) {
6563
- const status = String(interaction.status);
6564
- span2.setAttribute(SpanAttributes2.LLM_RESPONSE_STATUS, status);
6565
- span2.setAttribute(SpanAttributes2.LLM_RESPONSE_FINISH_REASON, status);
6566
- span2.setAttribute("gen_ai.response.finish_reason", status);
6567
- }
6568
- if (interaction.previous_interaction_id !== void 0 && interaction.previous_interaction_id !== null) {
6569
- span2.setAttribute(
6570
- SpanAttributes2.LLM_RESPONSE_PREVIOUS_INTERACTION_ID,
6571
- String(interaction.previous_interaction_id)
6572
- );
6573
- }
6574
- setUsageAttributes3(span2, interaction.usage);
6575
- if (Array.isArray(interaction.steps)) {
6576
- span2.setAttribute(
6577
- SpanAttributes2.LLM_INTERACTION_STEP_COUNT,
6578
- interaction.steps.length
6579
- );
6580
- }
6581
- if (!isTraceContentEnabled()) return;
6582
- const reasoning = [];
6583
- const emitted = [];
6584
- let index = 0;
6585
- for (const step of outputSteps(interaction.steps)) {
6586
- const message = stepMessage(step);
6587
- if (!message) continue;
6588
- if (message.stepType === "thought") {
6589
- if (message.content) reasoning.push(message.content);
6590
- continue;
6591
- }
6592
- if (!message.content) continue;
6593
- const prefix = `${SpanAttributes2.LLM_COMPLETIONS}.${index}`;
6594
- span2.setAttribute(`${prefix}.role`, message.role);
6595
- span2.setAttribute(`${prefix}.content`, message.content);
6596
- span2.setAttribute(`${prefix}.step_type`, message.stepType ?? "");
6597
- if (message.toolCall) {
6598
- span2.setAttribute(
6599
- `${prefix}.tool_calls.0.name`,
6600
- String(message.toolCall.name ?? "")
6601
- );
6602
- if (message.toolCall.id !== void 0) {
6603
- span2.setAttribute(
6604
- `${prefix}.tool_calls.0.id`,
6605
- String(message.toolCall.id)
6606
- );
6607
- }
6608
- if (message.toolCall.arguments !== void 0) {
6609
- span2.setAttribute(
6610
- `${prefix}.tool_calls.0.arguments`,
6611
- safeStringify(message.toolCall.arguments)
6612
- );
6613
- }
6614
- }
6615
- if (message.modalities && message.modalities.length > 0) {
6616
- span2.setAttribute(`${prefix}.modality`, message.modalities);
6617
- }
6618
- emitted.push(message);
6619
- index += 1;
6620
- }
6621
- if (emitted.length > 0) {
6622
- span2.setAttribute(
6623
- "output",
6624
- JSON.stringify(
6625
- emitted.map((m) => ({ role: m.role, content: m.content }))
6626
- )
6627
- );
6628
- }
6629
- if (reasoning.length > 0) {
6630
- span2.setAttribute(
6631
- SpanAttributes2.LLM_RESPONSE_REASONING,
6632
- reasoning.join("")
6633
- );
6634
- }
6635
- } catch (e) {
6636
- Logger.error(`${LOG_PREFIX2}: setInteractionResponseAttributes error`, e);
6637
- }
6638
- }
6639
-
6640
- // src/instrumentation/google-genai/types.ts
6641
- var SPAN_NAMES2 = {
6642
- CHAT: "google_genai.chat",
6643
- EMBEDDING: "google_genai.embedding",
6644
- INTERACTION: "google_genai.interaction"
6645
- };
6646
-
6647
- // src/instrumentation/google-genai/interactions-wrapper.ts
6648
- var LOG_PREFIX3 = "netra.instrumentation.google_genai";
6649
- var NETRA_STREAM = /* @__PURE__ */ Symbol.for("netra.googlegenai.interactions.stream");
6650
- var INTERACTION_CREATED = "interaction.created";
6651
- var INTERACTION_COMPLETED = "interaction.completed";
6652
- var INTERACTION_STATUS_UPDATE = "interaction.status_update";
6653
- var STEP_START = "step.start";
6654
- var STEP_DELTA = "step.delta";
6655
- var ERROR_EVENT = "error";
6656
- function field2(obj, name) {
6657
- if (obj === null || obj === void 0) return void 0;
6658
- return obj[name];
6659
- }
6660
- var InteractionStreamAccumulator = class {
6661
- constructor(span2, startTime) {
6662
- this.span = span2;
6663
- this.startTime = startTime;
6664
- this.finalized = false;
6665
- this.unobserved = null;
6666
- this.firstTextRecorded = false;
6667
- this.stepTypes = /* @__PURE__ */ new Map();
6668
- this.stepText = /* @__PURE__ */ new Map();
6669
- this.stepThoughts = /* @__PURE__ */ new Map();
6670
- this.stepArguments = /* @__PURE__ */ new Map();
6671
- this.stepMeta = /* @__PURE__ */ new Map();
6672
- this.completedSteps = null;
6673
- this.output = "";
6674
- }
6675
- processEvent(event) {
6676
- try {
6677
- this.reduce(event);
6678
- } catch (e) {
6679
- Logger.error(`${LOG_PREFIX3}: interaction event error`, e);
6680
- }
6681
- }
6682
- reduce(event) {
6683
- this.absorbUsage(event);
6684
- const eventType = field2(event, "event_type");
6685
- switch (eventType) {
6686
- case INTERACTION_CREATED: {
6687
- const interaction = field2(event, "interaction");
6688
- this.id = field2(interaction, "id") ?? this.id;
6689
- this.model = field2(interaction, "model") ?? this.model;
6690
- this.status = field2(interaction, "status") ?? this.status;
6691
- break;
6692
- }
6693
- case STEP_START: {
6694
- const index = field2(event, "index");
6695
- const step = field2(event, "step");
6696
- if (typeof index !== "number") break;
6697
- const stepType = field2(step, "type");
6698
- if (typeof stepType === "string") this.stepTypes.set(index, stepType);
6699
- if (stepType === "function_call") {
6700
- this.stepMeta.set(index, {
6701
- id: field2(step, "id"),
6702
- name: field2(step, "name")
6703
- });
6704
- }
6705
- break;
6706
- }
6707
- case STEP_DELTA:
6708
- this.reduceDelta(field2(event, "index"), field2(event, "delta"));
6709
- break;
6710
- case INTERACTION_STATUS_UPDATE:
6711
- this.status = field2(event, "status") ?? this.status;
6712
- break;
6713
- case INTERACTION_COMPLETED: {
6714
- const interaction = field2(event, "interaction");
6715
- this.id = field2(interaction, "id") ?? this.id;
6716
- this.model = field2(interaction, "model") ?? this.model;
6717
- this.status = field2(interaction, "status") ?? this.status;
6718
- const steps = field2(interaction, "steps");
6719
- if (Array.isArray(steps) && steps.length > 0) this.completedSteps = steps;
6720
- break;
6721
- }
6722
- case ERROR_EVENT:
6723
- this.error = field2(event, "error");
6724
- break;
6725
- }
6726
- }
6727
- reduceDelta(index, delta) {
6728
- if (typeof index !== "number" || delta === null || delta === void 0) return;
6729
- const deltaType = field2(delta, "type");
6730
- if (deltaType === "text") {
6731
- const text = field2(delta, "text");
6732
- if (typeof text === "string" && text.length > 0) {
6733
- push(this.stepText, index, text);
6734
- if (!this.stepTypes.has(index)) this.stepTypes.set(index, "model_output");
6735
- this.recordFirstText();
6736
- }
6737
- } else if (deltaType === "thought_summary") {
6738
- const text = deltaContentText(field2(delta, "content"));
6739
- if (text) {
6740
- push(this.stepThoughts, index, text);
6741
- if (!this.stepTypes.has(index)) this.stepTypes.set(index, "thought");
6742
- }
6743
- } else if (deltaType === "arguments_delta") {
6744
- const fragment = field2(delta, "arguments") ?? field2(delta, "delta");
6745
- if (typeof fragment === "string" && fragment.length > 0) {
6746
- push(this.stepArguments, index, fragment);
6747
- if (!this.stepTypes.has(index)) this.stepTypes.set(index, "function_call");
6748
- }
6749
- } else if (deltaType === "image" || deltaType === "audio" || deltaType === "document" || deltaType === "video") {
6750
- push(this.stepText, index, `<${deltaType}>`);
6751
- if (!this.stepTypes.has(index)) this.stepTypes.set(index, "model_output");
6752
- }
6753
- }
6754
- recordFirstText() {
6755
- if (this.firstTextRecorded) return;
6756
- this.firstTextRecorded = true;
6757
- this.span.setAttribute(
6758
- "gen_ai.performance.time_to_first_token",
6759
- (Date.now() - this.startTime) / 1e3
6760
- );
6761
- }
6762
- absorbUsage(event) {
6763
- const metadata = field2(event, "metadata");
6764
- const candidates = [
6765
- field2(metadata, "total_usage"),
6766
- field2(metadata, "usage"),
6767
- field2(event, "usage"),
6768
- field2(field2(event, "interaction"), "usage")
6769
- ];
6770
- for (const candidate of candidates) {
6771
- if (candidate !== void 0 && candidate !== null) {
6772
- this.usage = candidate;
6773
- return;
6774
- }
6775
- }
6776
- }
6777
- /** Mark the stream as consumed through a path we cannot observe. */
6778
- abandon(via) {
6779
- this.unobserved = via;
6780
- this.finalize();
6781
- }
6782
- buildInteraction() {
6783
- const steps = this.completedSteps && this.stepText.size === 0 ? this.completedSteps : this.buildSteps();
6784
- return {
6785
- id: this.id,
6786
- model: this.model,
6787
- status: this.status,
6788
- usage: this.usage,
6789
- steps
6790
- };
6791
- }
6792
- buildSteps() {
6793
- const indices = /* @__PURE__ */ new Set([
6794
- ...this.stepTypes.keys(),
6795
- ...this.stepText.keys(),
6796
- ...this.stepThoughts.keys()
6797
- ]);
6798
- return [...indices].sort((a, b) => a - b).map((index) => {
6799
- const stepType = this.stepTypes.get(index) ?? "model_output";
6800
- if (stepType === "thought") {
6801
- return {
6802
- type: "thought",
6803
- summary: [
6804
- { type: "text", text: (this.stepThoughts.get(index) ?? []).join("") }
6805
- ]
6806
- };
6807
- }
6808
- if (stepType === "function_call") {
6809
- const meta = this.stepMeta.get(index) ?? {};
6810
- return {
6811
- type: "function_call",
6812
- id: meta.id,
6813
- name: meta.name,
6814
- arguments: parseArguments(
6815
- (this.stepArguments.get(index) ?? []).join("")
6816
- )
6817
- };
6818
- }
6819
- return {
6820
- type: stepType,
6821
- content: [
6822
- { type: "text", text: (this.stepText.get(index) ?? []).join("") }
6823
- ]
6824
- };
6825
- });
6826
- }
6827
- /** Close the span. Safe to call more than once. */
6828
- finalize() {
6829
- if (this.finalized) return;
6830
- this.finalized = true;
6831
- try {
6832
- const interaction = this.buildInteraction();
6833
- setInteractionResponseAttributes(this.span, interaction);
6834
- this.output = interactionOutputText(interaction.steps);
6835
- this.span.setAttribute(
6836
- SpanAttributes2.LLM_RESPONSE_DURATION,
6837
- (Date.now() - this.startTime) / 1e3
6838
- );
6839
- if (this.unobserved) {
6840
- this.span.setAttribute(SpanAttributes2.STREAM_UNOBSERVED, this.unobserved);
6841
- }
6842
- if (this.error) {
6843
- this.span.setAttribute(
6844
- "error.type",
6845
- String(field2(this.error, "code") ?? "error")
6846
- );
6847
- this.span.setStatus({
6848
- code: SpanStatusCode.ERROR,
6849
- message: String(field2(this.error, "message") ?? "interaction failed")
6850
- });
6851
- } else {
6852
- this.span.setStatus({ code: SpanStatusCode.OK });
6853
- }
6854
- } catch (e) {
6855
- Logger.error(`${LOG_PREFIX3}: interaction finalize error`, e);
6856
- } finally {
6857
- this.span.end();
6858
- }
6859
- }
6860
- fail(error) {
6861
- if (this.finalized) return;
6862
- this.span.setStatus({
6863
- code: SpanStatusCode.ERROR,
6864
- message: error instanceof Error ? error.message : String(error)
6865
- });
6866
- this.span.recordException(error);
6867
- this.finalize();
6868
- }
6869
- };
6870
- function push(map, index, value) {
6871
- const existing = map.get(index);
6872
- if (existing) existing.push(value);
6873
- else map.set(index, [value]);
6874
- }
6875
- function deltaContentText(content) {
6876
- if (content === null || content === void 0) return "";
6877
- if (typeof content === "string") return content;
6878
- const items = Array.isArray(content) ? content : [content];
6879
- return items.map((item) => String(field2(item, "text") ?? "")).join("");
6880
- }
6881
- function parseArguments(raw) {
6882
- if (!raw) return {};
6883
- try {
6884
- return JSON.parse(raw);
6885
- } catch {
6886
- return raw;
6887
- }
6888
- }
6889
- function isInteractionStream(value) {
6890
- return value !== null && value !== void 0 && typeof value[Symbol.asyncIterator] === "function";
6891
- }
6892
- function wrapIterator(iterator, accumulator, withContext) {
6893
- return {
6894
- async next(value) {
6895
- try {
6896
- const result = await withContext(() => iterator.next(value));
6897
- if (result.done) accumulator.finalize();
6898
- else accumulator.processEvent(result.value);
6899
- return result;
6900
- } catch (e) {
6901
- accumulator.fail(e);
6902
- throw e;
6903
- }
6904
- },
6905
- async return(value) {
6906
- try {
6907
- const result = await withContext(
6908
- () => iterator.return?.(value) ?? { done: true, value }
6909
- );
6910
- accumulator.finalize();
6911
- return result;
6912
- } catch (e) {
6913
- accumulator.fail(e);
6914
- throw e;
6915
- }
6916
- },
6917
- async throw(e) {
6918
- try {
6919
- const result = await withContext(() => {
6920
- if (iterator.throw) return iterator.throw(e);
6921
- throw e;
6922
- });
6923
- if (result.done) accumulator.finalize();
6924
- return result;
6925
- } catch (err) {
6926
- accumulator.fail(err);
6927
- throw err;
6928
- }
6929
- }
6930
- };
6931
- }
6932
- var UNOBSERVED_METHODS = /* @__PURE__ */ new Set(["getReader", "pipeTo", "pipeThrough", "tee"]);
6933
- function instrumentInteractionStream(stream, accumulator, withContext) {
6934
- if (stream[NETRA_STREAM]) return stream;
6935
- const makeIterator = (options) => wrapIterator(stream[Symbol.asyncIterator](options), accumulator, withContext);
6936
- return new Proxy(stream, {
6937
- get(target, property) {
6938
- if (property === NETRA_STREAM) return true;
6939
- if (property === Symbol.asyncIterator || property === "values") {
6940
- return (options) => makeIterator(options);
6941
- }
6942
- if (typeof property === "string" && UNOBSERVED_METHODS.has(property)) {
6943
- const original = Reflect.get(target, property, target);
6944
- if (typeof original !== "function") return original;
6945
- return (...args) => {
6946
- accumulator.abandon(property);
6947
- return original.apply(target, args);
6948
- };
6949
- }
6950
- const value = Reflect.get(target, property, target);
6951
- return typeof value === "function" ? value.bind(target) : value;
6952
- }
6953
- });
6954
- }
6955
- function interactionsWrapper(tracer) {
6956
- return function wrapper(original) {
6957
- return function(...args) {
6958
- if (shouldSuppressInstrumentation()) {
6959
- return original.apply(this, args);
6960
- }
6961
- const params = args[0] ?? {};
6962
- const currentContext = context.active();
6963
- return tracer.startActiveSpan(
6964
- SPAN_NAMES2.INTERACTION,
6965
- { kind: SpanKind.CLIENT },
6966
- (span2) => {
6967
- const startTime = Date.now();
6968
- try {
6969
- setInteractionRequestAttributes(span2, params);
6970
- const spanContext = trace.setSpan(currentContext, span2);
6971
- const withContext = (fn) => context.with(spanContext, fn);
6972
- const suppressedCtx = createSuppressedContext(spanContext);
6973
- const response = context.with(
6974
- suppressedCtx,
6975
- () => original.apply(this, args)
6976
- );
6977
- if (!isPromise(response)) {
6978
- return finishNonStreaming(span2, response, startTime);
6979
- }
6980
- return response.then(
6981
- (value) => {
6982
- if (isInteractionStream(value)) {
6983
- span2.setAttribute(SpanAttributes2.LLM_IS_STREAMING, true);
6984
- const accumulator = new InteractionStreamAccumulator(
6985
- span2,
6986
- startTime
6987
- );
6988
- return instrumentInteractionStream(
6989
- value,
6990
- accumulator,
6991
- withContext
6992
- );
6993
- }
6994
- return finishNonStreaming(span2, value, startTime);
6995
- },
6996
- (error) => {
6997
- span2.setStatus({
6998
- code: SpanStatusCode.ERROR,
6999
- message: error instanceof Error ? error.message : String(error)
7000
- });
7001
- span2.recordException(error);
7002
- span2.end();
7003
- throw error;
7004
- }
7005
- );
7006
- } catch (error) {
7007
- span2.setStatus({
7008
- code: SpanStatusCode.ERROR,
7009
- message: error instanceof Error ? error.message : String(error)
7010
- });
7011
- span2.recordException(error);
7012
- span2.end();
7013
- throw error;
7014
- }
7015
- }
7016
- );
7017
- };
7018
- };
7019
- }
7020
- function finishNonStreaming(span2, value, startTime) {
7021
- try {
7022
- span2.setAttribute(SpanAttributes2.LLM_IS_STREAMING, false);
7023
- setInteractionResponseAttributes(span2, value);
7024
- span2.setAttribute(
7025
- SpanAttributes2.LLM_RESPONSE_DURATION,
7026
- (Date.now() - startTime) / 1e3
7027
- );
7028
- span2.setStatus({ code: SpanStatusCode.OK });
6175
+ }
6176
+ if (chunk.usageMetadata) {
6177
+ accumulated.usageMetadata = chunk.usageMetadata;
6178
+ }
6179
+ if (Array.isArray(chunk.candidates) && chunk.candidates.length > 0) {
6180
+ const reason = chunk.candidates[0]?.finishReason;
6181
+ if (reason) {
6182
+ if (!accumulated.candidates) accumulated.candidates = [{}];
6183
+ accumulated.candidates[0].finishReason = reason;
6184
+ }
6185
+ }
6186
+ if (Logger.isDebugMode()) {
6187
+ span2.addEvent("llm.content.completion.chunk");
6188
+ }
7029
6189
  } catch (e) {
7030
- Logger.error(`${LOG_PREFIX3}: interaction response error`, e);
7031
- } finally {
7032
- span2.end();
6190
+ Logger.error(`${LOG_PREFIX}: processStreamChunk error`, e);
7033
6191
  }
7034
- return value;
6192
+ }
6193
+ function buildAccumulatedResponse(accumulated) {
6194
+ const response = {
6195
+ responseId: accumulated.responseId,
6196
+ modelVersion: accumulated.modelVersion,
6197
+ usageMetadata: accumulated.usageMetadata,
6198
+ candidates: accumulated.candidates
6199
+ };
6200
+ if (accumulated._text) {
6201
+ response.text = accumulated._text;
6202
+ }
6203
+ if (accumulated._functionCalls) {
6204
+ response.functionCalls = accumulated._functionCalls;
6205
+ }
6206
+ return response;
7035
6207
  }
7036
6208
 
7037
- // src/instrumentation/google-genai/version.ts
7038
- var __version__2 = "1.0.0";
7039
- var LOG_PREFIX4 = "netra.instrumentation.google_genai";
6209
+ // src/instrumentation/google-genai/wrappers.ts
6210
+ var LOG_PREFIX2 = "netra.instrumentation.google_genai";
7040
6211
  function buildParams(args, self) {
7041
6212
  const raw = args[0];
7042
6213
  const params = typeof raw === "object" && raw !== null ? { ...raw } : { message: raw };
@@ -7176,7 +6347,7 @@ function streamWrapperFactory(tracer, spanName, requestType) {
7176
6347
  (endTime - startTime) / 1e3
7177
6348
  );
7178
6349
  } catch (e) {
7179
- Logger.error(`${LOG_PREFIX4}: stream finalize error`, e);
6350
+ Logger.error(`${LOG_PREFIX2}: stream finalize error`, e);
7180
6351
  }
7181
6352
  if (status === "ok") {
7182
6353
  span2.setStatus({ code: SpanStatusCode.OK });
@@ -7205,9 +6376,6 @@ var chatStreamWrapper2 = (tracer) => streamWrapperFactory(tracer, SPAN_NAMES2.CH
7205
6376
  var embeddingsWrapper = (tracer) => genericWrapperFactory(tracer, SPAN_NAMES2.EMBEDDING, "embedding");
7206
6377
 
7207
6378
  // src/instrumentation/google-genai/index.ts
7208
- var INTERACTIONS_PATCHED = /* @__PURE__ */ Symbol.for(
7209
- "netra.googlegenai.interactions.patched"
7210
- );
7211
6379
  var NetraGoogleGenAIInstrumentor = class extends BaseInstrumentor {
7212
6380
  constructor() {
7213
6381
  super(...arguments);
@@ -7215,15 +6383,11 @@ var NetraGoogleGenAIInstrumentor = class extends BaseInstrumentor {
7215
6383
  this.instrumentationVersion = __version__2;
7216
6384
  this.packageName = "@google/genai";
7217
6385
  this.displayName = "Google GenAI";
7218
- /** Original `interactions` descriptors, for an exact restore on unpatch. */
7219
- this.interactionsDescriptors = [];
7220
- /** Resource prototypes whose `create` we wrapped. */
7221
- this.patchedInteractionProtos = [];
7222
6386
  }
7223
6387
  extractClasses(mod) {
7224
6388
  const root = mod.default ?? mod;
7225
6389
  if (!root.Models) return null;
7226
- return { Models: root.Models, Chat: root.Chat, GoogleGenAI: root.GoogleGenAI };
6390
+ return { Models: root.Models, Chat: root.Chat };
7227
6391
  }
7228
6392
  isSameClasses(a, b) {
7229
6393
  return a.Models === b.Models;
@@ -7258,57 +6422,8 @@ var NetraGoogleGenAIInstrumentor = class extends BaseInstrumentor {
7258
6422
  wrapped = true;
7259
6423
  }
7260
6424
  }
7261
- if (this.patchInteractions(classes.GoogleGenAI, tracer)) {
7262
- wrapped = true;
7263
- }
7264
6425
  return wrapped;
7265
6426
  }
7266
- /**
7267
- * Redefine the `interactions` accessor so the resource prototype gets patched
7268
- * on first access.
7269
- *
7270
- * shimmer cannot be used on the accessor itself -- it does a plain property
7271
- * assignment, which would clobber the getter. Nothing is constructed here
7272
- * either: `new GoogleGenAI({})` writes an API-key warning to the console.
7273
- *
7274
- * A client that read `.interactions` before instrumentation finished keeps
7275
- * its cached resource, but the prototype is shared, so the patch still
7276
- * applies the next time any instance reads the accessor. Netra.init() is
7277
- * awaited before user code, so this is an edge case rather than a hole.
7278
- */
7279
- patchInteractions(GoogleGenAI, tracer) {
7280
- if (!GoogleGenAI?.prototype) return false;
7281
- const descriptor = Object.getOwnPropertyDescriptor(
7282
- GoogleGenAI.prototype,
7283
- "interactions"
7284
- );
7285
- if (!descriptor?.get || !descriptor.configurable) return false;
7286
- const originalGet = descriptor.get;
7287
- const patchedProtos = this.patchedInteractionProtos;
7288
- this.interactionsDescriptors.push([GoogleGenAI, descriptor]);
7289
- Object.defineProperty(GoogleGenAI.prototype, "interactions", {
7290
- configurable: true,
7291
- enumerable: descriptor.enumerable,
7292
- get() {
7293
- const resource = originalGet.call(this);
7294
- try {
7295
- const proto = resource && Object.getPrototypeOf(resource);
7296
- if (proto && !proto[INTERACTIONS_PATCHED] && typeof proto.create === "function") {
7297
- Object.defineProperty(proto, INTERACTIONS_PATCHED, {
7298
- value: true,
7299
- configurable: true
7300
- });
7301
- shimmer.wrap(proto, "create", interactionsWrapper(tracer));
7302
- patchedProtos.push(proto);
7303
- }
7304
- } catch (error) {
7305
- Logger.error(`Google GenAI: failed to patch interactions: ${error}`);
7306
- }
7307
- return resource;
7308
- }
7309
- });
7310
- return true;
7311
- }
7312
6427
  removePatches(classes) {
7313
6428
  const modelsProto = classes.Models?.prototype;
7314
6429
  if (modelsProto) {
@@ -7327,25 +6442,6 @@ var NetraGoogleGenAIInstrumentor = class extends BaseInstrumentor {
7327
6442
  shimmer.unwrap(chatProto, "sendMessageStream");
7328
6443
  }
7329
6444
  }
7330
- onUninstrument() {
7331
- for (const proto of this.patchedInteractionProtos) {
7332
- try {
7333
- shimmer.unwrap(proto, "create");
7334
- delete proto[INTERACTIONS_PATCHED];
7335
- } catch (error) {
7336
- Logger.error(`Google GenAI: failed to unwrap interactions.create: ${error}`);
7337
- }
7338
- }
7339
- this.patchedInteractionProtos = [];
7340
- for (const [GoogleGenAI, descriptor] of this.interactionsDescriptors) {
7341
- try {
7342
- Object.defineProperty(GoogleGenAI.prototype, "interactions", descriptor);
7343
- } catch (error) {
7344
- Logger.error(`Google GenAI: failed to restore interactions accessor: ${error}`);
7345
- }
7346
- }
7347
- this.interactionsDescriptors = [];
7348
- }
7349
6445
  };
7350
6446
  var googleGenAIInstrumentor = new NetraGoogleGenAIInstrumentor();
7351
6447
 
@@ -7749,7 +6845,7 @@ function _setEmbeddingResponseAttributes(span2, response) {
7749
6845
  }
7750
6846
 
7751
6847
  // src/instrumentation/google-generative-ai/wrappers.ts
7752
- var LOG_PREFIX5 = "netra.instrumentation.google_generative_ai";
6848
+ var LOG_PREFIX3 = "netra.instrumentation.google_generative_ai";
7753
6849
  var CHAT_SPAN_NAME = "google_generative_ai.chat";
7754
6850
  var EMBEDDING_SPAN_NAME = "google_generative_ai.embedding";
7755
6851
  function buildKwargs(instance) {
@@ -7794,7 +6890,7 @@ function googleGenerativeAIWrapper(tracer, spanName, requestType) {
7794
6890
  try {
7795
6891
  setRequestAttributes4(span2, kwargs, requestType, args[0]);
7796
6892
  } catch (e) {
7797
- Logger.error(`${LOG_PREFIX5}:`, e);
6893
+ Logger.error(`${LOG_PREFIX3}:`, e);
7798
6894
  }
7799
6895
  const startTime = Date.now();
7800
6896
  const response = original.apply(this, args);
@@ -7815,7 +6911,7 @@ function googleGenerativeAIWrapper(tracer, spanName, requestType) {
7815
6911
  );
7816
6912
  }
7817
6913
  } catch (e) {
7818
- Logger.error(`${LOG_PREFIX5}:`, e);
6914
+ Logger.error(`${LOG_PREFIX3}:`, e);
7819
6915
  }
7820
6916
  span2.setStatus({ code: SpanStatusCode.OK });
7821
6917
  span2.end();
@@ -7840,7 +6936,7 @@ function googleGenerativeAIWrapper(tracer, spanName, requestType) {
7840
6936
  (endTime - startTime) / 1e3
7841
6937
  );
7842
6938
  } catch (e) {
7843
- Logger.error(`${LOG_PREFIX5}:`, e);
6939
+ Logger.error(`${LOG_PREFIX3}:`, e);
7844
6940
  }
7845
6941
  span2.setStatus({ code: SpanStatusCode.OK });
7846
6942
  span2.end();
@@ -7882,7 +6978,7 @@ function googleGenerativeAIStreamWrapper(tracer, spanName, requestType) {
7882
6978
  try {
7883
6979
  setRequestAttributes4(span2, kwargs, requestType, args[0]);
7884
6980
  } catch (e) {
7885
- Logger.error(`${LOG_PREFIX5}:`, e);
6981
+ Logger.error(`${LOG_PREFIX3}:`, e);
7886
6982
  }
7887
6983
  const response = original.apply(this, args);
7888
6984
  if (!isPromise(response)) {
@@ -7906,7 +7002,7 @@ function googleGenerativeAIStreamWrapper(tracer, spanName, requestType) {
7906
7002
  duration
7907
7003
  );
7908
7004
  } catch (e) {
7909
- Logger.error(`${LOG_PREFIX5}:`, e);
7005
+ Logger.error(`${LOG_PREFIX3}:`, e);
7910
7006
  }
7911
7007
  span2.setStatus({ code: SpanStatusCode.OK });
7912
7008
  span2.end();
@@ -7942,7 +7038,7 @@ function googleGenerativeAIStreamWrapper(tracer, spanName, requestType) {
7942
7038
  duration
7943
7039
  );
7944
7040
  } catch (e) {
7945
- Logger.error(`${LOG_PREFIX5}:`, e);
7041
+ Logger.error(`${LOG_PREFIX3}:`, e);
7946
7042
  }
7947
7043
  span2.setStatus({ code: SpanStatusCode.OK });
7948
7044
  span2.end();
@@ -8783,184 +7879,209 @@ function enterWithContext(newContext) {
8783
7879
  contextManager._asyncLocalStorage.enterWith(newContext);
8784
7880
  }
8785
7881
  }
8786
- var NetraLanggraphCallbackHandler = class extends BaseCallbackHandler {
8787
- constructor(tracer, rootSpan) {
8788
- super();
8789
- this.tracer = tracer;
8790
- this.rootSpan = rootSpan;
8791
- this.name = "netra-langgraph-callback-handler";
8792
- // Map runId -> Span for explicit parenting
8793
- this.spans = /* @__PURE__ */ new Map();
8794
- this.nodeAttributes = /* @__PURE__ */ new Map();
8795
- this.runStack = [];
8796
- this.inferredParents = /* @__PURE__ */ new Map();
8797
- }
8798
- getParentSpan(parentRunId) {
8799
- if (parentRunId && this.spans.has(parentRunId)) {
8800
- return this.spans.get(parentRunId);
8801
- }
8802
- return this.rootSpan;
8803
- }
8804
- addNodeAttributes(runId, attributes) {
8805
- const current = this.nodeAttributes.get(runId) || {};
8806
- this.nodeAttributes.set(runId, { ...current, ...attributes });
8807
- }
8808
- inferParentRunId(parentRunId) {
8809
- if (parentRunId) return parentRunId;
8810
- return this.runStack.length > 0 ? this.runStack[this.runStack.length - 1] : void 0;
8811
- }
8812
- pushRun(runId) {
8813
- this.runStack.push(runId);
8814
- }
8815
- popRun(runId) {
8816
- const last = this.runStack[this.runStack.length - 1];
8817
- if (last === runId) {
8818
- this.runStack.pop();
8819
- return;
8820
- }
8821
- const idx = this.runStack.lastIndexOf(runId);
8822
- if (idx >= 0) {
8823
- this.runStack.splice(idx, 1);
8824
- }
8825
- }
8826
- async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runName, runType) {
8827
- const metadataNodeName = typeof metadata?.langgraph_node === "string" ? metadata.langgraph_node : "";
8828
- const runNameValue = typeof runName === "string" ? runName : "";
8829
- const chainIdName = Array.isArray(chain.id) && chain.id.length > 0 ? chain.id[chain.id.length - 1] : "";
8830
- const nodeName = metadataNodeName || runNameValue || chainIdName || "Chain";
8831
- const nodeType = chainIdName || "Unknown";
8832
- const metadataKeys = metadata && typeof metadata === "object" ? Object.keys(metadata).join(",") : "n/a";
8833
- Logger.debug(
8834
- `NetraLanggraph handleChainStart: runId=${runId} parentRunId=${parentRunId} nodeName=${nodeName} nodeType=${nodeType} runName=${runNameValue || "n/a"} metadataKeys=${metadataKeys}`
8835
- );
8836
- if (["__start__"].includes(nodeName.toLowerCase())) {
8837
- return;
8838
- }
8839
- const effectiveParentRunId = this.inferParentRunId(parentRunId);
8840
- if (!parentRunId && effectiveParentRunId && effectiveParentRunId !== runId) {
8841
- this.inferredParents.set(runId, effectiveParentRunId);
8842
- Logger.debug(`NetraLanggraph inferred parent: runId=${runId} parentRunId=${effectiveParentRunId}`);
8843
- }
8844
- const parentSpan = this.getParentSpan(effectiveParentRunId);
8845
- const ctx = trace.setSpan(context.active(), parentSpan);
8846
- const span2 = this.tracer.startSpan(`${nodeName}.task`, void 0, ctx);
8847
- setChainInputAttributes(span2, inputs, tags, metadata);
8848
- this.spans.set(runId, span2);
8849
- this.pushRun(runId);
8850
- }
8851
- async handleChainEnd(outputs, runId, parentRunId, tags, kwargs) {
8852
- const span2 = this.spans.get(runId);
8853
- if (!span2) return;
8854
- setChainOutputAttributes(span2, outputs, tags);
8855
- span2.end();
8856
- this.spans.delete(runId);
8857
- this.nodeAttributes.delete(runId);
8858
- this.inferredParents.delete(runId);
8859
- this.popRun(runId);
8860
- }
8861
- async handleChainError(err, runId, parentRunId, tags, kwargs) {
8862
- const span2 = this.spans.get(runId);
8863
- if (!span2) return;
8864
- span2.recordException(err);
8865
- span2.end();
8866
- this.spans.delete(runId);
8867
- this.nodeAttributes.delete(runId);
8868
- this.inferredParents.delete(runId);
8869
- this.popRun(runId);
8870
- }
8871
- async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, runName) {
8872
- const effectiveParentRunId = parentRunId ?? this.inferParentRunId(parentRunId);
8873
- {
8874
- const llmId = llm.id?.[llm.id.length - 1] || "llm";
8875
- Logger.debug(`NetraLanggraph handleLLMStart: runId=${runId} parentRunId=${effectiveParentRunId} llmId=${llmId}`);
8876
- }
8877
- this.addNodeAttributes(runId, {
8878
- llmIds: llm.id,
8879
- metadata,
8880
- prompts,
8881
- extraParams,
8882
- parentRunId: effectiveParentRunId
8883
- // Store parent ID to link back
8884
- });
8885
- }
8886
- async handleLLMEnd(output, runId, parentRunId) {
8887
- const attributes = this.nodeAttributes.get(runId);
8888
- if (!attributes) return;
8889
- const response = output?.generations?.[0]?.[0]?.message;
8890
- const llmIds = attributes.llmIds ?? [];
8891
- const llmId = llmIds?.length > 0 ? llmIds[llmIds.length - 1] : "llm";
8892
- const effectiveParentRunId = parentRunId ?? attributes.parentRunId ?? this.inferredParents.get(runId);
8893
- const parentSpan = this.getParentSpan(effectiveParentRunId);
8894
- const ctx = trace.setSpan(context.active(), parentSpan);
8895
- const span2 = this.tracer.startSpan(`${llmId}.task`, void 0, ctx);
8896
- setLlmRequestAttributes(
8897
- span2,
8898
- attributes.metadata,
8899
- attributes.prompts,
8900
- attributes.extraParams
8901
- );
8902
- setResponseAttributes(span2, response);
8903
- span2.end();
8904
- this.nodeAttributes.delete(runId);
8905
- }
8906
- async handleLLMError(err, runId, parentRunId, tags, extraParams) {
8907
- const attributes = this.nodeAttributes.get(runId);
8908
- if (!attributes) return;
8909
- const llmIds = attributes.llmIds ?? [];
8910
- const llmId = llmIds?.length > 0 ? llmIds[llmIds.length - 1] : "llm";
8911
- const effectiveParentRunId = parentRunId ?? attributes.parentRunId ?? this.inferredParents.get(runId);
8912
- const parentSpan = this.getParentSpan(effectiveParentRunId);
8913
- const ctx = trace.setSpan(context.active(), parentSpan);
8914
- const span2 = this.tracer.startSpan(`${llmId}.task`, void 0, ctx);
8915
- span2.recordException(err);
8916
- span2.end();
8917
- 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");
8918
7890
  }
8919
- async handleToolStart(tool, input, runId, parentRunId, tags, metadata, runName) {
8920
- let parsedInput;
7891
+ if (!Base) {
8921
7892
  try {
8922
- parsedInput = JSON.parse(input);
7893
+ const req = createRequire(import.meta.url);
7894
+ Base = req("@langchain/core/callbacks/base").BaseCallbackHandler;
8923
7895
  } catch {
8924
- parsedInput = {};
7896
+ Logger.debug("@langchain/core: CJS require not available");
8925
7897
  }
8926
- const effectiveParentRunId = parentRunId ?? this.inferParentRunId(parentRunId);
8927
- {
8928
- const toolName = tool.id?.[tool.id.length - 1] || "tool";
8929
- Logger.debug(`NetraLanggraph handleToolStart: runId=${runId} parentRunId=${effectiveParentRunId} tool=${toolName}`);
8930
- }
8931
- this.addNodeAttributes(runId, {
8932
- input: parsedInput,
8933
- metadata,
8934
- tags,
8935
- parentRunId: effectiveParentRunId
8936
- });
8937
7898
  }
8938
- async handleToolEnd(output, runId, parentRunId, tags) {
8939
- const attributes = this.nodeAttributes.get(runId);
8940
- if (!attributes) return;
8941
- const toolName = attributes?.input?.name ?? "custom";
8942
- const { input, metadata } = attributes;
8943
- const effectiveParentRunId = parentRunId ?? attributes.parentRunId ?? this.inferredParents.get(runId);
8944
- const parentSpan = this.getParentSpan(effectiveParentRunId);
8945
- const ctx = trace.setSpan(context.active(), parentSpan);
8946
- const span2 = this.tracer.startSpan(`${toolName}.tool`, void 0, ctx);
8947
- setToolAttributes(span2, toolName, input ?? {}, output, metadata, tags);
8948
- span2.end();
8949
- this.nodeAttributes.delete(runId);
8950
- }
8951
- async handleToolError(err, runId, parentRunId, tags) {
8952
- const attributes = this.nodeAttributes.get(runId);
8953
- if (!attributes) return;
8954
- const toolName = attributes?.input?.name ?? "custom";
8955
- const effectiveParentRunId = parentRunId ?? attributes.parentRunId ?? this.inferredParents.get(runId);
8956
- const parentSpan = this.getParentSpan(effectiveParentRunId);
8957
- const ctx = trace.setSpan(context.active(), parentSpan);
8958
- const span2 = this.tracer.startSpan(`${toolName}.tool`, void 0, ctx);
8959
- span2.recordException(err);
8960
- span2.end();
8961
- this.nodeAttributes.delete(runId);
7899
+ if (!Base) {
7900
+ return false;
8962
7901
  }
8963
- };
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
+ }
8964
8085
  var LanggraphStreamingWrapper = class {
8965
8086
  constructor(rootSpan, rootContext) {
8966
8087
  this.output = {};
@@ -9010,7 +8131,7 @@ var LanggraphWrapper = class {
9010
8131
  this.spanName = "Langgraph.workflow";
9011
8132
  }
9012
8133
  getUpdatedConfig(config, rootSpan) {
9013
- if (!rootSpan) return config || {};
8134
+ if (!rootSpan || !NetraLanggraphCallbackHandler) return config || {};
9014
8135
  const callbackHandler = new NetraLanggraphCallbackHandler(
9015
8136
  this.tracer,
9016
8137
  rootSpan
@@ -9177,6 +8298,10 @@ var NetraLanggraphInstrumentor = class {
9177
8298
  Logger.warn("LangGraph class not found, skipping instrumentation");
9178
8299
  return this;
9179
8300
  }
8301
+ if (!await loadLanggraphCallbackHandler()) {
8302
+ Logger.warn("@langchain/core not found, skipping LangGraph instrumentation");
8303
+ return this;
8304
+ }
9180
8305
  try {
9181
8306
  this.tracerProvider = options.tracerProvider;
9182
8307
  this.tracer = this.tracerProvider ? this.tracerProvider.getTracer(INSTRUMENTATION_NAME3, __version__5) : trace.getTracer(INSTRUMENTATION_NAME3, __version__5);
@@ -10737,11 +9862,11 @@ function setGenerationAttributes(span2, data, systemName) {
10737
9862
  }
10738
9863
  const effectiveOutput = unwrapGenerationOutput(data.output);
10739
9864
  if (data.usage) {
10740
- setUsageAttributes4(span2, data.usage);
9865
+ setUsageAttributes3(span2, data.usage);
10741
9866
  } else if (effectiveOutput && typeof effectiveOutput === "object" && !Array.isArray(effectiveOutput)) {
10742
9867
  const respUsage = effectiveOutput.usage;
10743
9868
  if (respUsage && typeof respUsage === "object") {
10744
- setUsageAttributes4(span2, respUsage);
9869
+ setUsageAttributes3(span2, respUsage);
10745
9870
  }
10746
9871
  }
10747
9872
  if (data.input !== void 0) {
@@ -10780,7 +9905,7 @@ function setResponseAttributes8(span2, agentSpan, systemName) {
10780
9905
  }
10781
9906
  const resp = data._response;
10782
9907
  if (data.usage && !(resp && typeof resp === "object" && resp.usage)) {
10783
- setUsageAttributes4(span2, data.usage);
9908
+ setUsageAttributes3(span2, data.usage);
10784
9909
  }
10785
9910
  }
10786
9911
  function setFunctionAttributes(span2, data) {
@@ -10829,7 +9954,7 @@ function setCustomAttributes(span2, data) {
10829
9954
  span2.setAttribute(NETRA_CUSTOM_DATA, safeStringify(data.data));
10830
9955
  }
10831
9956
  }
10832
- function setUsageAttributes4(span2, usage) {
9957
+ function setUsageAttributes3(span2, usage) {
10833
9958
  const promptTokens = usage.input_tokens ?? usage.prompt_tokens;
10834
9959
  const completionTokens = usage.output_tokens ?? usage.completion_tokens;
10835
9960
  const totalTokens = usage.total_tokens;
@@ -10864,6 +9989,7 @@ function setUsageAttributes4(span2, usage) {
10864
9989
  if (inputDetails.cache_write_tokens !== void 0) {
10865
9990
  span2.setAttribute(SpanAttributes2.LLM_USAGE_CACHE_CREATION_INPUT_TOKENS, Number(inputDetails.cache_write_tokens));
10866
9991
  }
9992
+ setCacheWriteTtlAttributes(span2, inputDetails);
10867
9993
  }
10868
9994
  const outputDetails = usage.output_tokens_details ?? usage.completion_tokens_details;
10869
9995
  if (outputDetails) {
@@ -10916,6 +10042,7 @@ function setResponseObjectUsageAttributes(span2, usage) {
10916
10042
  if (usage.input_tokens_details?.cache_write_tokens !== void 0) {
10917
10043
  span2.setAttribute(SpanAttributes2.LLM_USAGE_CACHE_CREATION_INPUT_TOKENS, usage.input_tokens_details.cache_write_tokens);
10918
10044
  }
10045
+ setCacheWriteTtlAttributes(span2, usage.input_tokens_details);
10919
10046
  if (usage.output_tokens_details?.reasoning_tokens !== void 0) {
10920
10047
  span2.setAttribute(SpanAttributes2.LLM_USAGE_REASONING_TOKENS, usage.output_tokens_details.reasoning_tokens);
10921
10048
  }
@@ -12394,7 +11521,7 @@ function patchTraceloopLangchainCallbackHandler() {
12394
11521
  } catch (e) {
12395
11522
  Logger.debug("require() for traceloop langchain failed, falling back to import().");
12396
11523
  }
12397
- import('./dist-4UBY6Q6Z.js').then((mod) => {
11524
+ import('@traceloop/instrumentation-langchain').then((mod) => {
12398
11525
  applyPatch(mod, "import");
12399
11526
  }).catch(() => {
12400
11527
  });
@@ -12960,22 +12087,278 @@ async function uninstrumentAll() {
12960
12087
  }
12961
12088
  }
12962
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
+
12963
12346
  // src/simulation/task.ts
12964
12347
  var BaseTask = class {
12965
12348
  };
12966
12349
 
12967
12350
  // src/simulation/utils.ts
12968
- var LOG_PREFIX6 = "netra.simulation";
12351
+ var LOG_PREFIX4 = "netra.simulation";
12969
12352
  var DEFAULT_FILE_DOWNLOAD_TIMEOUT_S = 30;
12970
12353
  var MAX_FILE_DOWNLOAD_WORKERS = 8;
12971
12354
  var _cachedFileDownloadTimeoutMs = null;
12972
12355
  function validateSimulationInputs(datasetId, task2) {
12973
12356
  if (!datasetId) {
12974
- Logger.error(`${LOG_PREFIX6}: dataset_id is required`);
12357
+ Logger.error(`${LOG_PREFIX4}: dataset_id is required`);
12975
12358
  return false;
12976
12359
  }
12977
12360
  if (!(task2 instanceof BaseTask)) {
12978
- Logger.error(`${LOG_PREFIX6}: task must be a BaseTask instance`);
12361
+ Logger.error(`${LOG_PREFIX4}: task must be a BaseTask instance`);
12979
12362
  return false;
12980
12363
  }
12981
12364
  return true;
@@ -12992,7 +12375,7 @@ function _getFileDownloadTimeout() {
12992
12375
  return _cachedFileDownloadTimeoutMs;
12993
12376
  }
12994
12377
  Logger.warn(
12995
- `${LOG_PREFIX6}: Invalid file download timeout '${envVal}', using default ${DEFAULT_FILE_DOWNLOAD_TIMEOUT_S}s`
12378
+ `${LOG_PREFIX4}: Invalid file download timeout '${envVal}', using default ${DEFAULT_FILE_DOWNLOAD_TIMEOUT_S}s`
12996
12379
  );
12997
12380
  }
12998
12381
  _cachedFileDownloadTimeoutMs = DEFAULT_FILE_DOWNLOAD_TIMEOUT_S * 1e3;
@@ -13021,7 +12404,7 @@ async function _downloadSingleFile(fileData, timeoutMs, signal) {
13021
12404
  const status = axios.isAxiosError(error) ? error.response?.status : void 0;
13022
12405
  const reason = status ? `HTTP ${status}` : error instanceof Error ? error.message : String(error);
13023
12406
  Logger.error(
13024
- `${LOG_PREFIX6}: Failed to download file '${fileData.fileName}': ${reason}`
12407
+ `${LOG_PREFIX4}: Failed to download file '${fileData.fileName}': ${reason}`
13025
12408
  );
13026
12409
  throw new Error(
13027
12410
  `Failed to download file '${fileData.fileName}': ${reason}`
@@ -13038,7 +12421,7 @@ function parseFiles(rawFiles) {
13038
12421
  const downloadUrl = entry.downloadUrl || "";
13039
12422
  if (!fileName || !downloadUrl) {
13040
12423
  Logger.warn(
13041
- `${LOG_PREFIX6}: Skipping malformed file attachment (missing fileName or downloadUrl)`
12424
+ `${LOG_PREFIX4}: Skipping malformed file attachment (missing fileName or downloadUrl)`
13042
12425
  );
13043
12426
  continue;
13044
12427
  }
@@ -13082,7 +12465,7 @@ async function executeTask2(task2, message, sessionId, rawFiles, setupContext) {
13082
12465
  }
13083
12466
 
13084
12467
  // src/simulation/client.ts
13085
- var LOG_PREFIX7 = "netra.simulation";
12468
+ var LOG_PREFIX5 = "netra.simulation";
13086
12469
  var DEFAULT_TIMEOUT = 1e4;
13087
12470
  var SimulationHttpClient = class {
13088
12471
  constructor(config) {
@@ -13095,7 +12478,7 @@ var SimulationHttpClient = class {
13095
12478
  _createClient(config) {
13096
12479
  const endpoint = (config.otlpEndpoint || "").trim();
13097
12480
  if (!endpoint) {
13098
- Logger.error(`${LOG_PREFIX7}: NETRA_OTLP_ENDPOINT is required`);
12481
+ Logger.error(`${LOG_PREFIX5}: NETRA_OTLP_ENDPOINT is required`);
13099
12482
  return null;
13100
12483
  }
13101
12484
  const baseURL = this._resolveBaseUrl(endpoint);
@@ -13117,7 +12500,7 @@ var SimulationHttpClient = class {
13117
12500
  );
13118
12501
  return instance;
13119
12502
  } catch (error) {
13120
- Logger.error(`${LOG_PREFIX7}: Failed to create HTTP client:`, error);
12503
+ Logger.error(`${LOG_PREFIX5}: Failed to create HTTP client:`, error);
13121
12504
  return null;
13122
12505
  }
13123
12506
  }
@@ -13152,7 +12535,7 @@ var SimulationHttpClient = class {
13152
12535
  const timeout = parseFloat(timeoutStr);
13153
12536
  if (isNaN(timeout)) {
13154
12537
  Logger.warn(
13155
- `${LOG_PREFIX7}: Invalid timeout '${timeoutStr}', using default ${DEFAULT_TIMEOUT}ms`
12538
+ `${LOG_PREFIX5}: Invalid timeout '${timeoutStr}', using default ${DEFAULT_TIMEOUT}ms`
13156
12539
  );
13157
12540
  return DEFAULT_TIMEOUT;
13158
12541
  }
@@ -13164,9 +12547,9 @@ var SimulationHttpClient = class {
13164
12547
  * Used in the two-phase flow so that beforeAll/before hooks can run
13165
12548
  * before any LLM spend.
13166
12549
  */
13167
- async initializeRun(name, datasetId, context17, hooksMeta) {
12550
+ async initializeRun(name, datasetId, context16, hooksMeta) {
13168
12551
  if (!this.client) {
13169
- Logger.error(`${LOG_PREFIX7}: Client not initialized`);
12552
+ Logger.error(`${LOG_PREFIX5}: Client not initialized`);
13170
12553
  return null;
13171
12554
  }
13172
12555
  try {
@@ -13174,7 +12557,7 @@ var SimulationHttpClient = class {
13174
12557
  const payload = {
13175
12558
  name,
13176
12559
  datasetId,
13177
- context: context17 || {}
12560
+ context: context16 || {}
13178
12561
  };
13179
12562
  if (hooksMeta) {
13180
12563
  payload.lifecycleHooks = hooksMeta;
@@ -13184,7 +12567,7 @@ var SimulationHttpClient = class {
13184
12567
  const responseData = data.data || {};
13185
12568
  const items = responseData.items || [];
13186
12569
  if (items.length === 0) {
13187
- Logger.warn(`${LOG_PREFIX7}: No items returned from initialize_run`);
12570
+ Logger.warn(`${LOG_PREFIX5}: No items returned from initialize_run`);
13188
12571
  return null;
13189
12572
  }
13190
12573
  const runId = responseData.id || "";
@@ -13197,7 +12580,7 @@ var SimulationHttpClient = class {
13197
12580
  };
13198
12581
  } catch (error) {
13199
12582
  const errorMsg = this._extractErrorMessage(error);
13200
- Logger.error(`${LOG_PREFIX7}: Failed to initialize run:`, errorMsg);
12583
+ Logger.error(`${LOG_PREFIX5}: Failed to initialize run:`, errorMsg);
13201
12584
  return null;
13202
12585
  }
13203
12586
  }
@@ -13208,11 +12591,11 @@ var SimulationHttpClient = class {
13208
12591
  */
13209
12592
  async generateFirstTurn(runId, runItemId) {
13210
12593
  if (!this.client) {
13211
- Logger.error(`${LOG_PREFIX7}: Client not initialized`);
12594
+ Logger.error(`${LOG_PREFIX5}: Client not initialized`);
13212
12595
  return null;
13213
12596
  }
13214
12597
  try {
13215
- const url = `/evaluations/run/${runId}/item/${runItemId}/first-turn`;
12598
+ const url = apiPath`/evaluations/run/${runId}/item/${runItemId}/first-turn`;
13216
12599
  const response = await this.client.post(url, {});
13217
12600
  const data = response.data;
13218
12601
  const responseData = data.data || {};
@@ -13226,7 +12609,7 @@ var SimulationHttpClient = class {
13226
12609
  } catch (error) {
13227
12610
  const errorMsg = this._extractErrorMessage(error);
13228
12611
  Logger.error(
13229
- `${LOG_PREFIX7}: Failed to generate first turn for item ${runItemId}:`,
12612
+ `${LOG_PREFIX5}: Failed to generate first turn for item ${runItemId}:`,
13230
12613
  errorMsg
13231
12614
  );
13232
12615
  return null;
@@ -13237,7 +12620,7 @@ var SimulationHttpClient = class {
13237
12620
  */
13238
12621
  async triggerConversation(message, turnId, sessionId, traceId) {
13239
12622
  if (!this.client) {
13240
- Logger.error(`${LOG_PREFIX7}: Client not initialized`);
12623
+ Logger.error(`${LOG_PREFIX5}: Client not initialized`);
13241
12624
  return null;
13242
12625
  }
13243
12626
  try {
@@ -13260,7 +12643,7 @@ var SimulationHttpClient = class {
13260
12643
  }
13261
12644
  const userMessages = responseData.userMessages || [];
13262
12645
  if (userMessages.length === 0) {
13263
- Logger.warn(`${LOG_PREFIX7}: No user messages in continue response`);
12646
+ Logger.warn(`${LOG_PREFIX5}: No user messages in continue response`);
13264
12647
  return null;
13265
12648
  }
13266
12649
  const nextMsg = userMessages[0];
@@ -13273,7 +12656,7 @@ var SimulationHttpClient = class {
13273
12656
  };
13274
12657
  } catch (error) {
13275
12658
  const errorMsg = this._extractErrorMessage(error);
13276
- Logger.error(`${LOG_PREFIX7}: Failed to trigger conversation:`, errorMsg);
12659
+ Logger.error(`${LOG_PREFIX5}: Failed to trigger conversation:`, errorMsg);
13277
12660
  return null;
13278
12661
  }
13279
12662
  }
@@ -13292,17 +12675,17 @@ var SimulationHttpClient = class {
13292
12675
  */
13293
12676
  async reportFailure(runId, runItemId, error, status = "failed") {
13294
12677
  if (!this.client) {
13295
- Logger.error(`${LOG_PREFIX7}: Client not initialized`);
12678
+ Logger.error(`${LOG_PREFIX5}: Client not initialized`);
13296
12679
  return;
13297
12680
  }
13298
12681
  try {
13299
- const url = `/evaluations/run/${runId}/item/${runItemId}/status`;
12682
+ const url = apiPath`/evaluations/run/${runId}/item/${runItemId}/status`;
13300
12683
  const payload = { status, failureReason: error };
13301
12684
  await this.client.patch(url, payload);
13302
- Logger.info(`${LOG_PREFIX7}: Reported failure - ${error}`);
12685
+ Logger.info(`${LOG_PREFIX5}: Reported failure - ${error}`);
13303
12686
  } catch (err) {
13304
12687
  const errorMsg = this._extractErrorMessage(err);
13305
- Logger.error(`${LOG_PREFIX7}: Failed to report failure:`, errorMsg);
12688
+ Logger.error(`${LOG_PREFIX5}: Failed to report failure:`, errorMsg);
13306
12689
  }
13307
12690
  }
13308
12691
  /**
@@ -13311,24 +12694,24 @@ var SimulationHttpClient = class {
13311
12694
  async postRunStatus(runId, status) {
13312
12695
  if (!this.client) {
13313
12696
  Logger.error(
13314
- `${LOG_PREFIX7}: Client not initialized; cannot post run status`
12697
+ `${LOG_PREFIX5}: Client not initialized; cannot post run status`
13315
12698
  );
13316
12699
  return { success: false };
13317
12700
  }
13318
12701
  try {
13319
- const url = `/evaluations/run/${runId}/status`;
12702
+ const url = apiPath`/evaluations/run/${runId}/status`;
13320
12703
  const payload = { status };
13321
12704
  const response = await this.client.post(url, payload);
13322
12705
  const data = response.data;
13323
12706
  if (data && typeof data === "object" && "data" in data) {
13324
- Logger.info(`${LOG_PREFIX7}: Completed test run successfully`);
12707
+ Logger.info(`${LOG_PREFIX5}: Completed test run successfully`);
13325
12708
  return data.data || {};
13326
12709
  }
13327
12710
  return data;
13328
12711
  } catch (error) {
13329
12712
  const errorMsg = this._extractErrorMessage(error);
13330
12713
  Logger.error(
13331
- `${LOG_PREFIX7}: Failed to post run status for run '${runId}':`,
12714
+ `${LOG_PREFIX5}: Failed to post run status for run '${runId}':`,
13332
12715
  errorMsg
13333
12716
  );
13334
12717
  return { success: false };
@@ -13353,7 +12736,7 @@ var SimulationHttpClient = class {
13353
12736
  };
13354
12737
 
13355
12738
  // src/simulation/hooks.ts
13356
- var LOG_PREFIX8 = "netra.simulation";
12739
+ var LOG_PREFIX6 = "netra.simulation";
13357
12740
  function describeHooks(hooks) {
13358
12741
  const descFn = (fn) => {
13359
12742
  if (!fn) return null;
@@ -13397,11 +12780,11 @@ function describeHooks(hooks) {
13397
12780
  }
13398
12781
  async function runBeforeAll(hooks) {
13399
12782
  if (!hooks?.beforeAll) return null;
13400
- Logger.info(`${LOG_PREFIX8}: running beforeAll hook`);
12783
+ Logger.info(`${LOG_PREFIX6}: running beforeAll hook`);
13401
12784
  const result = await hooks.beforeAll();
13402
12785
  if (result !== null && result !== void 0 && typeof result !== "object") {
13403
12786
  Logger.warn(
13404
- `${LOG_PREFIX8}: beforeAll returned ${typeof result} (expected object or null); ignoring value`
12787
+ `${LOG_PREFIX6}: beforeAll returned ${typeof result} (expected object or null); ignoring value`
13405
12788
  );
13406
12789
  return null;
13407
12790
  }
@@ -13410,7 +12793,7 @@ async function runBeforeAll(hooks) {
13410
12793
  async function runBefore(hooks, datasetItemId, sharedContext) {
13411
12794
  if (hooks?.before && datasetItemId in hooks.before) {
13412
12795
  Logger.info(
13413
- `${LOG_PREFIX8}: running before hook for datasetItemId=${datasetItemId}`
12796
+ `${LOG_PREFIX6}: running before hook for datasetItemId=${datasetItemId}`
13414
12797
  );
13415
12798
  const itemHook = hooks.before[datasetItemId];
13416
12799
  const result = await itemHook(sharedContext);
@@ -13420,7 +12803,7 @@ async function runBefore(hooks, datasetItemId, sharedContext) {
13420
12803
  Object.assign(base, result);
13421
12804
  } else {
13422
12805
  Logger.warn(
13423
- `${LOG_PREFIX8}: before hook returned ${typeof result} (expected object or null); ignoring value`
12806
+ `${LOG_PREFIX6}: before hook returned ${typeof result} (expected object or null); ignoring value`
13424
12807
  );
13425
12808
  }
13426
12809
  }
@@ -13431,7 +12814,7 @@ async function runBefore(hooks, datasetItemId, sharedContext) {
13431
12814
  async function runBeforeEach(hooks, datasetItemId, sharedContext) {
13432
12815
  if (!hooks?.beforeEach) return sharedContext;
13433
12816
  Logger.info(
13434
- `${LOG_PREFIX8}: running beforeEach hook for datasetItemId=${datasetItemId}`
12817
+ `${LOG_PREFIX6}: running beforeEach hook for datasetItemId=${datasetItemId}`
13435
12818
  );
13436
12819
  const result = await hooks.beforeEach(sharedContext);
13437
12820
  const base = { ...sharedContext || {} };
@@ -13440,7 +12823,7 @@ async function runBeforeEach(hooks, datasetItemId, sharedContext) {
13440
12823
  Object.assign(base, result);
13441
12824
  } else {
13442
12825
  Logger.warn(
13443
- `${LOG_PREFIX8}: beforeEach hook returned ${typeof result} (expected object or null); ignoring value`
12826
+ `${LOG_PREFIX6}: beforeEach hook returned ${typeof result} (expected object or null); ignoring value`
13444
12827
  );
13445
12828
  }
13446
12829
  }
@@ -13449,7 +12832,7 @@ async function runBeforeEach(hooks, datasetItemId, sharedContext) {
13449
12832
  async function runAfter(hooks, datasetItemId, itemResult, setupContext) {
13450
12833
  if (hooks?.after && datasetItemId in hooks.after) {
13451
12834
  Logger.info(
13452
- `${LOG_PREFIX8}: running after hook for datasetItemId=${datasetItemId}`
12835
+ `${LOG_PREFIX6}: running after hook for datasetItemId=${datasetItemId}`
13453
12836
  );
13454
12837
  await hooks.after[datasetItemId](itemResult, setupContext);
13455
12838
  }
@@ -13457,18 +12840,18 @@ async function runAfter(hooks, datasetItemId, itemResult, setupContext) {
13457
12840
  async function runAfterEach(hooks, datasetItemId, itemResult, setupContext) {
13458
12841
  if (!hooks?.afterEach) return;
13459
12842
  Logger.info(
13460
- `${LOG_PREFIX8}: running afterEach hook for datasetItemId=${datasetItemId}`
12843
+ `${LOG_PREFIX6}: running afterEach hook for datasetItemId=${datasetItemId}`
13461
12844
  );
13462
12845
  await hooks.afterEach(itemResult, setupContext);
13463
12846
  }
13464
12847
  async function runAfterAll(hooks, results, sharedContext) {
13465
12848
  if (!hooks?.afterAll) return;
13466
- Logger.info(`${LOG_PREFIX8}: running afterAll hook`);
12849
+ Logger.info(`${LOG_PREFIX6}: running afterAll hook`);
13467
12850
  await hooks.afterAll(results, sharedContext);
13468
12851
  }
13469
12852
 
13470
12853
  // src/simulation/api.ts
13471
- var LOG_PREFIX9 = "netra.simulation";
12854
+ var LOG_PREFIX7 = "netra.simulation";
13472
12855
  var SPAN_NAME = "Netra.Simulation.TestRun";
13473
12856
  var Simulation = class {
13474
12857
  constructor(config) {
@@ -13492,7 +12875,7 @@ var Simulation = class {
13492
12875
  name,
13493
12876
  datasetId,
13494
12877
  task: task2,
13495
- context: context17,
12878
+ context: context16,
13496
12879
  maxConcurrency = 5,
13497
12880
  hooks
13498
12881
  } = options;
@@ -13504,7 +12887,7 @@ var Simulation = class {
13504
12887
  const initResult = await this._client.initializeRun(
13505
12888
  name,
13506
12889
  datasetId,
13507
- context17,
12890
+ context16,
13508
12891
  hooksMeta && Object.keys(hooksMeta).length > 0 ? hooksMeta : null
13509
12892
  );
13510
12893
  if (!initResult) {
@@ -13512,41 +12895,13 @@ var Simulation = class {
13512
12895
  }
13513
12896
  const { runId, items } = initResult;
13514
12897
  if (!items || items.length === 0) {
13515
- Logger.error(`${LOG_PREFIX9}: No items returned from initialize_run`);
12898
+ Logger.error(`${LOG_PREFIX7}: No items returned from initialize_run`);
13516
12899
  return null;
13517
12900
  }
13518
- let interrupted = false;
13519
- const proc = typeof process !== "undefined" ? process : void 0;
13520
- const finalizeFailure = (signal) => {
13521
- if (interrupted) {
13522
- return;
13523
- }
13524
- interrupted = true;
13525
- proc?.removeListener("SIGINT", handleSignal);
13526
- proc?.removeListener("SIGTERM", handleSignal);
13527
- proc?.removeListener("uncaughtException", handleException);
13528
- proc?.removeListener("unhandledRejection", handleRejection);
13529
- void this._client.postRunStatus(runId, "failed").finally(() => {
13530
- if (signal) {
13531
- proc?.kill(proc.pid, signal);
13532
- }
13533
- });
13534
- };
13535
- const handleSignal = (signal) => {
13536
- finalizeFailure(signal);
13537
- };
13538
- const handleException = () => {
13539
- finalizeFailure();
13540
- };
13541
- const handleRejection = () => {
13542
- finalizeFailure();
13543
- };
13544
- if (proc && typeof proc.once === "function") {
13545
- proc.once("SIGINT", handleSignal);
13546
- proc.once("SIGTERM", handleSignal);
13547
- proc.once("uncaughtException", handleException);
13548
- proc.once("unhandledRejection", handleRejection);
13549
- }
12901
+ const unregisterExitTask = registerExitTask(
12902
+ () => this._client.postRunStatus(runId, "failed"),
12903
+ { unhandledRejection: true }
12904
+ );
13550
12905
  try {
13551
12906
  let sharedContext = null;
13552
12907
  if (hooks?.beforeAll) {
@@ -13554,7 +12909,7 @@ var Simulation = class {
13554
12909
  sharedContext = await runBeforeAll(hooks);
13555
12910
  } catch (error) {
13556
12911
  const errorMsg = `beforeAll hook failed: ${error instanceof Error ? error.message : String(error)}`;
13557
- Logger.error(`${LOG_PREFIX9}: ${errorMsg} \u2014 aborting run (no LLM spent)`);
12912
+ Logger.error(`${LOG_PREFIX7}: ${errorMsg} \u2014 aborting run (no LLM spent)`);
13558
12913
  await this._reportFailures(
13559
12914
  runId,
13560
12915
  items.map((item) => item.runItemId),
@@ -13576,7 +12931,7 @@ var Simulation = class {
13576
12931
  await runAfterAll(hooks, results, null);
13577
12932
  } catch (afterAllError) {
13578
12933
  const afterAllMsg = `afterAll hook failed: ${afterAllError instanceof Error ? afterAllError.message : String(afterAllError)}`;
13579
- Logger.error(`${LOG_PREFIX9}: ${afterAllMsg}`);
12934
+ Logger.error(`${LOG_PREFIX7}: ${afterAllMsg}`);
13580
12935
  }
13581
12936
  await this._client.postRunStatus(runId, "completed");
13582
12937
  return results;
@@ -13599,7 +12954,7 @@ var Simulation = class {
13599
12954
  setupContexts.set(runItemId, setupContext);
13600
12955
  } catch (error) {
13601
12956
  const errorMsg = `before hook failed: ${error instanceof Error ? error.message : String(error)}`;
13602
- Logger.error(`${LOG_PREFIX9}: ${errorMsg} for runItemId=${runItemId}`);
12957
+ Logger.error(`${LOG_PREFIX7}: ${errorMsg} for runItemId=${runItemId}`);
13603
12958
  await this._client.reportFailure(runId, runItemId, errorMsg, "prescript_failed");
13604
12959
  const itemResult = {
13605
12960
  runItemId,
@@ -13615,7 +12970,7 @@ var Simulation = class {
13615
12970
  }
13616
12971
  const simItem = await this._client.generateFirstTurn(runId, runItemId);
13617
12972
  if (!simItem) {
13618
- Logger.warn(`${LOG_PREFIX9}: Failed to generate first turn for item ${runItemId}, marking failed`);
12973
+ Logger.warn(`${LOG_PREFIX7}: Failed to generate first turn for item ${runItemId}, marking failed`);
13619
12974
  await this._client.reportFailure(runId, runItemId, "Failed to generate first user message");
13620
12975
  const itemResult = {
13621
12976
  runItemId,
@@ -13631,7 +12986,7 @@ var Simulation = class {
13631
12986
  );
13632
12987
  await Promise.all(setupPromises);
13633
12988
  if (simulationItems.length === 0) {
13634
- Logger.error(`${LOG_PREFIX9}: All items failed during setup/generation`);
12989
+ Logger.error(`${LOG_PREFIX7}: All items failed during setup/generation`);
13635
12990
  const results = {
13636
12991
  success: false,
13637
12992
  completed: [],
@@ -13642,12 +12997,12 @@ var Simulation = class {
13642
12997
  await runAfterAll(hooks, results, sharedContext);
13643
12998
  } catch (afterAllError) {
13644
12999
  const afterAllMsg = `afterAll hook failed: ${afterAllError instanceof Error ? afterAllError.message : String(afterAllError)}`;
13645
- Logger.error(`${LOG_PREFIX9}: ${afterAllMsg}`);
13000
+ Logger.error(`${LOG_PREFIX7}: ${afterAllMsg}`);
13646
13001
  }
13647
13002
  await this._client.postRunStatus(runId, "completed");
13648
13003
  return results;
13649
13004
  }
13650
- Logger.info(`${LOG_PREFIX9}: Starting simulation with ${simulationItems.length} items`);
13005
+ Logger.info(`${LOG_PREFIX7}: Starting simulation with ${simulationItems.length} items`);
13651
13006
  try {
13652
13007
  const result = await this._runSimulationAsync(
13653
13008
  runId,
@@ -13660,21 +13015,16 @@ var Simulation = class {
13660
13015
  failedItems
13661
13016
  );
13662
13017
  const elapsedTime = ((Date.now() - startTime) / 1e3).toFixed(2);
13663
- Logger.info(`${LOG_PREFIX9}: Simulation completed in ${elapsedTime} seconds`);
13018
+ Logger.info(`${LOG_PREFIX7}: Simulation completed in ${elapsedTime} seconds`);
13664
13019
  await this._client.postRunStatus(runId, "completed");
13665
13020
  return result;
13666
13021
  } catch (error) {
13667
- Logger.error(`${LOG_PREFIX9}: Run simulation failed`);
13022
+ Logger.error(`${LOG_PREFIX7}: Run simulation failed`);
13668
13023
  await this._client.postRunStatus(runId, "failed");
13669
13024
  throw error;
13670
13025
  }
13671
13026
  } finally {
13672
- if (proc && typeof proc.removeListener === "function") {
13673
- proc.removeListener("SIGINT", handleSignal);
13674
- proc.removeListener("SIGTERM", handleSignal);
13675
- proc.removeListener("uncaughtException", handleException);
13676
- proc.removeListener("unhandledRejection", handleRejection);
13677
- }
13027
+ unregisterExitTask();
13678
13028
  }
13679
13029
  }
13680
13030
  /**
@@ -13706,7 +13056,7 @@ var Simulation = class {
13706
13056
  }
13707
13057
  processedCount++;
13708
13058
  Logger.info(
13709
- `${LOG_PREFIX9}: ${processedCount}/${runItems.length} processed (run_item_id=${runItem.runItemId})`
13059
+ `${LOG_PREFIX7}: ${processedCount}/${runItems.length} processed (run_item_id=${runItem.runItemId})`
13710
13060
  );
13711
13061
  return result;
13712
13062
  })
@@ -13717,7 +13067,7 @@ var Simulation = class {
13717
13067
  await runAfterAll(hooks, results, sharedContext);
13718
13068
  } catch (error) {
13719
13069
  const errorMsg = `afterAll hook failed: ${error instanceof Error ? error.message : String(error)}`;
13720
- Logger.error(`${LOG_PREFIX9}: ${errorMsg}`);
13070
+ Logger.error(`${LOG_PREFIX7}: ${errorMsg}`);
13721
13071
  const completed = results.completed;
13722
13072
  const successfulIds = completed.map((item) => item.runItemId);
13723
13073
  await this._reportFailures(
@@ -13737,7 +13087,7 @@ var Simulation = class {
13737
13087
  }
13738
13088
  results.success = results.failed.length === 0;
13739
13089
  Logger.info(
13740
- `${LOG_PREFIX9}: Completed=${results.completed.length}, Failed=${results.failed.length}`
13090
+ `${LOG_PREFIX7}: Completed=${results.completed.length}, Failed=${results.failed.length}`
13741
13091
  );
13742
13092
  return results;
13743
13093
  }
@@ -13768,14 +13118,14 @@ var Simulation = class {
13768
13118
  await runAfter(hooks, datasetItemId, itemResult, setupContext);
13769
13119
  } catch (error) {
13770
13120
  const errorMsg = `after hook failed: ${error instanceof Error ? error.message : String(error)}`;
13771
- Logger.error(`${LOG_PREFIX9}: ${errorMsg} for runItemId=${runItemId}`);
13121
+ Logger.error(`${LOG_PREFIX7}: ${errorMsg} for runItemId=${runItemId}`);
13772
13122
  errors.push(errorMsg);
13773
13123
  }
13774
13124
  try {
13775
13125
  await runAfterEach(hooks, datasetItemId, itemResult, setupContext);
13776
13126
  } catch (error) {
13777
13127
  const errorMsg = `afterEach hook failed: ${error instanceof Error ? error.message : String(error)}`;
13778
- Logger.error(`${LOG_PREFIX9}: ${errorMsg} for runItemId=${runItemId}`);
13128
+ Logger.error(`${LOG_PREFIX7}: ${errorMsg} for runItemId=${runItemId}`);
13779
13129
  errors.push(errorMsg);
13780
13130
  }
13781
13131
  if (errors.length > 0 && itemResult.success) {
@@ -13808,7 +13158,7 @@ var Simulation = class {
13808
13158
  const span2 = new SpanWrapper(
13809
13159
  SPAN_NAME,
13810
13160
  { [Config.TRACE_ORIGIN_KEY]: Config.TRACE_ORIGIN_EVALUATION },
13811
- LOG_PREFIX9
13161
+ LOG_PREFIX7
13812
13162
  );
13813
13163
  span2.start();
13814
13164
  try {
@@ -13839,7 +13189,7 @@ var Simulation = class {
13839
13189
  }
13840
13190
  if (response.decision === "stop") {
13841
13191
  Logger.info(
13842
- `${LOG_PREFIX9}: Completed run_item_id=${runItemId} reason=${response.reason}`
13192
+ `${LOG_PREFIX7}: Completed run_item_id=${runItemId} reason=${response.reason}`
13843
13193
  );
13844
13194
  const itemResult = {
13845
13195
  runItemId,
@@ -13855,7 +13205,7 @@ var Simulation = class {
13855
13205
  } catch (error) {
13856
13206
  const errorMsg = error instanceof Error ? error.message : String(error);
13857
13207
  Logger.error(
13858
- `${LOG_PREFIX9}: Task failed run_item_id=${runItemId}, turn_id=${turnId}: ${errorMsg}`
13208
+ `${LOG_PREFIX7}: Task failed run_item_id=${runItemId}, turn_id=${turnId}: ${errorMsg}`
13859
13209
  );
13860
13210
  await this._client.reportFailure(runId, runItemId, errorMsg);
13861
13211
  const itemResult = {
@@ -13872,7 +13222,7 @@ var Simulation = class {
13872
13222
  }
13873
13223
  }
13874
13224
  };
13875
- var Tracer19 = class {
13225
+ var Tracer18 = class {
13876
13226
  constructor(cfg, effectiveProvider) {
13877
13227
  if (effectiveProvider && typeof effectiveProvider.getTracer === "function") {
13878
13228
  this.tracer = effectiveProvider.getTracer(Config.LIBRARY_NAME, Config.LIBRARY_VERSION);
@@ -13883,8 +13233,8 @@ var Tracer19 = class {
13883
13233
  };
13884
13234
  function spanHasOutput(span2) {
13885
13235
  try {
13886
- for (const field3 of ["attributes", "_attributes"]) {
13887
- const attrs = span2[field3];
13236
+ for (const field of ["attributes", "_attributes"]) {
13237
+ const attrs = span2[field];
13888
13238
  if (attrs && typeof attrs === "object" && attrs["output"]) return true;
13889
13239
  }
13890
13240
  } catch (e) {
@@ -14060,7 +13410,7 @@ function span(targetOrOptions, options) {
14060
13410
  }
14061
13411
 
14062
13412
  // src/index.ts
14063
- var Netra = class {
13413
+ var _Netra = class _Netra {
14064
13414
  static getConfig() {
14065
13415
  if (!this._config) {
14066
13416
  throw new Error("Netra SDK not initialized. Call Netra.init() first.");
@@ -14074,6 +13424,9 @@ var Netra = class {
14074
13424
  * Initialize the Netra SDK.
14075
13425
  */
14076
13426
  static async init(config = {}) {
13427
+ if (this._shutdownPromise) {
13428
+ await this._shutdownPromise;
13429
+ }
14077
13430
  if (this._initialized) {
14078
13431
  Logger.warn("Netra.init() called more than once; ignoring subsequent calls.");
14079
13432
  return;
@@ -14087,7 +13440,7 @@ var Netra = class {
14087
13440
  config.blockInstruments,
14088
13441
  config.rootInstruments
14089
13442
  );
14090
- const tracer = new Tracer19(cfg, effectiveProvider);
13443
+ const tracer = new Tracer18(cfg, effectiveProvider);
14091
13444
  this._tracer = tracer.tracer;
14092
13445
  try {
14093
13446
  this.usage = new Usage(cfg);
@@ -14135,56 +13488,82 @@ var Netra = class {
14135
13488
  `SDK version=${pkgVersion} libraryVersion=${Config.LIBRARY_VERSION} build=langgraph-parenting-v3 packageJson=${pkgPath}`
14136
13489
  );
14137
13490
  }
14138
- const handleSignal = async (signal) => {
14139
- Logger.log(`
14140
- Received ${signal}. Shutting down Netra SDK...`);
14141
- await this.shutdown();
14142
- process.exit(0);
14143
- };
14144
- const handleUncaughtException = async (error) => {
14145
- Logger.error("Uncaught exception:", error);
14146
- Logger.error("Shutting down Netra SDK due to crash...");
14147
- try {
14148
- await this.shutdown();
14149
- } catch (err) {
14150
- Logger.error("Error during crash shutdown:", err);
14151
- }
14152
- process.exit(1);
14153
- };
14154
- process.once("beforeExit", async () => {
14155
- await this.shutdown();
14156
- });
14157
- process.once("SIGINT", () => handleSignal("SIGINT"));
14158
- process.once("SIGTERM", () => handleSignal("SIGTERM"));
14159
- process.once("uncaughtException", handleUncaughtException);
13491
+ if (config.registerShutdownHooks !== false) {
13492
+ this._registerShutdownHooks();
13493
+ }
14160
13494
  await instrumentationsReady;
14161
13495
  }
14162
- static async shutdown() {
14163
- 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) {
14164
13505
  return;
14165
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();
14166
13542
  try {
14167
13543
  await uninstrumentAll();
14168
13544
  } catch (e) {
14169
13545
  Logger.error("Error during uninstrumentAll:", e);
14170
13546
  }
14171
- const FLUSH_TIMEOUT_MS = 5e3;
13547
+ let flushTimer;
14172
13548
  try {
14173
- const traceProvider = trace.getTracerProvider();
13549
+ const globalProvider = trace.getTracerProvider();
13550
+ const traceProvider = typeof globalProvider.getDelegate === "function" ? globalProvider.getDelegate() : globalProvider;
14174
13551
  const flushPromise = (async () => {
14175
- if ("forceFlush" in traceProvider && typeof traceProvider.forceFlush === "function") {
13552
+ if (typeof traceProvider?.forceFlush === "function") {
14176
13553
  await traceProvider.forceFlush();
14177
13554
  }
14178
- if ("shutdown" in traceProvider && typeof traceProvider.shutdown === "function") {
14179
- await traceProvider.shutdown();
14180
- }
14181
13555
  })();
14182
13556
  await Promise.race([
14183
13557
  flushPromise,
14184
- new Promise((resolve) => setTimeout(resolve, FLUSH_TIMEOUT_MS))
13558
+ new Promise((resolve) => {
13559
+ flushTimer = setTimeout(resolve, FLUSH_TIMEOUT_MS);
13560
+ flushTimer.unref?.();
13561
+ })
14185
13562
  ]);
14186
13563
  } catch (e) {
14187
13564
  Logger.error("Error during Netra trace shutdown:", e);
13565
+ } finally {
13566
+ clearTimeout(flushTimer);
14188
13567
  }
14189
13568
  try {
14190
13569
  this.prompts?.clearCache();
@@ -14192,6 +13571,11 @@ Received ${signal}. Shutting down Netra SDK...`);
14192
13571
  } catch (e) {
14193
13572
  Logger.error("Error clearing SDK API caches:", e);
14194
13573
  }
13574
+ try {
13575
+ await settleOtherExitTasks(this._flushTask);
13576
+ } catch (e) {
13577
+ Logger.error("Error awaiting pending shutdown tasks:", e);
13578
+ }
14195
13579
  this._initialized = false;
14196
13580
  this._tracer = void 0;
14197
13581
  }
@@ -14344,10 +13728,12 @@ Received ${signal}. Shutting down Netra SDK...`);
14344
13728
  });
14345
13729
  }
14346
13730
  };
14347
- Netra._SDK_NAME = "netra_sdk";
14348
- Netra._initialized = false;
14349
- Netra._metricsEnabled = false;
14350
- 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;
14351
13737
  var index_default = Netra;
14352
13738
 
14353
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 };