@brizz/sdk 0.1.52 → 0.1.54

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.
Files changed (39) hide show
  1. package/README.md +38 -0
  2. package/dist/chunk-DBN4NKIG.js +107 -0
  3. package/dist/{chunk-KFETJN5M.cjs → chunk-FQBVTIBR.cjs} +7 -0
  4. package/dist/{chunk-2T7OEV33.cjs → chunk-KGNFUQ6Z.cjs} +1 -1
  5. package/dist/{chunk-W7VSQ4KQ.js → chunk-MLMF2O5P.js} +1 -1
  6. package/dist/chunk-VZJNEST4.cjs +107 -0
  7. package/dist/{chunk-TEY6FAVZ.js → chunk-YGLDHCWC.js} +7 -0
  8. package/dist/google-genai-44O4QORJ.cjs +11 -0
  9. package/dist/{google-genai-T7I4FFIP.js → google-genai-PERR37LR.js} +2 -1
  10. package/dist/google-genai.cjs +3 -2
  11. package/dist/google-genai.js +2 -1
  12. package/dist/index.cjs +510 -107
  13. package/dist/index.js +486 -83
  14. package/dist/{mcp-MVZSP5NE.cjs → mcp-4M4XL46N.cjs} +39 -16
  15. package/dist/{mcp-TOZFTC5Y.js → mcp-KU7MFTOB.js} +29 -6
  16. package/dist/types/cjs/index.d.ts +1 -1
  17. package/dist/types/cjs/internal/config.d.ts +1 -0
  18. package/dist/types/cjs/internal/instrumentation/openai.d.ts +5 -0
  19. package/dist/types/cjs/internal/instrumentation/registry.d.ts +1 -0
  20. package/dist/types/cjs/internal/instrumentation/typesafe.d.ts +34 -0
  21. package/dist/types/cjs/internal/log/logging.d.ts +1 -0
  22. package/dist/types/cjs/internal/metric/metrics.d.ts +1 -0
  23. package/dist/types/cjs/internal/sdk.d.ts +3 -0
  24. package/dist/types/cjs/internal/trace/index.d.ts +1 -0
  25. package/dist/types/cjs/internal/trace/provider.d.ts +15 -0
  26. package/dist/types/cjs/internal/trace/tracing.d.ts +1 -0
  27. package/dist/types/esm/index.d.ts +1 -1
  28. package/dist/types/esm/internal/config.d.ts +1 -0
  29. package/dist/types/esm/internal/instrumentation/openai.d.ts +5 -0
  30. package/dist/types/esm/internal/instrumentation/registry.d.ts +1 -0
  31. package/dist/types/esm/internal/instrumentation/typesafe.d.ts +34 -0
  32. package/dist/types/esm/internal/log/logging.d.ts +1 -0
  33. package/dist/types/esm/internal/metric/metrics.d.ts +1 -0
  34. package/dist/types/esm/internal/sdk.d.ts +3 -0
  35. package/dist/types/esm/internal/trace/index.d.ts +1 -0
  36. package/dist/types/esm/internal/trace/provider.d.ts +15 -0
  37. package/dist/types/esm/internal/trace/tracing.d.ts +1 -0
  38. package/package.json +22 -15
  39. package/dist/google-genai-LMEZ62FB.cjs +0 -10
package/dist/index.js CHANGED
@@ -5,7 +5,16 @@ import {
5
5
  import {
6
6
  configure,
7
7
  getSDKVersion
8
- } from "./chunk-W7VSQ4KQ.js";
8
+ } from "./chunk-MLMF2O5P.js";
9
+ import {
10
+ bindToBrizz,
11
+ brizzTracerProvider,
12
+ ensureContextManager,
13
+ extractTraceContext,
14
+ getTracerProvider,
15
+ injectTraceContext,
16
+ setPrivateTracerProvider
17
+ } from "./chunk-DBN4NKIG.js";
9
18
  import {
10
19
  DEFAULT_LOG_LEVEL,
11
20
  LogLevel,
@@ -83,7 +92,6 @@ import {
83
92
  } from "./chunk-3RG5ZIWI.js";
84
93
 
85
94
  // src/internal/instrumentation/auto-init.ts
86
- import { OpenAIInstrumentation } from "@arizeai/openinference-instrumentation-openai";
87
95
  import { registerInstrumentations } from "@opentelemetry/instrumentation";
88
96
  import { AnthropicInstrumentation } from "@traceloop/instrumentation-anthropic";
89
97
  import { BedrockInstrumentation } from "@traceloop/instrumentation-bedrock";
@@ -174,6 +182,7 @@ var parentRecorded = /* @__PURE__ */ new WeakSet();
174
182
  var LangGraphInstrumentation = class extends InstrumentationBase {
175
183
  constructor(config = {}) {
176
184
  super(INSTRUMENTATION_NAME, INSTRUMENTATION_VERSION, config);
185
+ this.setTracerProvider(brizzTracerProvider);
177
186
  }
178
187
  init() {
179
188
  return [
@@ -426,6 +435,226 @@ function attachRunToIteration(stream, run) {
426
435
  return iterable;
427
436
  }
428
437
 
438
+ // src/internal/instrumentation/openai.ts
439
+ import { OpenAIInstrumentation } from "@arizeai/openinference-instrumentation-openai";
440
+ var BrizzOpenAIInstrumentation = class extends OpenAIInstrumentation {
441
+ get tracer() {
442
+ return brizzTracerProvider.getTracer(this.instrumentationName, this.instrumentationVersion);
443
+ }
444
+ };
445
+
446
+ // src/internal/instrumentation/typesafe.ts
447
+ import { createRequire as createRequire2 } from "module";
448
+ import { SpanKind, SpanStatusCode as SpanStatusCode2, context as context2, trace as trace2 } from "@opentelemetry/api";
449
+ import {
450
+ InstrumentationBase as InstrumentationBase2,
451
+ InstrumentationNodeModuleDefinition as InstrumentationNodeModuleDefinition2
452
+ } from "@opentelemetry/instrumentation";
453
+ var INSTRUMENTATION_NAME2 = "@brizz/sdk/typesafe";
454
+ var MODULE_NAME2 = "@typesafe-ai/sdk";
455
+ var SUPPORTED_VERSIONS2 = [">=0.5.7 <1"];
456
+ var SPAN_NAME = "typesafe.system_one";
457
+ var PROVIDER_NAME = "typesafe";
458
+ var OPERATION_NAME = "classify";
459
+ var ATTR_OPERATION_NAME = "gen_ai.operation.name";
460
+ var ATTR_PROVIDER_NAME = "gen_ai.provider.name";
461
+ var ATTR_REQUEST_MODEL = "gen_ai.request.model";
462
+ var ATTR_RESPONSE_MODEL = "gen_ai.response.model";
463
+ var ATTR_INPUT_TOKENS = "gen_ai.usage.input_tokens";
464
+ var ATTR_OUTPUT_TOKENS = "gen_ai.usage.output_tokens";
465
+ var ATTR_INPUT_MESSAGES = "gen_ai.input.messages";
466
+ var ATTR_QUESTIONS = "typesafe.questions";
467
+ var ATTR_ANSWERS = "typesafe.answers";
468
+ var PATCHED_FLAG2 = /* @__PURE__ */ Symbol.for("brizz.typesafe.patched");
469
+ var TypeSafeInstrumentation = class extends InstrumentationBase2 {
470
+ constructor(config = {}) {
471
+ super(INSTRUMENTATION_NAME2, getSDKVersion(), config);
472
+ this.setTracerProvider(brizzTracerProvider);
473
+ }
474
+ init() {
475
+ return [
476
+ new InstrumentationNodeModuleDefinition2(
477
+ MODULE_NAME2,
478
+ SUPPORTED_VERSIONS2,
479
+ (moduleExports) => {
480
+ this.manuallyInstrument(moduleExports);
481
+ return moduleExports;
482
+ },
483
+ (moduleExports) => moduleExports
484
+ )
485
+ ];
486
+ }
487
+ /**
488
+ * Patch a `@typesafe-ai/sdk` module the caller already imported. The
489
+ * module-load hook above only fires for CommonJS requires, so an ESM or
490
+ * bundled consumer reaches the instrumentation through here — from
491
+ * `patchInstalledTypeSafe`, or `instrumentModules: { typesafe }`.
492
+ */
493
+ manuallyInstrument(moduleExports) {
494
+ const client = moduleExports?.TypeSafeClient;
495
+ if (typeof client !== "function" || !client.prototype) {
496
+ logger.debug("Brizz TypeSafe: module does not expose TypeSafeClient \u2014 skipping patch");
497
+ return;
498
+ }
499
+ if (patchSystemOne(client.prototype, () => this.tracer)) {
500
+ logger.debug("Brizz TypeSafe: patched TypeSafeClient.systemOne");
501
+ }
502
+ }
503
+ };
504
+ function patchInstalledTypeSafe() {
505
+ let requireFromSdk;
506
+ let version;
507
+ try {
508
+ requireFromSdk = createRequire2(import.meta.url);
509
+ version = requireFromSdk(`${MODULE_NAME2}/package.json`).version;
510
+ } catch (error) {
511
+ logger.debug(`TypeSafe not resolved, not patched: ${String(error)}`);
512
+ return;
513
+ }
514
+ if (!isSupportedVersion2(version)) {
515
+ logger.debug(`TypeSafe ${version} is outside ${SUPPORTED_VERSIONS2.join(" ")}, not patched`);
516
+ return;
517
+ }
518
+ let instrumentation;
519
+ try {
520
+ instrumentation = new TypeSafeInstrumentation({ enabled: false });
521
+ } catch (error) {
522
+ logger.debug(`TypeSafe instrumentation not constructed: ${String(error)}`);
523
+ return;
524
+ }
525
+ try {
526
+ const loaded = requireFromSdk.cache[requireFromSdk.resolve(MODULE_NAME2)];
527
+ if (loaded) {
528
+ instrumentation.manuallyInstrument(loaded.exports);
529
+ }
530
+ } catch (error) {
531
+ logger.debug(`TypeSafe CJS build not patched: ${String(error)}`);
532
+ }
533
+ void (async () => {
534
+ try {
535
+ instrumentation.manuallyInstrument(await import("@typesafe-ai/sdk"));
536
+ } catch (error) {
537
+ logger.debug(`TypeSafe not patched: ${String(error)}`);
538
+ }
539
+ })();
540
+ }
541
+ function isSupportedVersion2(version) {
542
+ const [major, minor, patch] = version.split(".").map((part) => Number.parseInt(part, 10));
543
+ if ([major, minor, patch].some((part) => part === void 0 || Number.isNaN(part))) {
544
+ return false;
545
+ }
546
+ return major === 0 && (minor > 5 || minor === 5 && patch >= 7);
547
+ }
548
+ function patchSystemOne(proto, getTracer) {
549
+ const target = proto;
550
+ const original = proto.systemOne;
551
+ if (target[PATCHED_FLAG2] || typeof original !== "function") {
552
+ return false;
553
+ }
554
+ proto.systemOne = function brizzSystemOne(request, ...rest) {
555
+ const span = startSpan(getTracer, request);
556
+ if (!span) {
557
+ return original.call(this, request, ...rest);
558
+ }
559
+ let pending;
560
+ try {
561
+ pending = context2.with(
562
+ trace2.setSpan(context2.active(), span),
563
+ () => original.call(this, request, ...rest)
564
+ );
565
+ } catch (error) {
566
+ endSpan(span, error);
567
+ throw error;
568
+ }
569
+ return observe(pending, span);
570
+ };
571
+ target[PATCHED_FLAG2] = true;
572
+ return true;
573
+ }
574
+ function observe(pending, span) {
575
+ const onError = (error) => endSpan(span, error);
576
+ try {
577
+ if (typeof pending?.asResponse === "function") {
578
+ pending.asResponse().then((response) => {
579
+ if (typeof response?.clone !== "function") {
580
+ endSpan(span);
581
+ return;
582
+ }
583
+ response.clone().json().then((body) => {
584
+ recordResult(span, body);
585
+ endSpan(span);
586
+ }, onError);
587
+ }, onError);
588
+ return pending;
589
+ }
590
+ if (typeof pending?.then === "function") {
591
+ pending.then((result) => {
592
+ recordResult(span, result);
593
+ endSpan(span);
594
+ }, onError);
595
+ return pending;
596
+ }
597
+ } catch (error) {
598
+ logger.debug(`Brizz TypeSafe: could not observe the call: ${String(error)}`);
599
+ }
600
+ endSpan(span);
601
+ return pending;
602
+ }
603
+ function startSpan(getTracer, request) {
604
+ try {
605
+ const model = typeof request?.model === "string" && request.model !== "" ? request.model : void 0;
606
+ const attributes = {
607
+ [ATTR_OPERATION_NAME]: OPERATION_NAME,
608
+ [ATTR_PROVIDER_NAME]: PROVIDER_NAME,
609
+ [ATTR_INPUT_MESSAGES]: JSON.stringify([
610
+ { role: "user", parts: [{ type: "text", content: text(request?.state) }] }
611
+ ])
612
+ };
613
+ if (model) {
614
+ attributes[ATTR_REQUEST_MODEL] = model;
615
+ }
616
+ if (request?.questions !== void 0) {
617
+ attributes[ATTR_QUESTIONS] = JSON.stringify(request.questions);
618
+ }
619
+ return getTracer().startSpan(SPAN_NAME, { kind: SpanKind.CLIENT, attributes });
620
+ } catch (error) {
621
+ logger.debug(`Brizz TypeSafe: could not start span: ${String(error)}`);
622
+ return void 0;
623
+ }
624
+ }
625
+ function recordResult(span, result) {
626
+ try {
627
+ const { model, usage, answers } = result ?? {};
628
+ if (typeof model === "string" && model) {
629
+ span.setAttribute(ATTR_RESPONSE_MODEL, model);
630
+ }
631
+ if (typeof usage?.input_tokens === "number") {
632
+ span.setAttribute(ATTR_INPUT_TOKENS, usage.input_tokens);
633
+ }
634
+ if (typeof usage?.output_tokens === "number") {
635
+ span.setAttribute(ATTR_OUTPUT_TOKENS, usage.output_tokens);
636
+ }
637
+ if (answers !== void 0) {
638
+ span.setAttribute(ATTR_ANSWERS, JSON.stringify(answers));
639
+ }
640
+ } catch (error) {
641
+ logger.debug(`Brizz TypeSafe: could not record the answers: ${String(error)}`);
642
+ }
643
+ }
644
+ function endSpan(span, error) {
645
+ if (!span.isRecording()) {
646
+ return;
647
+ }
648
+ if (error !== void 0) {
649
+ span.recordException(error instanceof Error ? error : new Error(String(error)));
650
+ span.setStatus({ code: SpanStatusCode2.ERROR, message: String(error) });
651
+ }
652
+ span.end();
653
+ }
654
+ function text(value) {
655
+ return typeof value === "string" ? value : JSON.stringify(value) ?? "";
656
+ }
657
+
429
658
  // src/internal/instrumentation/auto-init.ts
430
659
  var exceptionLogger = (error) => {
431
660
  logger.error(`Exception in instrumentation: ${String(error)}`);
@@ -433,7 +662,7 @@ var exceptionLogger = (error) => {
433
662
  function loadGenAIInstrumentations() {
434
663
  const instrumentations = [];
435
664
  try {
436
- instrumentations.push(new OpenAIInstrumentation());
665
+ instrumentations.push(new BrizzOpenAIInstrumentation());
437
666
  logger.debug("Auto-loaded OpenAI instrumentation");
438
667
  } catch (error) {
439
668
  logger.error(`Failed to auto-load OpenAI instrumentation: ${String(error)}`);
@@ -458,7 +687,7 @@ function loadGenAIInstrumentations() {
458
687
  }
459
688
  }
460
689
  try {
461
- registerInstrumentations({ instrumentations });
690
+ registerInstrumentations({ instrumentations, tracerProvider: brizzTracerProvider });
462
691
  logger.info(`Auto-registered ${instrumentations.length} GenAI instrumentations`);
463
692
  } catch (error) {
464
693
  logger.error(`Failed to register GenAI instrumentations: ${String(error)}`);
@@ -468,9 +697,9 @@ function loadGenAIInstrumentations() {
468
697
  function loadMCPInstrumentation() {
469
698
  void (async () => {
470
699
  try {
471
- const { MCPInstrumentation } = await import("./mcp-TOZFTC5Y.js");
700
+ const { MCPInstrumentation } = await import("./mcp-KU7MFTOB.js");
472
701
  const mcp = new MCPInstrumentation({ exceptionLogger });
473
- registerInstrumentations({ instrumentations: [mcp] });
702
+ registerInstrumentations({ instrumentations: [mcp], tracerProvider: brizzTracerProvider });
474
703
  logger.debug("Auto-loaded MCP instrumentation");
475
704
  } catch (error) {
476
705
  logger.debug(
@@ -481,18 +710,35 @@ function loadMCPInstrumentation() {
481
710
  }
482
711
  function loadLangGraphInstrumentation() {
483
712
  try {
484
- registerInstrumentations({ instrumentations: [new LangGraphInstrumentation()] });
713
+ registerInstrumentations({
714
+ instrumentations: [new LangGraphInstrumentation()],
715
+ tracerProvider: brizzTracerProvider
716
+ });
485
717
  logger.debug("Auto-loaded LangGraph instrumentation");
486
718
  } catch (error) {
487
719
  logger.debug(`LangGraph instrumentation not loaded: ${String(error)}`);
488
720
  }
489
721
  }
722
+ function loadTypeSafeInstrumentation() {
723
+ try {
724
+ registerInstrumentations({
725
+ instrumentations: [new TypeSafeInstrumentation()],
726
+ tracerProvider: brizzTracerProvider
727
+ });
728
+ logger.debug("Auto-loaded TypeSafe instrumentation");
729
+ } catch (error) {
730
+ logger.debug(`TypeSafe instrumentation not loaded: ${String(error)}`);
731
+ }
732
+ }
490
733
  function loadVertexAIInstrumentation() {
491
734
  void (async () => {
492
735
  try {
493
736
  const { VertexAIInstrumentation } = await import("@traceloop/instrumentation-vertexai");
494
737
  const vertexAI = new VertexAIInstrumentation({ exceptionLogger });
495
- registerInstrumentations({ instrumentations: [vertexAI] });
738
+ registerInstrumentations({
739
+ instrumentations: [vertexAI],
740
+ tracerProvider: brizzTracerProvider
741
+ });
496
742
  logger.debug("Auto-loaded Vertex AI instrumentation");
497
743
  } catch (error) {
498
744
  logger.debug(
@@ -504,9 +750,12 @@ function loadVertexAIInstrumentation() {
504
750
  function loadGoogleGenAIInstrumentation() {
505
751
  void (async () => {
506
752
  try {
507
- const { GoogleGenAIInstrumentation } = await import("./google-genai-T7I4FFIP.js");
753
+ const { GoogleGenAIInstrumentation } = await import("./google-genai-PERR37LR.js");
508
754
  const googleGenAI = new GoogleGenAIInstrumentation({ exceptionLogger });
509
- registerInstrumentations({ instrumentations: [googleGenAI] });
755
+ registerInstrumentations({
756
+ instrumentations: [googleGenAI],
757
+ tracerProvider: brizzTracerProvider
758
+ });
510
759
  logger.debug("Auto-loaded Google GenAI instrumentation");
511
760
  } catch (error) {
512
761
  logger.debug(
@@ -538,7 +787,9 @@ function loadVercelAITelemetry() {
538
787
  try {
539
788
  const otel = await import("@ai-sdk/otel");
540
789
  if (typeof otel.LegacyOpenTelemetry === "function") {
541
- integrations.push(new otel.LegacyOpenTelemetry());
790
+ integrations.push(
791
+ new otel.LegacyOpenTelemetry({ tracer: brizzTracerProvider.getTracer("ai") })
792
+ );
542
793
  otelCollectorLoaded = true;
543
794
  }
544
795
  } catch {
@@ -565,6 +816,7 @@ function autoInitializeInstrumentations() {
565
816
  const genAIInstrumentations = loadGenAIInstrumentations();
566
817
  loadMCPInstrumentation();
567
818
  loadLangGraphInstrumentation();
819
+ loadTypeSafeInstrumentation();
568
820
  loadVertexAIInstrumentation();
569
821
  loadGoogleGenAIInstrumentation();
570
822
  loadVercelAITelemetry();
@@ -580,7 +832,7 @@ function autoInitializeInstrumentations() {
580
832
  var autoInstrumentationsLoaded = autoInitializeInstrumentations();
581
833
 
582
834
  // src/internal/sdk.ts
583
- import { metrics } from "@opentelemetry/api";
835
+ import { metrics, trace as trace4 } from "@opentelemetry/api";
584
836
  import { registerInstrumentations as registerInstrumentations2 } from "@opentelemetry/instrumentation";
585
837
  import {
586
838
  defaultResource,
@@ -591,9 +843,22 @@ import {
591
843
  resourceFromAttributes as resourceFromAttributes3
592
844
  } from "@opentelemetry/resources";
593
845
  import { MeterProvider } from "@opentelemetry/sdk-metrics";
846
+ import { AlwaysOnSampler } from "@opentelemetry/sdk-trace-base";
594
847
  import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
595
848
 
596
849
  // src/internal/config.ts
850
+ function parseBoolEnv(name) {
851
+ const raw = process.env[name];
852
+ if (raw === void 0) {
853
+ return void 0;
854
+ }
855
+ const value = raw.trim().toLowerCase();
856
+ if (value === "true" || value === "false") {
857
+ return value === "true";
858
+ }
859
+ logger.warn(`Brizz: ignoring ${name}=${raw}; expected true or false.`);
860
+ return void 0;
861
+ }
597
862
  function resolveConfig(options) {
598
863
  const envLogLevel = process.env["BRIZZ_LOG_LEVEL"] || options.logLevel?.toString() || DEFAULT_LOG_LEVEL.toString();
599
864
  let resolvedLogLevel;
@@ -645,7 +910,8 @@ function resolveConfig(options) {
645
910
  disableSpanExporter: process.env["BRIZZ_DISABLE_SPAN_EXPORTER"] === "true" || !!options.disableSpanExporter,
646
911
  environment: process.env["BRIZZ_ENVIRONMENT"] || options.environment,
647
912
  logLevel: resolvedLogLevel,
648
- masking: resolvedMasking
913
+ masking: resolvedMasking,
914
+ setGlobalTracerProvider: parseBoolEnv("BRIZZ_SET_GLOBAL_TRACER_PROVIDER") ?? options.setGlobalTracerProvider ?? true
649
915
  };
650
916
  const dsnInput = process.env["BRIZZ_DSN"] || options.dsn;
651
917
  let parsedDSN = null;
@@ -715,6 +981,7 @@ function resolveConfig(options) {
715
981
  hasApiKey: !!resolvedConfig.apiKey,
716
982
  dsnProvided: !!dsnInput,
717
983
  disableBatch: resolvedConfig.disableBatch,
984
+ setGlobalTracerProvider: resolvedConfig.setGlobalTracerProvider,
718
985
  envOverrides: {
719
986
  hasEnvApiKey: !!process.env["BRIZZ_API_KEY"],
720
987
  hasEnvBaseUrl: !!process.env["BRIZZ_BASE_URL"],
@@ -732,7 +999,6 @@ var BRIZZ_SDK_LANGUAGE = "brizz.sdk.language";
732
999
  var SDK_LANGUAGE = "typescript";
733
1000
 
734
1001
  // src/internal/instrumentation/registry.ts
735
- import { OpenAIInstrumentation as OpenAIInstrumentation2 } from "@arizeai/openinference-instrumentation-openai";
736
1002
  import { AnthropicInstrumentation as AnthropicInstrumentation2 } from "@traceloop/instrumentation-anthropic";
737
1003
  import { BedrockInstrumentation as BedrockInstrumentation2 } from "@traceloop/instrumentation-bedrock";
738
1004
  import { ChromaDBInstrumentation as ChromaDBInstrumentation2 } from "@traceloop/instrumentation-chromadb";
@@ -743,8 +1009,8 @@ import { QdrantInstrumentation as QdrantInstrumentation2 } from "@traceloop/inst
743
1009
  import { TogetherInstrumentation as TogetherInstrumentation2 } from "@traceloop/instrumentation-together";
744
1010
 
745
1011
  // src/internal/instrumentation/langchain.ts
746
- import { createRequire as createRequire2 } from "module";
747
- import { context as context2 } from "@opentelemetry/api";
1012
+ import { createRequire as createRequire3 } from "module";
1013
+ import { context as context3 } from "@opentelemetry/api";
748
1014
  var SCOPE_NAME = "@arizeai/openinference-instrumentation-langchain";
749
1015
  var PATCHED_MARKER = /* @__PURE__ */ Symbol.for("brizz.langchain.callbackManagerPatched");
750
1016
  var OMITTED_KEYS = /* @__PURE__ */ new Set([
@@ -757,7 +1023,7 @@ var TOOL_CALL_ID_METADATA_KEY = "brizz_tool_call_id";
757
1023
  var TOOL_ID = "tool.id";
758
1024
  var TOOL_CALL_ID_ARG = 7;
759
1025
  function runMetadataFromContext() {
760
- const bag = context2.active().getValue(PROPERTIES_CONTEXT_KEY);
1026
+ const bag = context3.active().getValue(PROPERTIES_CONTEXT_KEY);
761
1027
  if (!bag) {
762
1028
  return void 0;
763
1029
  }
@@ -829,7 +1095,7 @@ function patchInstalledCallbackManager() {
829
1095
  logger.debug(`LangChain callback manager not patched: ${String(error)}`);
830
1096
  }
831
1097
  try {
832
- const requireFromSdk = createRequire2(import.meta.url);
1098
+ const requireFromSdk = createRequire3(import.meta.url);
833
1099
  patchCallbackManagerModule(requireFromSdk("@langchain/core/callbacks/manager"));
834
1100
  } catch (error) {
835
1101
  logger.debug(`LangChain CJS callback manager not patched: ${String(error)}`);
@@ -881,9 +1147,11 @@ var InstrumentationRegistry = class _InstrumentationRegistry {
881
1147
  */
882
1148
  loadInstrumentation(InstrumentationClass, name, manualModule, exceptionLogger2) {
883
1149
  try {
884
- const inst = new InstrumentationClass({
885
- exceptionLogger: exceptionLogger2 || ((error) => logger.error(`Exception in instrumentation: ${String(error)}`))
886
- });
1150
+ const inst = bindToBrizz(
1151
+ new InstrumentationClass({
1152
+ exceptionLogger: exceptionLogger2 || ((error) => logger.error(`Exception in instrumentation: ${String(error)}`))
1153
+ })
1154
+ );
887
1155
  if (manualModule) {
888
1156
  inst.manuallyInstrument(manualModule);
889
1157
  logger.debug(`Manual instrumentation enabled for ${name}`);
@@ -901,7 +1169,7 @@ var InstrumentationRegistry = class _InstrumentationRegistry {
901
1169
  loadManualInstrumentations(instrumentations, exceptionLogger2) {
902
1170
  if (this.manualModules?.openAI) {
903
1171
  try {
904
- const openAIInst = new OpenAIInstrumentation2();
1172
+ const openAIInst = new BrizzOpenAIInstrumentation();
905
1173
  openAIInst.manuallyInstrument(this.manualModules.openAI);
906
1174
  instrumentations.push(openAIInst);
907
1175
  logger.debug("Manual instrumentation enabled for OpenAI");
@@ -942,7 +1210,7 @@ var InstrumentationRegistry = class _InstrumentationRegistry {
942
1210
  void (async () => {
943
1211
  try {
944
1212
  const { LangChainInstrumentation } = await import("@arizeai/openinference-instrumentation-langchain");
945
- const lcInst = new LangChainInstrumentation();
1213
+ const lcInst = new LangChainInstrumentation({ tracerProvider: brizzTracerProvider });
946
1214
  lcInst.manuallyInstrument(callbackManagerModule);
947
1215
  patchCallbackManagerModule(callbackManagerModule);
948
1216
  logger.debug("Manual instrumentation enabled for LangChain");
@@ -961,12 +1229,20 @@ var InstrumentationRegistry = class _InstrumentationRegistry {
961
1229
  logger.error(`Failed to apply LangGraph instrumentation: ${String(error)}`);
962
1230
  }
963
1231
  }
1232
+ if (this.manualModules?.typesafe) {
1233
+ try {
1234
+ new TypeSafeInstrumentation().manuallyInstrument(this.manualModules.typesafe);
1235
+ logger.debug("Manual instrumentation enabled for TypeSafe");
1236
+ } catch (error) {
1237
+ logger.error(`Failed to apply TypeSafe instrumentation: ${String(error)}`);
1238
+ }
1239
+ }
964
1240
  if (this.manualModules?.google_vertexai) {
965
1241
  const vertexModule = this.manualModules.google_vertexai;
966
1242
  void (async () => {
967
1243
  try {
968
1244
  const { VertexAIInstrumentation } = await import("@traceloop/instrumentation-vertexai");
969
- const vertexInst = new VertexAIInstrumentation({ exceptionLogger: exceptionLogger2 });
1245
+ const vertexInst = bindToBrizz(new VertexAIInstrumentation({ exceptionLogger: exceptionLogger2 }));
970
1246
  vertexInst.manuallyInstrument(vertexModule);
971
1247
  logger.debug("Manual instrumentation enabled for Vertex AI");
972
1248
  } catch (error) {
@@ -980,7 +1256,7 @@ var InstrumentationRegistry = class _InstrumentationRegistry {
980
1256
  const genaiModule = this.manualModules.google_genai;
981
1257
  void (async () => {
982
1258
  try {
983
- const { GoogleGenAIInstrumentation } = await import("./google-genai-T7I4FFIP.js");
1259
+ const { GoogleGenAIInstrumentation } = await import("./google-genai-PERR37LR.js");
984
1260
  const genaiInst = new GoogleGenAIInstrumentation({ exceptionLogger: exceptionLogger2 });
985
1261
  genaiInst.manuallyInstrument(genaiModule);
986
1262
  logger.debug("Manual instrumentation enabled for Google GenAI");
@@ -995,7 +1271,7 @@ var InstrumentationRegistry = class _InstrumentationRegistry {
995
1271
  const mcpModules = this.manualModules.mcp;
996
1272
  void (async () => {
997
1273
  try {
998
- const { MCPInstrumentation } = await import("./mcp-TOZFTC5Y.js");
1274
+ const { MCPInstrumentation } = await import("./mcp-KU7MFTOB.js");
999
1275
  const instrumentation = new MCPInstrumentation({ exceptionLogger: exceptionLogger2 });
1000
1276
  instrumentation.manuallyInstrument(mcpModules);
1001
1277
  logger.debug("Manual instrumentation enabled for MCP");
@@ -1038,9 +1314,10 @@ import { resourceFromAttributes } from "@opentelemetry/resources";
1038
1314
  import { LoggerProvider } from "@opentelemetry/sdk-logs";
1039
1315
 
1040
1316
  // src/internal/trace/session.ts
1041
- import { context as context3, isSpanContextValid, trace as trace2, SpanStatusCode as SpanStatusCode2 } from "@opentelemetry/api";
1317
+ import { context as context4, isSpanContextValid, trace as trace3, SpanStatusCode as SpanStatusCode3 } from "@opentelemetry/api";
1318
+ var sessionTracer = brizzTracerProvider.getTracer("@brizz/sdk");
1042
1319
  function setCurrentSpanCustomProperties(properties) {
1043
- const current = trace2.getActiveSpan();
1320
+ const current = trace3.getActiveSpan();
1044
1321
  if (!current || !current.isRecording()) {
1045
1322
  return;
1046
1323
  }
@@ -1052,11 +1329,11 @@ function setCurrentSpanCustomProperties(properties) {
1052
1329
  }
1053
1330
  }
1054
1331
  function callWithProperties(properties, fn, thisArg, ...args) {
1055
- const base = context3.active();
1332
+ const base = context4.active();
1056
1333
  const prev = base.getValue(PROPERTIES_CONTEXT_KEY);
1057
1334
  const merged = prev ? { ...prev, ...properties } : properties;
1058
1335
  const next = base.setValue(PROPERTIES_CONTEXT_KEY, merged);
1059
- return context3.with(next, fn, thisArg, ...args);
1336
+ return context4.with(next, fn, thisArg, ...args);
1060
1337
  }
1061
1338
  function withProperties(properties, fn, thisArg) {
1062
1339
  return function wrapped(...args) {
@@ -1068,9 +1345,9 @@ function withProperties(properties, fn, thisArg) {
1068
1345
  );
1069
1346
  };
1070
1347
  }
1071
- function propagatePropertiesImperatively(properties, base = context3.active()) {
1348
+ function propagatePropertiesImperatively(properties, base = context4.active()) {
1072
1349
  try {
1073
- const manager = context3;
1350
+ const manager = context4;
1074
1351
  const mgr = manager._getContextManager?.();
1075
1352
  const store = mgr?._asyncLocalStorage;
1076
1353
  if (!store || typeof store.enterWith !== "function") {
@@ -1173,7 +1450,7 @@ function withServiceName(name, fn, thisArg) {
1173
1450
  return withProperties(serviceNameProperties(name), fn, thisArg);
1174
1451
  }
1175
1452
  function resolveServiceNameFromContext() {
1176
- const props = context3.active().getValue(PROPERTIES_CONTEXT_KEY);
1453
+ const props = context4.active().getValue(PROPERTIES_CONTEXT_KEY);
1177
1454
  return props?.[SERVICE_NAME];
1178
1455
  }
1179
1456
  function userProperties(user) {
@@ -1240,7 +1517,7 @@ function withMessageId(id, fn, thisArg) {
1240
1517
  return withProperties({ [MESSAGE_ID]: id }, fn, thisArg);
1241
1518
  }
1242
1519
  function inheritedMuteTools() {
1243
- const properties = context3.active().getValue(PROPERTIES_CONTEXT_KEY);
1520
+ const properties = context4.active().getValue(PROPERTIES_CONTEXT_KEY);
1244
1521
  return properties?.[MUTE_TOOLS];
1245
1522
  }
1246
1523
  function muteProperties(options) {
@@ -1300,9 +1577,9 @@ var Session = class {
1300
1577
  * @param text - Text to append (null becomes a null/"hide marker")
1301
1578
  * @param context - Optional per-turn context bag to attach to this turn
1302
1579
  */
1303
- setInput(text, context7) {
1304
- this.inputs.push(text);
1305
- this.inputContexts.push(context7 ?? {});
1580
+ setInput(text2, context8) {
1581
+ this.inputs.push(text2);
1582
+ this.inputContexts.push(context8 ?? {});
1306
1583
  this.span.setAttribute(SESSION_INPUT, JSON.stringify(this.inputs));
1307
1584
  this.span.setAttribute(SESSION_INPUT_CONTEXT, JSON.stringify(this.inputContexts));
1308
1585
  }
@@ -1316,9 +1593,9 @@ var Session = class {
1316
1593
  * @param text - Text to append (null becomes a null/"hide marker")
1317
1594
  * @param context - Optional per-turn context bag to attach to this turn
1318
1595
  */
1319
- setOutput(text, context7) {
1320
- this.outputs.push(text);
1321
- this.outputContexts.push(context7 ?? {});
1596
+ setOutput(text2, context8) {
1597
+ this.outputs.push(text2);
1598
+ this.outputContexts.push(context8 ?? {});
1322
1599
  this.span.setAttribute(SESSION_OUTPUT, JSON.stringify(this.outputs));
1323
1600
  this.span.setAttribute(SESSION_OUTPUT_CONTEXT, JSON.stringify(this.outputContexts));
1324
1601
  }
@@ -1421,18 +1698,18 @@ var SessionTitle = class {
1421
1698
  }
1422
1699
  };
1423
1700
  function getActiveSession() {
1424
- return context3.active().getValue(SESSION_OBJECT_CONTEXT_KEY);
1701
+ return context4.active().getValue(SESSION_OBJECT_CONTEXT_KEY);
1425
1702
  }
1426
1703
  function resolveSessionIdFromContext() {
1427
1704
  const active = getActiveSession();
1428
1705
  if (active) {
1429
1706
  return active.sessionId;
1430
1707
  }
1431
- const props = context3.active().getValue(PROPERTIES_CONTEXT_KEY);
1708
+ const props = context4.active().getValue(PROPERTIES_CONTEXT_KEY);
1432
1709
  return props?.[SESSION_ID];
1433
1710
  }
1434
1711
  function resolveMessageIdFromContext() {
1435
- const props = context3.active().getValue(PROPERTIES_CONTEXT_KEY);
1712
+ const props = context4.active().getValue(PROPERTIES_CONTEXT_KEY);
1436
1713
  return props?.[MESSAGE_ID];
1437
1714
  }
1438
1715
  function emitExternalLink(sessionId, url, title, linkType) {
@@ -1614,14 +1891,14 @@ function recordMetricImpl(options) {
1614
1891
  );
1615
1892
  continue;
1616
1893
  }
1617
- let text = typeof attrValue === "string" ? attrValue : String(attrValue);
1618
- if (text.length > METRIC_ATTRIBUTE_VALUE_MAX_LEN) {
1894
+ let text2 = typeof attrValue === "string" ? attrValue : String(attrValue);
1895
+ if (text2.length > METRIC_ATTRIBUTE_VALUE_MAX_LEN) {
1619
1896
  logger.warn(
1620
1897
  `recordMetric(${name}) attribute ${JSON.stringify(normalizedKey)} exceeds ${METRIC_ATTRIBUTE_VALUE_MAX_LEN} characters; truncated.`
1621
1898
  );
1622
- text = text.slice(0, METRIC_ATTRIBUTE_VALUE_MAX_LEN);
1899
+ text2 = text2.slice(0, METRIC_ATTRIBUTE_VALUE_MAX_LEN);
1623
1900
  }
1624
- eventAttributes[`${METRIC_ATTRIBUTE_PREFIX}${normalizedKey}`] = text;
1901
+ eventAttributes[`${METRIC_ATTRIBUTE_PREFIX}${normalizedKey}`] = text2;
1625
1902
  accepted += 1;
1626
1903
  }
1627
1904
  }
@@ -1630,7 +1907,7 @@ function recordMetricImpl(options) {
1630
1907
  eventAttributes[METRIC_TRACE_ID] = traceId;
1631
1908
  }
1632
1909
  if (scope === METRIC_SCOPE_TRACE && traceId === void 0) {
1633
- const spanContext = trace2.getActiveSpan()?.spanContext();
1910
+ const spanContext = trace3.getActiveSpan()?.spanContext();
1634
1911
  if (!spanContext || !isSpanContextValid(spanContext)) {
1635
1912
  logger.warn(
1636
1913
  `recordMetric(${name}) called with scope 'trace' but no trace; metric dropped. Pass options.traceId, or call inside the span of the trace being scored.`
@@ -1646,7 +1923,7 @@ function recordMetricImpl(options) {
1646
1923
  );
1647
1924
  return;
1648
1925
  }
1649
- const base = context3.active();
1926
+ const base = context4.active();
1650
1927
  const ambient = base.getValue(PROPERTIES_CONTEXT_KEY);
1651
1928
  const properties = { ...ambient };
1652
1929
  if (sessionId === void 0) {
@@ -1659,7 +1936,7 @@ function recordMetricImpl(options) {
1659
1936
  properties[SERVICE_NAME] = options.serviceName;
1660
1937
  }
1661
1938
  try {
1662
- context3.with(
1939
+ context4.with(
1663
1940
  base.setValue(PROPERTIES_CONTEXT_KEY, properties),
1664
1941
  () => emitEvent(METRIC_EVENT_NAME, eventAttributes)
1665
1942
  );
@@ -1670,8 +1947,7 @@ function recordMetricImpl(options) {
1670
1947
  function startSession(sessionId, callback, extraProperties, options) {
1671
1948
  const isTitle = options?.mode === "title";
1672
1949
  const spanName = isTitle ? SESSION_TITLE_SPAN_NAME : SESSION_SPAN_NAME;
1673
- const tracer = trace2.getTracer("@brizz/sdk");
1674
- return tracer.startActiveSpan(spanName, (span) => {
1950
+ return sessionTracer.startActiveSpan(spanName, (span) => {
1675
1951
  span.setAttribute(`${BRIZZ}.${SESSION_ID}`, sessionId);
1676
1952
  if (extraProperties) {
1677
1953
  for (const [key, value] of Object.entries(extraProperties)) {
@@ -1689,8 +1965,8 @@ function startSession(sessionId, callback, extraProperties, options) {
1689
1965
  }
1690
1966
  }
1691
1967
  return callWithProperties(contextProperties, () => {
1692
- const sessionCtx = context3.active().setValue(SESSION_OBJECT_CONTEXT_KEY, session);
1693
- return context3.with(sessionCtx, () => {
1968
+ const sessionCtx = context4.active().setValue(SESSION_OBJECT_CONTEXT_KEY, session);
1969
+ return context4.with(sessionCtx, () => {
1694
1970
  try {
1695
1971
  const result = callback(session);
1696
1972
  if (result && typeof result.then === "function") {
@@ -1699,7 +1975,7 @@ function startSession(sessionId, callback, extraProperties, options) {
1699
1975
  return value;
1700
1976
  }).catch((error) => {
1701
1977
  span.recordException(error);
1702
- span.setStatus({ code: SpanStatusCode2.ERROR });
1978
+ span.setStatus({ code: SpanStatusCode3.ERROR });
1703
1979
  span.end();
1704
1980
  throw error;
1705
1981
  });
@@ -1708,7 +1984,7 @@ function startSession(sessionId, callback, extraProperties, options) {
1708
1984
  return result;
1709
1985
  } catch (error) {
1710
1986
  span.recordException(error);
1711
- span.setStatus({ code: SpanStatusCode2.ERROR });
1987
+ span.setStatus({ code: SpanStatusCode3.ERROR });
1712
1988
  span.end();
1713
1989
  throw error;
1714
1990
  }
@@ -1718,8 +1994,7 @@ function startSession(sessionId, callback, extraProperties, options) {
1718
1994
  }
1719
1995
  function startSessionTitle(callback, options) {
1720
1996
  const resolvedSessionId = options?.sessionId ?? getActiveSession()?.sessionId;
1721
- const tracer = trace2.getTracer("@brizz/sdk");
1722
- return tracer.startActiveSpan(SESSION_TITLE_SPAN_NAME, (span) => {
1997
+ return sessionTracer.startActiveSpan(SESSION_TITLE_SPAN_NAME, (span) => {
1723
1998
  if (resolvedSessionId) {
1724
1999
  span.setAttribute(`${BRIZZ}.${SESSION_ID}`, resolvedSessionId);
1725
2000
  }
@@ -1737,7 +2012,7 @@ function startSessionTitle(callback, options) {
1737
2012
  return value;
1738
2013
  }).catch((error) => {
1739
2014
  span.recordException(error);
1740
- span.setStatus({ code: SpanStatusCode2.ERROR });
2015
+ span.setStatus({ code: SpanStatusCode3.ERROR });
1741
2016
  span.end();
1742
2017
  throw error;
1743
2018
  });
@@ -1746,7 +2021,7 @@ function startSessionTitle(callback, options) {
1746
2021
  return result;
1747
2022
  } catch (error) {
1748
2023
  span.recordException(error);
1749
- span.setStatus({ code: SpanStatusCode2.ERROR });
2024
+ span.setStatus({ code: SpanStatusCode3.ERROR });
1750
2025
  span.end();
1751
2026
  throw error;
1752
2027
  }
@@ -1755,7 +2030,7 @@ function startSessionTitle(callback, options) {
1755
2030
  }
1756
2031
 
1757
2032
  // src/internal/log/processors/log-processor.ts
1758
- import { context as context4 } from "@opentelemetry/api";
2033
+ import { context as context5 } from "@opentelemetry/api";
1759
2034
  import { BatchLogRecordProcessor, SimpleLogRecordProcessor } from "@opentelemetry/sdk-logs";
1760
2035
 
1761
2036
  // src/internal/masking/patterns.ts
@@ -2139,10 +2414,12 @@ function maskValue(value, rule) {
2139
2414
  return maskStringByPatternBasedRule(value, rule);
2140
2415
  }
2141
2416
  if (typeof value === "boolean" || typeof value === "number") {
2142
- return maskStringByPatternBasedRule(String(value), rule);
2417
+ const masked = maskStringByPatternBasedRule(String(value), rule);
2418
+ return masked === String(value) ? value : masked;
2143
2419
  }
2144
2420
  if (Array.isArray(value)) {
2145
- return value.map((v) => maskStringByPatternBasedRule(String(v), rule));
2421
+ const masked = value.map((v) => maskStringByPatternBasedRule(String(v), rule));
2422
+ return masked.every((m, i) => m === String(value[i])) ? value : masked;
2146
2423
  }
2147
2424
  if (value !== null && typeof value === "object") {
2148
2425
  const result = {};
@@ -2193,7 +2470,7 @@ var BrizzSimpleLogRecordProcessor = class extends SimpleLogRecordProcessor {
2193
2470
  if (maskingConfig) {
2194
2471
  maskLog(logRecord, maskingConfig);
2195
2472
  }
2196
- const associationProperties = context4.active().getValue(PROPERTIES_CONTEXT_KEY);
2473
+ const associationProperties = context5.active().getValue(PROPERTIES_CONTEXT_KEY);
2197
2474
  if (associationProperties) {
2198
2475
  for (const [key, value] of Object.entries(associationProperties)) {
2199
2476
  logRecord.setAttribute(`${BRIZZ}.${key}`, value);
@@ -2213,7 +2490,7 @@ var BrizzBatchLogRecordProcessor = class extends BatchLogRecordProcessor {
2213
2490
  if (maskingConfig) {
2214
2491
  maskLog(logRecord, maskingConfig);
2215
2492
  }
2216
- const associationProperties = context4.active().getValue(PROPERTIES_CONTEXT_KEY);
2493
+ const associationProperties = context5.active().getValue(PROPERTIES_CONTEXT_KEY);
2217
2494
  if (associationProperties) {
2218
2495
  for (const [key, value] of Object.entries(associationProperties)) {
2219
2496
  logRecord.setAttribute(`${BRIZZ}.${key}`, value);
@@ -2416,6 +2693,11 @@ var LoggingModule = class _LoggingModule {
2416
2693
  getLoggerProvider() {
2417
2694
  return this.loggerProvider;
2418
2695
  }
2696
+ async forceFlush() {
2697
+ await Promise.all(
2698
+ [...this.scopedProviders.values(), this.loggerProvider].map(async (p) => p?.forceFlush())
2699
+ );
2700
+ }
2419
2701
  /**
2420
2702
  * Shutdown the logging module
2421
2703
  */
@@ -2525,6 +2807,9 @@ var MetricsModule = class _MetricsModule {
2525
2807
  }
2526
2808
  return this.metricsReader;
2527
2809
  }
2810
+ async forceFlush() {
2811
+ await this.metricsReader?.forceFlush();
2812
+ }
2528
2813
  /**
2529
2814
  * Shutdown the metrics module
2530
2815
  */
@@ -2700,13 +2985,13 @@ var BrizzSpanExporter = class {
2700
2985
  };
2701
2986
 
2702
2987
  // src/internal/trace/processors/span-processor.ts
2703
- import { context as context5 } from "@opentelemetry/api";
2988
+ import { context as context6 } from "@opentelemetry/api";
2704
2989
  import {
2705
2990
  BatchSpanProcessor,
2706
2991
  SimpleSpanProcessor
2707
2992
  } from "@opentelemetry/sdk-trace-base";
2708
2993
  function applyContextAttributes(span) {
2709
- const sessionProperties = context5.active().getValue(PROPERTIES_CONTEXT_KEY);
2994
+ const sessionProperties = context6.active().getValue(PROPERTIES_CONTEXT_KEY);
2710
2995
  if (sessionProperties) {
2711
2996
  for (const [key, value] of Object.entries(sessionProperties)) {
2712
2997
  span.setAttribute(`${BRIZZ}.${key}`, value);
@@ -2726,7 +3011,10 @@ var LIBRARY_ID_ATTRIBUTES = [
2726
3011
  "langsmith.metadata.thread_id",
2727
3012
  "langsmith.metadata.session_id",
2728
3013
  "langsmith.metadata.conversation_id",
2729
- "langsmith.trace.session_id"
3014
+ "langsmith.trace.session_id",
3015
+ // User-id aliases the streamer copies into brizz.user.id (userIDAliases).
3016
+ "user.id",
3017
+ "langfuse.user.id"
2730
3018
  ];
2731
3019
  var DEFAULT_RULE_ATTRIBUTES = String.raw`^(?!brizz\.(?!session\.(?:input|output)(?:\.context)?$|session\.title$|internal\.intent$)` + `|(?:${LIBRARY_ID_ATTRIBUTES.map((key) => key.replaceAll(".", String.raw`\.`)).join("|")})$)`;
2732
3020
  var isText = (value) => typeof value === "string" || Array.isArray(value) && value.some((item) => typeof item === "string");
@@ -2789,8 +3077,8 @@ function maskReadableSpan(span, config) {
2789
3077
  masked = maskAttributes(masked, config.rules);
2790
3078
  }
2791
3079
  if (!config.disableDefaultRules) {
2792
- const text = Object.fromEntries(Object.entries(masked).filter(([k]) => isText(attrs[k])));
2793
- Object.assign(masked, maskAttributes(text, DEFAULT_MASKING_RULES));
3080
+ const text2 = Object.fromEntries(Object.entries(masked).filter(([k]) => isText(attrs[k])));
3081
+ Object.assign(masked, maskAttributes(text2, DEFAULT_MASKING_RULES));
2794
3082
  }
2795
3083
  const maskedEntries = Object.entries(masked);
2796
3084
  for (const [k, v] of maskedEntries) {
@@ -2900,6 +3188,9 @@ var TracingModule = class _TracingModule {
2900
3188
  }
2901
3189
  return this.spanProcessor;
2902
3190
  }
3191
+ async forceFlush() {
3192
+ await this.spanProcessor?.forceFlush();
3193
+ }
2903
3194
  async shutdown() {
2904
3195
  logger.debug("Shutting down tracing module");
2905
3196
  if (this.spanProcessor) {
@@ -2923,12 +3214,12 @@ function getSpanProcessor() {
2923
3214
 
2924
3215
  // src/internal/trace/agent.ts
2925
3216
  import { randomUUID } from "crypto";
2926
- import { context as context6, propagation } from "@opentelemetry/api";
3217
+ import { context as context7 } from "@opentelemetry/api";
2927
3218
  function newInstanceId() {
2928
3219
  return randomUUID().replaceAll("-", "").slice(0, 8);
2929
3220
  }
2930
3221
  function activeProperties() {
2931
- return context6.active().getValue(PROPERTIES_CONTEXT_KEY) ?? {};
3222
+ return context7.active().getValue(PROPERTIES_CONTEXT_KEY) ?? {};
2932
3223
  }
2933
3224
  function encodeToken(agent) {
2934
3225
  const payload = {
@@ -2943,7 +3234,7 @@ function encodeToken(agent) {
2943
3234
  function currentTraceparent() {
2944
3235
  const carrier = {};
2945
3236
  try {
2946
- propagation.inject(context6.active(), carrier);
3237
+ injectTraceContext(context7.active(), carrier);
2947
3238
  } catch {
2948
3239
  }
2949
3240
  return carrier["traceparent"] ?? "";
@@ -2987,7 +3278,7 @@ function resolveAgent(agent) {
2987
3278
  let parentId;
2988
3279
  let name;
2989
3280
  let sessionId = "";
2990
- let parentContext = context6.active();
3281
+ let parentContext = context7.active();
2991
3282
  if (options.token === void 0) {
2992
3283
  id = options.id || newInstanceId();
2993
3284
  parentId = options.parentId || activeProperties()[AGENT_ID] || "";
@@ -3004,7 +3295,7 @@ function resolveAgent(agent) {
3004
3295
  sessionId = decoded.sessionId;
3005
3296
  if (decoded.traceparent) {
3006
3297
  try {
3007
- parentContext = propagation.extract(parentContext, { traceparent: decoded.traceparent });
3298
+ parentContext = extractTraceContext(parentContext, { traceparent: decoded.traceparent });
3008
3299
  } catch {
3009
3300
  }
3010
3301
  }
@@ -3024,7 +3315,7 @@ function startAgent(agent, callback) {
3024
3315
  return callback(unreadableAgent(agent));
3025
3316
  }
3026
3317
  const { id, parentId, name, properties, parentContext } = resolved;
3027
- return context6.with(
3318
+ return context7.with(
3028
3319
  parentContext,
3029
3320
  () => callWithProperties(properties, () => callback(agentHandle(id, parentId, name)))
3030
3321
  );
@@ -3057,6 +3348,11 @@ function resolveMcpSessionTracking(configured) {
3057
3348
  const enabled = fromEnv === "true";
3058
3349
  return typeof configured === "object" ? { ...configured, enabled } : enabled;
3059
3350
  }
3351
+ var BRIZZ_OWNED = /* @__PURE__ */ Symbol.for("brizz.sdk.ownedTracerProvider");
3352
+ function globalTracerDelegate() {
3353
+ const global = trace4.getTracerProvider();
3354
+ return typeof global.getDelegate === "function" ? global.getDelegate() : global;
3355
+ }
3060
3356
  var _Brizz = class __Brizz {
3061
3357
  static instance = null;
3062
3358
  static getInstance() {
@@ -3080,6 +3376,7 @@ var _Brizz = class __Brizz {
3080
3376
  configure(resolveMcpSessionTracking(options.mcpSessionTracking));
3081
3377
  patchInstalledCallbackManager();
3082
3378
  patchInstalledLangGraph();
3379
+ patchInstalledTypeSafe();
3083
3380
  if (options.instrumentModules && Object.keys(options.instrumentModules).length > 0) {
3084
3381
  registry.setManualModules(options.instrumentModules);
3085
3382
  }
@@ -3093,8 +3390,17 @@ var _Brizz = class __Brizz {
3093
3390
  const registry = InstrumentationRegistry.getInstance();
3094
3391
  const manualInstrumentations = registry.getManualInstrumentations();
3095
3392
  if (options.disableNodeSdk) {
3393
+ setPrivateTracerProvider(null);
3394
+ if (!resolvedConfig.setGlobalTracerProvider) {
3395
+ logger.warn(
3396
+ "Brizz: setGlobalTracerProvider: false has no effect with disableNodeSdk: true. Brizz creates no TracerProvider, so spans follow the provider you register with getSpanProcessor()."
3397
+ );
3398
+ }
3096
3399
  if (manualInstrumentations.length > 0) {
3097
- registerInstrumentations2({ instrumentations: manualInstrumentations });
3400
+ registerInstrumentations2({
3401
+ instrumentations: manualInstrumentations,
3402
+ tracerProvider: brizzTracerProvider
3403
+ });
3098
3404
  }
3099
3405
  logger.info("NodeSDK disabled - only telemetry modules initialized");
3100
3406
  return;
@@ -3112,15 +3418,34 @@ var _Brizz = class __Brizz {
3112
3418
  resourceAttributes["service.version"] = resolvedConfig.appVersion;
3113
3419
  }
3114
3420
  const resource = defaultResource().merge(detectResources({ detectors: [envDetector, hostDetector, processDetector] })).merge(resourceFromAttributes3(resourceAttributes));
3115
- this._tracerProvider = new NodeTracerProvider({
3116
- resource,
3117
- spanProcessors: resolvedConfig.disableSpanExporter ? [] : [new InterruptPropagator(), getSpanProcessor()]
3118
- });
3119
- this._tracerProvider.register();
3421
+ const spanProcessors = resolvedConfig.disableSpanExporter ? [] : [new InterruptPropagator(), getSpanProcessor()];
3422
+ if (resolvedConfig.setGlobalTracerProvider) {
3423
+ this._tracerProvider = new NodeTracerProvider({ resource, spanProcessors });
3424
+ this.registerGlobalTracerProvider(this._tracerProvider);
3425
+ } else {
3426
+ this._tracerProvider = new NodeTracerProvider({
3427
+ resource,
3428
+ spanProcessors,
3429
+ sampler: new AlwaysOnSampler()
3430
+ });
3431
+ if (ensureContextManager() === "failed") {
3432
+ logger.warn(
3433
+ "Brizz: no OpenTelemetry context manager is active and Brizz could not install one; span parenting and session/user propagation will not work."
3434
+ );
3435
+ }
3436
+ setPrivateTracerProvider(this._tracerProvider);
3437
+ logger.info(
3438
+ "Brizz: using a private TracerProvider; Brizz spans are exported to Brizz only and the global TracerProvider is left untouched."
3439
+ );
3440
+ }
3441
+ Reflect.set(this._tracerProvider, BRIZZ_OWNED, true);
3120
3442
  this._meterProvider = new MeterProvider({ resource, readers: [getMetricsReader()] });
3121
3443
  metrics.setGlobalMeterProvider(this._meterProvider);
3122
3444
  if (manualInstrumentations.length > 0) {
3123
- registerInstrumentations2({ instrumentations: manualInstrumentations });
3445
+ registerInstrumentations2({
3446
+ instrumentations: manualInstrumentations,
3447
+ tracerProvider: brizzTracerProvider
3448
+ });
3124
3449
  logger.info(
3125
3450
  `Telemetry providers started with ${manualInstrumentations.length} manual instrumentations`
3126
3451
  );
@@ -3130,6 +3455,27 @@ var _Brizz = class __Brizz {
3130
3455
  );
3131
3456
  }
3132
3457
  }
3458
+ /**
3459
+ * Register `provider` globally and say so when another provider already
3460
+ * holds the slot: OpenTelemetry refuses the second registration without a
3461
+ * word, and every Brizz span then goes to the other provider.
3462
+ * @private
3463
+ */
3464
+ registerGlobalTracerProvider(provider) {
3465
+ setPrivateTracerProvider(null);
3466
+ provider.register();
3467
+ const registered = globalTracerDelegate();
3468
+ if (registered === provider) {
3469
+ return;
3470
+ }
3471
+ if (Reflect.get(registered, BRIZZ_OWNED) === true) {
3472
+ logger.debug("A TracerProvider from an earlier Brizz.initialize() is still registered");
3473
+ return;
3474
+ }
3475
+ logger.warn(
3476
+ "Brizz: another OpenTelemetry TracerProvider is already registered globally, so Brizz could not register its own. Spans from Brizz instrumentations will go to that provider, not to Brizz. Pass setGlobalTracerProvider: false to Brizz.initialize() (or set BRIZZ_SET_GLOBAL_TRACER_PROVIDER=false) to send them to Brizz on a separate provider."
3477
+ );
3478
+ }
3133
3479
  /**
3134
3480
  * Initialize telemetry modules.
3135
3481
  *
@@ -3228,6 +3574,62 @@ var _Brizz = class __Brizz {
3228
3574
  throw new Error(`Failed to initialize SDK: ${String(error)}`, { cause: error });
3229
3575
  }
3230
3576
  }
3577
+ /**
3578
+ * Send the telemetry Brizz has queued, without shutting down.
3579
+ *
3580
+ * On serverless platforms that throttle CPU once a response is sent (Cloud
3581
+ * Run, Lambda), await it before responding: the batch timer may not fire
3582
+ * again before the instance is frozen or recycled. Never throws.
3583
+ *
3584
+ * @param timeoutMillis - How long to wait. Defaults to 5000.
3585
+ * @returns `true` when everything was sent within the budget; `false` on a
3586
+ * timeout, an export error, or before `initialize()`.
3587
+ *
3588
+ * @example
3589
+ * ```typescript
3590
+ * await Brizz.flush();
3591
+ * res.send(reply);
3592
+ * ```
3593
+ */
3594
+ async flush(timeoutMillis = 5e3) {
3595
+ if (!this._initialized) {
3596
+ logger.debug("Brizz.flush called before Brizz.initialize; nothing to flush");
3597
+ return false;
3598
+ }
3599
+ const settle = async (name, flush) => {
3600
+ try {
3601
+ await flush();
3602
+ return true;
3603
+ } catch (error) {
3604
+ logger.debug(`Brizz.flush: flushing ${name} failed: ${String(error)}`);
3605
+ return false;
3606
+ }
3607
+ };
3608
+ const work = Promise.all([
3609
+ settle("spans", () => TracingModule.getInstance().forceFlush()),
3610
+ settle("logs", () => LoggingModule.getInstance().forceFlush()),
3611
+ // Under disableNodeSdk the reader belongs to whatever MeterProvider the
3612
+ // app registered, if any; an unbound reader cannot flush.
3613
+ ...this._meterProvider ? [settle("metrics", () => MetricsModule.getInstance().forceFlush())] : []
3614
+ ]).then((results) => results.every(Boolean));
3615
+ let timer;
3616
+ const timedOut = new Promise((resolve) => {
3617
+ timer = setTimeout(() => resolve("timeout"), timeoutMillis);
3618
+ timer.unref();
3619
+ });
3620
+ try {
3621
+ const result = await Promise.race([work, timedOut]);
3622
+ if (result === "timeout") {
3623
+ logger.warn(
3624
+ `Brizz.flush did not finish within ${timeoutMillis}ms; telemetry still queued will be sent with the next batch.`
3625
+ );
3626
+ return false;
3627
+ }
3628
+ return result;
3629
+ } finally {
3630
+ clearTimeout(timer);
3631
+ }
3632
+ }
3231
3633
  /**
3232
3634
  * Gracefully shutdown the Brizz SDK.
3233
3635
  *
@@ -3296,6 +3698,7 @@ export {
3296
3698
  getMetricsReader,
3297
3699
  getSpanExporter,
3298
3700
  getSpanProcessor,
3701
+ getTracerProvider,
3299
3702
  logger,
3300
3703
  maskAttributes,
3301
3704
  maskValue,