netra-sdk 1.9.0 → 1.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { __toESM, require_decamelize, require_camelcase, init_esm_node, __publicField, v7_default, __require } from './chunk-WMQRYJGR.js';
1
+ import { __require, BaseCallbackHandler } from './chunk-LRCHNZDG.js';
2
2
  import { createContextKey, propagation, trace, context, SpanKind, SpanStatusCode, ROOT_CONTEXT } from '@opentelemetry/api';
3
3
  import { createRequire } from 'module';
4
4
  import { AsyncLocalStorage } from 'async_hooks';
@@ -253,10 +253,10 @@ var UsageHttpClient = class extends NetraHttpClient {
253
253
  user_id: params.userId,
254
254
  tenant_id: params.tenantId
255
255
  };
256
- for (const [field, value] of Object.entries(filterMapping)) {
256
+ for (const [field3, value] of Object.entries(filterMapping)) {
257
257
  if (value !== void 0) {
258
258
  filters.push({
259
- field,
259
+ field: field3,
260
260
  operator: "equals",
261
261
  type: "string",
262
262
  value
@@ -465,8 +465,8 @@ var Usage = class {
465
465
  if (!page) {
466
466
  break;
467
467
  }
468
- for (const trace24 of page.traces) {
469
- yield trace24;
468
+ for (const trace25 of page.traces) {
469
+ yield trace25;
470
470
  }
471
471
  if (!page.hasNextPage || !page.nextCursor) {
472
472
  break;
@@ -579,7 +579,7 @@ var Usage = class {
579
579
  };
580
580
 
581
581
  // src/version.ts
582
- var SDK_VERSION = "1.8.0";
582
+ var SDK_VERSION = "1.10.0";
583
583
 
584
584
  // src/config.ts
585
585
  var NetraInstruments = /* @__PURE__ */ ((NetraInstruments2) => {
@@ -1943,13 +1943,13 @@ async function runSingleEvaluator(params) {
1943
1943
  if (config) {
1944
1944
  expectedName = config.name;
1945
1945
  }
1946
- const context16 = {
1946
+ const context17 = {
1947
1947
  input: itemInput,
1948
1948
  taskOutput,
1949
1949
  expectedOutput,
1950
1950
  metadata
1951
1951
  };
1952
- let result = evaluator.evaluate(context16);
1952
+ let result = evaluator.evaluate(context17);
1953
1953
  if (result instanceof Promise) {
1954
1954
  result = await result;
1955
1955
  }
@@ -2992,6 +2992,33 @@ var Dashboard = class {
2992
2992
  }
2993
2993
  };
2994
2994
 
2995
+ // src/cache.ts
2996
+ var TTLCache = class {
2997
+ constructor(defaultTtl = 60) {
2998
+ this.store = /* @__PURE__ */ new Map();
2999
+ this.defaultTtl = defaultTtl;
3000
+ }
3001
+ get(key) {
3002
+ const entry = this.store.get(key);
3003
+ if (!entry) return void 0;
3004
+ if (performance.now() > entry.expiresAt) {
3005
+ this.store.delete(key);
3006
+ return void 0;
3007
+ }
3008
+ return entry.value;
3009
+ }
3010
+ set(key, value, ttl) {
3011
+ const ttlMs = (ttl ?? this.defaultTtl) * 1e3;
3012
+ this.store.set(key, { value, expiresAt: performance.now() + ttlMs });
3013
+ }
3014
+ invalidate(key) {
3015
+ this.store.delete(key);
3016
+ }
3017
+ clear() {
3018
+ this.store.clear();
3019
+ }
3020
+ };
3021
+
2995
3022
  // src/api/prompts/client.ts
2996
3023
  var PromptsHttpClient = class extends NetraHttpClient {
2997
3024
  constructor(config) {
@@ -3027,17 +3054,27 @@ var PromptsHttpClient = class extends NetraHttpClient {
3027
3054
  }
3028
3055
  };
3029
3056
 
3057
+ // src/api/prompts/models.ts
3058
+ var PROMPT_CACHE_TTL_SECONDS = 60;
3059
+
3030
3060
  // src/api/prompts/api.ts
3031
3061
  var Prompts = class {
3032
3062
  constructor(config) {
3033
3063
  this.config = config;
3034
3064
  this.client = new PromptsHttpClient(config);
3065
+ this.cache = new TTLCache(PROMPT_CACHE_TTL_SECONDS);
3066
+ }
3067
+ /** Clear all cached prompt entries. */
3068
+ clearCache() {
3069
+ this.cache.clear();
3035
3070
  }
3036
3071
  /**
3037
3072
  * Fetch prompt version by name and label.
3038
3073
  *
3039
- * @param params.name - Name of the prompt (required)
3040
- * @param params.label - Label of the prompt version (default: "production")
3074
+ * @param params.name - Name of the prompt (required)
3075
+ * @param params.label - Label of the prompt version (default: "production")
3076
+ * @param params.useCache - When true, read/write the in-memory cache (default: false)
3077
+ * @param params.cacheTtl - Per-call cache TTL in seconds (default: PROMPT_CACHE_TTL_SECONDS)
3041
3078
  */
3042
3079
  async getPrompt(params) {
3043
3080
  if (!params || typeof params.name !== "string" || !params.name) {
@@ -3045,11 +3082,99 @@ var Prompts = class {
3045
3082
  return null;
3046
3083
  }
3047
3084
  const label = params.label ?? "production";
3085
+ const useCache = params.useCache === true;
3086
+ const cacheKey = `prompt:${params.name}:${label}`;
3087
+ if (useCache) {
3088
+ const cached = this.cache.get(cacheKey);
3089
+ if (cached !== void 0) {
3090
+ return cached;
3091
+ }
3092
+ }
3048
3093
  const result = await this.client.getPromptVersion(params.name, label);
3049
3094
  if (!result) {
3050
3095
  return null;
3051
3096
  }
3052
- return result.data ?? null;
3097
+ const data = result.data ?? null;
3098
+ if (data !== null && useCache) {
3099
+ this.cache.set(cacheKey, data, params.cacheTtl);
3100
+ }
3101
+ return data;
3102
+ }
3103
+ };
3104
+
3105
+ // src/api/models/client.ts
3106
+ var ModelsHttpClient = class extends NetraHttpClient {
3107
+ constructor(config) {
3108
+ super(config, "NETRA_MODELS_TIMEOUT", 10);
3109
+ }
3110
+ async getModelPricing(name) {
3111
+ if (!this.isInitialized()) {
3112
+ Logger.error(
3113
+ "netra.models: Models client is not initialized; cannot fetch model pricing"
3114
+ );
3115
+ return null;
3116
+ }
3117
+ try {
3118
+ const params = name ? { name } : void 0;
3119
+ const response = await this.get("/sdk/models", params);
3120
+ if (!response.ok) {
3121
+ const errorMessage = response.data?.error?.message ?? "Unknown error";
3122
+ Logger.error(
3123
+ `netra.models: Failed to fetch model pricing: ${errorMessage}`
3124
+ );
3125
+ return null;
3126
+ }
3127
+ const items = this.extractData(response, null);
3128
+ if (items !== null && !Array.isArray(items)) {
3129
+ Logger.error(
3130
+ "netra.models: Unexpected response format; expected an array"
3131
+ );
3132
+ return null;
3133
+ }
3134
+ return items;
3135
+ } catch (err) {
3136
+ const message = err?.response?.data?.error?.message ?? err?.message ?? "";
3137
+ Logger.error("netra.models: Failed to fetch model pricing:", message);
3138
+ return null;
3139
+ }
3140
+ }
3141
+ };
3142
+
3143
+ // src/api/models/models.ts
3144
+ var MODEL_PRICING_CACHE_TTL_SECONDS = 300;
3145
+
3146
+ // src/api/models/api.ts
3147
+ var Models = class {
3148
+ constructor(config) {
3149
+ this.config = config;
3150
+ this.client = new ModelsHttpClient(config);
3151
+ this.cache = new TTLCache(MODEL_PRICING_CACHE_TTL_SECONDS);
3152
+ }
3153
+ /** Clear all cached model pricing entries. */
3154
+ clearCache() {
3155
+ this.cache.clear();
3156
+ }
3157
+ /**
3158
+ * Fetch model pricing from the backend.
3159
+ *
3160
+ * @param params.name - Optional model name filter
3161
+ * @param params.useCache - When true, read/write the in-memory cache (default: false)
3162
+ * @param params.cacheTtl - Per-call cache TTL in seconds (default: MODEL_PRICING_CACHE_TTL_SECONDS)
3163
+ */
3164
+ async getModelPricing(params = {}) {
3165
+ const useCache = params.useCache === true;
3166
+ const cacheKey = `model:pricing:${params.name ?? "all"}`;
3167
+ if (useCache) {
3168
+ const cached = this.cache.get(cacheKey);
3169
+ if (cached !== void 0) {
3170
+ return cached;
3171
+ }
3172
+ }
3173
+ const data = await this.client.getModelPricing(params.name);
3174
+ if (data !== null && useCache) {
3175
+ this.cache.set(cacheKey, data, params.cacheTtl);
3176
+ }
3177
+ return data;
3053
3178
  }
3054
3179
  };
3055
3180
 
@@ -3821,14 +3946,14 @@ var SpanIOProcessor = class {
3821
3946
  if (promptMatch) {
3822
3947
  original(key, value);
3823
3948
  const idx = parseInt(promptMatch[1], 10);
3824
- const field = promptMatch[2];
3949
+ const field3 = promptMatch[2];
3825
3950
  if (!prompts) prompts = /* @__PURE__ */ new Map();
3826
3951
  let entry = prompts.get(idx);
3827
3952
  if (!entry) {
3828
3953
  entry = {};
3829
3954
  prompts.set(idx, entry);
3830
3955
  }
3831
- entry[field] = String(value);
3956
+ entry[field3] = String(value);
3832
3957
  if (!inputLocked() && (inputIsEmpty() || genAiOwnsInput)) {
3833
3958
  original("input", buildMessages(prompts));
3834
3959
  genAiOwnsInput = true;
@@ -3839,14 +3964,14 @@ var SpanIOProcessor = class {
3839
3964
  if (completionMatch) {
3840
3965
  original(key, value);
3841
3966
  const idx = parseInt(completionMatch[1], 10);
3842
- const field = completionMatch[2];
3967
+ const field3 = completionMatch[2];
3843
3968
  if (!completions) completions = /* @__PURE__ */ new Map();
3844
3969
  let entry = completions.get(idx);
3845
3970
  if (!entry) {
3846
3971
  entry = {};
3847
3972
  completions.set(idx, entry);
3848
3973
  }
3849
- entry[field] = String(value);
3974
+ entry[field3] = String(value);
3850
3975
  if (!outputLocked() && (outputIsEmpty() || genAiOwnsOutput)) {
3851
3976
  original("output", buildMessages(completions));
3852
3977
  genAiOwnsOutput = true;
@@ -4113,7 +4238,33 @@ var SpanAttributes2 = {
4113
4238
  LLM_CHAT_STOP_SEQUENCES: "llm.chat.stop_sequences",
4114
4239
  LLM_IS_STREAMING: "llm.is_streaming",
4115
4240
  LLM_COMPLETIONS: "gen_ai.completion",
4116
- LLM_PROMPTS: "gen_ai.prompt"
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"
4117
4268
  };
4118
4269
  var VALID_NATIVE_TRACING_MODES = /* @__PURE__ */ new Set(["both", "netra", "netra-strict"]);
4119
4270
  function parseNativeTracingEnv(name) {
@@ -5630,15 +5781,6 @@ var BaseInstrumentor = class {
5630
5781
  }
5631
5782
  };
5632
5783
 
5633
- // src/instrumentation/google-genai/version.ts
5634
- var __version__2 = "1.0.0";
5635
-
5636
- // src/instrumentation/google-genai/types.ts
5637
- var SPAN_NAMES2 = {
5638
- CHAT: "google_genai.chat",
5639
- EMBEDDING: "google_genai.embedding"
5640
- };
5641
-
5642
5784
  // src/instrumentation/google-genai/utils.ts
5643
5785
  var LOG_PREFIX = "netra.instrumentation.google_genai";
5644
5786
  function setRequestAttributes3(span2, params, requestType) {
@@ -6021,8 +6163,880 @@ function buildAccumulatedResponse(accumulated) {
6021
6163
  return response;
6022
6164
  }
6023
6165
 
6024
- // src/instrumentation/google-genai/wrappers.ts
6166
+ // src/instrumentation/google-genai/interactions-utils.ts
6025
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 });
7029
+ } catch (e) {
7030
+ Logger.error(`${LOG_PREFIX3}: interaction response error`, e);
7031
+ } finally {
7032
+ span2.end();
7033
+ }
7034
+ return value;
7035
+ }
7036
+
7037
+ // src/instrumentation/google-genai/version.ts
7038
+ var __version__2 = "1.0.0";
7039
+ var LOG_PREFIX4 = "netra.instrumentation.google_genai";
6026
7040
  function buildParams(args, self) {
6027
7041
  const raw = args[0];
6028
7042
  const params = typeof raw === "object" && raw !== null ? { ...raw } : { message: raw };
@@ -6162,7 +7176,7 @@ function streamWrapperFactory(tracer, spanName, requestType) {
6162
7176
  (endTime - startTime) / 1e3
6163
7177
  );
6164
7178
  } catch (e) {
6165
- Logger.error(`${LOG_PREFIX2}: stream finalize error`, e);
7179
+ Logger.error(`${LOG_PREFIX4}: stream finalize error`, e);
6166
7180
  }
6167
7181
  if (status === "ok") {
6168
7182
  span2.setStatus({ code: SpanStatusCode.OK });
@@ -6191,6 +7205,9 @@ var chatStreamWrapper2 = (tracer) => streamWrapperFactory(tracer, SPAN_NAMES2.CH
6191
7205
  var embeddingsWrapper = (tracer) => genericWrapperFactory(tracer, SPAN_NAMES2.EMBEDDING, "embedding");
6192
7206
 
6193
7207
  // src/instrumentation/google-genai/index.ts
7208
+ var INTERACTIONS_PATCHED = /* @__PURE__ */ Symbol.for(
7209
+ "netra.googlegenai.interactions.patched"
7210
+ );
6194
7211
  var NetraGoogleGenAIInstrumentor = class extends BaseInstrumentor {
6195
7212
  constructor() {
6196
7213
  super(...arguments);
@@ -6198,11 +7215,15 @@ var NetraGoogleGenAIInstrumentor = class extends BaseInstrumentor {
6198
7215
  this.instrumentationVersion = __version__2;
6199
7216
  this.packageName = "@google/genai";
6200
7217
  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 = [];
6201
7222
  }
6202
7223
  extractClasses(mod) {
6203
7224
  const root = mod.default ?? mod;
6204
7225
  if (!root.Models) return null;
6205
- return { Models: root.Models, Chat: root.Chat };
7226
+ return { Models: root.Models, Chat: root.Chat, GoogleGenAI: root.GoogleGenAI };
6206
7227
  }
6207
7228
  isSameClasses(a, b) {
6208
7229
  return a.Models === b.Models;
@@ -6237,8 +7258,57 @@ var NetraGoogleGenAIInstrumentor = class extends BaseInstrumentor {
6237
7258
  wrapped = true;
6238
7259
  }
6239
7260
  }
7261
+ if (this.patchInteractions(classes.GoogleGenAI, tracer)) {
7262
+ wrapped = true;
7263
+ }
6240
7264
  return wrapped;
6241
7265
  }
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
+ }
6242
7312
  removePatches(classes) {
6243
7313
  const modelsProto = classes.Models?.prototype;
6244
7314
  if (modelsProto) {
@@ -6257,6 +7327,25 @@ var NetraGoogleGenAIInstrumentor = class extends BaseInstrumentor {
6257
7327
  shimmer.unwrap(chatProto, "sendMessageStream");
6258
7328
  }
6259
7329
  }
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
+ }
6260
7349
  };
6261
7350
  var googleGenAIInstrumentor = new NetraGoogleGenAIInstrumentor();
6262
7351
 
@@ -6660,7 +7749,7 @@ function _setEmbeddingResponseAttributes(span2, response) {
6660
7749
  }
6661
7750
 
6662
7751
  // src/instrumentation/google-generative-ai/wrappers.ts
6663
- var LOG_PREFIX3 = "netra.instrumentation.google_generative_ai";
7752
+ var LOG_PREFIX5 = "netra.instrumentation.google_generative_ai";
6664
7753
  var CHAT_SPAN_NAME = "google_generative_ai.chat";
6665
7754
  var EMBEDDING_SPAN_NAME = "google_generative_ai.embedding";
6666
7755
  function buildKwargs(instance) {
@@ -6705,7 +7794,7 @@ function googleGenerativeAIWrapper(tracer, spanName, requestType) {
6705
7794
  try {
6706
7795
  setRequestAttributes4(span2, kwargs, requestType, args[0]);
6707
7796
  } catch (e) {
6708
- Logger.error(`${LOG_PREFIX3}:`, e);
7797
+ Logger.error(`${LOG_PREFIX5}:`, e);
6709
7798
  }
6710
7799
  const startTime = Date.now();
6711
7800
  const response = original.apply(this, args);
@@ -6726,7 +7815,7 @@ function googleGenerativeAIWrapper(tracer, spanName, requestType) {
6726
7815
  );
6727
7816
  }
6728
7817
  } catch (e) {
6729
- Logger.error(`${LOG_PREFIX3}:`, e);
7818
+ Logger.error(`${LOG_PREFIX5}:`, e);
6730
7819
  }
6731
7820
  span2.setStatus({ code: SpanStatusCode.OK });
6732
7821
  span2.end();
@@ -6751,7 +7840,7 @@ function googleGenerativeAIWrapper(tracer, spanName, requestType) {
6751
7840
  (endTime - startTime) / 1e3
6752
7841
  );
6753
7842
  } catch (e) {
6754
- Logger.error(`${LOG_PREFIX3}:`, e);
7843
+ Logger.error(`${LOG_PREFIX5}:`, e);
6755
7844
  }
6756
7845
  span2.setStatus({ code: SpanStatusCode.OK });
6757
7846
  span2.end();
@@ -6793,7 +7882,7 @@ function googleGenerativeAIStreamWrapper(tracer, spanName, requestType) {
6793
7882
  try {
6794
7883
  setRequestAttributes4(span2, kwargs, requestType, args[0]);
6795
7884
  } catch (e) {
6796
- Logger.error(`${LOG_PREFIX3}:`, e);
7885
+ Logger.error(`${LOG_PREFIX5}:`, e);
6797
7886
  }
6798
7887
  const response = original.apply(this, args);
6799
7888
  if (!isPromise(response)) {
@@ -6817,7 +7906,7 @@ function googleGenerativeAIStreamWrapper(tracer, spanName, requestType) {
6817
7906
  duration
6818
7907
  );
6819
7908
  } catch (e) {
6820
- Logger.error(`${LOG_PREFIX3}:`, e);
7909
+ Logger.error(`${LOG_PREFIX5}:`, e);
6821
7910
  }
6822
7911
  span2.setStatus({ code: SpanStatusCode.OK });
6823
7912
  span2.end();
@@ -6853,7 +7942,7 @@ function googleGenerativeAIStreamWrapper(tracer, spanName, requestType) {
6853
7942
  duration
6854
7943
  );
6855
7944
  } catch (e) {
6856
- Logger.error(`${LOG_PREFIX3}:`, e);
7945
+ Logger.error(`${LOG_PREFIX5}:`, e);
6857
7946
  }
6858
7947
  span2.setStatus({ code: SpanStatusCode.OK });
6859
7948
  span2.end();
@@ -7533,350 +8622,6 @@ var groqInstrumentor = new NetraGroqInstrumentor();
7533
8622
  // src/instrumentation/langgraph/version.ts
7534
8623
  var __version__5 = "1.0.0";
7535
8624
 
7536
- // node_modules/@langchain/core/dist/_virtual/rolldown_runtime.js
7537
- var __defProp = Object.defineProperty;
7538
- var __export = (target, all) => {
7539
- for (var name in all) __defProp(target, name, {
7540
- get: all[name],
7541
- enumerable: true
7542
- });
7543
- };
7544
-
7545
- // node_modules/@langchain/core/dist/load/map_keys.js
7546
- var import_decamelize = __toESM(require_decamelize(), 1);
7547
- __toESM(require_camelcase(), 1);
7548
- function keyToJson(key, map) {
7549
- return map?.[key] || (0, import_decamelize.default)(key);
7550
- }
7551
- function mapKeys(fields, mapper, map) {
7552
- const mapped = {};
7553
- for (const key in fields) if (Object.hasOwn(fields, key)) mapped[mapper(key, map)] = fields[key];
7554
- return mapped;
7555
- }
7556
-
7557
- // node_modules/@langchain/core/dist/load/validation.js
7558
- var LC_ESCAPED_KEY = "__lc_escaped__";
7559
- function needsEscaping(obj) {
7560
- return "lc" in obj || Object.keys(obj).length === 1 && LC_ESCAPED_KEY in obj;
7561
- }
7562
- function escapeObject(obj) {
7563
- return { [LC_ESCAPED_KEY]: obj };
7564
- }
7565
- function isSerializableLike(obj) {
7566
- return obj !== null && typeof obj === "object" && "lc_serializable" in obj && typeof obj.toJSON === "function";
7567
- }
7568
- function createNotImplemented(obj) {
7569
- let id;
7570
- if (obj !== null && typeof obj === "object") if ("lc_id" in obj && Array.isArray(obj.lc_id)) id = obj.lc_id;
7571
- else id = [obj.constructor?.name ?? "Object"];
7572
- else id = [typeof obj];
7573
- return {
7574
- lc: 1,
7575
- type: "not_implemented",
7576
- id
7577
- };
7578
- }
7579
- function escapeIfNeeded(value, pathSet = /* @__PURE__ */ new WeakSet()) {
7580
- if (value !== null && typeof value === "object" && !Array.isArray(value)) {
7581
- if (pathSet.has(value)) return createNotImplemented(value);
7582
- if (isSerializableLike(value)) return value;
7583
- pathSet.add(value);
7584
- const record = value;
7585
- if (needsEscaping(record)) {
7586
- pathSet.delete(value);
7587
- return escapeObject(record);
7588
- }
7589
- const result = {};
7590
- for (const [key, val] of Object.entries(record)) result[key] = escapeIfNeeded(val, pathSet);
7591
- pathSet.delete(value);
7592
- return result;
7593
- }
7594
- if (Array.isArray(value)) return value.map((item) => escapeIfNeeded(item, pathSet));
7595
- return value;
7596
- }
7597
-
7598
- // node_modules/@langchain/core/dist/load/serializable.js
7599
- var serializable_exports = {};
7600
- __export(serializable_exports, {
7601
- Serializable: () => Serializable,
7602
- get_lc_unique_name: () => get_lc_unique_name
7603
- });
7604
- function shallowCopy(obj) {
7605
- return Array.isArray(obj) ? [...obj] : { ...obj };
7606
- }
7607
- function replaceSecrets(root, secretsMap) {
7608
- const result = shallowCopy(root);
7609
- for (const [path, secretId] of Object.entries(secretsMap)) {
7610
- const [last, ...partsReverse] = path.split(".").reverse();
7611
- let current = result;
7612
- for (const part of partsReverse.reverse()) {
7613
- if (current[part] === void 0) break;
7614
- current[part] = shallowCopy(current[part]);
7615
- current = current[part];
7616
- }
7617
- if (current[last] !== void 0) current[last] = {
7618
- lc: 1,
7619
- type: "secret",
7620
- id: [secretId]
7621
- };
7622
- }
7623
- return result;
7624
- }
7625
- function get_lc_unique_name(serializableClass) {
7626
- const parentClass = Object.getPrototypeOf(serializableClass);
7627
- const lcNameIsSubclassed = typeof serializableClass.lc_name === "function" && (typeof parentClass.lc_name !== "function" || serializableClass.lc_name() !== parentClass.lc_name());
7628
- if (lcNameIsSubclassed) return serializableClass.lc_name();
7629
- else return serializableClass.name;
7630
- }
7631
- var Serializable = class Serializable2 {
7632
- constructor(kwargs, ..._args) {
7633
- __publicField(this, "lc_serializable", false);
7634
- __publicField(this, "lc_kwargs");
7635
- if (this.lc_serializable_keys !== void 0) this.lc_kwargs = Object.fromEntries(Object.entries(kwargs || {}).filter(([key]) => this.lc_serializable_keys?.includes(key)));
7636
- else this.lc_kwargs = kwargs ?? {};
7637
- }
7638
- /**
7639
- * The name of the serializable. Override to provide an alias or
7640
- * to preserve the serialized module name in minified environments.
7641
- *
7642
- * Implemented as a static method to support loading logic.
7643
- */
7644
- static lc_name() {
7645
- return this.name;
7646
- }
7647
- /**
7648
- * The final serialized identifier for the module.
7649
- */
7650
- get lc_id() {
7651
- return [...this.lc_namespace, get_lc_unique_name(this.constructor)];
7652
- }
7653
- /**
7654
- * A map of secrets, which will be omitted from serialization.
7655
- * Keys are paths to the secret in constructor args, e.g. "foo.bar.baz".
7656
- * Values are the secret ids, which will be used when deserializing.
7657
- */
7658
- get lc_secrets() {
7659
- return void 0;
7660
- }
7661
- /**
7662
- * A map of additional attributes to merge with constructor args.
7663
- * Keys are the attribute names, e.g. "foo".
7664
- * Values are the attribute values, which will be serialized.
7665
- * These attributes need to be accepted by the constructor as arguments.
7666
- */
7667
- get lc_attributes() {
7668
- return void 0;
7669
- }
7670
- /**
7671
- * A map of aliases for constructor args.
7672
- * Keys are the attribute names, e.g. "foo".
7673
- * Values are the alias that will replace the key in serialization.
7674
- * This is used to eg. make argument names match Python.
7675
- */
7676
- get lc_aliases() {
7677
- return void 0;
7678
- }
7679
- /**
7680
- * A manual list of keys that should be serialized.
7681
- * If not overridden, all fields passed into the constructor will be serialized.
7682
- */
7683
- get lc_serializable_keys() {
7684
- return void 0;
7685
- }
7686
- toJSON() {
7687
- if (!this.lc_serializable) return this.toJSONNotImplemented();
7688
- if (this.lc_kwargs instanceof Serializable2 || typeof this.lc_kwargs !== "object" || Array.isArray(this.lc_kwargs)) return this.toJSONNotImplemented();
7689
- const aliases = {};
7690
- const secrets = {};
7691
- const kwargs = Object.keys(this.lc_kwargs).reduce((acc, key) => {
7692
- acc[key] = key in this ? this[key] : this.lc_kwargs[key];
7693
- return acc;
7694
- }, {});
7695
- for (let current = Object.getPrototypeOf(this); current; current = Object.getPrototypeOf(current)) {
7696
- Object.assign(aliases, Reflect.get(current, "lc_aliases", this));
7697
- Object.assign(secrets, Reflect.get(current, "lc_secrets", this));
7698
- Object.assign(kwargs, Reflect.get(current, "lc_attributes", this));
7699
- }
7700
- Object.keys(secrets).forEach((keyPath) => {
7701
- let read = this;
7702
- let write = kwargs;
7703
- const [last, ...partsReverse] = keyPath.split(".").reverse();
7704
- for (const key of partsReverse.reverse()) {
7705
- if (!(key in read) || read[key] === void 0) return;
7706
- if (!(key in write) || write[key] === void 0) {
7707
- if (typeof read[key] === "object" && read[key] != null) write[key] = {};
7708
- else if (Array.isArray(read[key])) write[key] = [];
7709
- }
7710
- read = read[key];
7711
- write = write[key];
7712
- }
7713
- if (last in read && read[last] !== void 0) write[last] = write[last] || read[last];
7714
- });
7715
- const escapedKwargs = {};
7716
- const pathSet = /* @__PURE__ */ new WeakSet();
7717
- pathSet.add(this);
7718
- for (const [key, value] of Object.entries(kwargs)) escapedKwargs[key] = escapeIfNeeded(value, pathSet);
7719
- const kwargsWithSecrets = Object.keys(secrets).length ? replaceSecrets(escapedKwargs, secrets) : escapedKwargs;
7720
- const processedKwargs = mapKeys(kwargsWithSecrets, keyToJson, aliases);
7721
- return {
7722
- lc: 1,
7723
- type: "constructor",
7724
- id: this.lc_id,
7725
- kwargs: processedKwargs
7726
- };
7727
- }
7728
- toJSONNotImplemented() {
7729
- return {
7730
- lc: 1,
7731
- type: "not_implemented",
7732
- id: this.lc_id
7733
- };
7734
- }
7735
- };
7736
-
7737
- // node_modules/@langchain/core/dist/utils/env.js
7738
- var env_exports = {};
7739
- __export(env_exports, {
7740
- getEnv: () => getEnv,
7741
- getEnvironmentVariable: () => getEnvironmentVariable,
7742
- getRuntimeEnvironment: () => getRuntimeEnvironment,
7743
- isBrowser: () => isBrowser,
7744
- isDeno: () => isDeno,
7745
- isJsDom: () => isJsDom,
7746
- isNode: () => isNode,
7747
- isWebWorker: () => isWebWorker
7748
- });
7749
- var isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined";
7750
- var isWebWorker = () => typeof globalThis === "object" && globalThis.constructor && globalThis.constructor.name === "DedicatedWorkerGlobalScope";
7751
- var isJsDom = () => typeof window !== "undefined" && window.name === "nodejs" || typeof navigator !== "undefined" && navigator.userAgent.includes("jsdom");
7752
- var isDeno = () => typeof Deno !== "undefined";
7753
- var isNode = () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined" && !isDeno();
7754
- var getEnv = () => {
7755
- let env;
7756
- if (isBrowser()) env = "browser";
7757
- else if (isNode()) env = "node";
7758
- else if (isWebWorker()) env = "webworker";
7759
- else if (isJsDom()) env = "jsdom";
7760
- else if (isDeno()) env = "deno";
7761
- else env = "other";
7762
- return env;
7763
- };
7764
- var runtimeEnvironment;
7765
- function getRuntimeEnvironment() {
7766
- if (runtimeEnvironment === void 0) {
7767
- const env = getEnv();
7768
- runtimeEnvironment = {
7769
- library: "langchain-js",
7770
- runtime: env
7771
- };
7772
- }
7773
- return runtimeEnvironment;
7774
- }
7775
- function getEnvironmentVariable(name) {
7776
- try {
7777
- if (typeof process !== "undefined") return process.env?.[name];
7778
- else if (isDeno()) return Deno?.env.get(name);
7779
- else return void 0;
7780
- } catch {
7781
- return void 0;
7782
- }
7783
- }
7784
-
7785
- // node_modules/@langchain/core/dist/callbacks/base.js
7786
- init_esm_node();
7787
- var base_exports = {};
7788
- __export(base_exports, {
7789
- BaseCallbackHandler: () => BaseCallbackHandler,
7790
- callbackHandlerPrefersStreaming: () => callbackHandlerPrefersStreaming,
7791
- isBaseCallbackHandler: () => isBaseCallbackHandler
7792
- });
7793
- var BaseCallbackHandlerMethodsClass = class {
7794
- };
7795
- function callbackHandlerPrefersStreaming(x) {
7796
- return "lc_prefer_streaming" in x && x.lc_prefer_streaming;
7797
- }
7798
- var BaseCallbackHandler = class extends BaseCallbackHandlerMethodsClass {
7799
- constructor(input) {
7800
- super();
7801
- __publicField(this, "lc_serializable", false);
7802
- __publicField(this, "lc_kwargs");
7803
- __publicField(this, "ignoreLLM", false);
7804
- __publicField(this, "ignoreChain", false);
7805
- __publicField(this, "ignoreAgent", false);
7806
- __publicField(this, "ignoreRetriever", false);
7807
- __publicField(this, "ignoreCustomEvent", false);
7808
- __publicField(this, "raiseError", false);
7809
- __publicField(this, "awaitHandlers", getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") === "false");
7810
- this.lc_kwargs = input || {};
7811
- if (input) {
7812
- this.ignoreLLM = input.ignoreLLM ?? this.ignoreLLM;
7813
- this.ignoreChain = input.ignoreChain ?? this.ignoreChain;
7814
- this.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent;
7815
- this.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever;
7816
- this.ignoreCustomEvent = input.ignoreCustomEvent ?? this.ignoreCustomEvent;
7817
- this.raiseError = input.raiseError ?? this.raiseError;
7818
- this.awaitHandlers = this.raiseError || (input._awaitHandler ?? this.awaitHandlers);
7819
- }
7820
- }
7821
- get lc_namespace() {
7822
- return [
7823
- "langchain_core",
7824
- "callbacks",
7825
- this.name
7826
- ];
7827
- }
7828
- get lc_secrets() {
7829
- return void 0;
7830
- }
7831
- get lc_attributes() {
7832
- return void 0;
7833
- }
7834
- get lc_aliases() {
7835
- return void 0;
7836
- }
7837
- get lc_serializable_keys() {
7838
- return void 0;
7839
- }
7840
- /**
7841
- * The name of the serializable. Override to provide an alias or
7842
- * to preserve the serialized module name in minified environments.
7843
- *
7844
- * Implemented as a static method to support loading logic.
7845
- */
7846
- static lc_name() {
7847
- return this.name;
7848
- }
7849
- /**
7850
- * The final serialized identifier for the module.
7851
- */
7852
- get lc_id() {
7853
- return [...this.lc_namespace, get_lc_unique_name(this.constructor)];
7854
- }
7855
- copy() {
7856
- return new this.constructor(this);
7857
- }
7858
- toJSON() {
7859
- return Serializable.prototype.toJSON.call(this);
7860
- }
7861
- toJSONNotImplemented() {
7862
- return Serializable.prototype.toJSONNotImplemented.call(this);
7863
- }
7864
- static fromMethods(methods) {
7865
- class Handler extends BaseCallbackHandler {
7866
- constructor() {
7867
- super();
7868
- __publicField(this, "name", v7_default());
7869
- Object.assign(this, methods);
7870
- }
7871
- }
7872
- return new Handler();
7873
- }
7874
- };
7875
- var isBaseCallbackHandler = (x) => {
7876
- const callbackHandler = x;
7877
- return callbackHandler !== void 0 && typeof callbackHandler.copy === "function" && typeof callbackHandler.name === "string" && typeof callbackHandler.awaitHandlers === "boolean";
7878
- };
7879
-
7880
8625
  // src/instrumentation/langgraph/utils.ts
7881
8626
  var NetraLanggraphAttributes = {
7882
8627
  spanType: "netra.span.type",
@@ -9992,11 +10737,11 @@ function setGenerationAttributes(span2, data, systemName) {
9992
10737
  }
9993
10738
  const effectiveOutput = unwrapGenerationOutput(data.output);
9994
10739
  if (data.usage) {
9995
- setUsageAttributes3(span2, data.usage);
10740
+ setUsageAttributes4(span2, data.usage);
9996
10741
  } else if (effectiveOutput && typeof effectiveOutput === "object" && !Array.isArray(effectiveOutput)) {
9997
10742
  const respUsage = effectiveOutput.usage;
9998
10743
  if (respUsage && typeof respUsage === "object") {
9999
- setUsageAttributes3(span2, respUsage);
10744
+ setUsageAttributes4(span2, respUsage);
10000
10745
  }
10001
10746
  }
10002
10747
  if (data.input !== void 0) {
@@ -10035,7 +10780,7 @@ function setResponseAttributes8(span2, agentSpan, systemName) {
10035
10780
  }
10036
10781
  const resp = data._response;
10037
10782
  if (data.usage && !(resp && typeof resp === "object" && resp.usage)) {
10038
- setUsageAttributes3(span2, data.usage);
10783
+ setUsageAttributes4(span2, data.usage);
10039
10784
  }
10040
10785
  }
10041
10786
  function setFunctionAttributes(span2, data) {
@@ -10084,7 +10829,7 @@ function setCustomAttributes(span2, data) {
10084
10829
  span2.setAttribute(NETRA_CUSTOM_DATA, safeStringify(data.data));
10085
10830
  }
10086
10831
  }
10087
- function setUsageAttributes3(span2, usage) {
10832
+ function setUsageAttributes4(span2, usage) {
10088
10833
  const promptTokens = usage.input_tokens ?? usage.prompt_tokens;
10089
10834
  const completionTokens = usage.output_tokens ?? usage.completion_tokens;
10090
10835
  const totalTokens = usage.total_tokens;
@@ -11649,7 +12394,7 @@ function patchTraceloopLangchainCallbackHandler() {
11649
12394
  } catch (e) {
11650
12395
  Logger.debug("require() for traceloop langchain failed, falling back to import().");
11651
12396
  }
11652
- import('./dist-GIPRCO2C.js').then((mod) => {
12397
+ import('./dist-4UBY6Q6Z.js').then((mod) => {
11653
12398
  applyPatch(mod, "import");
11654
12399
  }).catch(() => {
11655
12400
  });
@@ -12220,17 +12965,17 @@ var BaseTask = class {
12220
12965
  };
12221
12966
 
12222
12967
  // src/simulation/utils.ts
12223
- var LOG_PREFIX4 = "netra.simulation";
12968
+ var LOG_PREFIX6 = "netra.simulation";
12224
12969
  var DEFAULT_FILE_DOWNLOAD_TIMEOUT_S = 30;
12225
12970
  var MAX_FILE_DOWNLOAD_WORKERS = 8;
12226
12971
  var _cachedFileDownloadTimeoutMs = null;
12227
12972
  function validateSimulationInputs(datasetId, task2) {
12228
12973
  if (!datasetId) {
12229
- Logger.error(`${LOG_PREFIX4}: dataset_id is required`);
12974
+ Logger.error(`${LOG_PREFIX6}: dataset_id is required`);
12230
12975
  return false;
12231
12976
  }
12232
12977
  if (!(task2 instanceof BaseTask)) {
12233
- Logger.error(`${LOG_PREFIX4}: task must be a BaseTask instance`);
12978
+ Logger.error(`${LOG_PREFIX6}: task must be a BaseTask instance`);
12234
12979
  return false;
12235
12980
  }
12236
12981
  return true;
@@ -12247,7 +12992,7 @@ function _getFileDownloadTimeout() {
12247
12992
  return _cachedFileDownloadTimeoutMs;
12248
12993
  }
12249
12994
  Logger.warn(
12250
- `${LOG_PREFIX4}: Invalid file download timeout '${envVal}', using default ${DEFAULT_FILE_DOWNLOAD_TIMEOUT_S}s`
12995
+ `${LOG_PREFIX6}: Invalid file download timeout '${envVal}', using default ${DEFAULT_FILE_DOWNLOAD_TIMEOUT_S}s`
12251
12996
  );
12252
12997
  }
12253
12998
  _cachedFileDownloadTimeoutMs = DEFAULT_FILE_DOWNLOAD_TIMEOUT_S * 1e3;
@@ -12276,7 +13021,7 @@ async function _downloadSingleFile(fileData, timeoutMs, signal) {
12276
13021
  const status = axios.isAxiosError(error) ? error.response?.status : void 0;
12277
13022
  const reason = status ? `HTTP ${status}` : error instanceof Error ? error.message : String(error);
12278
13023
  Logger.error(
12279
- `${LOG_PREFIX4}: Failed to download file '${fileData.fileName}': ${reason}`
13024
+ `${LOG_PREFIX6}: Failed to download file '${fileData.fileName}': ${reason}`
12280
13025
  );
12281
13026
  throw new Error(
12282
13027
  `Failed to download file '${fileData.fileName}': ${reason}`
@@ -12293,7 +13038,7 @@ function parseFiles(rawFiles) {
12293
13038
  const downloadUrl = entry.downloadUrl || "";
12294
13039
  if (!fileName || !downloadUrl) {
12295
13040
  Logger.warn(
12296
- `${LOG_PREFIX4}: Skipping malformed file attachment (missing fileName or downloadUrl)`
13041
+ `${LOG_PREFIX6}: Skipping malformed file attachment (missing fileName or downloadUrl)`
12297
13042
  );
12298
13043
  continue;
12299
13044
  }
@@ -12337,7 +13082,7 @@ async function executeTask2(task2, message, sessionId, rawFiles, setupContext) {
12337
13082
  }
12338
13083
 
12339
13084
  // src/simulation/client.ts
12340
- var LOG_PREFIX5 = "netra.simulation";
13085
+ var LOG_PREFIX7 = "netra.simulation";
12341
13086
  var DEFAULT_TIMEOUT = 1e4;
12342
13087
  var SimulationHttpClient = class {
12343
13088
  constructor(config) {
@@ -12350,7 +13095,7 @@ var SimulationHttpClient = class {
12350
13095
  _createClient(config) {
12351
13096
  const endpoint = (config.otlpEndpoint || "").trim();
12352
13097
  if (!endpoint) {
12353
- Logger.error(`${LOG_PREFIX5}: NETRA_OTLP_ENDPOINT is required`);
13098
+ Logger.error(`${LOG_PREFIX7}: NETRA_OTLP_ENDPOINT is required`);
12354
13099
  return null;
12355
13100
  }
12356
13101
  const baseURL = this._resolveBaseUrl(endpoint);
@@ -12372,7 +13117,7 @@ var SimulationHttpClient = class {
12372
13117
  );
12373
13118
  return instance;
12374
13119
  } catch (error) {
12375
- Logger.error(`${LOG_PREFIX5}: Failed to create HTTP client:`, error);
13120
+ Logger.error(`${LOG_PREFIX7}: Failed to create HTTP client:`, error);
12376
13121
  return null;
12377
13122
  }
12378
13123
  }
@@ -12407,7 +13152,7 @@ var SimulationHttpClient = class {
12407
13152
  const timeout = parseFloat(timeoutStr);
12408
13153
  if (isNaN(timeout)) {
12409
13154
  Logger.warn(
12410
- `${LOG_PREFIX5}: Invalid timeout '${timeoutStr}', using default ${DEFAULT_TIMEOUT}ms`
13155
+ `${LOG_PREFIX7}: Invalid timeout '${timeoutStr}', using default ${DEFAULT_TIMEOUT}ms`
12411
13156
  );
12412
13157
  return DEFAULT_TIMEOUT;
12413
13158
  }
@@ -12419,9 +13164,9 @@ var SimulationHttpClient = class {
12419
13164
  * Used in the two-phase flow so that beforeAll/before hooks can run
12420
13165
  * before any LLM spend.
12421
13166
  */
12422
- async initializeRun(name, datasetId, context16, hooksMeta) {
13167
+ async initializeRun(name, datasetId, context17, hooksMeta) {
12423
13168
  if (!this.client) {
12424
- Logger.error(`${LOG_PREFIX5}: Client not initialized`);
13169
+ Logger.error(`${LOG_PREFIX7}: Client not initialized`);
12425
13170
  return null;
12426
13171
  }
12427
13172
  try {
@@ -12429,7 +13174,7 @@ var SimulationHttpClient = class {
12429
13174
  const payload = {
12430
13175
  name,
12431
13176
  datasetId,
12432
- context: context16 || {}
13177
+ context: context17 || {}
12433
13178
  };
12434
13179
  if (hooksMeta) {
12435
13180
  payload.lifecycleHooks = hooksMeta;
@@ -12439,7 +13184,7 @@ var SimulationHttpClient = class {
12439
13184
  const responseData = data.data || {};
12440
13185
  const items = responseData.items || [];
12441
13186
  if (items.length === 0) {
12442
- Logger.warn(`${LOG_PREFIX5}: No items returned from initialize_run`);
13187
+ Logger.warn(`${LOG_PREFIX7}: No items returned from initialize_run`);
12443
13188
  return null;
12444
13189
  }
12445
13190
  const runId = responseData.id || "";
@@ -12452,7 +13197,7 @@ var SimulationHttpClient = class {
12452
13197
  };
12453
13198
  } catch (error) {
12454
13199
  const errorMsg = this._extractErrorMessage(error);
12455
- Logger.error(`${LOG_PREFIX5}: Failed to initialize run:`, errorMsg);
13200
+ Logger.error(`${LOG_PREFIX7}: Failed to initialize run:`, errorMsg);
12456
13201
  return null;
12457
13202
  }
12458
13203
  }
@@ -12463,7 +13208,7 @@ var SimulationHttpClient = class {
12463
13208
  */
12464
13209
  async generateFirstTurn(runId, runItemId) {
12465
13210
  if (!this.client) {
12466
- Logger.error(`${LOG_PREFIX5}: Client not initialized`);
13211
+ Logger.error(`${LOG_PREFIX7}: Client not initialized`);
12467
13212
  return null;
12468
13213
  }
12469
13214
  try {
@@ -12481,7 +13226,7 @@ var SimulationHttpClient = class {
12481
13226
  } catch (error) {
12482
13227
  const errorMsg = this._extractErrorMessage(error);
12483
13228
  Logger.error(
12484
- `${LOG_PREFIX5}: Failed to generate first turn for item ${runItemId}:`,
13229
+ `${LOG_PREFIX7}: Failed to generate first turn for item ${runItemId}:`,
12485
13230
  errorMsg
12486
13231
  );
12487
13232
  return null;
@@ -12492,7 +13237,7 @@ var SimulationHttpClient = class {
12492
13237
  */
12493
13238
  async triggerConversation(message, turnId, sessionId, traceId) {
12494
13239
  if (!this.client) {
12495
- Logger.error(`${LOG_PREFIX5}: Client not initialized`);
13240
+ Logger.error(`${LOG_PREFIX7}: Client not initialized`);
12496
13241
  return null;
12497
13242
  }
12498
13243
  try {
@@ -12515,7 +13260,7 @@ var SimulationHttpClient = class {
12515
13260
  }
12516
13261
  const userMessages = responseData.userMessages || [];
12517
13262
  if (userMessages.length === 0) {
12518
- Logger.warn(`${LOG_PREFIX5}: No user messages in continue response`);
13263
+ Logger.warn(`${LOG_PREFIX7}: No user messages in continue response`);
12519
13264
  return null;
12520
13265
  }
12521
13266
  const nextMsg = userMessages[0];
@@ -12528,7 +13273,7 @@ var SimulationHttpClient = class {
12528
13273
  };
12529
13274
  } catch (error) {
12530
13275
  const errorMsg = this._extractErrorMessage(error);
12531
- Logger.error(`${LOG_PREFIX5}: Failed to trigger conversation:`, errorMsg);
13276
+ Logger.error(`${LOG_PREFIX7}: Failed to trigger conversation:`, errorMsg);
12532
13277
  return null;
12533
13278
  }
12534
13279
  }
@@ -12547,17 +13292,17 @@ var SimulationHttpClient = class {
12547
13292
  */
12548
13293
  async reportFailure(runId, runItemId, error, status = "failed") {
12549
13294
  if (!this.client) {
12550
- Logger.error(`${LOG_PREFIX5}: Client not initialized`);
13295
+ Logger.error(`${LOG_PREFIX7}: Client not initialized`);
12551
13296
  return;
12552
13297
  }
12553
13298
  try {
12554
13299
  const url = `/evaluations/run/${runId}/item/${runItemId}/status`;
12555
13300
  const payload = { status, failureReason: error };
12556
13301
  await this.client.patch(url, payload);
12557
- Logger.info(`${LOG_PREFIX5}: Reported failure - ${error}`);
13302
+ Logger.info(`${LOG_PREFIX7}: Reported failure - ${error}`);
12558
13303
  } catch (err) {
12559
13304
  const errorMsg = this._extractErrorMessage(err);
12560
- Logger.error(`${LOG_PREFIX5}: Failed to report failure:`, errorMsg);
13305
+ Logger.error(`${LOG_PREFIX7}: Failed to report failure:`, errorMsg);
12561
13306
  }
12562
13307
  }
12563
13308
  /**
@@ -12566,7 +13311,7 @@ var SimulationHttpClient = class {
12566
13311
  async postRunStatus(runId, status) {
12567
13312
  if (!this.client) {
12568
13313
  Logger.error(
12569
- `${LOG_PREFIX5}: Client not initialized; cannot post run status`
13314
+ `${LOG_PREFIX7}: Client not initialized; cannot post run status`
12570
13315
  );
12571
13316
  return { success: false };
12572
13317
  }
@@ -12576,14 +13321,14 @@ var SimulationHttpClient = class {
12576
13321
  const response = await this.client.post(url, payload);
12577
13322
  const data = response.data;
12578
13323
  if (data && typeof data === "object" && "data" in data) {
12579
- Logger.info(`${LOG_PREFIX5}: Completed test run successfully`);
13324
+ Logger.info(`${LOG_PREFIX7}: Completed test run successfully`);
12580
13325
  return data.data || {};
12581
13326
  }
12582
13327
  return data;
12583
13328
  } catch (error) {
12584
13329
  const errorMsg = this._extractErrorMessage(error);
12585
13330
  Logger.error(
12586
- `${LOG_PREFIX5}: Failed to post run status for run '${runId}':`,
13331
+ `${LOG_PREFIX7}: Failed to post run status for run '${runId}':`,
12587
13332
  errorMsg
12588
13333
  );
12589
13334
  return { success: false };
@@ -12608,7 +13353,7 @@ var SimulationHttpClient = class {
12608
13353
  };
12609
13354
 
12610
13355
  // src/simulation/hooks.ts
12611
- var LOG_PREFIX6 = "netra.simulation";
13356
+ var LOG_PREFIX8 = "netra.simulation";
12612
13357
  function describeHooks(hooks) {
12613
13358
  const descFn = (fn) => {
12614
13359
  if (!fn) return null;
@@ -12652,11 +13397,11 @@ function describeHooks(hooks) {
12652
13397
  }
12653
13398
  async function runBeforeAll(hooks) {
12654
13399
  if (!hooks?.beforeAll) return null;
12655
- Logger.info(`${LOG_PREFIX6}: running beforeAll hook`);
13400
+ Logger.info(`${LOG_PREFIX8}: running beforeAll hook`);
12656
13401
  const result = await hooks.beforeAll();
12657
13402
  if (result !== null && result !== void 0 && typeof result !== "object") {
12658
13403
  Logger.warn(
12659
- `${LOG_PREFIX6}: beforeAll returned ${typeof result} (expected object or null); ignoring value`
13404
+ `${LOG_PREFIX8}: beforeAll returned ${typeof result} (expected object or null); ignoring value`
12660
13405
  );
12661
13406
  return null;
12662
13407
  }
@@ -12665,7 +13410,7 @@ async function runBeforeAll(hooks) {
12665
13410
  async function runBefore(hooks, datasetItemId, sharedContext) {
12666
13411
  if (hooks?.before && datasetItemId in hooks.before) {
12667
13412
  Logger.info(
12668
- `${LOG_PREFIX6}: running before hook for datasetItemId=${datasetItemId}`
13413
+ `${LOG_PREFIX8}: running before hook for datasetItemId=${datasetItemId}`
12669
13414
  );
12670
13415
  const itemHook = hooks.before[datasetItemId];
12671
13416
  const result = await itemHook(sharedContext);
@@ -12675,7 +13420,7 @@ async function runBefore(hooks, datasetItemId, sharedContext) {
12675
13420
  Object.assign(base, result);
12676
13421
  } else {
12677
13422
  Logger.warn(
12678
- `${LOG_PREFIX6}: before hook returned ${typeof result} (expected object or null); ignoring value`
13423
+ `${LOG_PREFIX8}: before hook returned ${typeof result} (expected object or null); ignoring value`
12679
13424
  );
12680
13425
  }
12681
13426
  }
@@ -12686,7 +13431,7 @@ async function runBefore(hooks, datasetItemId, sharedContext) {
12686
13431
  async function runBeforeEach(hooks, datasetItemId, sharedContext) {
12687
13432
  if (!hooks?.beforeEach) return sharedContext;
12688
13433
  Logger.info(
12689
- `${LOG_PREFIX6}: running beforeEach hook for datasetItemId=${datasetItemId}`
13434
+ `${LOG_PREFIX8}: running beforeEach hook for datasetItemId=${datasetItemId}`
12690
13435
  );
12691
13436
  const result = await hooks.beforeEach(sharedContext);
12692
13437
  const base = { ...sharedContext || {} };
@@ -12695,7 +13440,7 @@ async function runBeforeEach(hooks, datasetItemId, sharedContext) {
12695
13440
  Object.assign(base, result);
12696
13441
  } else {
12697
13442
  Logger.warn(
12698
- `${LOG_PREFIX6}: beforeEach hook returned ${typeof result} (expected object or null); ignoring value`
13443
+ `${LOG_PREFIX8}: beforeEach hook returned ${typeof result} (expected object or null); ignoring value`
12699
13444
  );
12700
13445
  }
12701
13446
  }
@@ -12704,7 +13449,7 @@ async function runBeforeEach(hooks, datasetItemId, sharedContext) {
12704
13449
  async function runAfter(hooks, datasetItemId, itemResult, setupContext) {
12705
13450
  if (hooks?.after && datasetItemId in hooks.after) {
12706
13451
  Logger.info(
12707
- `${LOG_PREFIX6}: running after hook for datasetItemId=${datasetItemId}`
13452
+ `${LOG_PREFIX8}: running after hook for datasetItemId=${datasetItemId}`
12708
13453
  );
12709
13454
  await hooks.after[datasetItemId](itemResult, setupContext);
12710
13455
  }
@@ -12712,18 +13457,18 @@ async function runAfter(hooks, datasetItemId, itemResult, setupContext) {
12712
13457
  async function runAfterEach(hooks, datasetItemId, itemResult, setupContext) {
12713
13458
  if (!hooks?.afterEach) return;
12714
13459
  Logger.info(
12715
- `${LOG_PREFIX6}: running afterEach hook for datasetItemId=${datasetItemId}`
13460
+ `${LOG_PREFIX8}: running afterEach hook for datasetItemId=${datasetItemId}`
12716
13461
  );
12717
13462
  await hooks.afterEach(itemResult, setupContext);
12718
13463
  }
12719
13464
  async function runAfterAll(hooks, results, sharedContext) {
12720
13465
  if (!hooks?.afterAll) return;
12721
- Logger.info(`${LOG_PREFIX6}: running afterAll hook`);
13466
+ Logger.info(`${LOG_PREFIX8}: running afterAll hook`);
12722
13467
  await hooks.afterAll(results, sharedContext);
12723
13468
  }
12724
13469
 
12725
13470
  // src/simulation/api.ts
12726
- var LOG_PREFIX7 = "netra.simulation";
13471
+ var LOG_PREFIX9 = "netra.simulation";
12727
13472
  var SPAN_NAME = "Netra.Simulation.TestRun";
12728
13473
  var Simulation = class {
12729
13474
  constructor(config) {
@@ -12747,7 +13492,7 @@ var Simulation = class {
12747
13492
  name,
12748
13493
  datasetId,
12749
13494
  task: task2,
12750
- context: context16,
13495
+ context: context17,
12751
13496
  maxConcurrency = 5,
12752
13497
  hooks
12753
13498
  } = options;
@@ -12759,7 +13504,7 @@ var Simulation = class {
12759
13504
  const initResult = await this._client.initializeRun(
12760
13505
  name,
12761
13506
  datasetId,
12762
- context16,
13507
+ context17,
12763
13508
  hooksMeta && Object.keys(hooksMeta).length > 0 ? hooksMeta : null
12764
13509
  );
12765
13510
  if (!initResult) {
@@ -12767,7 +13512,7 @@ var Simulation = class {
12767
13512
  }
12768
13513
  const { runId, items } = initResult;
12769
13514
  if (!items || items.length === 0) {
12770
- Logger.error(`${LOG_PREFIX7}: No items returned from initialize_run`);
13515
+ Logger.error(`${LOG_PREFIX9}: No items returned from initialize_run`);
12771
13516
  return null;
12772
13517
  }
12773
13518
  let interrupted = false;
@@ -12809,7 +13554,7 @@ var Simulation = class {
12809
13554
  sharedContext = await runBeforeAll(hooks);
12810
13555
  } catch (error) {
12811
13556
  const errorMsg = `beforeAll hook failed: ${error instanceof Error ? error.message : String(error)}`;
12812
- Logger.error(`${LOG_PREFIX7}: ${errorMsg} \u2014 aborting run (no LLM spent)`);
13557
+ Logger.error(`${LOG_PREFIX9}: ${errorMsg} \u2014 aborting run (no LLM spent)`);
12813
13558
  await this._reportFailures(
12814
13559
  runId,
12815
13560
  items.map((item) => item.runItemId),
@@ -12831,7 +13576,7 @@ var Simulation = class {
12831
13576
  await runAfterAll(hooks, results, null);
12832
13577
  } catch (afterAllError) {
12833
13578
  const afterAllMsg = `afterAll hook failed: ${afterAllError instanceof Error ? afterAllError.message : String(afterAllError)}`;
12834
- Logger.error(`${LOG_PREFIX7}: ${afterAllMsg}`);
13579
+ Logger.error(`${LOG_PREFIX9}: ${afterAllMsg}`);
12835
13580
  }
12836
13581
  await this._client.postRunStatus(runId, "completed");
12837
13582
  return results;
@@ -12854,7 +13599,7 @@ var Simulation = class {
12854
13599
  setupContexts.set(runItemId, setupContext);
12855
13600
  } catch (error) {
12856
13601
  const errorMsg = `before hook failed: ${error instanceof Error ? error.message : String(error)}`;
12857
- Logger.error(`${LOG_PREFIX7}: ${errorMsg} for runItemId=${runItemId}`);
13602
+ Logger.error(`${LOG_PREFIX9}: ${errorMsg} for runItemId=${runItemId}`);
12858
13603
  await this._client.reportFailure(runId, runItemId, errorMsg, "prescript_failed");
12859
13604
  const itemResult = {
12860
13605
  runItemId,
@@ -12870,7 +13615,7 @@ var Simulation = class {
12870
13615
  }
12871
13616
  const simItem = await this._client.generateFirstTurn(runId, runItemId);
12872
13617
  if (!simItem) {
12873
- Logger.warn(`${LOG_PREFIX7}: Failed to generate first turn for item ${runItemId}, marking failed`);
13618
+ Logger.warn(`${LOG_PREFIX9}: Failed to generate first turn for item ${runItemId}, marking failed`);
12874
13619
  await this._client.reportFailure(runId, runItemId, "Failed to generate first user message");
12875
13620
  const itemResult = {
12876
13621
  runItemId,
@@ -12886,7 +13631,7 @@ var Simulation = class {
12886
13631
  );
12887
13632
  await Promise.all(setupPromises);
12888
13633
  if (simulationItems.length === 0) {
12889
- Logger.error(`${LOG_PREFIX7}: All items failed during setup/generation`);
13634
+ Logger.error(`${LOG_PREFIX9}: All items failed during setup/generation`);
12890
13635
  const results = {
12891
13636
  success: false,
12892
13637
  completed: [],
@@ -12897,12 +13642,12 @@ var Simulation = class {
12897
13642
  await runAfterAll(hooks, results, sharedContext);
12898
13643
  } catch (afterAllError) {
12899
13644
  const afterAllMsg = `afterAll hook failed: ${afterAllError instanceof Error ? afterAllError.message : String(afterAllError)}`;
12900
- Logger.error(`${LOG_PREFIX7}: ${afterAllMsg}`);
13645
+ Logger.error(`${LOG_PREFIX9}: ${afterAllMsg}`);
12901
13646
  }
12902
13647
  await this._client.postRunStatus(runId, "completed");
12903
13648
  return results;
12904
13649
  }
12905
- Logger.info(`${LOG_PREFIX7}: Starting simulation with ${simulationItems.length} items`);
13650
+ Logger.info(`${LOG_PREFIX9}: Starting simulation with ${simulationItems.length} items`);
12906
13651
  try {
12907
13652
  const result = await this._runSimulationAsync(
12908
13653
  runId,
@@ -12915,11 +13660,11 @@ var Simulation = class {
12915
13660
  failedItems
12916
13661
  );
12917
13662
  const elapsedTime = ((Date.now() - startTime) / 1e3).toFixed(2);
12918
- Logger.info(`${LOG_PREFIX7}: Simulation completed in ${elapsedTime} seconds`);
13663
+ Logger.info(`${LOG_PREFIX9}: Simulation completed in ${elapsedTime} seconds`);
12919
13664
  await this._client.postRunStatus(runId, "completed");
12920
13665
  return result;
12921
13666
  } catch (error) {
12922
- Logger.error(`${LOG_PREFIX7}: Run simulation failed`);
13667
+ Logger.error(`${LOG_PREFIX9}: Run simulation failed`);
12923
13668
  await this._client.postRunStatus(runId, "failed");
12924
13669
  throw error;
12925
13670
  }
@@ -12961,7 +13706,7 @@ var Simulation = class {
12961
13706
  }
12962
13707
  processedCount++;
12963
13708
  Logger.info(
12964
- `${LOG_PREFIX7}: ${processedCount}/${runItems.length} processed (run_item_id=${runItem.runItemId})`
13709
+ `${LOG_PREFIX9}: ${processedCount}/${runItems.length} processed (run_item_id=${runItem.runItemId})`
12965
13710
  );
12966
13711
  return result;
12967
13712
  })
@@ -12972,7 +13717,7 @@ var Simulation = class {
12972
13717
  await runAfterAll(hooks, results, sharedContext);
12973
13718
  } catch (error) {
12974
13719
  const errorMsg = `afterAll hook failed: ${error instanceof Error ? error.message : String(error)}`;
12975
- Logger.error(`${LOG_PREFIX7}: ${errorMsg}`);
13720
+ Logger.error(`${LOG_PREFIX9}: ${errorMsg}`);
12976
13721
  const completed = results.completed;
12977
13722
  const successfulIds = completed.map((item) => item.runItemId);
12978
13723
  await this._reportFailures(
@@ -12992,7 +13737,7 @@ var Simulation = class {
12992
13737
  }
12993
13738
  results.success = results.failed.length === 0;
12994
13739
  Logger.info(
12995
- `${LOG_PREFIX7}: Completed=${results.completed.length}, Failed=${results.failed.length}`
13740
+ `${LOG_PREFIX9}: Completed=${results.completed.length}, Failed=${results.failed.length}`
12996
13741
  );
12997
13742
  return results;
12998
13743
  }
@@ -13023,14 +13768,14 @@ var Simulation = class {
13023
13768
  await runAfter(hooks, datasetItemId, itemResult, setupContext);
13024
13769
  } catch (error) {
13025
13770
  const errorMsg = `after hook failed: ${error instanceof Error ? error.message : String(error)}`;
13026
- Logger.error(`${LOG_PREFIX7}: ${errorMsg} for runItemId=${runItemId}`);
13771
+ Logger.error(`${LOG_PREFIX9}: ${errorMsg} for runItemId=${runItemId}`);
13027
13772
  errors.push(errorMsg);
13028
13773
  }
13029
13774
  try {
13030
13775
  await runAfterEach(hooks, datasetItemId, itemResult, setupContext);
13031
13776
  } catch (error) {
13032
13777
  const errorMsg = `afterEach hook failed: ${error instanceof Error ? error.message : String(error)}`;
13033
- Logger.error(`${LOG_PREFIX7}: ${errorMsg} for runItemId=${runItemId}`);
13778
+ Logger.error(`${LOG_PREFIX9}: ${errorMsg} for runItemId=${runItemId}`);
13034
13779
  errors.push(errorMsg);
13035
13780
  }
13036
13781
  if (errors.length > 0 && itemResult.success) {
@@ -13063,7 +13808,7 @@ var Simulation = class {
13063
13808
  const span2 = new SpanWrapper(
13064
13809
  SPAN_NAME,
13065
13810
  { [Config.TRACE_ORIGIN_KEY]: Config.TRACE_ORIGIN_EVALUATION },
13066
- LOG_PREFIX7
13811
+ LOG_PREFIX9
13067
13812
  );
13068
13813
  span2.start();
13069
13814
  try {
@@ -13094,7 +13839,7 @@ var Simulation = class {
13094
13839
  }
13095
13840
  if (response.decision === "stop") {
13096
13841
  Logger.info(
13097
- `${LOG_PREFIX7}: Completed run_item_id=${runItemId} reason=${response.reason}`
13842
+ `${LOG_PREFIX9}: Completed run_item_id=${runItemId} reason=${response.reason}`
13098
13843
  );
13099
13844
  const itemResult = {
13100
13845
  runItemId,
@@ -13110,7 +13855,7 @@ var Simulation = class {
13110
13855
  } catch (error) {
13111
13856
  const errorMsg = error instanceof Error ? error.message : String(error);
13112
13857
  Logger.error(
13113
- `${LOG_PREFIX7}: Task failed run_item_id=${runItemId}, turn_id=${turnId}: ${errorMsg}`
13858
+ `${LOG_PREFIX9}: Task failed run_item_id=${runItemId}, turn_id=${turnId}: ${errorMsg}`
13114
13859
  );
13115
13860
  await this._client.reportFailure(runId, runItemId, errorMsg);
13116
13861
  const itemResult = {
@@ -13127,7 +13872,7 @@ var Simulation = class {
13127
13872
  }
13128
13873
  }
13129
13874
  };
13130
- var Tracer18 = class {
13875
+ var Tracer19 = class {
13131
13876
  constructor(cfg, effectiveProvider) {
13132
13877
  if (effectiveProvider && typeof effectiveProvider.getTracer === "function") {
13133
13878
  this.tracer = effectiveProvider.getTracer(Config.LIBRARY_NAME, Config.LIBRARY_VERSION);
@@ -13138,8 +13883,8 @@ var Tracer18 = class {
13138
13883
  };
13139
13884
  function spanHasOutput(span2) {
13140
13885
  try {
13141
- for (const field of ["attributes", "_attributes"]) {
13142
- const attrs = span2[field];
13886
+ for (const field3 of ["attributes", "_attributes"]) {
13887
+ const attrs = span2[field3];
13143
13888
  if (attrs && typeof attrs === "object" && attrs["output"]) return true;
13144
13889
  }
13145
13890
  } catch (e) {
@@ -13325,6 +14070,9 @@ var Netra = class {
13325
14070
  static isInitialized() {
13326
14071
  return this._initialized;
13327
14072
  }
14073
+ /**
14074
+ * Initialize the Netra SDK.
14075
+ */
13328
14076
  static async init(config = {}) {
13329
14077
  if (this._initialized) {
13330
14078
  Logger.warn("Netra.init() called more than once; ignoring subsequent calls.");
@@ -13339,7 +14087,7 @@ var Netra = class {
13339
14087
  config.blockInstruments,
13340
14088
  config.rootInstruments
13341
14089
  );
13342
- const tracer = new Tracer18(cfg, effectiveProvider);
14090
+ const tracer = new Tracer19(cfg, effectiveProvider);
13343
14091
  this._tracer = tracer.tracer;
13344
14092
  try {
13345
14093
  this.usage = new Usage(cfg);
@@ -13366,6 +14114,11 @@ var Netra = class {
13366
14114
  } catch (e) {
13367
14115
  Logger.warn("Netra: failed to initialize prompts client:", e);
13368
14116
  }
14117
+ try {
14118
+ this.models = new Models(cfg);
14119
+ } catch (e) {
14120
+ Logger.warn("Netra: failed to initialize models client:", e);
14121
+ }
13369
14122
  this._initialized = true;
13370
14123
  Logger.info("Netra successfully initialized.");
13371
14124
  {
@@ -13433,6 +14186,12 @@ Received ${signal}. Shutting down Netra SDK...`);
13433
14186
  } catch (e) {
13434
14187
  Logger.error("Error during Netra trace shutdown:", e);
13435
14188
  }
14189
+ try {
14190
+ this.prompts?.clearCache();
14191
+ this.models?.clearCache();
14192
+ } catch (e) {
14193
+ Logger.error("Error clearing SDK API caches:", e);
14194
+ }
13436
14195
  this._initialized = false;
13437
14196
  this._tracer = void 0;
13438
14197
  }
@@ -13591,6 +14350,6 @@ Netra._metricsEnabled = false;
13591
14350
  Netra.withBlockedSpansLocal = withBlockedSpansLocal;
13592
14351
  var index_default = Netra;
13593
14352
 
13594
- export { Aggregation, BaseTask, ChartType, Config, ConversationType, DEFAULT_INSTRUMENTS, DEFAULT_INSTRUMENTS_FOR_ROOT, Dashboard, DimensionField, EntryStatus, Evaluation, FilterField, FilterType, FilteringSpanExporter, GroupBy, InstrumentationSpanProcessor, Measure, Netra, NetraAgentsTracingProcessor, NetraInstruments, NetraOpenAIAgentsInstrumentor, Operator, 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 };
14353
+ 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 };
13595
14354
  //# sourceMappingURL=index.js.map
13596
14355
  //# sourceMappingURL=index.js.map