netra-sdk 1.0.5 → 1.1.0-beta

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.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { Span, Context, TracerProvider } from '@opentelemetry/api';
1
+ import { Span, Context, TracerProvider, Tracer, SpanContext } from '@opentelemetry/api';
2
2
  import { SpanProcessor, ReadableSpan, SpanExporter } from '@opentelemetry/sdk-trace-base';
3
3
  import { ExportResultCode, ExportResult } from '@opentelemetry/core';
4
4
 
@@ -18,11 +18,18 @@ interface NetraConfig {
18
18
  blockedSpans?: string[];
19
19
  instruments?: Set<NetraInstruments>;
20
20
  blockInstruments?: Set<NetraInstruments>;
21
+ rootInstruments?: Set<NetraInstruments>;
21
22
  }
22
23
  declare enum NetraInstruments {
24
+ /**
25
+ * Sentinel value: when included in `instruments` or `rootInstruments`,
26
+ * restores the legacy behaviour where every available instrumentation is
27
+ * enabled automatically (no curated default list is applied).
28
+ */
29
+ ALL = "__all__",
23
30
  OPENAI = "openai",
24
31
  GOOGLE_GENERATIVE_AI = "google_genai",
25
- MISTRAL = "mistral",
32
+ MISTRAL = "mistral_ai",
26
33
  GROQ = "groq",
27
34
  VERTEX_AI = "vertexai",
28
35
  TOGETHER = "together",
@@ -30,24 +37,25 @@ declare enum NetraInstruments {
30
37
  LANGCHAIN = "langchain",
31
38
  LANGGRAPH = "langgraph",
32
39
  LLAMA_INDEX = "llama_index",
40
+ OPENAI_AGENTS = "openai_agents",
33
41
  PINECONE = "pinecone",
34
42
  QDRANT = "qdrant",
35
43
  CHROMADB = "chromadb",
36
44
  HTTP = "http",
37
- HTTPS = "https",
38
- FETCH = "fetch",
39
45
  PRISMA = "prisma",
40
46
  TYPEORM = "typeorm",
41
- MONGODB = "mongodb",
42
- POSTGRES = "postgres",
43
- MYSQL = "mysql",
44
- REDIS = "redis",
45
- EXPRESS = "express",
46
- FASTIFY = "fastify",
47
- NESTJS = "nestjs",
48
- KAFKA = "kafka",
49
- RABBITMQ = "rabbitmq"
47
+ EXPRESS = "express"
50
48
  }
49
+ /**
50
+ * Subset of DEFAULT_INSTRUMENTS allowed to produce root-level spans.
51
+ * Covers core LLM/AI providers and agent frameworks.
52
+ */
53
+ declare const DEFAULT_INSTRUMENTS_FOR_ROOT: Set<NetraInstruments>;
54
+ /**
55
+ * Full set of instrumentations installed by default. Includes the root
56
+ * defaults plus common vector DBs, HTTP clients, and database libraries.
57
+ */
58
+ declare const DEFAULT_INSTRUMENTS: Set<NetraInstruments>;
51
59
  declare class Config {
52
60
  static readonly SDK_NAME = "netra";
53
61
  static readonly LIBRARY_NAME = "netra";
@@ -89,235 +97,190 @@ declare class Config {
89
97
  }
90
98
 
91
99
  /**
92
- * Dashboard API Models
100
+ * Usage API Models
93
101
  */
94
- declare enum Scope {
95
- SPANS = "Spans",
96
- TRACES = "Traces"
97
- }
98
- declare enum ChartType {
99
- LINE_TIME_SERIES = "Line Time Series",
100
- BAR_TIME_SERIES = "Bar Time Series",
101
- HORIZONTAL_BAR = "Horizontal Bar",
102
- VERTICAL_BAR = "Vertical Bar",
103
- PIE = "Pie",
104
- NUMBER = "Number"
102
+ interface SessionUsageData {
103
+ sessionId: string;
104
+ tokenCount: number;
105
+ requestCount: number;
106
+ totalCost: number;
105
107
  }
106
- declare enum Measure {
107
- LATENCY = "Latency",
108
- ERROR_RATE = "Error Rate",
109
- PII_COUNT = "PII Count",
110
- REQUEST_COUNT = "Request Count",
111
- TOTAL_COST = "Total Cost",
112
- VIOLATIONS = "Violations",
113
- TOTAL_TOKENS = "Total Tokens",
114
- AUDIO_DURATION = "Audio Duration",
115
- CHARACTER_COUNT = "Character Count"
108
+ interface TenantUsageData {
109
+ tenantId: string;
110
+ organisationId: string;
111
+ tokenCount: number;
112
+ requestCount: number;
113
+ sessionCount: number;
114
+ totalCost: number;
116
115
  }
117
- declare enum Aggregation {
118
- AVERAGE = "Average",
119
- P50 = "p50",
120
- P90 = "p90",
121
- P95 = "p95",
122
- P99 = "p99",
123
- MEDIAN = "Median (p50)",
124
- PERCENTAGE = "Percentage",
125
- TOTAL_COUNT = "Total Count"
116
+ interface TraceSummary {
117
+ id: string;
118
+ name: string;
119
+ kind: string;
120
+ latencyMs: number;
121
+ startTime: string;
122
+ endTime: string;
123
+ cursor: string;
124
+ organisationId: string;
125
+ projectId: string;
126
+ sessionId?: string;
127
+ tenantId?: string;
128
+ userId?: string;
129
+ environment?: string;
130
+ models?: string[];
131
+ promptTokens?: number;
132
+ completionTokens?: number;
133
+ cachedTokens?: number;
134
+ totalTokens?: number;
135
+ promptTokensCost?: number;
136
+ completionTokensCost?: number;
137
+ cachedTokensCost?: number;
138
+ totalCost?: number;
139
+ hasPii?: boolean;
140
+ piiEntities?: any[];
141
+ hasViolation?: boolean;
142
+ violations?: any[];
143
+ hasError?: boolean;
144
+ service?: string;
126
145
  }
127
- declare enum GroupBy {
128
- DAY = "day",
129
- HOUR = "hour",
130
- MINUTE = "minute"
146
+ interface TracesPage {
147
+ traces: TraceSummary[];
148
+ hasNextPage: boolean;
149
+ nextCursor?: string;
131
150
  }
132
- declare enum DimensionField {
133
- ENVIRONMENT = "environment",
134
- SERVICE = "service",
135
- MODEL_NAME = "model_name"
151
+ interface TraceSpan {
152
+ id: string;
153
+ traceId: string;
154
+ name: string;
155
+ kind: string;
156
+ parentSpanId?: string;
157
+ latencyMs?: number;
158
+ startTimeMs?: string;
159
+ endTimeMs?: string;
160
+ organisationId: string;
161
+ projectId: string;
162
+ sessionId?: string;
163
+ tenantId?: string;
164
+ userId?: string;
165
+ environment?: string;
166
+ modelName?: string;
167
+ promptTokens?: number;
168
+ completionTokens?: number;
169
+ cachedTokens?: number;
170
+ totalTokens?: number;
171
+ promptTokensCost?: number;
172
+ completionTokensCost?: number;
173
+ cachedTokensCost?: number;
174
+ totalCost?: number;
175
+ hasPii?: boolean;
176
+ piiEntities?: any[];
177
+ piiActions?: Record<string, any>;
178
+ hasViolation?: boolean;
179
+ violations?: any[];
180
+ violationActions?: Record<string, any>;
181
+ status?: string;
182
+ attributes?: string;
183
+ events?: string;
184
+ links?: string;
185
+ resources?: string;
186
+ metadata?: Record<string, any>;
187
+ hasError?: boolean;
188
+ createdAt: string;
189
+ cursor: string;
136
190
  }
137
- declare enum Operator {
138
- EQUALS = "equals",
139
- NOT_EQUALS = "not_equals",
140
- CONTAINS = "contains",
141
- NOT_CONTAINS = "not_contains",
142
- STARTS_WITH = "starts_with",
143
- ENDS_WITH = "ends_with",
144
- GREATER_THAN = "greater_than",
145
- LESS_THAN = "less_than",
146
- GREATER_EQUAL_TO = "greater_equal_to",
147
- LESS_EQUAL_TO = "less_equal_to",
148
- ANY_OF = "any_of",
149
- NONE_OF = "none_of"
191
+ interface SpansPage {
192
+ spans: TraceSpan[];
193
+ hasNextPage: boolean;
194
+ nextCursor?: string;
150
195
  }
151
- declare enum FilterType {
152
- STRING = "string",
153
- NUMBER = "number",
154
- BOOLEAN = "boolean",
155
- ARRAY_OPTIONS = "arrayOptions",
156
- OBJECT = "object"
196
+ interface ListTracesParams {
197
+ startTime: string;
198
+ endTime: string;
199
+ traceId?: string;
200
+ sessionId?: string;
201
+ userId?: string;
202
+ tenantId?: string;
203
+ limit?: number;
204
+ cursor?: string;
205
+ direction?: "up" | "down";
206
+ sortField?: string;
207
+ sortOrder?: "asc" | "desc";
157
208
  }
158
- declare enum FilterField {
159
- TOTAL_COST = "total_cost",
160
- SERVICE = "service",
161
- TENANT_ID = "tenant_id",
162
- USER_ID = "user_id",
163
- SESSION_ID = "session_id",
164
- ENVIRONMENT = "environment",
165
- LATENCY = "latency",
166
- MODEL_NAME = "model_name",
167
- MODELS = "models",
168
- METADATA = "metadata"
209
+ interface ListSpansParams {
210
+ traceId: string;
211
+ cursor?: string;
212
+ direction?: "up" | "down";
213
+ limit?: number;
214
+ spanName?: string;
169
215
  }
170
- declare enum SessionFilterField {
171
- TENANT_ID = "tenant_id"
216
+
217
+ /**
218
+ * Public Usage API
219
+ * Exposed as Netra.usage
220
+ */
221
+
222
+ declare class Usage {
223
+ private config;
224
+ private client;
225
+ constructor(config: Config);
226
+ /**
227
+ * Get session usage data
228
+ * @param sessionId Session identifier
229
+ * @param startTime Start time for the usage data (in ISO 8601 UTC format)
230
+ * @param endTime End time for the usage data (in ISO 8601 UTC format)
231
+ * @returns Session usage data or null on error
232
+ */
233
+ getSessionUsage(sessionId: string, startTime: string, endTime: string): Promise<SessionUsageData | null>;
234
+ /**
235
+ * Get tenant usage data
236
+ * @param tenantId Tenant identifier
237
+ * @param startTime Start time for the usage data (in ISO 8601 UTC format)
238
+ * @param endTime End time for the usage data (in ISO 8601 UTC format)
239
+ * @returns Tenant usage data or null on error
240
+ */
241
+ getTenantUsage(tenantId: string, startTime: string, endTime: string): Promise<TenantUsageData | null>;
242
+ /**
243
+ * List all traces
244
+ * @param params List traces parameters
245
+ * @returns Traces page or null on error
246
+ */
247
+ listTraces(params: ListTracesParams): Promise<TracesPage | null>;
248
+ /**
249
+ * List all spans for a given trace
250
+ * @param params List spans parameters
251
+ * @returns Spans page or null on error
252
+ */
253
+ listSpansByTraceId(params: ListSpansParams): Promise<SpansPage | null>;
254
+ /**
255
+ * Iterate over traces using cursor-based pagination
256
+ * @param params List traces parameters
257
+ * @returns Async generator yielding TraceSummary items
258
+ */
259
+ iterTraces(params: ListTracesParams): AsyncGenerator<TraceSummary, void, unknown>;
260
+ /**
261
+ * Iterate over spans for a given trace using cursor-based pagination
262
+ * @param params List spans parameters
263
+ * @returns Async generator yielding TraceSpan items
264
+ */
265
+ iterSpansByTraceId(params: ListSpansParams): AsyncGenerator<TraceSpan, void, unknown>;
266
+ private mapToTraceSummary;
267
+ private mapToTraceSpan;
172
268
  }
173
- declare enum SessionOperator {
174
- ANY_OF = "any_of"
269
+
270
+ /**
271
+ * Evaluation API Models
272
+ */
273
+ interface DatasetEntry {
274
+ id: string;
275
+ input: string;
276
+ datasetId: string;
277
+ expectedOutput?: any;
175
278
  }
176
- declare enum SessionFilterType {
177
- ARRAY = "arrayOptions"
178
- }
179
- declare enum SortField {
180
- SESSION_ID = "session_id",
181
- START_TIME = "start_time",
182
- TOTAL_REQUESTS = "totalRequests",
183
- TOTAL_COST = "totalCost"
184
- }
185
- declare enum SortOrder {
186
- ASC = "asc",
187
- DESC = "desc"
188
- }
189
- /**
190
- * Create a metadata filter field
191
- * @param key The metadata key to filter on
192
- * @returns The formatted metadata field string
193
- * @example
194
- * metadataField("customer_tier") // returns "metadata['customer_tier']"
195
- */
196
- declare function metadataField(key: string): string;
197
- interface Filter {
198
- field: FilterField | string;
199
- operator: Operator;
200
- type: FilterType;
201
- value: any;
202
- key?: string;
203
- }
204
- interface Metrics {
205
- measure: Measure;
206
- aggregation: Aggregation;
207
- }
208
- interface Dimension {
209
- field: DimensionField;
210
- }
211
- interface FilterConfig {
212
- startTime: string;
213
- endTime: string;
214
- groupBy: GroupBy;
215
- filters?: Filter[];
216
- }
217
- interface TimeRange {
218
- startTime: string;
219
- endTime: string;
220
- }
221
- interface TimeSeriesDataPoint {
222
- date: string;
223
- value: number;
224
- }
225
- interface DimensionValue {
226
- dimension: string;
227
- value: number;
228
- }
229
- interface TimeSeriesWithDimension {
230
- date: string;
231
- values: DimensionValue[];
232
- }
233
- interface TimeSeriesResponse {
234
- timeSeries: TimeSeriesWithDimension[];
235
- dimensions: string[];
236
- }
237
- interface CategoricalDataPoint {
238
- dimension: string;
239
- value: number;
240
- }
241
- interface NumberResponse {
242
- value: number;
243
- }
244
- type DashboardData = TimeSeriesDataPoint[] | TimeSeriesResponse | CategoricalDataPoint[] | NumberResponse | Record<string, any>;
245
- interface QueryResponse {
246
- timeRange: TimeRange;
247
- data: DashboardData;
248
- }
249
- interface QueryDataParams {
250
- scope: Scope;
251
- chartType: ChartType;
252
- metrics: Metrics;
253
- filter: FilterConfig;
254
- dimension?: Dimension;
255
- }
256
- interface SessionFilter {
257
- field: SessionFilterField;
258
- operator: SessionOperator;
259
- type: SessionFilterType;
260
- value: string[];
261
- }
262
- interface SessionStatsResult {
263
- data: SessionStatsData[];
264
- hasNextPage: boolean;
265
- nextCursor?: string;
266
- }
267
- interface SessionFilterConfig {
268
- startTime: string;
269
- endTime: string;
270
- filters?: SessionFilter[];
271
- }
272
- interface SessionStatsData {
273
- session_id: string;
274
- session_start_time: string;
275
- totalRequests: number;
276
- totalCost: number;
277
- session_duration: string;
278
- cursor: string;
279
- }
280
-
281
- /**
282
- * Public Dashboard API
283
- * Exposed as Netra.dashboard
284
- */
285
-
286
- declare class Dashboard {
287
- private config;
288
- private client;
289
- constructor(config: Config);
290
- /**
291
- * Execute a dynamic query for dashboards to retrieve metrics and time-series data
292
- * @param params Query parameters
293
- * @returns Query response containing timeRange and data, or null on error
294
- */
295
- queryData(params: QueryDataParams): Promise<QueryResponse | null>;
296
- getSessionStats(startTime: string, endTime: string, limit?: number, filters?: SessionFilter[], cursor?: string, sortField?: SortField, sortOrder?: SortOrder): Promise<SessionStatsResult | null>;
297
- iterSessionStats(startTime: string, endTime: string, filters?: SessionFilter[], sortField?: SortField, sortOrder?: SortOrder): AsyncGenerator<SessionStatsData, void, unknown>;
298
- getSessionSummary(filter: SessionFilterConfig): Promise<any | null>;
299
- private isValidScope;
300
- private isValidChartType;
301
- private isValidMetrics;
302
- private isValidFilterConfig;
303
- private isValidDimension;
304
- private isSessionFilterConfig;
305
- }
306
-
307
- /**
308
- * Evaluation API Models
309
- */
310
- interface DatasetEntry {
311
- id: string;
312
- input: string;
313
- datasetId: string;
314
- expectedOutput?: any;
315
- }
316
- interface DatasetItem {
317
- input: any;
318
- expectedOutput?: any;
319
- metadata?: Record<string, any>;
320
- tags?: string[];
279
+ interface DatasetItem {
280
+ input: any;
281
+ expectedOutput?: any;
282
+ metadata?: Record<string, any>;
283
+ tags?: string[];
321
284
  }
322
285
  interface DatasetRecord {
323
286
  id: string;
@@ -452,6 +415,12 @@ declare class Evaluation {
452
415
  * @returns runId: The id of the created run
453
416
  */
454
417
  createRun(name: string, datasetId?: string, evaluatorsConfig?: EvaluatorConfig[]): Promise<string | null>;
418
+ /**
419
+ * Fetch test run results based on run ID
420
+ * @param runId The id of the run to fetch
421
+ * @returns The run results data
422
+ */
423
+ getRunResults(runId: string): Promise<any>;
455
424
  /**
456
425
  * Netra evaluation function to initiate a test suite
457
426
  * @param name The name of the run
@@ -566,6 +535,12 @@ declare class EvaluationHttpClient extends NetraHttpClient {
566
535
  * Add a single item to an existing dataset
567
536
  */
568
537
  addDatasetItem(datasetId: string, itemPayload: Record<string, any>): Promise<any>;
538
+ /**
539
+ * Fetch test run results by run ID
540
+ * @param runId The id of the run to fetch
541
+ * @returns The run results data
542
+ */
543
+ getRunResults(runId: string): Promise<any>;
569
544
  /**
570
545
  * Submit a new run item to the backend
571
546
  */
@@ -631,190 +606,460 @@ declare class RunEntryContext {
631
606
  }
632
607
 
633
608
  /**
634
- * Usage API Models
609
+ * Dashboard API Models
635
610
  */
636
- interface SessionUsageData {
637
- sessionId: string;
638
- tokenCount: number;
639
- requestCount: number;
640
- totalCost: number;
611
+ declare enum Scope {
612
+ SPANS = "Spans",
613
+ TRACES = "Traces"
641
614
  }
642
- interface TenantUsageData {
643
- tenantId: string;
644
- organisationId: string;
645
- tokenCount: number;
646
- requestCount: number;
647
- sessionCount: number;
648
- totalCost: number;
615
+ declare enum ChartType {
616
+ LINE_TIME_SERIES = "Line Time Series",
617
+ BAR_TIME_SERIES = "Bar Time Series",
618
+ HORIZONTAL_BAR = "Horizontal Bar",
619
+ VERTICAL_BAR = "Vertical Bar",
620
+ PIE = "Pie",
621
+ NUMBER = "Number"
649
622
  }
650
- interface TraceSummary {
651
- id: string;
652
- name: string;
653
- kind: string;
654
- latencyMs: number;
655
- startTime: string;
656
- endTime: string;
657
- cursor: string;
658
- organisationId: string;
659
- projectId: string;
660
- sessionId?: string;
661
- tenantId?: string;
662
- userId?: string;
663
- environment?: string;
664
- models?: string[];
665
- promptTokens?: number;
666
- completionTokens?: number;
667
- cachedTokens?: number;
668
- totalTokens?: number;
669
- promptTokensCost?: number;
670
- completionTokensCost?: number;
671
- cachedTokensCost?: number;
672
- totalCost?: number;
673
- hasPii?: boolean;
674
- piiEntities?: any[];
675
- hasViolation?: boolean;
676
- violations?: any[];
677
- hasError?: boolean;
678
- service?: string;
623
+ declare enum Measure {
624
+ LATENCY = "Latency",
625
+ ERROR_RATE = "Error Rate",
626
+ PII_COUNT = "PII Count",
627
+ REQUEST_COUNT = "Request Count",
628
+ TOTAL_COST = "Total Cost",
629
+ VIOLATIONS = "Violations",
630
+ TOTAL_TOKENS = "Total Tokens",
631
+ AUDIO_DURATION = "Audio Duration",
632
+ CHARACTER_COUNT = "Character Count"
679
633
  }
680
- interface TracesPage {
681
- traces: TraceSummary[];
682
- hasNextPage: boolean;
683
- nextCursor?: string;
634
+ declare enum Aggregation {
635
+ AVERAGE = "Average",
636
+ P50 = "p50",
637
+ P90 = "p90",
638
+ P95 = "p95",
639
+ P99 = "p99",
640
+ MEDIAN = "Median (p50)",
641
+ PERCENTAGE = "Percentage",
642
+ TOTAL_COUNT = "Total Count"
684
643
  }
685
- interface TraceSpan {
686
- id: string;
687
- traceId: string;
688
- name: string;
689
- kind: string;
690
- parentSpanId?: string;
691
- latencyMs?: number;
692
- startTimeMs?: string;
693
- endTimeMs?: string;
694
- organisationId: string;
695
- projectId: string;
696
- sessionId?: string;
697
- tenantId?: string;
698
- userId?: string;
699
- environment?: string;
700
- modelName?: string;
701
- promptTokens?: number;
702
- completionTokens?: number;
703
- cachedTokens?: number;
704
- totalTokens?: number;
705
- promptTokensCost?: number;
706
- completionTokensCost?: number;
707
- cachedTokensCost?: number;
708
- totalCost?: number;
709
- hasPii?: boolean;
710
- piiEntities?: any[];
711
- piiActions?: Record<string, any>;
712
- hasViolation?: boolean;
713
- violations?: any[];
714
- violationActions?: Record<string, any>;
715
- status?: string;
716
- attributes?: string;
717
- events?: string;
718
- links?: string;
719
- resources?: string;
720
- metadata?: Record<string, any>;
721
- hasError?: boolean;
722
- createdAt: string;
723
- cursor: string;
644
+ declare enum GroupBy {
645
+ DAY = "day",
646
+ HOUR = "hour",
647
+ MINUTE = "minute"
724
648
  }
725
- interface SpansPage {
726
- spans: TraceSpan[];
649
+ declare enum DimensionField {
650
+ ENVIRONMENT = "environment",
651
+ SERVICE = "service",
652
+ MODEL_NAME = "model_name"
653
+ }
654
+ declare enum Operator {
655
+ EQUALS = "equals",
656
+ NOT_EQUALS = "not_equals",
657
+ CONTAINS = "contains",
658
+ NOT_CONTAINS = "not_contains",
659
+ STARTS_WITH = "starts_with",
660
+ ENDS_WITH = "ends_with",
661
+ GREATER_THAN = "greater_than",
662
+ LESS_THAN = "less_than",
663
+ GREATER_EQUAL_TO = "greater_equal_to",
664
+ LESS_EQUAL_TO = "less_equal_to",
665
+ ANY_OF = "any_of",
666
+ NONE_OF = "none_of"
667
+ }
668
+ declare enum FilterType {
669
+ STRING = "string",
670
+ NUMBER = "number",
671
+ BOOLEAN = "boolean",
672
+ ARRAY_OPTIONS = "arrayOptions",
673
+ OBJECT = "object"
674
+ }
675
+ declare enum FilterField {
676
+ TOTAL_COST = "total_cost",
677
+ SERVICE = "service",
678
+ TENANT_ID = "tenant_id",
679
+ USER_ID = "user_id",
680
+ SESSION_ID = "session_id",
681
+ ENVIRONMENT = "environment",
682
+ LATENCY = "latency",
683
+ MODEL_NAME = "model_name",
684
+ MODELS = "models",
685
+ METADATA = "metadata"
686
+ }
687
+ declare enum SessionFilterField {
688
+ TENANT_ID = "tenant_id"
689
+ }
690
+ declare enum SessionOperator {
691
+ ANY_OF = "any_of"
692
+ }
693
+ declare enum SessionFilterType {
694
+ ARRAY = "arrayOptions"
695
+ }
696
+ declare enum SortField {
697
+ SESSION_ID = "session_id",
698
+ START_TIME = "start_time",
699
+ TOTAL_REQUESTS = "totalRequests",
700
+ TOTAL_COST = "totalCost"
701
+ }
702
+ declare enum SortOrder {
703
+ ASC = "asc",
704
+ DESC = "desc"
705
+ }
706
+ /**
707
+ * Create a metadata filter field
708
+ * @param key The metadata key to filter on
709
+ * @returns The formatted metadata field string
710
+ * @example
711
+ * metadataField("customer_tier") // returns "metadata['customer_tier']"
712
+ */
713
+ declare function metadataField(key: string): string;
714
+ interface Filter {
715
+ field: FilterField | string;
716
+ operator: Operator;
717
+ type: FilterType;
718
+ value: any;
719
+ key?: string;
720
+ }
721
+ interface Metrics {
722
+ measure: Measure;
723
+ aggregation: Aggregation;
724
+ }
725
+ interface Dimension {
726
+ field: DimensionField;
727
+ }
728
+ interface FilterConfig {
729
+ startTime: string;
730
+ endTime: string;
731
+ groupBy: GroupBy;
732
+ filters?: Filter[];
733
+ }
734
+ interface TimeRange {
735
+ startTime: string;
736
+ endTime: string;
737
+ }
738
+ interface TimeSeriesDataPoint {
739
+ date: string;
740
+ value: number;
741
+ }
742
+ interface DimensionValue {
743
+ dimension: string;
744
+ value: number;
745
+ }
746
+ interface TimeSeriesWithDimension {
747
+ date: string;
748
+ values: DimensionValue[];
749
+ }
750
+ interface TimeSeriesResponse {
751
+ timeSeries: TimeSeriesWithDimension[];
752
+ dimensions: string[];
753
+ }
754
+ interface CategoricalDataPoint {
755
+ dimension: string;
756
+ value: number;
757
+ }
758
+ interface NumberResponse {
759
+ value: number;
760
+ }
761
+ type DashboardData = TimeSeriesDataPoint[] | TimeSeriesResponse | CategoricalDataPoint[] | NumberResponse | Record<string, any>;
762
+ interface QueryResponse {
763
+ timeRange: TimeRange;
764
+ data: DashboardData;
765
+ }
766
+ interface QueryDataParams {
767
+ scope: Scope;
768
+ chartType: ChartType;
769
+ metrics: Metrics;
770
+ filter: FilterConfig;
771
+ dimension?: Dimension;
772
+ }
773
+ interface SessionFilter {
774
+ field: SessionFilterField;
775
+ operator: SessionOperator;
776
+ type: SessionFilterType;
777
+ value: string[];
778
+ }
779
+ interface SessionStatsResult {
780
+ data: SessionStatsData[];
727
781
  hasNextPage: boolean;
728
782
  nextCursor?: string;
729
783
  }
730
- interface ListTracesParams {
784
+ interface SessionFilterConfig {
731
785
  startTime: string;
732
786
  endTime: string;
733
- traceId?: string;
734
- sessionId?: string;
735
- userId?: string;
736
- tenantId?: string;
737
- limit?: number;
738
- cursor?: string;
739
- direction?: "up" | "down";
740
- sortField?: string;
741
- sortOrder?: "asc" | "desc";
787
+ filters?: SessionFilter[];
742
788
  }
743
- interface ListSpansParams {
744
- traceId: string;
745
- cursor?: string;
746
- direction?: "up" | "down";
747
- limit?: number;
748
- spanName?: string;
789
+ interface SessionStatsData {
790
+ session_id: string;
791
+ session_start_time: string;
792
+ totalRequests: number;
793
+ totalCost: number;
794
+ session_duration: string;
795
+ cursor: string;
749
796
  }
750
797
 
751
798
  /**
752
- * Public Usage API
753
- * Exposed as Netra.usage
799
+ * Public Dashboard API
800
+ * Exposed as Netra.dashboard
754
801
  */
755
802
 
756
- declare class Usage {
803
+ declare class Dashboard {
757
804
  private config;
758
805
  private client;
759
806
  constructor(config: Config);
760
807
  /**
761
- * Get session usage data
762
- * @param sessionId Session identifier
763
- * @param startTime Start time for the usage data (in ISO 8601 UTC format)
764
- * @param endTime End time for the usage data (in ISO 8601 UTC format)
765
- * @returns Session usage data or null on error
808
+ * Execute a dynamic query for dashboards to retrieve metrics and time-series data
809
+ * @param params Query parameters
810
+ * @returns Query response containing timeRange and data, or null on error
766
811
  */
767
- getSessionUsage(sessionId: string, startTime: string, endTime: string): Promise<SessionUsageData | null>;
812
+ queryData(params: QueryDataParams): Promise<QueryResponse | null>;
813
+ getSessionStats(startTime: string, endTime: string, limit?: number, filters?: SessionFilter[], cursor?: string, sortField?: SortField, sortOrder?: SortOrder): Promise<SessionStatsResult | null>;
814
+ iterSessionStats(startTime: string, endTime: string, filters?: SessionFilter[], sortField?: SortField, sortOrder?: SortOrder): AsyncGenerator<SessionStatsData, void, unknown>;
815
+ getSessionSummary(filter: SessionFilterConfig): Promise<any | null>;
816
+ private isValidScope;
817
+ private isValidChartType;
818
+ private isValidMetrics;
819
+ private isValidFilterConfig;
820
+ private isValidDimension;
821
+ private isSessionFilterConfig;
822
+ }
823
+
824
+ /**
825
+ * Prompts API Models
826
+ */
827
+ interface GetPromptParams {
828
+ name: string;
829
+ label?: string;
830
+ }
831
+ /**
832
+ * Prompt response is intentionally flexible because
833
+ * backend prompt structures may evolve (variables, templates, metadata etc.)
834
+ */
835
+ type PromptResponse = Record<string, any>;
836
+
837
+ declare class Prompts {
838
+ private config;
839
+ private client;
840
+ constructor(config: Config);
768
841
  /**
769
- * Get tenant usage data
770
- * @param tenantId Tenant identifier
771
- * @param startTime Start time for the usage data (in ISO 8601 UTC format)
772
- * @param endTime End time for the usage data (in ISO 8601 UTC format)
773
- * @returns Tenant usage data or null on error
842
+ * Fetch prompt version by name and label.
843
+ *
844
+ * @param params.name - Name of the prompt (required)
845
+ * @param params.label - Label of the prompt version (default: "production")
774
846
  */
775
- getTenantUsage(tenantId: string, startTime: string, endTime: string): Promise<TenantUsageData | null>;
847
+ getPrompt(params: GetPromptParams): Promise<PromptResponse | null>;
848
+ }
849
+
850
+ /**
851
+ * Instrumentation Span Processor
852
+ *
853
+ * OpenTelemetry span processor that:
854
+ * 1. Records the raw instrumentation scope name for each span
855
+ * 2. Truncates attribute values to prevent oversized payloads
856
+ */
857
+
858
+ declare class InstrumentationSpanProcessor implements SpanProcessor {
859
+ private maxAttributeLength;
860
+ constructor(maxAttributeLength?: number);
776
861
  /**
777
- * List all traces
778
- * @param params List traces parameters
779
- * @returns Traces page or null on error
862
+ * Detect the raw instrumentation name from the span's instrumentation scope.
780
863
  */
781
- listTraces(params: ListTracesParams): Promise<TracesPage | null>;
864
+ private detectRawInstrumentationName;
782
865
  /**
783
- * List all spans for a given trace
784
- * @param params List spans parameters
785
- * @returns Spans page or null on error
866
+ * Truncate a value to the maximum allowed length.
867
+ * Handles strings, bytes, and recursively handles lists and objects.
786
868
  */
787
- listSpansByTraceId(params: ListSpansParams): Promise<SpansPage | null>;
869
+ private truncateValue;
788
870
  /**
789
- * Iterate over traces using cursor-based pagination
790
- * @param params List traces parameters
791
- * @returns Async generator yielding TraceSummary items
871
+ * Called when a span starts. Wraps setAttribute to truncate values
872
+ * and records the instrumentation name.
792
873
  */
793
- iterTraces(params: ListTracesParams): AsyncGenerator<TraceSummary, void, unknown>;
874
+ onStart(span: Span, parentContext: Context): void;
794
875
  /**
795
- * Iterate over spans for a given trace using cursor-based pagination
796
- * @param params List spans parameters
797
- * @returns Async generator yielding TraceSpan items
876
+ * Called when a span ends. No-op for this processor.
798
877
  */
799
- iterSpansByTraceId(params: ListSpansParams): AsyncGenerator<TraceSpan, void, unknown>;
800
- private mapToTraceSummary;
801
- private mapToTraceSpan;
878
+ onEnd(span: ReadableSpan): void;
879
+ /**
880
+ * Shuts down the processor.
881
+ */
882
+ shutdown(): Promise<void>;
883
+ /**
884
+ * Forces a flush of any pending spans.
885
+ */
886
+ forceFlush(): Promise<void>;
887
+ }
888
+
889
+ declare function withBlockedSpansLocal<T>(patterns: readonly string[], fn: () => Promise<T>): Promise<T>;
890
+ declare function withBlockedSpansLocal<T>(patterns: readonly string[], fn: () => T): T;
891
+
892
+ /**
893
+ * Scrubbing Span Processor
894
+ *
895
+ * OpenTelemetry span processor that scrubs sensitive data from span attributes.
896
+ * This includes API keys, emails, phone numbers, SSNs, credit cards, passwords,
897
+ * bearer tokens, and other sensitive information.
898
+ */
899
+
900
+ declare class ScrubbingSpanProcessor implements SpanProcessor {
901
+ /**
902
+ * Check if a key is considered sensitive.
903
+ */
904
+ private isSensitiveKey;
905
+ /**
906
+ * Scrub sensitive patterns from a string value.
907
+ */
908
+ private scrubStringValue;
909
+ /**
910
+ * Recursively scrub sensitive data from a dictionary value.
911
+ */
912
+ private scrubDictValue;
913
+ /**
914
+ * Recursively scrub sensitive data from a list value.
915
+ */
916
+ private scrubListValue;
917
+ /**
918
+ * Scrub sensitive data from a key-value pair.
919
+ */
920
+ private scrubKeyValue;
921
+ /**
922
+ * Called when a span starts. No-op for this processor.
923
+ */
924
+ onStart(span: Span, parentContext: Context): void;
925
+ /**
926
+ * Called when a span ends. Scrubs sensitive data from span attributes.
927
+ */
928
+ onEnd(span: ReadableSpan): void;
929
+ /**
930
+ * Shuts down the processor.
931
+ */
932
+ shutdown(): Promise<void>;
933
+ /**
934
+ * Forces a flush of any pending spans.
935
+ */
936
+ forceFlush(): Promise<void>;
937
+ }
938
+
939
+ /**
940
+ * Session Span Processor
941
+ *
942
+ * OpenTelemetry span processor that automatically adds session attributes to spans.
943
+ * This includes session_id, user_id, tenant_id from OpenTelemetry baggage, and entity context
944
+ * (workflow, task, agent names) from SessionManager.
945
+ *
946
+ * Uses OpenTelemetry's baggage API for automatic context propagation across async boundaries.
947
+ */
948
+
949
+ declare class SessionSpanProcessor implements SpanProcessor {
950
+ /**
951
+ * Called when a span starts. Adds session and entity context attributes.
952
+ */
953
+ onStart(span: Span, parentContext: Context): void;
954
+ /**
955
+ * Called when a span ends. No-op for this processor.
956
+ */
957
+ onEnd(_span: ReadableSpan): void;
958
+ /**
959
+ * Shuts down the processor.
960
+ */
961
+ shutdown(): Promise<void>;
962
+ /**
963
+ * Forces a flush of any pending spans.
964
+ */
965
+ forceFlush(): Promise<void>;
966
+ }
967
+
968
+ declare class SpanIOProcessor implements SpanProcessor {
969
+ onStart(span: Span, _parentContext: Context): void;
970
+ onEnd(span: ReadableSpan): void;
971
+ shutdown(): Promise<void>;
972
+ forceFlush(): Promise<void>;
973
+ private _wrapSetAttribute;
974
+ }
975
+
976
+ /**
977
+ * Span Wrapper for custom span tracking
978
+ */
979
+
980
+ declare class SpanWrapper {
981
+ private name;
982
+ private attributes;
983
+ private moduleName;
984
+ private startTime?;
985
+ private endTime?;
986
+ private status;
987
+ private errorMessage?;
988
+ private span?;
989
+ private activeContext?;
990
+ private tracer?;
991
+ private blockedSpanPatterns?;
992
+ constructor(name: string, attributes?: SpanAttributes, moduleName?: string, asType?: SpanType, tracer?: any, blockedSpanPatterns?: string[]);
993
+ start(): this;
994
+ end(): this;
995
+ setAttribute(key: string, value: string | string[] | boolean): this;
996
+ /**
997
+ * Run a function with this span set as the active span in the OTel context.
998
+ * Child spans created inside `fn` will have this span as their parent and will
999
+ * also inherit any blocking baggage set via `blockedSpans`. Works for both
1000
+ * sync and async functions — context.with() passes through the return value as-is.
1001
+ */
1002
+ withActive<T>(fn: () => T): T;
1003
+ setPrompt(prompt: string): this;
1004
+ setNegativePrompt(negativePrompt: string): this;
1005
+ setUsage(usage: UsageModel[]): this;
1006
+ setAction(action: ActionModel[]): this;
1007
+ setModel(model: string): this;
1008
+ setLlmSystem(system: string): this;
1009
+ setError(errorMessage: string): this;
1010
+ setSuccess(): this;
1011
+ addEvent(name: string, attributes?: Record<string, string>): this;
1012
+ getCurrentSpan(): Span | undefined;
1013
+ private decodeBaggagePatterns;
1014
+ }
1015
+
1016
+ /**
1017
+ * Type definitions for Netra SDK
1018
+ */
1019
+
1020
+ declare enum SpanType {
1021
+ SPAN = "SPAN",
1022
+ GENERATION = "GENERATION",
1023
+ TOOL = "TOOL",
1024
+ EMBEDDING = "EMBEDDING",
1025
+ AGENT = "AGENT",
1026
+ HANDOFF = "HANDOFF",
1027
+ GUARDRAIL = "GUARDRAIL"
1028
+ }
1029
+ declare enum ConversationType {
1030
+ INPUT = "input",
1031
+ OUTPUT = "output"
1032
+ }
1033
+ interface UsageModel {
1034
+ model: string;
1035
+ usage_type: string;
1036
+ units_used?: number;
1037
+ cost_in_usd?: number;
1038
+ }
1039
+ interface ActionModel {
1040
+ start_time: string;
1041
+ action: string;
1042
+ action_type: string;
1043
+ success: boolean;
1044
+ affected_records?: Array<{
1045
+ record_id: string;
1046
+ record_type: string;
1047
+ }>;
1048
+ metadata?: Record<string, string>;
1049
+ }
1050
+ type SpanAttributes = Record<string, string | string[] | boolean>;
1051
+ interface SpanOptions {
1052
+ attributes?: SpanAttributes;
1053
+ moduleName?: string;
1054
+ asType?: SpanType;
1055
+ /** Patterns for blocking descendant spans (e.g. ["http.*", "*.resolve"]) */
1056
+ blockedSpans?: string[];
802
1057
  }
803
-
804
- declare function withBlockedSpansLocal<T>(patterns: readonly string[], fn: () => Promise<T> | T): Promise<T>;
805
-
806
- /**
807
- * Session Manager for tracking user sessions and context
808
- *
809
- * Uses AsyncLocalStorage for entity stacks (workflow, task, agent)
810
- * and OpenTelemetry's baggage API for session context (session_id, user_id, tenant_id).
811
- * This provides proper concurrency support for multi-request environments.
812
- */
813
-
814
- declare enum ConversationType {
815
- INPUT = "input",
816
- OUTPUT = "output"
1058
+ interface DecoratorOptions {
1059
+ name?: string;
1060
+ asType?: SpanType;
817
1061
  }
1062
+ type SpanCallback<T> = (span: SpanWrapper) => T;
818
1063
 
819
1064
  /**
820
1065
  * Represents a single item in a simulation run.
@@ -915,206 +1160,27 @@ interface CreateRunResult {
915
1160
  simulationItems: SimulationItem[];
916
1161
  }
917
1162
 
918
- /**
919
- * Type definitions for Netra SDK
920
- */
921
- declare enum SpanType {
922
- SPAN = "SPAN",
923
- GENERATION = "GENERATION",
924
- TOOL = "TOOL",
925
- EMBEDDING = "EMBEDDING",
926
- AGENT = "AGENT"
927
- }
928
- interface UsageModel {
929
- model: string;
930
- usage_type: string;
931
- units_used?: number;
932
- cost_in_usd?: number;
933
- }
934
- interface ActionModel {
935
- start_time: string;
936
- action: string;
937
- action_type: string;
938
- success: boolean;
939
- affected_records?: Array<{
940
- record_id: string;
941
- record_type: string;
942
- }>;
943
- metadata?: Record<string, string>;
944
- }
945
- interface DecoratorOptions {
946
- name?: string;
947
- asType?: SpanType;
948
- }
949
-
950
- /**
951
- * Span Wrapper for custom span tracking
952
- */
953
-
954
- declare class SpanWrapper {
955
- private name;
956
- private attributes;
957
- private moduleName;
958
- private startTime?;
959
- private endTime?;
960
- private status;
961
- private errorMessage?;
962
- private span?;
963
- private activeContext?;
964
- private tracer?;
965
- constructor(name: string, attributes?: Record<string, string>, moduleName?: string, asType?: SpanType, tracer?: any);
966
- start(): this;
967
- end(): this;
968
- setAttribute(key: string, value: string): this;
969
- /**
970
- * Run a function with this span set as the active span in the OTel context.
971
- * Useful for nesting spans.
972
- */
973
- withActive<T>(fn: () => T): T;
974
- /**
975
- * Async version of withActive(). Keeps the context active across async work.
976
- */
977
- withActiveAsync<T>(fn: () => Promise<T>): Promise<T>;
978
- setPrompt(prompt: string): this;
979
- setNegativePrompt(negativePrompt: string): this;
980
- setUsage(usage: UsageModel[]): this;
981
- setAction(action: ActionModel[]): this;
982
- setModel(model: string): this;
983
- setLlmSystem(system: string): this;
984
- setError(errorMessage: string): this;
985
- setSuccess(): this;
986
- addEvent(name: string, attributes?: Record<string, string>): this;
987
- getCurrentSpan(): Span | undefined;
988
- }
989
-
990
1163
  /**
991
1164
  * Decorators for easy instrumentation
992
1165
  */
993
1166
 
994
1167
  type AnyFunction = (...args: any[]) => any;
995
- declare function workflow<T extends AnyFunction>(target: T, options?: DecoratorOptions): T;
996
- declare function workflow<T extends AnyFunction>(options?: DecoratorOptions): (target: T) => T;
997
- declare function agent<T extends AnyFunction>(target: T, options?: DecoratorOptions): T;
998
- declare function agent<T extends AnyFunction>(options?: DecoratorOptions): (target: T) => T;
999
- declare function task<T extends AnyFunction>(target: T, options?: DecoratorOptions): T;
1000
- declare function task<T extends AnyFunction>(options?: DecoratorOptions): (target: T) => T;
1001
- declare function span<T extends AnyFunction>(target: T, options?: DecoratorOptions): T;
1002
- declare function span<T extends AnyFunction>(options?: DecoratorOptions): (target: T) => T;
1003
-
1004
- /**
1005
- * Session Span Processor
1006
- *
1007
- * OpenTelemetry span processor that automatically adds session attributes to spans.
1008
- * This includes session_id, user_id, tenant_id from OpenTelemetry baggage, and entity context
1009
- * (workflow, task, agent names) from SessionManager.
1010
- *
1011
- * Uses OpenTelemetry's baggage API for automatic context propagation across async boundaries.
1012
- */
1013
-
1014
- declare class SessionSpanProcessor implements SpanProcessor {
1015
- /**
1016
- * Called when a span starts. Adds session and entity context attributes.
1017
- */
1018
- onStart(span: Span, parentContext: Context): void;
1019
- /**
1020
- * Called when a span ends. No-op for this processor.
1021
- */
1022
- onEnd(span: ReadableSpan): void;
1023
- /**
1024
- * Shuts down the processor.
1025
- */
1026
- shutdown(): Promise<void>;
1027
- /**
1028
- * Forces a flush of any pending spans.
1029
- */
1030
- forceFlush(): Promise<void>;
1031
- }
1032
-
1033
- /**
1034
- * Instrumentation Span Processor
1035
- *
1036
- * OpenTelemetry span processor that:
1037
- * 1. Records the raw instrumentation scope name for each span
1038
- * 2. Truncates attribute values to prevent oversized payloads
1039
- */
1040
-
1041
- declare class InstrumentationSpanProcessor implements SpanProcessor {
1042
- private maxAttributeLength;
1043
- constructor(maxAttributeLength?: number);
1044
- /**
1045
- * Detect the raw instrumentation name from the span's instrumentation scope.
1046
- */
1047
- private detectRawInstrumentationName;
1048
- /**
1049
- * Truncate a value to the maximum allowed length.
1050
- * Handles strings, bytes, and recursively handles lists and objects.
1051
- */
1052
- private truncateValue;
1053
- /**
1054
- * Called when a span starts. Wraps setAttribute to truncate values
1055
- * and records the instrumentation name.
1056
- */
1057
- onStart(span: Span, parentContext: Context): void;
1058
- /**
1059
- * Called when a span ends. No-op for this processor.
1060
- */
1061
- onEnd(span: ReadableSpan): void;
1062
- /**
1063
- * Shuts down the processor.
1064
- */
1065
- shutdown(): Promise<void>;
1066
- /**
1067
- * Forces a flush of any pending spans.
1068
- */
1069
- forceFlush(): Promise<void>;
1070
- }
1071
-
1072
- /**
1073
- * Scrubbing Span Processor
1074
- *
1075
- * OpenTelemetry span processor that scrubs sensitive data from span attributes.
1076
- * This includes API keys, emails, phone numbers, SSNs, credit cards, passwords,
1077
- * bearer tokens, and other sensitive information.
1078
- */
1079
-
1080
- declare class ScrubbingSpanProcessor implements SpanProcessor {
1081
- /**
1082
- * Check if a key is considered sensitive.
1083
- */
1084
- private isSensitiveKey;
1085
- /**
1086
- * Scrub sensitive patterns from a string value.
1087
- */
1088
- private scrubStringValue;
1089
- /**
1090
- * Recursively scrub sensitive data from a dictionary value.
1091
- */
1092
- private scrubDictValue;
1093
- /**
1094
- * Recursively scrub sensitive data from a list value.
1095
- */
1096
- private scrubListValue;
1097
- /**
1098
- * Scrub sensitive data from a key-value pair.
1099
- */
1100
- private scrubKeyValue;
1101
- /**
1102
- * Called when a span starts. No-op for this processor.
1103
- */
1104
- onStart(span: Span, parentContext: Context): void;
1105
- /**
1106
- * Called when a span ends. Scrubs sensitive data from span attributes.
1107
- */
1108
- onEnd(span: ReadableSpan): void;
1109
- /**
1110
- * Shuts down the processor.
1111
- */
1112
- shutdown(): Promise<void>;
1113
- /**
1114
- * Forces a flush of any pending spans.
1115
- */
1116
- forceFlush(): Promise<void>;
1117
- }
1168
+ type AnyClass = new (...args: any[]) => any;
1169
+ type ClassDecoratorFn = (target: AnyClass) => void;
1170
+ type MethodDecoratorFn = (target: any, key: string | symbol, descriptor: PropertyDescriptor) => void;
1171
+ type UnifiedDecorator = ClassDecoratorFn & MethodDecoratorFn;
1172
+ declare function workflow(target: AnyClass): void;
1173
+ declare function workflow<T extends AnyFunction>(target: T): T;
1174
+ declare function workflow(options?: DecoratorOptions): UnifiedDecorator;
1175
+ declare function agent(target: AnyClass): void;
1176
+ declare function agent<T extends AnyFunction>(target: T): T;
1177
+ declare function agent(options?: DecoratorOptions): UnifiedDecorator;
1178
+ declare function task(target: AnyClass): void;
1179
+ declare function task<T extends AnyFunction>(target: T): T;
1180
+ declare function task(options?: DecoratorOptions): UnifiedDecorator;
1181
+ declare function span(target: AnyClass): void;
1182
+ declare function span<T extends AnyFunction>(target: T): T;
1183
+ declare function span(options?: DecoratorOptions): UnifiedDecorator;
1118
1184
 
1119
1185
  /**
1120
1186
  * Custom MistralAI instrumentor for Netra SDK
@@ -1123,7 +1189,7 @@ declare class ScrubbingSpanProcessor implements SpanProcessor {
1123
1189
  * to ensure we patch the same module instance the application uses.
1124
1190
  */
1125
1191
 
1126
- interface InstrumentorOptions {
1192
+ interface InstrumentorOptions$1 {
1127
1193
  tracerProvider?: TracerProvider;
1128
1194
  }
1129
1195
  /**
@@ -1143,12 +1209,12 @@ declare class NetraMistralAIInstrumentor {
1143
1209
  * Uses dynamic import() to ensure we get the same ES module instance
1144
1210
  * that the application uses.
1145
1211
  */
1146
- instrumentAsync(options?: InstrumentorOptions): Promise<NetraMistralAIInstrumentor>;
1212
+ instrumentAsync(options?: InstrumentorOptions$1): Promise<NetraMistralAIInstrumentor>;
1147
1213
  /**
1148
1214
  * Instrument MistralAI client methods (sync version - for backwards compatibility)
1149
1215
  * Note: This uses a cached Mistral class. Call instrumentAsync() for proper initialization.
1150
1216
  */
1151
- instrument(options?: InstrumentorOptions): NetraMistralAIInstrumentor;
1217
+ instrument(options?: InstrumentorOptions$1): NetraMistralAIInstrumentor;
1152
1218
  /**
1153
1219
  * Uninstrument MistralAI client methods
1154
1220
  */
@@ -1177,21 +1243,135 @@ declare class NetraMistralAIInstrumentor {
1177
1243
  }
1178
1244
  declare const mistralAIInstrumentor: NetraMistralAIInstrumentor;
1179
1245
 
1246
+ interface AgentTrace {
1247
+ traceId: string;
1248
+ name: string;
1249
+ groupId?: string;
1250
+ metadata?: Record<string, unknown>;
1251
+ disabled?: boolean;
1252
+ }
1253
+ interface AgentSpan {
1254
+ spanId: string;
1255
+ traceId: string;
1256
+ parentId?: string | null;
1257
+ startedAt?: string | null;
1258
+ endedAt?: string | null;
1259
+ spanData: SpanData;
1260
+ error?: {
1261
+ message: string;
1262
+ data?: Record<string, unknown>;
1263
+ } | null;
1264
+ }
1265
+ interface SpanData {
1266
+ type: string;
1267
+ name?: string;
1268
+ input?: unknown;
1269
+ output?: unknown;
1270
+ model?: string;
1271
+ model_config?: Record<string, unknown>;
1272
+ usage?: {
1273
+ input_tokens?: number;
1274
+ output_tokens?: number;
1275
+ details?: Record<string, unknown> | null;
1276
+ };
1277
+ to_agent?: string;
1278
+ from_agent?: string;
1279
+ response_id?: string;
1280
+ _input?: unknown;
1281
+ _response?: unknown;
1282
+ triggered?: boolean;
1283
+ mcp_data?: string;
1284
+ handoffs?: string[];
1285
+ tools?: string[];
1286
+ output_type?: string;
1287
+ data?: Record<string, unknown>;
1288
+ server?: string;
1289
+ result?: string[];
1290
+ }
1291
+ interface TracingProcessor {
1292
+ start?(): void;
1293
+ onTraceStart(trace: AgentTrace): Promise<void> | void;
1294
+ onTraceEnd(trace: AgentTrace): Promise<void> | void;
1295
+ onSpanStart(span: AgentSpan): Promise<void> | void;
1296
+ onSpanEnd(span: AgentSpan): Promise<void> | void;
1297
+ forceFlush(): Promise<void> | void;
1298
+ shutdown(timeout?: number): Promise<void> | void;
1299
+ }
1300
+ interface InstrumentorOptions {
1301
+ tracerProvider?: {
1302
+ getTracer(name: string, version?: string): any;
1303
+ };
1304
+ /** Override the `llm.system` attribute value (default: `"openai"`). */
1305
+ systemName?: string;
1306
+ }
1307
+
1308
+ declare class NetraAgentsTracingProcessor implements TracingProcessor {
1309
+ private static readonly MAX_TRACKED_SPANS;
1310
+ private static readonly MAX_TRACKED_TRACES;
1311
+ private _tracer;
1312
+ private _systemName;
1313
+ private _isShutdown;
1314
+ private _rootSpans;
1315
+ private _otelSpans;
1316
+ private _handoffs;
1317
+ private _traceErrors;
1318
+ private _traceSpans;
1319
+ constructor(tracer: Tracer, systemName?: string);
1320
+ private _parseTimestamp;
1321
+ private _evictOldestSpan;
1322
+ private _evictOldestTrace;
1323
+ onTraceStart(agentTrace: AgentTrace): void;
1324
+ onTraceEnd(agentTrace: AgentTrace): void;
1325
+ onSpanStart(agentSpan: AgentSpan): void;
1326
+ onSpanEnd(agentSpan: AgentSpan): void;
1327
+ forceFlush(): void;
1328
+ shutdown(): void;
1329
+ }
1330
+
1331
+ declare class NetraOpenAIAgentsInstrumentor {
1332
+ isInstrumented(): boolean;
1333
+ /**
1334
+ * Register the Netra tracing processor with the OpenAI Agents SDK.
1335
+ *
1336
+ * Returns `this` in all cases (success **and** failure) so the call can be
1337
+ * chained. Check {@link isInstrumented} afterwards to verify the processor
1338
+ * was registered successfully.
1339
+ */
1340
+ instrument(options?: InstrumentorOptions): Promise<NetraOpenAIAgentsInstrumentor>;
1341
+ uninstrument(): void;
1342
+ }
1343
+ declare const openaiAgentsInstrumentor: NetraOpenAIAgentsInstrumentor;
1344
+
1180
1345
  declare class FilteringSpanExporter implements SpanExporter {
1181
1346
  private readonly exporter;
1182
- private exact;
1183
- private prefixes;
1184
- private suffixes;
1185
- private rememberedBlockedParentMap;
1186
- constructor(exporter: SpanExporter, patterns: string[]);
1347
+ private readonly localBlockedMap?;
1348
+ private static readonly MAX_REMEMBERED_ENTRIES;
1349
+ /** Pre-compiled global patterns — compiled once in the constructor. */
1350
+ private readonly compiled;
1351
+ /**
1352
+ * Spans that were blocked in a previous export() call but whose children
1353
+ * may still arrive in a later call (e.g. out-of-order export batches).
1354
+ */
1355
+ private readonly rememberedBlockedParentMap;
1356
+ /** Cache for compiled local pattern sets to avoid per-span recompilation. */
1357
+ private readonly localPatternCache;
1358
+ private static readonly MAX_LOCAL_PATTERN_CACHE;
1359
+ constructor(exporter: SpanExporter, globalPatterns: string[], localBlockedMap?: ReadonlyMap<string, SpanContext | undefined> | undefined);
1187
1360
  export(spans: ReadableSpan[], resultCallback: (result: {
1188
1361
  code: ExportResultCode;
1189
1362
  }) => void): void;
1190
1363
  shutdown(): Promise<void>;
1191
1364
  forceFlush(): Promise<void>;
1192
- private isBlocked;
1193
- private matchesLocalPatterns;
1365
+ private getCompiledLocalPatterns;
1366
+ private evictRememberedIfNeeded;
1367
+ private getLocalPatterns;
1194
1368
  private hasLocalBlockFlag;
1369
+ /**
1370
+ * Walk up the blocked-parent chain for each surviving span and wrap it
1371
+ * with a ReparentedSpan pointing to the nearest non-blocked ancestor.
1372
+ *
1373
+ * A cycle guard (visited set) prevents infinite loops in malformed traces.
1374
+ */
1195
1375
  private reparentBlockedChildren;
1196
1376
  }
1197
1377
 
@@ -1217,102 +1397,32 @@ declare class TrialAwareOTLPExporter implements SpanExporter {
1217
1397
  */
1218
1398
 
1219
1399
  declare class Netra {
1400
+ private static _SDK_NAME;
1220
1401
  private static _initialized;
1221
1402
  private static _config;
1222
1403
  private static _tracer;
1223
- /**
1224
- * Usage API client for usage and traces
1225
- * Available after calling Netra.init()
1226
- */
1404
+ private static _rootSpan;
1405
+ private static _metricsEnabled;
1227
1406
  static usage: Usage;
1228
- /**
1229
- * Evaluation API client for datasets, runs, and test suites
1230
- * Available after calling Netra.init()
1231
- */
1232
1407
  static evaluation: Evaluation;
1233
- /**
1234
- * Dashboard API client for querying metrics and time-series data
1235
- * Available after calling Netra.init()
1236
- */
1237
1408
  static dashboard: Dashboard;
1238
1409
  static simulation: Simulation;
1239
- /**
1240
- * Get the current Netra configuration
1241
- */
1410
+ static prompts: Prompts;
1242
1411
  static getConfig(): Config;
1243
- /**
1244
- * Check if Netra has been initialized
1245
- */
1246
1412
  static isInitialized(): boolean;
1247
- /**
1248
- * Initialize the Netra SDK
1249
- *
1250
- * This method is async and must be awaited to ensure all instrumentations
1251
- * are ready before your application starts using instrumented modules.
1252
- *
1253
- * @example
1254
- * await Netra.init({ appName: 'my-app', instruments: new Set([NetraInstruments.OPENAI]) });
1255
- * // Now all instrumentations are ready
1256
- * const openai = new OpenAI();
1257
- */
1258
1413
  static init(config?: NetraConfig): Promise<void>;
1259
- /**
1260
- * @deprecated Use `Netra.init()` instead. The init method is now async by default.
1261
- *
1262
- * Initialize the Netra SDK and wait for all instrumentations to be ready.
1263
- * This method is kept for backwards compatibility.
1264
- */
1265
- static initAsync(config?: NetraConfig): Promise<void>;
1266
- /**
1267
- * @deprecated Since `Netra.init()` is now async and waits for instrumentations,
1268
- * this method is no longer necessary. It's kept for backwards compatibility.
1269
- *
1270
- * Returns a promise that resolves when all async instrumentations are ready.
1271
- */
1272
- static ready(): Promise<void>;
1273
- /**
1274
- * Optional cleanup to end the root span and uninstrument all.
1275
- * Now async to ensure spans are flushed.
1276
- */
1277
1414
  static shutdown(): Promise<void>;
1415
+ static getTraceId(): string | undefined;
1416
+ static setInput(value: any): void;
1417
+ static setOutput(value: any): void;
1418
+ static setRootInput(value: any): void;
1419
+ static setRootOutput(value: any): void;
1278
1420
  /**
1279
1421
  * Run a function with the root span as the active parent context.
1280
1422
  * All spans created within this function will be children of the root span.
1281
- *
1282
- * @param fn The function to run within the root span context
1283
- * @returns The result of the function
1423
+ * Note: required in JS because OTel JS has no persistent context.attach()
1284
1424
  */
1285
1425
  static runWithRootSpan<T>(fn: () => T): T;
1286
- /**
1287
- * Run an async function with the root span as the active parent context.
1288
- * All spans created within this function will be children of the root span.
1289
- *
1290
- * @param fn The async function to run within the root span context
1291
- * @returns A promise that resolves with the result of the function
1292
- */
1293
- static runWithRootSpanAsync<T>(fn: () => Promise<T>): Promise<T>;
1294
- /**
1295
- * Run a function within an isolated entity context.
1296
- * This ensures that entity stacks (workflow, task, agent, span) are isolated
1297
- * per request in concurrent environments.
1298
- *
1299
- * Note: Session context (session_id, user_id, tenant_id) is automatically
1300
- * isolated via OpenTelemetry's baggage API and AsyncLocalStorage.
1301
- * This method is primarily needed if you're using workflow/task/agent decorators
1302
- * or span wrappers in concurrent environments.
1303
- *
1304
- * @param fn The function to run with isolated entity context
1305
- * @returns The result of the function
1306
- *
1307
- */
1308
- static runWithContext<T>(fn: () => T): T;
1309
- /**
1310
- * Set session_id context attributes for all spans.
1311
- * Uses OpenTelemetry baggage API for automatic context propagation.
1312
- *
1313
- * Context automatically propagates across async boundaries in concurrent environments
1314
- * thanks to AsyncLocalStorage in @opentelemetry/sdk-node.
1315
- */
1316
1426
  static setSessionId(sessionId: string): void;
1317
1427
  /**
1318
1428
  * Set user_id context attributes for all spans.
@@ -1336,11 +1446,11 @@ declare class Netra {
1336
1446
  * Append a conversation entry to the current active span
1337
1447
  */
1338
1448
  static addConversation(conversationType: ConversationType, role: string, content: string | Record<string, any>): void;
1339
- /**
1340
- * Start a new span
1341
- */
1342
- static startSpan(name: string, attributes?: Record<string, string>, moduleName?: string, asType?: SpanType): SpanWrapper;
1449
+ static startSpan(name: string): SpanWrapper;
1450
+ static startSpan(name: string, options: SpanOptions): SpanWrapper;
1451
+ static startActiveSpan<T>(name: string, fn: SpanCallback<T>): T;
1452
+ static startActiveSpan<T>(name: string, options: SpanOptions, fn: SpanCallback<T>): T;
1343
1453
  static withBlockedSpansLocal: typeof withBlockedSpansLocal;
1344
1454
  }
1345
1455
 
1346
- export { type ActionModel, Aggregation, BaseTask, type CategoricalDataPoint, ChartType, Config, type ConversationResponse, type ConversationResult, ConversationType, type CreateDatasetParams, type CreateRunResult, Dashboard, type DashboardData, type Dataset, type DatasetEntry, type DatasetItem, type Dimension, DimensionField, type DimensionValue, EntryStatus, Evaluation, type EvaluationScore, type EvaluatorFunction, type Filter, type FilterConfig, FilterField, FilterType, FilteringSpanExporter, GroupBy, InstrumentationSpanProcessor, type ListSpansParams, type ListTracesParams, Measure, type Metrics, Netra, NetraInstruments, type NumberResponse, Operator, type QueryDataParams, type QueryResponse, type Run, RunEntryContext, RunStatus, Scope, ScrubbingSpanProcessor, SessionSpanProcessor, type SessionUsageData, Simulation, type SimulationItem, type SimulationOptions, type SimulationResult, SpanType, type SpansPage, type TaskFunction, type TaskResult, type TenantUsageData, type TestSuiteResult, type TimeRange, type TimeSeriesDataPoint, type TimeSeriesResponse, type TimeSeriesWithDimension, type TraceSpan, type TraceSummary, type TracesPage, TrialAwareOTLPExporter, Usage, type UsageModel, agent, Netra as default, metadataField, mistralAIInstrumentor, span, task, workflow };
1456
+ export { type ActionModel, Aggregation, BaseTask, type CategoricalDataPoint, ChartType, Config, type ConversationResponse, type ConversationResult, ConversationType, type CreateDatasetParams, type CreateRunResult, DEFAULT_INSTRUMENTS, DEFAULT_INSTRUMENTS_FOR_ROOT, Dashboard, type DashboardData, type Dataset, type DatasetEntry, type DatasetItem, type Dimension, DimensionField, type DimensionValue, EntryStatus, Evaluation, type EvaluationScore, type EvaluatorFunction, type Filter, type FilterConfig, FilterField, FilterType, FilteringSpanExporter, type GetPromptParams, GroupBy, InstrumentationSpanProcessor, type ListSpansParams, type ListTracesParams, Measure, type Metrics, Netra, NetraAgentsTracingProcessor, NetraInstruments, NetraOpenAIAgentsInstrumentor, type NumberResponse, Operator, type PromptResponse, Prompts, type QueryDataParams, type QueryResponse, type Run, RunEntryContext, RunStatus, Scope, ScrubbingSpanProcessor, SessionSpanProcessor, type SessionUsageData, Simulation, type SimulationItem, type SimulationOptions, type SimulationResult, SpanIOProcessor, type SpanOptions, SpanType, type SpansPage, type TaskFunction, type TaskResult, type TenantUsageData, type TestSuiteResult, type TimeRange, type TimeSeriesDataPoint, type TimeSeriesResponse, type TimeSeriesWithDimension, type TraceSpan, type TraceSummary, type TracesPage, TrialAwareOTLPExporter, Usage, type UsageModel, agent, Netra as default, metadataField, mistralAIInstrumentor, openaiAgentsInstrumentor, span, task, workflow };