netra-sdk 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -18,6 +18,26 @@ interface NetraConfig {
18
18
  blockedSpans?: string[];
19
19
  instruments?: Set<NetraInstruments>;
20
20
  blockInstruments?: Set<NetraInstruments>;
21
+ /**
22
+ * Set of instruments allowed to produce root-level spans. Independent of
23
+ * `instruments`. Defaults to `DEFAULT_INSTRUMENTS_FOR_ROOT` when omitted.
24
+ *
25
+ * When a root span comes from an instrumentation outside this set, only that
26
+ * span is dropped — its children are reparented onto its parent (a true
27
+ * root's children become the new roots). The peel then repeats: if a promoted
28
+ * child is itself from a non-root instrumentation it is dropped too,
29
+ * recursively, until a surviving span is reached (an allowed instrument, a
30
+ * Netra decorator / manual span, or any non-instrumentation span). This keeps
31
+ * LLM/vector spans that originate under an unwanted server root (e.g.
32
+ * Express/HTTP) without emitting the server span itself. A span whose parent
33
+ * link is remote (cross-process) is kept as a root so an upstream distributed
34
+ * trace is not severed.
35
+ *
36
+ * Note: when `enableRootSpan` is true, Netra attaches its own root span and
37
+ * every auto-instrumentation span becomes its child, so no reparenting
38
+ * occurs. Pass a set containing `NetraInstruments.ALL` to allow all
39
+ * instrumentations to produce root spans (legacy behaviour).
40
+ */
21
41
  rootInstruments?: Set<NetraInstruments>;
22
42
  }
23
43
  declare enum NetraInstruments {
@@ -60,11 +80,15 @@ declare const DEFAULT_INSTRUMENTS: Set<NetraInstruments>;
60
80
  declare class Config {
61
81
  static readonly SDK_NAME = "netra";
62
82
  static readonly LIBRARY_NAME = "netra";
63
- static readonly LIBRARY_VERSION = "1.5.0";
83
+ static readonly LIBRARY_VERSION = "1.6.0";
64
84
  static readonly TRIAL_BLOCK_DURATION_SECONDS = 900;
65
- static readonly ATTRIBUTE_MAX_LEN: number;
66
- static readonly CONVERSATION_MAX_LEN: number;
67
- static readonly SPAN_ATTRIBUTE_MAX_SIZE: number;
85
+ private static _spanAttributeMaxSize;
86
+ /**
87
+ * Lazily reads NETRA_SPAN_ATTRIBUTE_MAX_SIZE from process.env on first
88
+ * access so that env vars set before Netra.init() (via dotenv, shell
89
+ * export, Docker, etc.) are always respected regardless of import order.
90
+ */
91
+ static get SPAN_ATTRIBUTE_MAX_SIZE(): number;
68
92
  appName: string;
69
93
  otlpEndpoint?: string;
70
94
  apiKey?: string;
@@ -851,109 +875,76 @@ declare class Prompts {
851
875
  }
852
876
 
853
877
  /**
854
- * Attribute Size Limit Span Processor
878
+ * Instrumentation Span Processor
855
879
  *
856
- * Enforces a hard max length on every span attribute value via setAttribute
857
- * wrapping in onStart. Prevents "entity too large" errors during export.
880
+ * OpenTelemetry span processor that records the raw instrumentation scope
881
+ * name for each span. This enables downstream processors and the dashboard
882
+ * to identify which provider/framework produced a given span.
858
883
  */
859
884
 
860
- declare class AttributeSizeLimitProcessor implements SpanProcessor {
861
- private maxAttributeSize;
862
- constructor(maxAttributeSize?: number);
885
+ declare class InstrumentationSpanProcessor implements SpanProcessor {
886
+ private detectRawInstrumentationName;
863
887
  onStart(span: Span, _parentContext: Context): void;
864
888
  onEnd(_span: ReadableSpan): void;
865
889
  shutdown(): Promise<void>;
866
890
  forceFlush(): Promise<void>;
867
- private _wrapSetAttribute;
868
891
  }
869
892
 
893
+ declare function withBlockedSpansLocal<T>(patterns: readonly string[], fn: () => Promise<T>): Promise<T>;
894
+ declare function withBlockedSpansLocal<T>(patterns: readonly string[], fn: () => T): T;
895
+
870
896
  /**
871
- * Instrumentation Span Processor
897
+ * Scrubbing Span Processor
898
+ *
899
+ * OpenTelemetry span processor that scrubs sensitive data from span attributes
900
+ * at write time via setAttribute wrapping. This includes API keys, emails,
901
+ * phone numbers, SSNs, credit cards, passwords, bearer tokens, and other
902
+ * sensitive information.
872
903
  *
873
- * OpenTelemetry span processor that:
874
- * 1. Records the raw instrumentation scope name for each span
875
- * 2. Truncates attribute values to prevent oversized payloads
904
+ * Handles both pre-serialized string values (the normal path when
905
+ * SerializationSpanProcessor is active) and raw objects/arrays (defensive
906
+ * fallback for custom pipelines that skip serialization).
907
+ *
908
+ * Wraps in onStart to avoid unreliable _attributes mutation in onEnd.
909
+ * MUST be registered BEFORE SerializationSpanProcessor so it forms the
910
+ * innermost layer (closest to OTel storage). Because serialization wraps
911
+ * outside this layer, values are serialized to strings first, then this
912
+ * processor scrubs sensitive patterns from the resulting string values.
876
913
  */
877
914
 
878
- declare class InstrumentationSpanProcessor implements SpanProcessor {
879
- private maxAttributeLength;
880
- constructor(maxAttributeLength?: number);
881
- /**
882
- * Detect the raw instrumentation name from the span's instrumentation scope.
883
- */
884
- private detectRawInstrumentationName;
885
- /**
886
- * Truncate a value to the maximum allowed length.
887
- * Handles strings, bytes, and recursively handles lists and objects.
888
- */
889
- private truncateValue;
890
- /**
891
- * Called when a span starts. Wraps setAttribute to truncate values
892
- * and records the instrumentation name.
893
- */
894
- onStart(span: Span, parentContext: Context): void;
895
- /**
896
- * Called when a span ends. No-op for this processor.
897
- */
898
- onEnd(span: ReadableSpan): void;
899
- /**
900
- * Shuts down the processor.
901
- */
915
+ declare class ScrubbingSpanProcessor implements SpanProcessor {
916
+ onStart(span: Span, _parentContext: Context): void;
917
+ onEnd(_span: ReadableSpan): void;
902
918
  shutdown(): Promise<void>;
903
- /**
904
- * Forces a flush of any pending spans.
905
- */
906
919
  forceFlush(): Promise<void>;
920
+ private wrapSetAttribute;
907
921
  }
908
922
 
909
- declare function withBlockedSpansLocal<T>(patterns: readonly string[], fn: () => Promise<T>): Promise<T>;
910
- declare function withBlockedSpansLocal<T>(patterns: readonly string[], fn: () => T): T;
911
-
912
923
  /**
913
- * Scrubbing Span Processor
924
+ * Serialization Span Processor
925
+ *
926
+ * Single enforcement point for attribute serialization and truncation.
927
+ * Wraps span.setAttribute in onStart so every value is serialized and
928
+ * truncated at write time. Uses jsonrepair-based truncation for JSON
929
+ * values and `...[TRUNCATED]` suffix for plain strings, aligned with
930
+ * backend behavior.
914
931
  *
915
- * OpenTelemetry span processor that scrubs sensitive data from span attributes.
916
- * This includes API keys, emails, phone numbers, SSNs, credit cards, passwords,
917
- * bearer tokens, and other sensitive information.
932
+ * MUST be registered AFTER ScrubbingSpanProcessor so it wraps outside
933
+ * the scrubbing layer. In the resulting call chain, serialization runs
934
+ * before scrubbing — converting objects to JSON strings so the
935
+ * regex-based scrubber can detect sensitive patterns in string form.
936
+ * All values, including those assembled by SpanIOProcessor, pass
937
+ * through serialization → scrubbing before reaching OTel storage.
918
938
  */
919
939
 
920
- declare class ScrubbingSpanProcessor implements SpanProcessor {
921
- /**
922
- * Check if a key is considered sensitive.
923
- */
924
- private isSensitiveKey;
925
- /**
926
- * Scrub sensitive patterns from a string value.
927
- */
928
- private scrubStringValue;
929
- /**
930
- * Recursively scrub sensitive data from a dictionary value.
931
- */
932
- private scrubDictValue;
933
- /**
934
- * Recursively scrub sensitive data from a list value.
935
- */
936
- private scrubListValue;
937
- /**
938
- * Scrub sensitive data from a key-value pair.
939
- */
940
- private scrubKeyValue;
941
- /**
942
- * Called when a span starts. No-op for this processor.
943
- */
944
- onStart(span: Span, parentContext: Context): void;
945
- /**
946
- * Called when a span ends. Scrubs sensitive data from span attributes.
947
- */
948
- onEnd(span: ReadableSpan): void;
949
- /**
950
- * Shuts down the processor.
951
- */
940
+ declare class SerializationSpanProcessor implements SpanProcessor {
941
+ private readonly maxAttributeSize;
942
+ constructor(maxAttributeSize?: number);
943
+ onStart(span: Span, _parentContext: Context): void;
944
+ onEnd(_span: ReadableSpan): void;
952
945
  shutdown(): Promise<void>;
953
- /**
954
- * Forces a flush of any pending spans.
955
- */
956
946
  forceFlush(): Promise<void>;
947
+ private wrapSetAttribute;
957
948
  }
958
949
 
959
950
  /**
@@ -1236,6 +1227,30 @@ declare function span(target: AnyClass): void;
1236
1227
  declare function span<T extends AnyFunction>(target: T): T;
1237
1228
  declare function span(options?: DecoratorOptions): UnifiedDecorator;
1238
1229
 
1230
+ interface SafeStringifyOptions {
1231
+ maxLength?: number;
1232
+ }
1233
+ /**
1234
+ * Circular-reference-safe JSON serialization.
1235
+ *
1236
+ * Handles circular references, functions, symbols, bigints, and
1237
+ * large class instances gracefully. Never throws.
1238
+ *
1239
+ * When called without options, performs pure serialization with no truncation.
1240
+ * Pass `{ maxLength }` to enable hard truncation of the final result.
1241
+ */
1242
+ declare function safeStringify(value: unknown, options?: SafeStringifyOptions): string;
1243
+
1244
+ interface TruncatingSerializerConfig {
1245
+ maxAttributeSize: number;
1246
+ }
1247
+ type SerializedAttributeValue = string | number | boolean | Array<null | undefined | string> | Array<null | undefined | number> | Array<null | undefined | boolean>;
1248
+ declare class TruncatingSerializer {
1249
+ private readonly maxAttributeSize;
1250
+ constructor(config?: Partial<TruncatingSerializerConfig>);
1251
+ serializeAttribute(value: unknown, budget?: number): SerializedAttributeValue;
1252
+ }
1253
+
1239
1254
  /**
1240
1255
  * Shared utility functions for instrumentation.
1241
1256
  * Handles setting OTel span attributes for LLM request/response tracing.
@@ -1437,6 +1452,20 @@ declare class NetraOpenAIAgentsInstrumentor {
1437
1452
  }
1438
1453
  declare const openaiAgentsInstrumentor: NetraOpenAIAgentsInstrumentor;
1439
1454
 
1455
+ /**
1456
+ * SpanExporter wrapper that drops spans by name and by root-instrument policy.
1457
+ *
1458
+ * A span is dropped when any of the following holds:
1459
+ * - its trace id was blocked while a trial/quota block was active;
1460
+ * - its name matches a globally configured block pattern;
1461
+ * - its name matches a per-span local block pattern set by
1462
+ * `LocalFilteringSpanProcessor`;
1463
+ * - it is a root-connected span from an instrumentation not allowed to emit
1464
+ * root spans (resolved by `findRootSpansBlocked`).
1465
+ *
1466
+ * Children of a dropped span are reparented onto the dropped span's parent so
1467
+ * subtrees are never silently discarded.
1468
+ */
1440
1469
  declare class FilteringSpanExporter implements SpanExporter {
1441
1470
  private readonly exporter;
1442
1471
  private readonly localBlockedMap?;
@@ -1452,22 +1481,75 @@ declare class FilteringSpanExporter implements SpanExporter {
1452
1481
  private readonly localPatternCache;
1453
1482
  private static readonly MAX_LOCAL_PATTERN_CACHE;
1454
1483
  constructor(exporter: SpanExporter, globalPatterns: string[], localBlockedMap?: ReadonlyMap<string, SpanContext | undefined> | undefined);
1484
+ /**
1485
+ * Filter `spans`, reparent survivors, and forward them to the wrapped exporter.
1486
+ *
1487
+ * While a trial/quota block is active the whole batch is dropped and its trace
1488
+ * ids are remembered so their later spans are dropped too. Otherwise the batch
1489
+ * is classified into name/local drops and root-instrument drops, the survivors
1490
+ * are reparented past any dropped ancestor, and only they are forwarded.
1491
+ */
1455
1492
  export(spans: ReadableSpan[], resultCallback: (result: {
1456
1493
  code: ExportResultCode;
1457
1494
  }) => void): void;
1458
1495
  shutdown(): Promise<void>;
1459
1496
  forceFlush(): Promise<void>;
1497
+ /**
1498
+ * Remember the trace ids seen during a block so their later spans are dropped
1499
+ * too, even after the block expires.
1500
+ */
1501
+ private recordBlockedTraceIds;
1502
+ /**
1503
+ * Find the spans dropped unconditionally by a global or local name rule.
1504
+ *
1505
+ * Trace-blocked spans are skipped entirely (dropped without reparenting). Each
1506
+ * dropped span is also recorded in the cross-batch remembered map so a child
1507
+ * arriving in a later batch can still be reparented past it. The returned map
1508
+ * feeds both the root-connected candidate walk — as transparent dropped
1509
+ * ancestors — and the reparent map.
1510
+ *
1511
+ * @returns A `{droppedSpanId -> normalizedParent}` map for the name/locally
1512
+ * blocked spans in this batch.
1513
+ */
1514
+ private findSpansBlockedByName;
1515
+ /**
1516
+ * Check whether `span` is blocked by its per-span local rules — either its
1517
+ * name matches a local pattern or it carries the local-block flag.
1518
+ */
1519
+ private isLocallyBlocked;
1520
+ /**
1521
+ * Return the spans that survive filtering: not trace-blocked and not in
1522
+ * `allBlockedSpanIds` (name/local drops or the root-instrument policy).
1523
+ */
1524
+ private collectSurvivors;
1525
+ /**
1526
+ * Merge the cross-batch remembered map with this batch's dropped-parent maps.
1527
+ *
1528
+ * Ordering matters — later wins on conflict: the remembered map and the
1529
+ * injected local-block snapshot are the base, overlaid by root-blocked
1530
+ * parents, then this batch's name/local blocks, so in-batch drops win.
1531
+ *
1532
+ * @returns The merged `{droppedSpanId -> parent}` map used for reparenting.
1533
+ */
1534
+ private buildReparentMap;
1460
1535
  private getCompiledLocalPatterns;
1461
1536
  private evictRememberedIfNeeded;
1462
- private getLocalPatterns;
1537
+ /**
1538
+ * Read the per-span local-block patterns set by `LocalFilteringSpanProcessor`,
1539
+ * or an empty list when none are set.
1540
+ */
1541
+ private readLocalBlockPatterns;
1542
+ /** Check whether the processor explicitly flagged `span` as locally blocked. */
1463
1543
  private hasLocalBlockFlag;
1464
1544
  /**
1465
- * Walk up the blocked-parent chain for each surviving span and wrap it
1466
- * with a ReparentedSpan pointing to the nearest non-blocked ancestor.
1545
+ * Reparent each span past any dropped ancestor onto its first surviving one.
1467
1546
  *
1468
- * A cycle guard (visited set) prevents infinite loops in malformed traces.
1547
+ * Walks the chain of dropped parents (following `blockedMap`) until a surviving
1548
+ * parent — or `undefined` (promote to root) — is reached, then wraps the span
1549
+ * in a `ReparentedSpan` pointing there. A cycle guard (visited set) prevents
1550
+ * infinite loops in malformed traces.
1469
1551
  */
1470
- private reparentBlockedChildren;
1552
+ private reparentSpans;
1471
1553
  }
1472
1554
 
1473
1555
  interface ExporterConfig {
@@ -1624,4 +1706,4 @@ declare class Netra {
1624
1706
  static withBlockedSpansLocal: typeof withBlockedSpansLocal;
1625
1707
  }
1626
1708
 
1627
- export { type ActionModel, Aggregation, AttributeSizeLimitProcessor, 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 ProcessedFile, 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, netraExpressMiddleware, openaiAgentsInstrumentor, runWithExtractedContext, span, task, workflow };
1709
+ 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 ProcessedFile, type PromptResponse, Prompts, type QueryDataParams, type QueryResponse, type Run, RunEntryContext, RunStatus, type SafeStringifyOptions, Scope, ScrubbingSpanProcessor, SerializationSpanProcessor, 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, TruncatingSerializer, Usage, type UsageModel, agent, Netra as default, metadataField, mistralAIInstrumentor, netraExpressMiddleware, openaiAgentsInstrumentor, runWithExtractedContext, safeStringify, span, task, workflow };