@brizz/sdk 0.1.20 → 0.1.22

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.cjs CHANGED
@@ -5,6 +5,9 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
8
11
  var __export = (target, all) => {
9
12
  for (var name in all)
10
13
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -27,6 +30,839 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
27
30
  ));
28
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
32
 
33
+ // src/internal/logger.ts
34
+ function parseLogLevel(level) {
35
+ if (!level) {
36
+ return DEFAULT_LOG_LEVEL;
37
+ }
38
+ const normalizedLevel = level.toLowerCase().trim();
39
+ switch (normalizedLevel) {
40
+ case "debug":
41
+ return 4 /* DEBUG */;
42
+ case "info":
43
+ return 3 /* INFO */;
44
+ case "warn":
45
+ case "warning":
46
+ return 2 /* WARN */;
47
+ case "error":
48
+ return 1 /* ERROR */;
49
+ case "none":
50
+ case "off":
51
+ case "silent":
52
+ return 0 /* NONE */;
53
+ default: {
54
+ const numLevel = Number.parseInt(normalizedLevel, 10);
55
+ if (!Number.isNaN(numLevel) && numLevel >= 0 && numLevel <= 4) {
56
+ return numLevel;
57
+ }
58
+ return DEFAULT_LOG_LEVEL;
59
+ }
60
+ }
61
+ }
62
+ function setLogLevel(level) {
63
+ const resolvedLevel = typeof level === "string" ? parseLogLevel(level) : level;
64
+ logger.setLevel(resolvedLevel);
65
+ }
66
+ function getLogLevel() {
67
+ return logger.getLevel();
68
+ }
69
+ var import_api, import_pino, LogLevel, DEFAULT_LOG_LEVEL, PinoLogger, logger;
70
+ var init_logger = __esm({
71
+ "src/internal/logger.ts"() {
72
+ "use strict";
73
+ import_api = require("@opentelemetry/api");
74
+ import_pino = __toESM(require("pino"), 1);
75
+ LogLevel = /* @__PURE__ */ ((LogLevel2) => {
76
+ LogLevel2[LogLevel2["NONE"] = 0] = "NONE";
77
+ LogLevel2[LogLevel2["ERROR"] = 1] = "ERROR";
78
+ LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
79
+ LogLevel2[LogLevel2["INFO"] = 3] = "INFO";
80
+ LogLevel2[LogLevel2["DEBUG"] = 4] = "DEBUG";
81
+ return LogLevel2;
82
+ })(LogLevel || {});
83
+ DEFAULT_LOG_LEVEL = 2 /* WARN */;
84
+ PinoLogger = class {
85
+ _level = DEFAULT_LOG_LEVEL;
86
+ _pinoLogger = null;
87
+ constructor() {
88
+ const envLevel = this.getLogLevelFromEnv();
89
+ this._level = envLevel;
90
+ }
91
+ /**
92
+ * Lazy initialization of Pino logger to ensure it's created AFTER Jest spies
93
+ * are set up during tests. This prevents the pino-pretty transport from
94
+ * bypassing stdout/stderr spies.
95
+ */
96
+ ensurePinoLogger() {
97
+ if (!this._pinoLogger) {
98
+ this._pinoLogger = (0, import_pino.default)({
99
+ name: "Brizz",
100
+ level: this.logLevelToPino(this._level),
101
+ // Disable transport in test environment to allow proper spy capture
102
+ transport: this.isProduction() || this.isTest() ? void 0 : {
103
+ target: "pino-pretty",
104
+ options: {
105
+ singleLine: true,
106
+ colorize: true,
107
+ translateTime: "HH:MM:ss",
108
+ ignore: "pid,hostname",
109
+ messageFormat: "[{name}] {msg}"
110
+ }
111
+ }
112
+ });
113
+ }
114
+ return this._pinoLogger;
115
+ }
116
+ isProduction() {
117
+ return process.env["NODE_ENV"] === "production";
118
+ }
119
+ isTest() {
120
+ return process.env["NODE_ENV"] === "test";
121
+ }
122
+ getLogLevelFromEnv() {
123
+ const envLevel = process.env["BRIZZ_LOG_LEVEL"];
124
+ return envLevel ? parseLogLevel(envLevel) : DEFAULT_LOG_LEVEL;
125
+ }
126
+ logLevelToPino(level) {
127
+ switch (level) {
128
+ case 4 /* DEBUG */:
129
+ return "debug";
130
+ case 3 /* INFO */:
131
+ return "info";
132
+ case 2 /* WARN */:
133
+ return "warn";
134
+ case 1 /* ERROR */:
135
+ return "error";
136
+ default:
137
+ return "silent";
138
+ }
139
+ }
140
+ formatMeta(meta) {
141
+ if (meta.length === 0) {
142
+ return {};
143
+ }
144
+ if (meta.length === 1 && typeof meta[0] === "object" && meta[0] !== null) {
145
+ return meta[0];
146
+ }
147
+ return { metadata: meta };
148
+ }
149
+ setLevel(level) {
150
+ this._level = level;
151
+ if (this._pinoLogger) {
152
+ this._pinoLogger.level = this.logLevelToPino(level);
153
+ }
154
+ }
155
+ getLevel() {
156
+ return this._level;
157
+ }
158
+ debug = (msg, ...meta) => {
159
+ if (this._level >= 4 /* DEBUG */) {
160
+ this.ensurePinoLogger().debug(this.formatMeta(meta), msg);
161
+ }
162
+ };
163
+ info = (msg, ...meta) => {
164
+ if (this._level >= 3 /* INFO */) {
165
+ this.ensurePinoLogger().info(this.formatMeta(meta), msg);
166
+ }
167
+ };
168
+ warn = (msg, ...meta) => {
169
+ if (this._level >= 2 /* WARN */) {
170
+ this.ensurePinoLogger().warn(this.formatMeta(meta), msg);
171
+ }
172
+ };
173
+ error = (msg, ...meta) => {
174
+ if (this._level >= 1 /* ERROR */) {
175
+ this.ensurePinoLogger().error(this.formatMeta(meta), msg);
176
+ }
177
+ };
178
+ };
179
+ logger = new PinoLogger();
180
+ }
181
+ });
182
+
183
+ // src/internal/semantic-conventions.ts
184
+ var import_api2, BRIZZ, PROPERTIES, SESSION_ID, PROPERTIES_CONTEXT_KEY, SESSION_OBJECT_CONTEXT_KEY, SESSION_INPUT, SESSION_OUTPUT, SESSION_INPUT_CONTEXT, SESSION_OUTPUT_CONTEXT, SESSION_SPAN_NAME, SESSION_TITLE_SPAN_NAME, SESSION_TITLE_GENERATION, SESSION_TITLE;
185
+ var init_semantic_conventions = __esm({
186
+ "src/internal/semantic-conventions.ts"() {
187
+ "use strict";
188
+ import_api2 = require("@opentelemetry/api");
189
+ BRIZZ = "brizz";
190
+ PROPERTIES = "properties";
191
+ SESSION_ID = "session.id";
192
+ PROPERTIES_CONTEXT_KEY = (0, import_api2.createContextKey)(PROPERTIES);
193
+ SESSION_OBJECT_CONTEXT_KEY = (0, import_api2.createContextKey)("brizz.session.object");
194
+ SESSION_INPUT = "brizz.session.input";
195
+ SESSION_OUTPUT = "brizz.session.output";
196
+ SESSION_INPUT_CONTEXT = "brizz.session.input.context";
197
+ SESSION_OUTPUT_CONTEXT = "brizz.session.output.context";
198
+ SESSION_SPAN_NAME = "brizz.start_session";
199
+ SESSION_TITLE_SPAN_NAME = "brizz.session_title";
200
+ SESSION_TITLE_GENERATION = "session.title_generation";
201
+ SESSION_TITLE = "brizz.session.title";
202
+ }
203
+ });
204
+
205
+ // src/internal/instrumentation/mcp/session.ts
206
+ function stampAndPropagateSession(span, sessionId, baseContext = import_api3.context.active()) {
207
+ if (!sessionId) {
208
+ return { context: baseContext, sessionId: null };
209
+ }
210
+ if (span.isRecording()) {
211
+ try {
212
+ span.setAttribute(`${BRIZZ}.${SESSION_ID}`, sessionId);
213
+ } catch (error) {
214
+ logger.warn(
215
+ `Brizz MCP: failed to stamp session id on span: ${String(error)}`
216
+ );
217
+ }
218
+ }
219
+ try {
220
+ const prev = baseContext.getValue(PROPERTIES_CONTEXT_KEY);
221
+ const merged = prev ? { ...prev, [SESSION_ID]: sessionId } : { [SESSION_ID]: sessionId };
222
+ return {
223
+ context: baseContext.setValue(PROPERTIES_CONTEXT_KEY, merged),
224
+ sessionId
225
+ };
226
+ } catch (error) {
227
+ logger.warn(`Brizz MCP: failed to attach session context: ${String(error)}`);
228
+ return { context: baseContext, sessionId };
229
+ }
230
+ }
231
+ var import_api3;
232
+ var init_session = __esm({
233
+ "src/internal/instrumentation/mcp/session.ts"() {
234
+ "use strict";
235
+ import_api3 = require("@opentelemetry/api");
236
+ init_logger();
237
+ init_semantic_conventions();
238
+ }
239
+ });
240
+
241
+ // src/internal/instrumentation/mcp/semantic-conventions.ts
242
+ var MCP_TOOL_NAME, MCP_TOOL_ARGUMENTS, MCP_TOOL_RESULT, MCP_COMPONENT_TYPE, MCP_COMPONENT_TOOL, MCP_METHOD_NAME, MCP_REQUEST_ID, MCP_SESSION_ID, MCP_PROTOCOL_VERSION, MCP_RESOURCE_URI, RPC_SYSTEM, RPC_SYSTEM_MCP, RPC_RESPONSE_STATUS_CODE, GEN_AI_TOOL_NAME, GEN_AI_PROMPT_NAME, GEN_AI_OPERATION_NAME, GEN_AI_OPERATION_EXECUTE_TOOL, NETWORK_TRANSPORT, ERROR_TYPE, ERROR_TYPE_TOOL, JSONRPC_REQUEST_ID, SPAN_NAME_TOOLS_CALL, MAX_ATTRIBUTE_LENGTH, TRUNCATION_SUFFIX, METHOD_TOOLS_CALL, METHOD_RESOURCES_READ, METHOD_PROMPTS_GET, METHOD_INITIALIZE;
243
+ var init_semantic_conventions2 = __esm({
244
+ "src/internal/instrumentation/mcp/semantic-conventions.ts"() {
245
+ "use strict";
246
+ MCP_TOOL_NAME = "mcp.tool.name";
247
+ MCP_TOOL_ARGUMENTS = "mcp.tool.arguments";
248
+ MCP_TOOL_RESULT = "mcp.tool.result";
249
+ MCP_COMPONENT_TYPE = "mcp.component.type";
250
+ MCP_COMPONENT_TOOL = "tool";
251
+ MCP_METHOD_NAME = "mcp.method.name";
252
+ MCP_REQUEST_ID = "mcp.request.id";
253
+ MCP_SESSION_ID = "mcp.session.id";
254
+ MCP_PROTOCOL_VERSION = "mcp.protocol.version";
255
+ MCP_RESOURCE_URI = "mcp.resource.uri";
256
+ RPC_SYSTEM = "rpc.system";
257
+ RPC_SYSTEM_MCP = "mcp";
258
+ RPC_RESPONSE_STATUS_CODE = "rpc.response.status_code";
259
+ GEN_AI_TOOL_NAME = "gen_ai.tool.name";
260
+ GEN_AI_PROMPT_NAME = "gen_ai.prompt.name";
261
+ GEN_AI_OPERATION_NAME = "gen_ai.operation.name";
262
+ GEN_AI_OPERATION_EXECUTE_TOOL = "execute_tool";
263
+ NETWORK_TRANSPORT = "network.transport";
264
+ ERROR_TYPE = "error.type";
265
+ ERROR_TYPE_TOOL = "tool_error";
266
+ JSONRPC_REQUEST_ID = "jsonrpc.request.id";
267
+ SPAN_NAME_TOOLS_CALL = "tools/call";
268
+ MAX_ATTRIBUTE_LENGTH = 32 * 1024;
269
+ TRUNCATION_SUFFIX = "\u2026(truncated)";
270
+ METHOD_TOOLS_CALL = "tools/call";
271
+ METHOD_RESOURCES_READ = "resources/read";
272
+ METHOD_PROMPTS_GET = "prompts/get";
273
+ METHOD_INITIALIZE = "initialize";
274
+ }
275
+ });
276
+
277
+ // src/internal/instrumentation/mcp/patches/attributes.ts
278
+ function deriveSpanName(method, params) {
279
+ try {
280
+ if (method === METHOD_TOOLS_CALL) {
281
+ const name = typeof params?.["name"] === "string" ? params["name"] : "";
282
+ return name ? `${SPAN_NAME_TOOLS_CALL} ${name}` : SPAN_NAME_TOOLS_CALL;
283
+ }
284
+ if (method === METHOD_RESOURCES_READ) {
285
+ const uri = typeof params?.["uri"] === "string" ? params["uri"] : "";
286
+ return uri ? `${METHOD_RESOURCES_READ} ${uri}` : METHOD_RESOURCES_READ;
287
+ }
288
+ if (method === METHOD_PROMPTS_GET) {
289
+ const name = typeof params?.["name"] === "string" ? params["name"] : "";
290
+ return name ? `${METHOD_PROMPTS_GET} ${name}` : METHOD_PROMPTS_GET;
291
+ }
292
+ return method;
293
+ } catch {
294
+ return method || "mcp";
295
+ }
296
+ }
297
+ function applyBaseAttributes(span, request) {
298
+ span.setAttribute(RPC_SYSTEM, RPC_SYSTEM_MCP);
299
+ if (request.method) {
300
+ span.setAttribute(MCP_METHOD_NAME, request.method);
301
+ }
302
+ if (request.id !== void 0 && request.id !== null) {
303
+ const id = String(request.id);
304
+ span.setAttribute(MCP_REQUEST_ID, id);
305
+ span.setAttribute(JSONRPC_REQUEST_ID, id);
306
+ }
307
+ }
308
+ function applyClientRequestAttributes(span, request, transportName) {
309
+ applyBaseAttributes(span, request);
310
+ applyMethodSpecificRequestAttributes(span, request);
311
+ if (transportName) {
312
+ const transport = normalizeTransport(transportName);
313
+ if (transport) {
314
+ span.setAttribute(NETWORK_TRANSPORT, transport);
315
+ }
316
+ }
317
+ }
318
+ function applyServerRequestAttributes(span, request, protocol) {
319
+ applyBaseAttributes(span, request);
320
+ applyMethodSpecificRequestAttributes(span, request);
321
+ if (request.method === METHOD_TOOLS_CALL) {
322
+ const args = request.params?.["arguments"];
323
+ if (args !== void 0) {
324
+ span.setAttribute(MCP_TOOL_ARGUMENTS, serializeForAttribute(args));
325
+ }
326
+ }
327
+ const sessionId = protocol.sessionId ?? protocol._transport?.sessionId;
328
+ if (sessionId) {
329
+ span.setAttribute(MCP_SESSION_ID, String(sessionId));
330
+ }
331
+ }
332
+ function applyMethodSpecificRequestAttributes(span, request) {
333
+ const params = request.params ?? {};
334
+ switch (request.method) {
335
+ case METHOD_TOOLS_CALL: {
336
+ const name = typeof params["name"] === "string" ? params["name"] : "";
337
+ if (name) {
338
+ span.setAttribute(MCP_TOOL_NAME, name);
339
+ span.setAttribute(GEN_AI_TOOL_NAME, name);
340
+ }
341
+ span.setAttribute(MCP_COMPONENT_TYPE, MCP_COMPONENT_TOOL);
342
+ span.setAttribute(GEN_AI_OPERATION_NAME, GEN_AI_OPERATION_EXECUTE_TOOL);
343
+ break;
344
+ }
345
+ case METHOD_RESOURCES_READ: {
346
+ const uri = typeof params["uri"] === "string" ? params["uri"] : "";
347
+ if (uri) {
348
+ span.setAttribute(MCP_RESOURCE_URI, uri);
349
+ }
350
+ break;
351
+ }
352
+ case METHOD_PROMPTS_GET: {
353
+ const name = typeof params["name"] === "string" ? params["name"] : "";
354
+ if (name) {
355
+ span.setAttribute(GEN_AI_PROMPT_NAME, name);
356
+ }
357
+ break;
358
+ }
359
+ default:
360
+ break;
361
+ }
362
+ }
363
+ function applyResultAttributes(span, method, result) {
364
+ if (method === METHOD_INITIALIZE && result && typeof result === "object") {
365
+ const protocolVersion = result["protocolVersion"];
366
+ if (typeof protocolVersion === "string") {
367
+ span.setAttribute(MCP_PROTOCOL_VERSION, protocolVersion);
368
+ }
369
+ return;
370
+ }
371
+ if (method !== METHOD_TOOLS_CALL) {
372
+ return;
373
+ }
374
+ const obj = result && typeof result === "object" ? result : null;
375
+ const content = obj?.["content"] ?? result;
376
+ span.setAttribute(MCP_TOOL_RESULT, serializeForAttribute(content));
377
+ if (obj && obj["isError"] === true) {
378
+ span.setAttribute(ERROR_TYPE, ERROR_TYPE_TOOL);
379
+ const message = extractToolErrorMessage(obj);
380
+ span.setStatus({ code: import_api4.SpanStatusCode.ERROR, message });
381
+ }
382
+ }
383
+ function applyErrorAttributes(span, err) {
384
+ const error = err;
385
+ const code = error?.code;
386
+ if (typeof code === "number") {
387
+ span.setAttribute(RPC_RESPONSE_STATUS_CODE, code);
388
+ span.setAttribute(ERROR_TYPE, String(code));
389
+ } else if (error?.name === "AbortError") {
390
+ span.setAttribute(ERROR_TYPE, "cancelled");
391
+ } else if (error?.name === "TimeoutError") {
392
+ span.setAttribute(ERROR_TYPE, "timeout");
393
+ } else {
394
+ span.setAttribute(
395
+ ERROR_TYPE,
396
+ error?.constructor?.name || error?.name || "Error"
397
+ );
398
+ }
399
+ try {
400
+ span.recordException(error);
401
+ } catch {
402
+ }
403
+ span.setStatus({
404
+ code: import_api4.SpanStatusCode.ERROR,
405
+ message: typeof error?.message === "string" ? error.message : void 0
406
+ });
407
+ }
408
+ function serializeForAttribute(value) {
409
+ const raw = rawSerialize(value);
410
+ if (raw.length <= MAX_ATTRIBUTE_LENGTH) {
411
+ return raw;
412
+ }
413
+ return raw.slice(0, MAX_ATTRIBUTE_LENGTH - TRUNCATION_SUFFIX.length) + TRUNCATION_SUFFIX;
414
+ }
415
+ function rawSerialize(value) {
416
+ if (value === null || value === void 0) {
417
+ return "";
418
+ }
419
+ if (typeof value === "string") {
420
+ return value;
421
+ }
422
+ try {
423
+ return JSON.stringify(value);
424
+ } catch {
425
+ try {
426
+ if (value === null || value === void 0) {
427
+ return "";
428
+ }
429
+ const tag = Object.prototype.toString.call(value);
430
+ return typeof value.toString === "function" ? (
431
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string
432
+ String(value)
433
+ ) : tag;
434
+ } catch {
435
+ return "";
436
+ }
437
+ }
438
+ }
439
+ function extractToolErrorMessage(result) {
440
+ const content = result["content"];
441
+ if (Array.isArray(content)) {
442
+ for (const item of content) {
443
+ if (item && typeof item === "object") {
444
+ const text = item["text"];
445
+ if (typeof text === "string") {
446
+ return text;
447
+ }
448
+ }
449
+ }
450
+ }
451
+ return void 0;
452
+ }
453
+ function normalizeTransport(ctorName) {
454
+ const name = ctorName.toLowerCase();
455
+ if (name.includes("stdio")) {
456
+ return "stdio";
457
+ }
458
+ if (name.includes("sse")) {
459
+ return "sse";
460
+ }
461
+ if (name.includes("streamablehttp") || name.includes("http")) {
462
+ return "http";
463
+ }
464
+ return null;
465
+ }
466
+ var import_api4;
467
+ var init_attributes = __esm({
468
+ "src/internal/instrumentation/mcp/patches/attributes.ts"() {
469
+ "use strict";
470
+ import_api4 = require("@opentelemetry/api");
471
+ init_semantic_conventions2();
472
+ }
473
+ });
474
+
475
+ // src/internal/instrumentation/mcp/patches/protocol.ts
476
+ function patchProtocolPrototype(prototype, tracer) {
477
+ if (!prototype || typeof prototype !== "object") {
478
+ return false;
479
+ }
480
+ const proto = prototype;
481
+ if (proto[PATCHED_FLAG]) {
482
+ logger.debug("Brizz MCP: Protocol.prototype already patched, skipping");
483
+ return false;
484
+ }
485
+ const originalRequest = proto["request"];
486
+ const originalOnRequest = proto["_onrequest"];
487
+ if (typeof originalRequest === "function") {
488
+ proto["request"] = wrapRequest(originalRequest, tracer);
489
+ } else {
490
+ logger.debug(
491
+ "Brizz MCP: Protocol.prototype.request missing \u2014 skipping CLIENT patch"
492
+ );
493
+ }
494
+ if (typeof originalOnRequest === "function") {
495
+ proto["_onrequest"] = wrapOnRequest(
496
+ originalOnRequest,
497
+ tracer
498
+ );
499
+ } else {
500
+ logger.debug(
501
+ "Brizz MCP: Protocol.prototype._onrequest missing \u2014 skipping SERVER patch"
502
+ );
503
+ }
504
+ proto[PATCHED_FLAG] = true;
505
+ return true;
506
+ }
507
+ function wrapRequest(original, tracer) {
508
+ return function wrappedRequest(...args) {
509
+ const request = args[0];
510
+ if (!request || typeof request !== "object" || !request.method) {
511
+ return original.apply(this, args);
512
+ }
513
+ const span = safeStartClientSpan(tracer, request, this);
514
+ if (!span) {
515
+ return original.apply(this, args);
516
+ }
517
+ return executeAroundSpan(span, request.method, () => {
518
+ const ctx = import_api5.trace.setSpan(import_api5.context.active(), span);
519
+ return import_api5.context.with(ctx, () => original.apply(this, args));
520
+ });
521
+ };
522
+ }
523
+ function wrapOnRequest(original, tracer) {
524
+ return function wrappedOnRequest(...args) {
525
+ const request = args[0];
526
+ if (!request || typeof request !== "object" || !request.method) {
527
+ return original.apply(this, args);
528
+ }
529
+ const handlers = this._requestHandlers;
530
+ if (!handlers || typeof handlers.get !== "function") {
531
+ return original.apply(this, args);
532
+ }
533
+ const method = request.method;
534
+ const handler = handlers.get(method) ?? this.fallbackRequestHandler;
535
+ if (!handler) {
536
+ return original.apply(this, args);
537
+ }
538
+ const started = safeStartServerSpan(tracer, request, this);
539
+ if (!started) {
540
+ return original.apply(this, args);
541
+ }
542
+ const { span, spanCtx } = started;
543
+ const wrappedHandler = (req, extra) => import_api5.context.with(spanCtx, () => executeHandler(span, method, handler, req, extra));
544
+ const hadEntry = handlers.has(method);
545
+ const prev = handlers.get(method);
546
+ handlers.set(method, wrappedHandler);
547
+ const usedFallback = !hadEntry && this.fallbackRequestHandler === handler;
548
+ const fallbackPrev = usedFallback ? this.fallbackRequestHandler : void 0;
549
+ if (usedFallback) {
550
+ this.fallbackRequestHandler = wrappedHandler;
551
+ }
552
+ try {
553
+ return original.apply(this, args);
554
+ } finally {
555
+ if (hadEntry) {
556
+ handlers.set(method, prev);
557
+ } else {
558
+ handlers.delete(method);
559
+ }
560
+ if (usedFallback) {
561
+ this.fallbackRequestHandler = fallbackPrev;
562
+ }
563
+ }
564
+ };
565
+ }
566
+ function executeAroundSpan(span, method, run) {
567
+ let result;
568
+ try {
569
+ result = run();
570
+ } catch (error) {
571
+ safeApplyErrorAttributes(span, error);
572
+ safeEnd(span);
573
+ throw error;
574
+ }
575
+ if (!isThenable(result)) {
576
+ safeApplyResultAttributes(span, method, result);
577
+ safeEnd(span);
578
+ return result;
579
+ }
580
+ return result.then(
581
+ (value) => {
582
+ safeApplyResultAttributes(span, method, value);
583
+ safeEnd(span);
584
+ return value;
585
+ },
586
+ (error) => {
587
+ safeApplyErrorAttributes(span, error);
588
+ safeEnd(span);
589
+ throw error;
590
+ }
591
+ );
592
+ }
593
+ function executeHandler(span, method, handler, req, extra) {
594
+ return executeAroundSpan(span, method, () => handler(req, extra));
595
+ }
596
+ function safeStartClientSpan(tracer, request, protocol) {
597
+ try {
598
+ const spanName = deriveSpanName(request.method, request.params);
599
+ const span = tracer.startSpan(spanName, { kind: import_api5.SpanKind.CLIENT });
600
+ applyClientRequestAttributes(
601
+ span,
602
+ request,
603
+ protocol._transport?.constructor?.name
604
+ );
605
+ return span;
606
+ } catch (error) {
607
+ logger.debug(`Brizz MCP: failed to open CLIENT span: ${String(error)}`);
608
+ return null;
609
+ }
610
+ }
611
+ function safeStartServerSpan(tracer, request, protocol) {
612
+ try {
613
+ const parentCtx = extractParentContext(request);
614
+ const spanName = deriveSpanName(request.method, request.params);
615
+ const span = tracer.startSpan(
616
+ spanName,
617
+ { kind: import_api5.SpanKind.SERVER },
618
+ parentCtx
619
+ );
620
+ applyServerRequestAttributes(span, request, protocol);
621
+ const sessionId = protocol.sessionId ?? protocol._transport?.sessionId;
622
+ const { context: sessCtx } = stampAndPropagateSession(span, sessionId, parentCtx);
623
+ return { span, spanCtx: import_api5.trace.setSpan(sessCtx, span) };
624
+ } catch (error) {
625
+ logger.debug(`Brizz MCP: failed to open SERVER span: ${String(error)}`);
626
+ return null;
627
+ }
628
+ }
629
+ function extractParentContext(request) {
630
+ try {
631
+ const meta = request.params?._meta;
632
+ if (meta && typeof meta === "object") {
633
+ return import_api5.propagation.extract(import_api5.context.active(), meta);
634
+ }
635
+ } catch (error) {
636
+ logger.debug(
637
+ `Brizz MCP: failed to extract parent context from _meta: ${String(error)}`
638
+ );
639
+ }
640
+ return import_api5.context.active();
641
+ }
642
+ function isThenable(value) {
643
+ return !!value && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
644
+ }
645
+ function safeApplyResultAttributes(span, method, value) {
646
+ try {
647
+ applyResultAttributes(span, method, value);
648
+ } catch (error) {
649
+ logger.debug(
650
+ `Brizz MCP: failed to apply result attributes: ${String(error)}`
651
+ );
652
+ }
653
+ }
654
+ function safeApplyErrorAttributes(span, err) {
655
+ try {
656
+ applyErrorAttributes(span, err);
657
+ } catch (error) {
658
+ logger.debug(
659
+ `Brizz MCP: failed to apply error attributes: ${String(error)}`
660
+ );
661
+ }
662
+ }
663
+ function safeEnd(span) {
664
+ try {
665
+ span.end();
666
+ } catch (error) {
667
+ logger.debug(`Brizz MCP: failed to end span: ${String(error)}`);
668
+ }
669
+ }
670
+ var import_api5, PATCHED_FLAG;
671
+ var init_protocol = __esm({
672
+ "src/internal/instrumentation/mcp/patches/protocol.ts"() {
673
+ "use strict";
674
+ import_api5 = require("@opentelemetry/api");
675
+ init_logger();
676
+ init_session();
677
+ init_attributes();
678
+ PATCHED_FLAG = /* @__PURE__ */ Symbol("brizz.mcp.protocol-patched");
679
+ }
680
+ });
681
+
682
+ // src/internal/version.ts
683
+ function getSDKVersion() {
684
+ return "0.1.22";
685
+ }
686
+ var init_version = __esm({
687
+ "src/internal/version.ts"() {
688
+ "use strict";
689
+ }
690
+ });
691
+
692
+ // src/internal/instrumentation/mcp/version.ts
693
+ var INSTRUMENTATION_NAME, INSTRUMENTATION_VERSION;
694
+ var init_version2 = __esm({
695
+ "src/internal/instrumentation/mcp/version.ts"() {
696
+ "use strict";
697
+ init_version();
698
+ INSTRUMENTATION_NAME = "@brizz/sdk/mcp";
699
+ INSTRUMENTATION_VERSION = getSDKVersion();
700
+ }
701
+ });
702
+
703
+ // src/internal/instrumentation/mcp/instrumentation.ts
704
+ function isMCPInstrumentation(value) {
705
+ return !!value && typeof value === "object" && typeof value.instrumentationName === "string";
706
+ }
707
+ var import_openinference_instrumentation_mcp, import_api6, import_instrumentation, PROTOCOL_MODULE_NAME, PROTOCOL_SUPPORTED_VERSIONS, MCPInstrumentation;
708
+ var init_instrumentation = __esm({
709
+ "src/internal/instrumentation/mcp/instrumentation.ts"() {
710
+ "use strict";
711
+ import_openinference_instrumentation_mcp = require("@arizeai/openinference-instrumentation-mcp");
712
+ import_api6 = require("@opentelemetry/api");
713
+ import_instrumentation = require("@opentelemetry/instrumentation");
714
+ init_logger();
715
+ init_protocol();
716
+ init_version2();
717
+ PROTOCOL_MODULE_NAME = "@modelcontextprotocol/sdk/shared/protocol.js";
718
+ PROTOCOL_SUPPORTED_VERSIONS = [">=1.0.0 <2"];
719
+ MCPInstrumentation = class extends import_openinference_instrumentation_mcp.MCPInstrumentation {
720
+ /**
721
+ * Dedicated Brizz-named tracer for our SERVER + CLIENT spans.
722
+ *
723
+ * Why a separate tracer from the parent class's one: Arize's inherited
724
+ * transport patches don't emit spans (they only inject propagation
725
+ * headers), so using our own tracer here keeps Brizz spans attributed to
726
+ * `@brizz/sdk/mcp` in the dashboard. The parent's `tracer` is a
727
+ * `protected get` (no setter), so fighting it with assignment is the
728
+ * wrong tool.
729
+ */
730
+ brizzTracer;
731
+ constructor(_config) {
732
+ super({ instrumentationConfig: _config?.instrumentationConfig });
733
+ this.brizzTracer = import_api6.trace.getTracer(INSTRUMENTATION_NAME, INSTRUMENTATION_VERSION);
734
+ }
735
+ /**
736
+ * Extend `super.init()` with our protocol-layer module definition.
737
+ *
738
+ * Arize's `init()` returns definitions for the six transport modules
739
+ * (SSE client/server, stdio client/server, streamable-HTTP client/server)
740
+ * whose `send`/`start` methods get patched for W3C trace-context
741
+ * injection. We append one more: `@modelcontextprotocol/sdk/shared/protocol.js`
742
+ * where our patches open SERVER/CLIENT spans around the handler + outgoing
743
+ * request. If `super.init()` throws (unlikely but possible across Arize
744
+ * versions), we gracefully degrade to protocol-only instrumentation.
745
+ *
746
+ * The cast at the end satisfies the parent's strongly-typed generic
747
+ * without leaking the cast into call sites.
748
+ */
749
+ init() {
750
+ let base;
751
+ try {
752
+ base = super.init() ?? [];
753
+ } catch (error) {
754
+ logger.warn(
755
+ `Brizz MCP: base Arize init() failed \u2014 transport context propagation disabled: ${String(error)}`
756
+ );
757
+ base = [];
758
+ }
759
+ const baseArr = Array.isArray(base) ? base : [base];
760
+ const brizzDef = new import_instrumentation.InstrumentationNodeModuleDefinition(
761
+ PROTOCOL_MODULE_NAME,
762
+ PROTOCOL_SUPPORTED_VERSIONS,
763
+ (module2) => {
764
+ this.patchProtocolModule(module2);
765
+ return module2;
766
+ },
767
+ (module2) => {
768
+ this.unpatchProtocolModule(module2);
769
+ return module2;
770
+ }
771
+ );
772
+ return [...baseArr, brizzDef];
773
+ }
774
+ /**
775
+ * Manually instrument MCP modules for Next.js/Webpack where the
776
+ * auto-instrumentation module-load hook doesn't fire.
777
+ *
778
+ * Forwards the six transport module fields to the inherited Arize
779
+ * `manuallyInstrument(...)` (context propagation) and applies our
780
+ * protocol patch if `protocolModule` is provided (SERVER/CLIENT spans).
781
+ * Both legs are try/catch-guarded — a failure in one shouldn't prevent
782
+ * the other from taking effect.
783
+ */
784
+ manuallyInstrument(modules) {
785
+ const {
786
+ clientSSEModule,
787
+ serverSSEModule,
788
+ clientStdioModule,
789
+ serverStdioModule,
790
+ clientStreamableHTTPModule,
791
+ serverStreamableHTTPModule,
792
+ protocolModule
793
+ } = modules;
794
+ try {
795
+ super.manuallyInstrument({
796
+ clientSSEModule,
797
+ serverSSEModule,
798
+ clientStdioModule,
799
+ serverStdioModule,
800
+ clientStreamableHTTPModule,
801
+ serverStreamableHTTPModule
802
+ });
803
+ } catch (error) {
804
+ logger.warn(`Brizz MCP: Arize manuallyInstrument(...) failed: ${String(error)}`);
805
+ }
806
+ if (protocolModule) {
807
+ try {
808
+ this.patchProtocolModule(protocolModule);
809
+ } catch (error) {
810
+ logger.warn(
811
+ `Brizz MCP: failed to manually patch Protocol module: ${String(error)}`
812
+ );
813
+ }
814
+ }
815
+ }
816
+ /**
817
+ * Apply the SERVER + CLIENT patch to a loaded `protocol.js` module. Shared
818
+ * by both the automatic module-load callback in `init()` and the manual
819
+ * `manuallyInstrument(...)` path above so there's exactly one place that
820
+ * calls `patchProtocolPrototype`.
821
+ */
822
+ patchProtocolModule(module2) {
823
+ const proto = module2?.Protocol?.prototype;
824
+ if (!proto) {
825
+ logger.debug(
826
+ "Brizz MCP: module does not expose Protocol.prototype \u2014 skipping protocol patches"
827
+ );
828
+ return;
829
+ }
830
+ const ok = patchProtocolPrototype(proto, this.brizzTracer);
831
+ if (ok) {
832
+ logger.debug("Brizz MCP: patched Protocol.prototype for SERVER+CLIENT spans");
833
+ }
834
+ }
835
+ /**
836
+ * Unpatch is intentionally a no-op.
837
+ *
838
+ * `patchProtocolPrototype` wraps methods in place and sets a PATCHED_FLAG
839
+ * Symbol on the prototype to prevent double-patching. Restoring the
840
+ * originals would require us to hold references across module unloads,
841
+ * which isn't a pattern we need — instrumentation rarely gets torn down
842
+ * at runtime, and a process reload is the canonical way to detach.
843
+ */
844
+ unpatchProtocolModule(_module) {
845
+ logger.debug(
846
+ "Brizz MCP: unpatch is a no-op \u2014 reload the process to cleanly detach"
847
+ );
848
+ }
849
+ };
850
+ }
851
+ });
852
+
853
+ // src/internal/instrumentation/mcp/index.ts
854
+ var mcp_exports = {};
855
+ __export(mcp_exports, {
856
+ MCPInstrumentation: () => MCPInstrumentation,
857
+ isMCPInstrumentation: () => isMCPInstrumentation
858
+ });
859
+ var init_mcp = __esm({
860
+ "src/internal/instrumentation/mcp/index.ts"() {
861
+ "use strict";
862
+ init_instrumentation();
863
+ }
864
+ });
865
+
30
866
  // src/index.ts
31
867
  var src_exports = {};
32
868
  __export(src_exports, {
@@ -50,6 +886,7 @@ __export(src_exports, {
50
886
  logger: () => logger,
51
887
  maskAttributes: () => maskAttributes,
52
888
  maskValue: () => maskValue,
889
+ setCurrentSpanCustomProperties: () => setCurrentSpanCustomProperties,
53
890
  setLogLevel: () => setLogLevel,
54
891
  startSession: () => startSession,
55
892
  startSessionTitle: () => startSessionTitle,
@@ -60,7 +897,7 @@ module.exports = __toCommonJS(src_exports);
60
897
 
61
898
  // src/internal/instrumentation/auto-init.ts
62
899
  var import_auto_instrumentations_node = require("@opentelemetry/auto-instrumentations-node");
63
- var import_instrumentation = require("@opentelemetry/instrumentation");
900
+ var import_instrumentation3 = require("@opentelemetry/instrumentation");
64
901
  var import_instrumentation_anthropic = require("@traceloop/instrumentation-anthropic");
65
902
  var import_instrumentation_bedrock = require("@traceloop/instrumentation-bedrock");
66
903
  var import_instrumentation_chromadb = require("@traceloop/instrumentation-chromadb");
@@ -71,152 +908,7 @@ var import_instrumentation_pinecone = require("@traceloop/instrumentation-pineco
71
908
  var import_instrumentation_qdrant = require("@traceloop/instrumentation-qdrant");
72
909
  var import_instrumentation_together = require("@traceloop/instrumentation-together");
73
910
  var import_instrumentation_vertexai = require("@traceloop/instrumentation-vertexai");
74
-
75
- // src/internal/logger.ts
76
- var import_api = require("@opentelemetry/api");
77
- var import_pino = __toESM(require("pino"), 1);
78
- var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
79
- LogLevel2[LogLevel2["NONE"] = 0] = "NONE";
80
- LogLevel2[LogLevel2["ERROR"] = 1] = "ERROR";
81
- LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
82
- LogLevel2[LogLevel2["INFO"] = 3] = "INFO";
83
- LogLevel2[LogLevel2["DEBUG"] = 4] = "DEBUG";
84
- return LogLevel2;
85
- })(LogLevel || {});
86
- var DEFAULT_LOG_LEVEL = 2 /* WARN */;
87
- var PinoLogger = class {
88
- _level = DEFAULT_LOG_LEVEL;
89
- _pinoLogger = null;
90
- constructor() {
91
- const envLevel = this.getLogLevelFromEnv();
92
- this._level = envLevel;
93
- }
94
- /**
95
- * Lazy initialization of Pino logger to ensure it's created AFTER Jest spies
96
- * are set up during tests. This prevents the pino-pretty transport from
97
- * bypassing stdout/stderr spies.
98
- */
99
- ensurePinoLogger() {
100
- if (!this._pinoLogger) {
101
- this._pinoLogger = (0, import_pino.default)({
102
- name: "Brizz",
103
- level: this.logLevelToPino(this._level),
104
- // Disable transport in test environment to allow proper spy capture
105
- transport: this.isProduction() || this.isTest() ? void 0 : {
106
- target: "pino-pretty",
107
- options: {
108
- singleLine: true,
109
- colorize: true,
110
- translateTime: "HH:MM:ss",
111
- ignore: "pid,hostname",
112
- messageFormat: "[{name}] {msg}"
113
- }
114
- }
115
- });
116
- }
117
- return this._pinoLogger;
118
- }
119
- isProduction() {
120
- return process.env["NODE_ENV"] === "production";
121
- }
122
- isTest() {
123
- return process.env["NODE_ENV"] === "test";
124
- }
125
- getLogLevelFromEnv() {
126
- const envLevel = process.env["BRIZZ_LOG_LEVEL"];
127
- return envLevel ? parseLogLevel(envLevel) : DEFAULT_LOG_LEVEL;
128
- }
129
- logLevelToPino(level) {
130
- switch (level) {
131
- case 4 /* DEBUG */:
132
- return "debug";
133
- case 3 /* INFO */:
134
- return "info";
135
- case 2 /* WARN */:
136
- return "warn";
137
- case 1 /* ERROR */:
138
- return "error";
139
- default:
140
- return "silent";
141
- }
142
- }
143
- formatMeta(meta) {
144
- if (meta.length === 0) {
145
- return {};
146
- }
147
- if (meta.length === 1 && typeof meta[0] === "object" && meta[0] !== null) {
148
- return meta[0];
149
- }
150
- return { metadata: meta };
151
- }
152
- setLevel(level) {
153
- this._level = level;
154
- if (this._pinoLogger) {
155
- this._pinoLogger.level = this.logLevelToPino(level);
156
- }
157
- }
158
- getLevel() {
159
- return this._level;
160
- }
161
- debug = (msg, ...meta) => {
162
- if (this._level >= 4 /* DEBUG */) {
163
- this.ensurePinoLogger().debug(this.formatMeta(meta), msg);
164
- }
165
- };
166
- info = (msg, ...meta) => {
167
- if (this._level >= 3 /* INFO */) {
168
- this.ensurePinoLogger().info(this.formatMeta(meta), msg);
169
- }
170
- };
171
- warn = (msg, ...meta) => {
172
- if (this._level >= 2 /* WARN */) {
173
- this.ensurePinoLogger().warn(this.formatMeta(meta), msg);
174
- }
175
- };
176
- error = (msg, ...meta) => {
177
- if (this._level >= 1 /* ERROR */) {
178
- this.ensurePinoLogger().error(this.formatMeta(meta), msg);
179
- }
180
- };
181
- };
182
- function parseLogLevel(level) {
183
- if (!level) {
184
- return DEFAULT_LOG_LEVEL;
185
- }
186
- const normalizedLevel = level.toLowerCase().trim();
187
- switch (normalizedLevel) {
188
- case "debug":
189
- return 4 /* DEBUG */;
190
- case "info":
191
- return 3 /* INFO */;
192
- case "warn":
193
- case "warning":
194
- return 2 /* WARN */;
195
- case "error":
196
- return 1 /* ERROR */;
197
- case "none":
198
- case "off":
199
- case "silent":
200
- return 0 /* NONE */;
201
- default: {
202
- const numLevel = Number.parseInt(normalizedLevel, 10);
203
- if (!Number.isNaN(numLevel) && numLevel >= 0 && numLevel <= 4) {
204
- return numLevel;
205
- }
206
- return DEFAULT_LOG_LEVEL;
207
- }
208
- }
209
- }
210
- var logger = new PinoLogger();
211
- function setLogLevel(level) {
212
- const resolvedLevel = typeof level === "string" ? parseLogLevel(level) : level;
213
- logger.setLevel(resolvedLevel);
214
- }
215
- function getLogLevel() {
216
- return logger.getLevel();
217
- }
218
-
219
- // src/internal/instrumentation/auto-init.ts
911
+ init_logger();
220
912
  var autoInstrumentationsLoaded = false;
221
913
  var exceptionLogger = (error) => {
222
914
  logger.error(`Exception in instrumentation: ${String(error)}`);
@@ -231,7 +923,7 @@ function loadNodeAutoInstrumentations() {
231
923
  // Brizz backend parser with no payload to read.
232
924
  "@opentelemetry/instrumentation-openai": { enabled: false }
233
925
  });
234
- (0, import_instrumentation.registerInstrumentations)({ instrumentations: nodeInstrumentations });
926
+ (0, import_instrumentation3.registerInstrumentations)({ instrumentations: nodeInstrumentations });
235
927
  return nodeInstrumentations;
236
928
  } catch (error) {
237
929
  logger.error(`Failed to load Node.js auto-instrumentations: ${String(error)}`);
@@ -262,13 +954,27 @@ function loadGenAIInstrumentations() {
262
954
  }
263
955
  }
264
956
  try {
265
- (0, import_instrumentation.registerInstrumentations)({ instrumentations });
957
+ (0, import_instrumentation3.registerInstrumentations)({ instrumentations });
266
958
  logger.info(`Auto-registered ${instrumentations.length} GenAI instrumentations`);
267
959
  } catch (error) {
268
960
  logger.error(`Failed to register GenAI instrumentations: ${String(error)}`);
269
961
  }
270
962
  return instrumentations;
271
963
  }
964
+ function loadMCPInstrumentation() {
965
+ void (async () => {
966
+ try {
967
+ const { MCPInstrumentation: MCPInstrumentation2 } = await Promise.resolve().then(() => (init_mcp(), mcp_exports));
968
+ const mcp = new MCPInstrumentation2({ exceptionLogger });
969
+ (0, import_instrumentation3.registerInstrumentations)({ instrumentations: [mcp] });
970
+ logger.debug("Auto-loaded MCP instrumentation");
971
+ } catch (error) {
972
+ logger.debug(
973
+ `MCP instrumentation not loaded (install @modelcontextprotocol/sdk and @arizeai/openinference-instrumentation-mcp if you want MCP support): ${String(error)}`
974
+ );
975
+ }
976
+ })();
977
+ }
272
978
  function autoInitializeInstrumentations() {
273
979
  if (autoInstrumentationsLoaded) {
274
980
  return;
@@ -276,6 +982,7 @@ function autoInitializeInstrumentations() {
276
982
  try {
277
983
  const nodeInstrumentations = loadNodeAutoInstrumentations();
278
984
  const genAIInstrumentations = loadGenAIInstrumentations();
985
+ loadMCPInstrumentation();
279
986
  autoInstrumentationsLoaded = true;
280
987
  logger.info(
281
988
  `Auto-initialization complete: ${nodeInstrumentations.length} node + ${genAIInstrumentations.length} GenAI instrumentations`
@@ -292,6 +999,7 @@ var import_resources3 = require("@opentelemetry/resources");
292
999
  var import_sdk_node = require("@opentelemetry/sdk-node");
293
1000
 
294
1001
  // src/internal/config.ts
1002
+ init_logger();
295
1003
  function resolveConfig(options) {
296
1004
  const envLogLevel = process.env["BRIZZ_LOG_LEVEL"] || options.logLevel?.toString() || DEFAULT_LOG_LEVEL.toString();
297
1005
  let resolvedLogLevel;
@@ -390,6 +1098,8 @@ var import_instrumentation_pinecone2 = require("@traceloop/instrumentation-pinec
390
1098
  var import_instrumentation_qdrant2 = require("@traceloop/instrumentation-qdrant");
391
1099
  var import_instrumentation_together2 = require("@traceloop/instrumentation-together");
392
1100
  var import_instrumentation_vertexai2 = require("@traceloop/instrumentation-vertexai");
1101
+ init_logger();
1102
+ init_mcp();
393
1103
  var InstrumentationRegistry = class _InstrumentationRegistry {
394
1104
  static instance;
395
1105
  manualModules = null;
@@ -494,6 +1204,14 @@ var InstrumentationRegistry = class _InstrumentationRegistry {
494
1204
  }
495
1205
  })();
496
1206
  }
1207
+ if (this.manualModules?.mcp) {
1208
+ try {
1209
+ new MCPInstrumentation({ exceptionLogger: exceptionLogger2 }).manuallyInstrument(this.manualModules.mcp);
1210
+ logger.debug("Manual instrumentation enabled for MCP");
1211
+ } catch (error) {
1212
+ logger.error(`Failed to apply MCP instrumentation: ${String(error)}`);
1213
+ }
1214
+ }
497
1215
  }
498
1216
  };
499
1217
 
@@ -502,15 +1220,13 @@ var import_api_logs = require("@opentelemetry/api-logs");
502
1220
  var import_exporter_logs_otlp_http = require("@opentelemetry/exporter-logs-otlp-http");
503
1221
  var import_resources = require("@opentelemetry/resources");
504
1222
  var import_sdk_logs2 = require("@opentelemetry/sdk-logs");
505
-
506
- // src/internal/version.ts
507
- function getSDKVersion() {
508
- return "0.1.20";
509
- }
1223
+ init_logger();
1224
+ init_version();
510
1225
 
511
1226
  // src/internal/log/processors/log-processor.ts
512
- var import_api3 = require("@opentelemetry/api");
1227
+ var import_api7 = require("@opentelemetry/api");
513
1228
  var import_sdk_logs = require("@opentelemetry/sdk-logs");
1229
+ init_logger();
514
1230
 
515
1231
  // src/internal/masking/patterns.ts
516
1232
  var DEFAULT_PII_PATTERNS = [
@@ -921,6 +1637,7 @@ var DEFAULT_PII_PATTERNS = [
921
1637
  ];
922
1638
 
923
1639
  // src/internal/masking/utils.ts
1640
+ init_logger();
924
1641
  function isValidPatternName(name) {
925
1642
  return /^[a-zA-Z0-9_]+$/.test(name);
926
1643
  }
@@ -1136,23 +1853,8 @@ function maskAttributes(attributes, rules, outputOriginalValue = false) {
1136
1853
  return maskedAttributes;
1137
1854
  }
1138
1855
 
1139
- // src/internal/semantic-conventions.ts
1140
- var import_api2 = require("@opentelemetry/api");
1141
- var BRIZZ = "brizz";
1142
- var PROPERTIES = "properties";
1143
- var SESSION_ID = "session.id";
1144
- var PROPERTIES_CONTEXT_KEY = (0, import_api2.createContextKey)(PROPERTIES);
1145
- var SESSION_OBJECT_CONTEXT_KEY = (0, import_api2.createContextKey)("brizz.session.object");
1146
- var SESSION_INPUT = "brizz.session.input";
1147
- var SESSION_OUTPUT = "brizz.session.output";
1148
- var SESSION_INPUT_CONTEXT = "brizz.session.input.context";
1149
- var SESSION_OUTPUT_CONTEXT = "brizz.session.output.context";
1150
- var SESSION_SPAN_NAME = "brizz.start_session";
1151
- var SESSION_TITLE_SPAN_NAME = "brizz.session_title";
1152
- var SESSION_TITLE_GENERATION = "session.title_generation";
1153
- var SESSION_TITLE = "brizz.session.title";
1154
-
1155
1856
  // src/internal/log/processors/log-processor.ts
1857
+ init_semantic_conventions();
1156
1858
  var DEFAULT_LOG_MASKING_RULES = [
1157
1859
  {
1158
1860
  mode: "partial",
@@ -1171,7 +1873,7 @@ var BrizzSimpleLogRecordProcessor = class extends import_sdk_logs.SimpleLogRecor
1171
1873
  if (maskingConfig) {
1172
1874
  maskLog(logRecord, maskingConfig);
1173
1875
  }
1174
- const associationProperties = import_api3.context.active().getValue(PROPERTIES_CONTEXT_KEY);
1876
+ const associationProperties = import_api7.context.active().getValue(PROPERTIES_CONTEXT_KEY);
1175
1877
  if (associationProperties) {
1176
1878
  for (const [key, value] of Object.entries(associationProperties)) {
1177
1879
  logRecord.setAttribute(`${BRIZZ}.${key}`, value);
@@ -1191,7 +1893,7 @@ var BrizzBatchLogRecordProcessor = class extends import_sdk_logs.BatchLogRecordP
1191
1893
  if (maskingConfig) {
1192
1894
  maskLog(logRecord, maskingConfig);
1193
1895
  }
1194
- const associationProperties = import_api3.context.active().getValue(PROPERTIES_CONTEXT_KEY);
1896
+ const associationProperties = import_api7.context.active().getValue(PROPERTIES_CONTEXT_KEY);
1195
1897
  if (associationProperties) {
1196
1898
  for (const [key, value] of Object.entries(associationProperties)) {
1197
1899
  logRecord.setAttribute(`${BRIZZ}.${key}`, value);
@@ -1410,9 +2112,13 @@ function emitEvent(name, attributes, body, severityNumber = import_api_logs.Seve
1410
2112
  return LoggingModule.getInstance().emitEvent(name, attributes, body, severityNumber);
1411
2113
  }
1412
2114
 
2115
+ // src/internal/sdk.ts
2116
+ init_logger();
2117
+
1413
2118
  // src/internal/metric/metrics.ts
1414
2119
  var import_exporter_metrics_otlp_http = require("@opentelemetry/exporter-metrics-otlp-http");
1415
2120
  var import_sdk_metrics = require("@opentelemetry/sdk-metrics");
2121
+ init_logger();
1416
2122
  var MetricsModule = class _MetricsModule {
1417
2123
  static instance = null;
1418
2124
  metricsExporter = null;
@@ -1514,10 +2220,13 @@ function getMetricsReader() {
1514
2220
 
1515
2221
  // src/internal/trace/tracing.ts
1516
2222
  var import_exporter_trace_otlp_proto = require("@opentelemetry/exporter-trace-otlp-proto");
2223
+ init_logger();
1517
2224
 
1518
2225
  // src/internal/trace/exporters/span-exporter.ts
1519
2226
  var import_core = require("@opentelemetry/core");
1520
2227
  var import_resources2 = require("@opentelemetry/resources");
2228
+ init_logger();
2229
+ init_version();
1521
2230
  var BrizzSpanExporter = class {
1522
2231
  _delegate;
1523
2232
  _brizzResource;
@@ -1584,10 +2293,12 @@ var BrizzSpanExporter = class {
1584
2293
  };
1585
2294
 
1586
2295
  // src/internal/trace/processors/span-processor.ts
1587
- var import_api4 = require("@opentelemetry/api");
2296
+ var import_api8 = require("@opentelemetry/api");
1588
2297
  var import_sdk_trace_base = require("@opentelemetry/sdk-trace-base");
2298
+ init_logger();
2299
+ init_semantic_conventions();
1589
2300
  function applyContextAttributes(span) {
1590
- const sessionProperties = import_api4.context.active().getValue(PROPERTIES_CONTEXT_KEY);
2301
+ const sessionProperties = import_api8.context.active().getValue(PROPERTIES_CONTEXT_KEY);
1591
2302
  if (sessionProperties) {
1592
2303
  for (const [key, value] of Object.entries(sessionProperties)) {
1593
2304
  span.setAttribute(`${BRIZZ}.${key}`, value);
@@ -1787,13 +2498,26 @@ function getSpanProcessor() {
1787
2498
  }
1788
2499
 
1789
2500
  // src/internal/trace/session.ts
1790
- var import_api5 = require("@opentelemetry/api");
2501
+ var import_api9 = require("@opentelemetry/api");
2502
+ init_semantic_conventions();
2503
+ function setCurrentSpanCustomProperties(properties) {
2504
+ const current = import_api9.trace.getActiveSpan();
2505
+ if (!current || !current.isRecording()) {
2506
+ return;
2507
+ }
2508
+ for (const [key, value] of Object.entries(properties)) {
2509
+ try {
2510
+ current.setAttribute(`${BRIZZ}.${key}`, value);
2511
+ } catch {
2512
+ }
2513
+ }
2514
+ }
1791
2515
  function callWithProperties(properties, fn, thisArg, ...args) {
1792
- const base = import_api5.context.active();
2516
+ const base = import_api9.context.active();
1793
2517
  const prev = base.getValue(PROPERTIES_CONTEXT_KEY);
1794
2518
  const merged = prev ? { ...prev, ...properties } : properties;
1795
2519
  const next = base.setValue(PROPERTIES_CONTEXT_KEY, merged);
1796
- return import_api5.context.with(next, fn, thisArg, ...args);
2520
+ return import_api9.context.with(next, fn, thisArg, ...args);
1797
2521
  }
1798
2522
  function withProperties(properties, fn, thisArg) {
1799
2523
  return function wrapped(...args) {
@@ -1835,9 +2559,9 @@ var Session = class {
1835
2559
  * @param text - Text to append (null becomes a null/"hide marker")
1836
2560
  * @param context - Optional per-turn context bag to attach to this turn
1837
2561
  */
1838
- setInput(text, context4) {
2562
+ setInput(text, context6) {
1839
2563
  this.inputs.push(text);
1840
- this.inputContexts.push(context4 ?? {});
2564
+ this.inputContexts.push(context6 ?? {});
1841
2565
  this.span.setAttribute(SESSION_INPUT, JSON.stringify(this.inputs));
1842
2566
  this.span.setAttribute(SESSION_INPUT_CONTEXT, JSON.stringify(this.inputContexts));
1843
2567
  }
@@ -1851,9 +2575,9 @@ var Session = class {
1851
2575
  * @param text - Text to append (null becomes a null/"hide marker")
1852
2576
  * @param context - Optional per-turn context bag to attach to this turn
1853
2577
  */
1854
- setOutput(text, context4) {
2578
+ setOutput(text, context6) {
1855
2579
  this.outputs.push(text);
1856
- this.outputContexts.push(context4 ?? {});
2580
+ this.outputContexts.push(context6 ?? {});
1857
2581
  this.span.setAttribute(SESSION_OUTPUT, JSON.stringify(this.outputs));
1858
2582
  this.span.setAttribute(SESSION_OUTPUT_CONTEXT, JSON.stringify(this.outputContexts));
1859
2583
  }
@@ -1892,12 +2616,12 @@ var SessionTitle = class {
1892
2616
  }
1893
2617
  };
1894
2618
  function getActiveSession() {
1895
- return import_api5.context.active().getValue(SESSION_OBJECT_CONTEXT_KEY);
2619
+ return import_api9.context.active().getValue(SESSION_OBJECT_CONTEXT_KEY);
1896
2620
  }
1897
2621
  function startSession(sessionId, callback, extraProperties, options) {
1898
2622
  const isTitle = options?.mode === "title";
1899
2623
  const spanName = isTitle ? SESSION_TITLE_SPAN_NAME : SESSION_SPAN_NAME;
1900
- const tracer = import_api5.trace.getTracer("@brizz/sdk");
2624
+ const tracer = import_api9.trace.getTracer("@brizz/sdk");
1901
2625
  return tracer.startActiveSpan(spanName, (span) => {
1902
2626
  span.setAttribute(`${BRIZZ}.${SESSION_ID}`, sessionId);
1903
2627
  if (extraProperties) {
@@ -1916,8 +2640,8 @@ function startSession(sessionId, callback, extraProperties, options) {
1916
2640
  }
1917
2641
  }
1918
2642
  return callWithProperties(contextProperties, () => {
1919
- const sessionCtx = import_api5.context.active().setValue(SESSION_OBJECT_CONTEXT_KEY, session);
1920
- return import_api5.context.with(sessionCtx, () => {
2643
+ const sessionCtx = import_api9.context.active().setValue(SESSION_OBJECT_CONTEXT_KEY, session);
2644
+ return import_api9.context.with(sessionCtx, () => {
1921
2645
  try {
1922
2646
  const result = callback(session);
1923
2647
  if (result && typeof result.then === "function") {
@@ -1926,7 +2650,7 @@ function startSession(sessionId, callback, extraProperties, options) {
1926
2650
  return value;
1927
2651
  }).catch((error) => {
1928
2652
  span.recordException(error);
1929
- span.setStatus({ code: import_api5.SpanStatusCode.ERROR });
2653
+ span.setStatus({ code: import_api9.SpanStatusCode.ERROR });
1930
2654
  span.end();
1931
2655
  throw error;
1932
2656
  });
@@ -1935,7 +2659,7 @@ function startSession(sessionId, callback, extraProperties, options) {
1935
2659
  return result;
1936
2660
  } catch (error) {
1937
2661
  span.recordException(error);
1938
- span.setStatus({ code: import_api5.SpanStatusCode.ERROR });
2662
+ span.setStatus({ code: import_api9.SpanStatusCode.ERROR });
1939
2663
  span.end();
1940
2664
  throw error;
1941
2665
  }
@@ -1945,7 +2669,7 @@ function startSession(sessionId, callback, extraProperties, options) {
1945
2669
  }
1946
2670
  function startSessionTitle(callback, options) {
1947
2671
  const resolvedSessionId = options?.sessionId ?? getActiveSession()?.sessionId;
1948
- const tracer = import_api5.trace.getTracer("@brizz/sdk");
2672
+ const tracer = import_api9.trace.getTracer("@brizz/sdk");
1949
2673
  return tracer.startActiveSpan(SESSION_TITLE_SPAN_NAME, (span) => {
1950
2674
  if (resolvedSessionId) {
1951
2675
  span.setAttribute(`${BRIZZ}.${SESSION_ID}`, resolvedSessionId);
@@ -1964,7 +2688,7 @@ function startSessionTitle(callback, options) {
1964
2688
  return value;
1965
2689
  }).catch((error) => {
1966
2690
  span.recordException(error);
1967
- span.setStatus({ code: import_api5.SpanStatusCode.ERROR });
2691
+ span.setStatus({ code: import_api9.SpanStatusCode.ERROR });
1968
2692
  span.end();
1969
2693
  throw error;
1970
2694
  });
@@ -1973,7 +2697,7 @@ function startSessionTitle(callback, options) {
1973
2697
  return result;
1974
2698
  } catch (error) {
1975
2699
  span.recordException(error);
1976
- span.setStatus({ code: import_api5.SpanStatusCode.ERROR });
2700
+ span.setStatus({ code: import_api9.SpanStatusCode.ERROR });
1977
2701
  span.end();
1978
2702
  throw error;
1979
2703
  }
@@ -1982,6 +2706,7 @@ function startSessionTitle(callback, options) {
1982
2706
  }
1983
2707
 
1984
2708
  // src/internal/sdk.ts
2709
+ init_version();
1985
2710
  var _Brizz = class __Brizz {
1986
2711
  static instance = null;
1987
2712
  /** Flag indicating if SDK initialization has completed successfully */
@@ -2179,9 +2904,11 @@ var _Brizz = class __Brizz {
2179
2904
  var Brizz = new _Brizz();
2180
2905
 
2181
2906
  // src/index.ts
2907
+ init_logger();
2182
2908
  var import_api_logs2 = require("@opentelemetry/api-logs");
2183
2909
 
2184
2910
  // src/node/runtime.ts
2911
+ init_logger();
2185
2912
  function detectRuntime() {
2186
2913
  const [major, minor] = process.versions.node.split(".").map(Number);
2187
2914
  const noNodeJSGlobals = typeof __filename === "undefined" && typeof __dirname === "undefined";
@@ -2251,6 +2978,7 @@ var init_exports = {};
2251
2978
  logger,
2252
2979
  maskAttributes,
2253
2980
  maskValue,
2981
+ setCurrentSpanCustomProperties,
2254
2982
  setLogLevel,
2255
2983
  startSession,
2256
2984
  startSessionTitle,