@brizz/sdk 0.1.29 → 0.1.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3080 +1,177 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropNames = Object.getOwnPropertyNames;
3
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
- }) : x)(function(x) {
6
- if (typeof require !== "undefined") return require.apply(this, arguments);
7
- throw Error('Dynamic require of "' + x + '" is not supported');
8
- });
9
- var __esm = (fn, res) => function __init() {
10
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
- };
12
- var __export = (target, all) => {
13
- for (var name in all)
14
- __defProp(target, name, { get: all[name], enumerable: true });
15
- };
16
-
17
- // src/internal/logger.ts
18
- import { DiagLogLevel } from "@opentelemetry/api";
19
- import pino from "pino";
20
- function parseLogLevel(level) {
21
- if (!level) {
22
- return DEFAULT_LOG_LEVEL;
23
- }
24
- const normalizedLevel = level.toLowerCase().trim();
25
- switch (normalizedLevel) {
26
- case "debug":
27
- return 4 /* DEBUG */;
28
- case "info":
29
- return 3 /* INFO */;
30
- case "warn":
31
- case "warning":
32
- return 2 /* WARN */;
33
- case "error":
34
- return 1 /* ERROR */;
35
- case "none":
36
- case "off":
37
- case "silent":
38
- return 0 /* NONE */;
39
- default: {
40
- const numLevel = Number.parseInt(normalizedLevel, 10);
41
- if (!Number.isNaN(numLevel) && numLevel >= 0 && numLevel <= 4) {
42
- return numLevel;
43
- }
44
- return DEFAULT_LOG_LEVEL;
45
- }
46
- }
47
- }
48
- function setLogLevel(level) {
49
- const resolvedLevel = typeof level === "string" ? parseLogLevel(level) : level;
50
- logger.setLevel(resolvedLevel);
51
- }
52
- function getLogLevel() {
53
- return logger.getLevel();
54
- }
55
- var LogLevel, DEFAULT_LOG_LEVEL, PinoLogger, logger;
56
- var init_logger = __esm({
57
- "src/internal/logger.ts"() {
58
- "use strict";
59
- LogLevel = /* @__PURE__ */ ((LogLevel2) => {
60
- LogLevel2[LogLevel2["NONE"] = 0] = "NONE";
61
- LogLevel2[LogLevel2["ERROR"] = 1] = "ERROR";
62
- LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
63
- LogLevel2[LogLevel2["INFO"] = 3] = "INFO";
64
- LogLevel2[LogLevel2["DEBUG"] = 4] = "DEBUG";
65
- return LogLevel2;
66
- })(LogLevel || {});
67
- DEFAULT_LOG_LEVEL = 2 /* WARN */;
68
- PinoLogger = class {
69
- _level = DEFAULT_LOG_LEVEL;
70
- _pinoLogger = null;
71
- constructor() {
72
- const envLevel = this.getLogLevelFromEnv();
73
- this._level = envLevel;
74
- }
75
- /**
76
- * Lazy initialization of Pino logger to ensure it's created AFTER Jest spies
77
- * are set up during tests. This prevents the pino-pretty transport from
78
- * bypassing stdout/stderr spies.
79
- */
80
- ensurePinoLogger() {
81
- if (!this._pinoLogger) {
82
- this._pinoLogger = pino({
83
- name: "Brizz",
84
- level: this.logLevelToPino(this._level),
85
- // Disable transport in test environment to allow proper spy capture
86
- transport: this.isProduction() || this.isTest() ? void 0 : {
87
- target: "pino-pretty",
88
- options: {
89
- singleLine: true,
90
- colorize: true,
91
- translateTime: "HH:MM:ss",
92
- ignore: "pid,hostname",
93
- messageFormat: "[{name}] {msg}"
94
- }
95
- }
96
- });
97
- }
98
- return this._pinoLogger;
99
- }
100
- isProduction() {
101
- return process.env["NODE_ENV"] === "production";
102
- }
103
- isTest() {
104
- return process.env["NODE_ENV"] === "test";
105
- }
106
- getLogLevelFromEnv() {
107
- const envLevel = process.env["BRIZZ_LOG_LEVEL"];
108
- return envLevel ? parseLogLevel(envLevel) : DEFAULT_LOG_LEVEL;
109
- }
110
- logLevelToPino(level) {
111
- switch (level) {
112
- case 4 /* DEBUG */:
113
- return "debug";
114
- case 3 /* INFO */:
115
- return "info";
116
- case 2 /* WARN */:
117
- return "warn";
118
- case 1 /* ERROR */:
119
- return "error";
120
- default:
121
- return "silent";
122
- }
123
- }
124
- formatMeta(meta) {
125
- if (meta.length === 0) {
126
- return {};
127
- }
128
- if (meta.length === 1 && typeof meta[0] === "object" && meta[0] !== null) {
129
- return meta[0];
130
- }
131
- return { metadata: meta };
132
- }
133
- setLevel(level) {
134
- this._level = level;
135
- if (this._pinoLogger) {
136
- this._pinoLogger.level = this.logLevelToPino(level);
137
- }
138
- }
139
- getLevel() {
140
- return this._level;
141
- }
142
- debug = (msg, ...meta) => {
143
- if (this._level >= 4 /* DEBUG */) {
144
- this.ensurePinoLogger().debug(this.formatMeta(meta), msg);
145
- }
146
- };
147
- info = (msg, ...meta) => {
148
- if (this._level >= 3 /* INFO */) {
149
- this.ensurePinoLogger().info(this.formatMeta(meta), msg);
150
- }
151
- };
152
- warn = (msg, ...meta) => {
153
- if (this._level >= 2 /* WARN */) {
154
- this.ensurePinoLogger().warn(this.formatMeta(meta), msg);
155
- }
156
- };
157
- error = (msg, ...meta) => {
158
- if (this._level >= 1 /* ERROR */) {
159
- this.ensurePinoLogger().error(this.formatMeta(meta), msg);
160
- }
161
- };
162
- };
163
- logger = new PinoLogger();
164
- }
165
- });
166
-
167
- // src/internal/instrumentation/mcp/semantic-conventions.ts
168
- var MCP_TOOL_NAME, MCP_TOOL_ARGUMENTS, MCP_TOOL_RESULT, MCP_COMPONENT_TYPE, MCP_COMPONENT_TOOL, MCP_COMPONENT_TOOL_SCHEMA, MCP_TOOL_SCHEMA_PARAMETERS, MCP_TOOL_SCHEMA_OUTPUT, MCP_TOOL_DESCRIPTION, SPAN_NAME_TOOL_REGISTER, 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_TOOLS_LIST, METHOD_RESOURCES_READ, METHOD_PROMPTS_GET, METHOD_INITIALIZE;
169
- var init_semantic_conventions = __esm({
170
- "src/internal/instrumentation/mcp/semantic-conventions.ts"() {
171
- "use strict";
172
- MCP_TOOL_NAME = "mcp.tool.name";
173
- MCP_TOOL_ARGUMENTS = "mcp.tool.arguments";
174
- MCP_TOOL_RESULT = "mcp.tool.result";
175
- MCP_COMPONENT_TYPE = "mcp.component.type";
176
- MCP_COMPONENT_TOOL = "tool";
177
- MCP_COMPONENT_TOOL_SCHEMA = "tool_schema";
178
- MCP_TOOL_SCHEMA_PARAMETERS = "mcp.tool.schema.parameters";
179
- MCP_TOOL_SCHEMA_OUTPUT = "mcp.tool.schema.output";
180
- MCP_TOOL_DESCRIPTION = "mcp.tool.description";
181
- SPAN_NAME_TOOL_REGISTER = "mcp.tool.register";
182
- MCP_METHOD_NAME = "mcp.method.name";
183
- MCP_REQUEST_ID = "mcp.request.id";
184
- MCP_SESSION_ID = "mcp.session.id";
185
- MCP_PROTOCOL_VERSION = "mcp.protocol.version";
186
- MCP_RESOURCE_URI = "mcp.resource.uri";
187
- RPC_SYSTEM = "rpc.system";
188
- RPC_SYSTEM_MCP = "mcp";
189
- RPC_RESPONSE_STATUS_CODE = "rpc.response.status_code";
190
- GEN_AI_TOOL_NAME = "gen_ai.tool.name";
191
- GEN_AI_PROMPT_NAME = "gen_ai.prompt.name";
192
- GEN_AI_OPERATION_NAME = "gen_ai.operation.name";
193
- GEN_AI_OPERATION_EXECUTE_TOOL = "execute_tool";
194
- NETWORK_TRANSPORT = "network.transport";
195
- ERROR_TYPE = "error.type";
196
- ERROR_TYPE_TOOL = "tool_error";
197
- JSONRPC_REQUEST_ID = "jsonrpc.request.id";
198
- SPAN_NAME_TOOLS_CALL = "tools/call";
199
- MAX_ATTRIBUTE_LENGTH = 32 * 1024;
200
- TRUNCATION_SUFFIX = "\u2026(truncated)";
201
- METHOD_TOOLS_CALL = "tools/call";
202
- METHOD_TOOLS_LIST = "tools/list";
203
- METHOD_RESOURCES_READ = "resources/read";
204
- METHOD_PROMPTS_GET = "prompts/get";
205
- METHOD_INITIALIZE = "initialize";
206
- }
207
- });
208
-
209
- // src/internal/instrumentation/mcp/schemas.ts
210
- import { SpanKind, SpanStatusCode } from "@opentelemetry/api";
211
- function truncateSchemaAttr(value) {
212
- if (value.length <= _MAX_SCHEMA_ATTR_BYTES) {
213
- return value;
214
- }
215
- return `{"_truncated":true,"original_length":${value.length}}`;
216
- }
217
- function safeStringify(value) {
218
- if (value === null || value === void 0) {
219
- return "";
220
- }
221
- try {
222
- return JSON.stringify(value);
223
- } catch {
224
- return "";
225
- }
226
- }
227
- function emitSchemaSpansFromListResponse(result, transportSessionId, tracer) {
228
- if (!transportSessionId) {
229
- return;
230
- }
231
- const tools = extractTools(result);
232
- if (tools === void 0) {
233
- return;
234
- }
235
- for (const tool of tools) {
236
- const name = typeof tool.name === "string" ? tool.name : void 0;
237
- if (!name) {
238
- continue;
239
- }
240
- const span = tracer.startSpan(`${SPAN_NAME_TOOL_REGISTER} ${name}`, {
241
- kind: SpanKind.INTERNAL
242
- });
243
- try {
244
- stampSchemaAttributes(span, name, transportSessionId, tool);
245
- span.setStatus({ code: SpanStatusCode.OK });
246
- } finally {
247
- span.end();
248
- }
249
- }
250
- }
251
- function stampSchemaAttributes(span, toolName, transportSessionId, tool) {
252
- if (!span.isRecording()) {
253
- logger.warn(
254
- `Brizz MCP: schema span is not recording; dropping attributes for ${toolName}`
255
- );
256
- return;
257
- }
258
- const description = typeof tool.description === "string" ? tool.description : "";
259
- const parameters = truncateSchemaAttr(safeStringify(tool.inputSchema));
260
- const outputSchema = tool.outputSchema !== void 0 && tool.outputSchema !== null ? truncateSchemaAttr(safeStringify(tool.outputSchema)) : "";
261
- span.setAttribute(RPC_SYSTEM, RPC_SYSTEM_MCP);
262
- span.setAttribute(MCP_COMPONENT_TYPE, MCP_COMPONENT_TOOL_SCHEMA);
263
- span.setAttribute(MCP_SESSION_ID, transportSessionId);
264
- span.setAttribute(MCP_TOOL_NAME, toolName);
265
- span.setAttribute(MCP_TOOL_SCHEMA_PARAMETERS, parameters);
266
- span.setAttribute(MCP_TOOL_SCHEMA_OUTPUT, outputSchema);
267
- span.setAttribute(MCP_TOOL_DESCRIPTION, description);
268
- }
269
- function extractTools(result) {
270
- if (!result || typeof result !== "object") {
271
- return void 0;
272
- }
273
- const tools = result.tools;
274
- if (!Array.isArray(tools)) {
275
- return void 0;
276
- }
277
- return tools.filter(
278
- (t) => t !== null && typeof t === "object"
279
- );
280
- }
281
- var _MAX_SCHEMA_ATTR_BYTES;
282
- var init_schemas = __esm({
283
- "src/internal/instrumentation/mcp/schemas.ts"() {
284
- "use strict";
285
- init_logger();
286
- init_semantic_conventions();
287
- _MAX_SCHEMA_ATTR_BYTES = 4e3;
288
- }
289
- });
290
-
291
- // src/internal/semantic-conventions.ts
292
- import { createContextKey } from "@opentelemetry/api";
293
- var BRIZZ, PROPERTIES, SESSION_ID, PROPERTIES_CONTEXT_KEY, SESSION_OBJECT_CONTEXT_KEY, SESSION_INPUT, SESSION_OUTPUT, SESSION_INPUT_CONTEXT, SESSION_OUTPUT_CONTEXT, SESSION_SPAN_NAME, MUTE_INPUT, MUTE_OUTPUT, SESSION_TITLE_SPAN_NAME, SESSION_TITLE_GENERATION, SESSION_TITLE, INTERRUPT_TOOLS, INTERNAL_EVENT_PREFIX, EXTERNAL_LINK_EVENT_NAME, EXTERNAL_LINK_URL, EXTERNAL_LINK_TITLE, EXTERNAL_LINK_TYPE;
294
- var init_semantic_conventions2 = __esm({
295
- "src/internal/semantic-conventions.ts"() {
296
- "use strict";
297
- BRIZZ = "brizz";
298
- PROPERTIES = "properties";
299
- SESSION_ID = "session.id";
300
- PROPERTIES_CONTEXT_KEY = createContextKey(PROPERTIES);
301
- SESSION_OBJECT_CONTEXT_KEY = createContextKey("brizz.session.object");
302
- SESSION_INPUT = "brizz.session.input";
303
- SESSION_OUTPUT = "brizz.session.output";
304
- SESSION_INPUT_CONTEXT = "brizz.session.input.context";
305
- SESSION_OUTPUT_CONTEXT = "brizz.session.output.context";
306
- SESSION_SPAN_NAME = "brizz.start_session";
307
- MUTE_INPUT = "mute.input";
308
- MUTE_OUTPUT = "mute.output";
309
- SESSION_TITLE_SPAN_NAME = "brizz.session_title";
310
- SESSION_TITLE_GENERATION = "session.title_generation";
311
- SESSION_TITLE = "brizz.session.title";
312
- INTERRUPT_TOOLS = "brizz.internal.interrupt";
313
- INTERNAL_EVENT_PREFIX = "brizz.internal.";
314
- EXTERNAL_LINK_EVENT_NAME = "brizz.internal.external_link";
315
- EXTERNAL_LINK_URL = "brizz.internal.external_link.url";
316
- EXTERNAL_LINK_TITLE = "brizz.internal.external_link.title";
317
- EXTERNAL_LINK_TYPE = "brizz.internal.external_link.type";
318
- }
319
- });
320
-
321
- // src/internal/instrumentation/mcp/session.ts
322
- import { context } from "@opentelemetry/api";
323
- function stampAndPropagateSession(span, sessionId, baseContext = context.active()) {
324
- if (!sessionId) {
325
- return { context: baseContext, sessionId: null };
326
- }
327
- if (span.isRecording()) {
328
- try {
329
- span.setAttribute(`${BRIZZ}.${SESSION_ID}`, sessionId);
330
- } catch (error) {
331
- logger.warn(
332
- `Brizz MCP: failed to stamp session id on span: ${String(error)}`
333
- );
334
- }
335
- }
336
- try {
337
- const prev = baseContext.getValue(PROPERTIES_CONTEXT_KEY);
338
- const merged = prev ? { ...prev, [SESSION_ID]: sessionId } : { [SESSION_ID]: sessionId };
339
- return {
340
- context: baseContext.setValue(PROPERTIES_CONTEXT_KEY, merged),
341
- sessionId
342
- };
343
- } catch (error) {
344
- logger.warn(`Brizz MCP: failed to attach session context: ${String(error)}`);
345
- return { context: baseContext, sessionId };
346
- }
347
- }
348
- var init_session = __esm({
349
- "src/internal/instrumentation/mcp/session.ts"() {
350
- "use strict";
351
- init_logger();
352
- init_semantic_conventions2();
353
- }
354
- });
355
-
356
- // src/internal/instrumentation/mcp/patches/attributes.ts
357
- import { SpanStatusCode as SpanStatusCode2 } from "@opentelemetry/api";
358
- function deriveSpanName(method, params) {
359
- try {
360
- if (method === METHOD_TOOLS_CALL) {
361
- const name = typeof params?.["name"] === "string" ? params["name"] : "";
362
- return name ? `${SPAN_NAME_TOOLS_CALL} ${name}` : SPAN_NAME_TOOLS_CALL;
363
- }
364
- if (method === METHOD_RESOURCES_READ) {
365
- const uri = typeof params?.["uri"] === "string" ? params["uri"] : "";
366
- return uri ? `${METHOD_RESOURCES_READ} ${uri}` : METHOD_RESOURCES_READ;
367
- }
368
- if (method === METHOD_PROMPTS_GET) {
369
- const name = typeof params?.["name"] === "string" ? params["name"] : "";
370
- return name ? `${METHOD_PROMPTS_GET} ${name}` : METHOD_PROMPTS_GET;
371
- }
372
- return method;
373
- } catch {
374
- return method || "mcp";
375
- }
376
- }
377
- function applyBaseAttributes(span, request) {
378
- span.setAttribute(RPC_SYSTEM, RPC_SYSTEM_MCP);
379
- if (request.method) {
380
- span.setAttribute(MCP_METHOD_NAME, request.method);
381
- }
382
- if (request.id !== void 0 && request.id !== null) {
383
- const id = String(request.id);
384
- span.setAttribute(MCP_REQUEST_ID, id);
385
- span.setAttribute(JSONRPC_REQUEST_ID, id);
386
- }
387
- }
388
- function applyClientRequestAttributes(span, request, transportName) {
389
- applyBaseAttributes(span, request);
390
- applyMethodSpecificRequestAttributes(span, request);
391
- if (transportName) {
392
- const transport = normalizeTransport(transportName);
393
- if (transport) {
394
- span.setAttribute(NETWORK_TRANSPORT, transport);
395
- }
396
- }
397
- }
398
- function applyServerRequestAttributes(span, request, protocol) {
399
- applyBaseAttributes(span, request);
400
- applyMethodSpecificRequestAttributes(span, request);
401
- if (request.method === METHOD_TOOLS_CALL) {
402
- const args = request.params?.["arguments"];
403
- if (args !== void 0) {
404
- span.setAttribute(MCP_TOOL_ARGUMENTS, serializeForAttribute(args));
405
- }
406
- }
407
- const sessionId = protocol.sessionId ?? protocol._transport?.sessionId;
408
- if (sessionId) {
409
- span.setAttribute(MCP_SESSION_ID, String(sessionId));
410
- }
411
- }
412
- function applyMethodSpecificRequestAttributes(span, request) {
413
- const params = request.params ?? {};
414
- switch (request.method) {
415
- case METHOD_TOOLS_CALL: {
416
- const name = typeof params["name"] === "string" ? params["name"] : "";
417
- if (name) {
418
- span.setAttribute(MCP_TOOL_NAME, name);
419
- span.setAttribute(GEN_AI_TOOL_NAME, name);
420
- }
421
- span.setAttribute(MCP_COMPONENT_TYPE, MCP_COMPONENT_TOOL);
422
- span.setAttribute(GEN_AI_OPERATION_NAME, GEN_AI_OPERATION_EXECUTE_TOOL);
423
- break;
424
- }
425
- case METHOD_RESOURCES_READ: {
426
- const uri = typeof params["uri"] === "string" ? params["uri"] : "";
427
- if (uri) {
428
- span.setAttribute(MCP_RESOURCE_URI, uri);
429
- }
430
- break;
431
- }
432
- case METHOD_PROMPTS_GET: {
433
- const name = typeof params["name"] === "string" ? params["name"] : "";
434
- if (name) {
435
- span.setAttribute(GEN_AI_PROMPT_NAME, name);
436
- }
437
- break;
438
- }
439
- default:
440
- break;
441
- }
442
- }
443
- function applyResultAttributes(span, method, result) {
444
- if (method === METHOD_INITIALIZE && result && typeof result === "object") {
445
- const protocolVersion = result["protocolVersion"];
446
- if (typeof protocolVersion === "string") {
447
- span.setAttribute(MCP_PROTOCOL_VERSION, protocolVersion);
448
- }
449
- return;
450
- }
451
- if (method !== METHOD_TOOLS_CALL) {
452
- return;
453
- }
454
- const obj = result && typeof result === "object" ? result : null;
455
- const content = obj?.["content"] ?? result;
456
- span.setAttribute(MCP_TOOL_RESULT, serializeForAttribute(content));
457
- if (obj && obj["isError"] === true) {
458
- span.setAttribute(ERROR_TYPE, ERROR_TYPE_TOOL);
459
- const message = extractToolErrorMessage(obj);
460
- span.setStatus({ code: SpanStatusCode2.ERROR, message });
461
- }
462
- }
463
- function applyErrorAttributes(span, err) {
464
- const error = err;
465
- const code = error?.code;
466
- if (typeof code === "number") {
467
- span.setAttribute(RPC_RESPONSE_STATUS_CODE, code);
468
- span.setAttribute(ERROR_TYPE, String(code));
469
- } else if (error?.name === "AbortError") {
470
- span.setAttribute(ERROR_TYPE, "cancelled");
471
- } else if (error?.name === "TimeoutError") {
472
- span.setAttribute(ERROR_TYPE, "timeout");
473
- } else {
474
- span.setAttribute(
475
- ERROR_TYPE,
476
- error?.constructor?.name || error?.name || "Error"
477
- );
478
- }
479
- try {
480
- span.recordException(error);
481
- } catch {
482
- }
483
- span.setStatus({
484
- code: SpanStatusCode2.ERROR,
485
- message: typeof error?.message === "string" ? error.message : void 0
486
- });
487
- }
488
- function serializeForAttribute(value) {
489
- const raw = rawSerialize(value);
490
- if (raw.length <= MAX_ATTRIBUTE_LENGTH) {
491
- return raw;
492
- }
493
- return raw.slice(0, MAX_ATTRIBUTE_LENGTH - TRUNCATION_SUFFIX.length) + TRUNCATION_SUFFIX;
494
- }
495
- function rawSerialize(value) {
496
- if (value === null || value === void 0) {
497
- return "";
498
- }
499
- if (typeof value === "string") {
500
- return value;
501
- }
502
- try {
503
- return JSON.stringify(value);
504
- } catch {
505
- try {
506
- if (value === null || value === void 0) {
507
- return "";
508
- }
509
- const tag = Object.prototype.toString.call(value);
510
- return typeof value.toString === "function" ? (
511
- // eslint-disable-next-line @typescript-eslint/no-base-to-string
512
- String(value)
513
- ) : tag;
514
- } catch {
515
- return "";
516
- }
517
- }
518
- }
519
- function extractToolErrorMessage(result) {
520
- const content = result["content"];
521
- if (Array.isArray(content)) {
522
- for (const item of content) {
523
- if (item && typeof item === "object") {
524
- const text = item["text"];
525
- if (typeof text === "string") {
526
- return text;
527
- }
528
- }
529
- }
530
- }
531
- return void 0;
532
- }
533
- function normalizeTransport(ctorName) {
534
- const name = ctorName.toLowerCase();
535
- if (name.includes("stdio")) {
536
- return "stdio";
537
- }
538
- if (name.includes("sse")) {
539
- return "sse";
540
- }
541
- if (name.includes("streamablehttp") || name.includes("http")) {
542
- return "http";
543
- }
544
- return null;
545
- }
546
- var init_attributes = __esm({
547
- "src/internal/instrumentation/mcp/patches/attributes.ts"() {
548
- "use strict";
549
- init_semantic_conventions();
550
- }
551
- });
552
-
553
- // src/internal/instrumentation/mcp/patches/protocol.ts
554
- import { context as context2, propagation, SpanKind as SpanKind2, trace } from "@opentelemetry/api";
555
- function patchProtocolPrototype(prototype, tracer) {
556
- if (!prototype || typeof prototype !== "object") {
557
- return false;
558
- }
559
- const proto = prototype;
560
- if (proto[PATCHED_FLAG]) {
561
- logger.debug("Brizz MCP: Protocol.prototype already patched, skipping");
562
- return false;
563
- }
564
- const originalRequest = proto["request"];
565
- const originalOnRequest = proto["_onrequest"];
566
- if (typeof originalRequest === "function") {
567
- proto["request"] = wrapRequest(originalRequest, tracer);
568
- } else {
569
- logger.debug(
570
- "Brizz MCP: Protocol.prototype.request missing \u2014 skipping CLIENT patch"
571
- );
572
- }
573
- if (typeof originalOnRequest === "function") {
574
- proto["_onrequest"] = wrapOnRequest(
575
- originalOnRequest,
576
- tracer
577
- );
578
- } else {
579
- logger.debug(
580
- "Brizz MCP: Protocol.prototype._onrequest missing \u2014 skipping SERVER patch"
581
- );
582
- }
583
- proto[PATCHED_FLAG] = true;
584
- return true;
585
- }
586
- function wrapRequest(original, tracer) {
587
- return function wrappedRequest(...args) {
588
- const request = args[0];
589
- if (!request || typeof request !== "object" || !request.method) {
590
- return original.apply(this, args);
591
- }
592
- const span = safeStartClientSpan(tracer, request, this);
593
- if (!span) {
594
- return original.apply(this, args);
595
- }
596
- return executeAroundSpan(span, request.method, () => {
597
- const ctx = trace.setSpan(context2.active(), span);
598
- return context2.with(ctx, () => original.apply(this, args));
599
- });
600
- };
601
- }
602
- function wrapOnRequest(original, tracer) {
603
- return function wrappedOnRequest(...args) {
604
- const request = args[0];
605
- if (!request || typeof request !== "object" || !request.method) {
606
- return original.apply(this, args);
607
- }
608
- const handlers = this._requestHandlers;
609
- if (!handlers || typeof handlers.get !== "function") {
610
- return original.apply(this, args);
611
- }
612
- const method = request.method;
613
- const handler = handlers.get(method) ?? this.fallbackRequestHandler;
614
- if (!handler) {
615
- return original.apply(this, args);
616
- }
617
- const started = safeStartServerSpan(tracer, request, this);
618
- if (!started) {
619
- return original.apply(this, args);
620
- }
621
- const { span, spanCtx } = started;
622
- const transportSessionId = this.sessionId ?? this._transport?.sessionId;
623
- const postResult = method === METHOD_TOOLS_LIST ? (result) => {
624
- try {
625
- emitSchemaSpansFromListResponse(result, transportSessionId, tracer);
626
- } catch (error) {
627
- logger.warn(
628
- `Brizz MCP: failed to emit tools/list schema spans: ${String(error)}`
629
- );
630
- }
631
- } : void 0;
632
- const wrappedHandler = (req, extra) => context2.with(
633
- spanCtx,
634
- () => executeHandler(span, method, handler, req, extra, postResult)
635
- );
636
- const hadEntry = handlers.has(method);
637
- const prev = handlers.get(method);
638
- handlers.set(method, wrappedHandler);
639
- const usedFallback = !hadEntry && this.fallbackRequestHandler === handler;
640
- const fallbackPrev = usedFallback ? this.fallbackRequestHandler : void 0;
641
- if (usedFallback) {
642
- this.fallbackRequestHandler = wrappedHandler;
643
- }
644
- try {
645
- return original.apply(this, args);
646
- } finally {
647
- if (hadEntry) {
648
- handlers.set(method, prev);
649
- } else {
650
- handlers.delete(method);
651
- }
652
- if (usedFallback) {
653
- this.fallbackRequestHandler = fallbackPrev;
654
- }
655
- }
656
- };
657
- }
658
- function executeAroundSpan(span, method, run, postResult) {
659
- let result;
660
- try {
661
- result = run();
662
- } catch (error) {
663
- safeApplyErrorAttributes(span, error);
664
- safeEnd(span);
665
- throw error;
666
- }
667
- if (!isThenable(result)) {
668
- safeApplyResultAttributes(span, method, result);
669
- if (postResult) {
670
- postResult(result);
671
- }
672
- safeEnd(span);
673
- return result;
674
- }
675
- return result.then(
676
- (value) => {
677
- safeApplyResultAttributes(span, method, value);
678
- if (postResult) {
679
- postResult(value);
680
- }
681
- safeEnd(span);
682
- return value;
683
- },
684
- (error) => {
685
- safeApplyErrorAttributes(span, error);
686
- safeEnd(span);
687
- throw error;
688
- }
689
- );
690
- }
691
- function executeHandler(span, method, handler, req, extra, postResult) {
692
- return executeAroundSpan(span, method, () => handler(req, extra), postResult);
693
- }
694
- function safeStartClientSpan(tracer, request, protocol) {
695
- try {
696
- const spanName = deriveSpanName(request.method, request.params);
697
- const span = tracer.startSpan(spanName, { kind: SpanKind2.CLIENT });
698
- applyClientRequestAttributes(
699
- span,
700
- request,
701
- protocol._transport?.constructor?.name
702
- );
703
- return span;
704
- } catch (error) {
705
- logger.debug(`Brizz MCP: failed to open CLIENT span: ${String(error)}`);
706
- return null;
707
- }
708
- }
709
- function safeStartServerSpan(tracer, request, protocol) {
710
- try {
711
- const parentCtx = extractParentContext(request);
712
- const spanName = deriveSpanName(request.method, request.params);
713
- const span = tracer.startSpan(
714
- spanName,
715
- { kind: SpanKind2.SERVER },
716
- parentCtx
717
- );
718
- applyServerRequestAttributes(span, request, protocol);
719
- const sessionId = protocol.sessionId ?? protocol._transport?.sessionId;
720
- const { context: sessCtx } = stampAndPropagateSession(span, sessionId, parentCtx);
721
- return { span, spanCtx: trace.setSpan(sessCtx, span) };
722
- } catch (error) {
723
- logger.debug(`Brizz MCP: failed to open SERVER span: ${String(error)}`);
724
- return null;
725
- }
726
- }
727
- function extractParentContext(request) {
728
- try {
729
- const meta = request.params?._meta;
730
- if (meta && typeof meta === "object") {
731
- return propagation.extract(context2.active(), meta);
732
- }
733
- } catch (error) {
734
- logger.debug(
735
- `Brizz MCP: failed to extract parent context from _meta: ${String(error)}`
736
- );
737
- }
738
- return context2.active();
739
- }
740
- function isThenable(value) {
741
- return !!value && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
742
- }
743
- function safeApplyResultAttributes(span, method, value) {
744
- try {
745
- applyResultAttributes(span, method, value);
746
- } catch (error) {
747
- logger.debug(
748
- `Brizz MCP: failed to apply result attributes: ${String(error)}`
749
- );
750
- }
751
- }
752
- function safeApplyErrorAttributes(span, err) {
753
- try {
754
- applyErrorAttributes(span, err);
755
- } catch (error) {
756
- logger.debug(
757
- `Brizz MCP: failed to apply error attributes: ${String(error)}`
758
- );
759
- }
760
- }
761
- function safeEnd(span) {
762
- try {
763
- span.end();
764
- } catch (error) {
765
- logger.debug(`Brizz MCP: failed to end span: ${String(error)}`);
766
- }
767
- }
768
- var PATCHED_FLAG;
769
- var init_protocol = __esm({
770
- "src/internal/instrumentation/mcp/patches/protocol.ts"() {
771
- "use strict";
772
- init_logger();
773
- init_schemas();
774
- init_semantic_conventions();
775
- init_session();
776
- init_attributes();
777
- PATCHED_FLAG = /* @__PURE__ */ Symbol("brizz.mcp.protocol-patched");
778
- }
779
- });
780
-
781
- // src/internal/version.ts
782
- function getSDKVersion() {
783
- return "0.1.29";
784
- }
785
- var init_version = __esm({
786
- "src/internal/version.ts"() {
787
- "use strict";
788
- }
789
- });
790
-
791
- // src/internal/instrumentation/mcp/version.ts
792
- var INSTRUMENTATION_NAME, INSTRUMENTATION_VERSION;
793
- var init_version2 = __esm({
794
- "src/internal/instrumentation/mcp/version.ts"() {
795
- "use strict";
796
- init_version();
797
- INSTRUMENTATION_NAME = "@brizz/sdk/mcp";
798
- INSTRUMENTATION_VERSION = getSDKVersion();
799
- }
800
- });
801
-
802
- // src/internal/instrumentation/mcp/instrumentation.ts
803
- import { MCPInstrumentation as BaseMCPInstrumentation } from "@arizeai/openinference-instrumentation-mcp";
804
- import { trace as trace2 } from "@opentelemetry/api";
805
- import { InstrumentationNodeModuleDefinition } from "@opentelemetry/instrumentation";
806
- function isMCPInstrumentation(value) {
807
- return !!value && typeof value === "object" && typeof value.instrumentationName === "string";
808
- }
809
- var PROTOCOL_MODULE_NAME, PROTOCOL_SUPPORTED_VERSIONS, MCPInstrumentation;
810
- var init_instrumentation = __esm({
811
- "src/internal/instrumentation/mcp/instrumentation.ts"() {
812
- "use strict";
813
- init_logger();
814
- init_protocol();
815
- init_version2();
816
- PROTOCOL_MODULE_NAME = "@modelcontextprotocol/sdk/shared/protocol.js";
817
- PROTOCOL_SUPPORTED_VERSIONS = [">=1.0.0 <2"];
818
- MCPInstrumentation = class extends BaseMCPInstrumentation {
819
- /**
820
- * Dedicated Brizz-named tracer for our SERVER + CLIENT spans.
821
- *
822
- * Why a separate tracer from the parent class's one: Arize's inherited
823
- * transport patches don't emit spans (they only inject propagation
824
- * headers), so using our own tracer here keeps Brizz spans attributed to
825
- * `@brizz/sdk/mcp` in the dashboard. The parent's `tracer` is a
826
- * `protected get` (no setter), so fighting it with assignment is the
827
- * wrong tool.
828
- */
829
- brizzTracer;
830
- constructor(_config) {
831
- super({ instrumentationConfig: _config?.instrumentationConfig });
832
- this.brizzTracer = trace2.getTracer(INSTRUMENTATION_NAME, INSTRUMENTATION_VERSION);
833
- }
834
- /**
835
- * Extend `super.init()` with our protocol-layer module definition.
836
- *
837
- * Arize's `init()` returns definitions for the six transport modules
838
- * (SSE client/server, stdio client/server, streamable-HTTP client/server)
839
- * whose `send`/`start` methods get patched for W3C trace-context
840
- * injection. We append one more: `@modelcontextprotocol/sdk/shared/protocol.js`
841
- * where our patches open SERVER/CLIENT spans around the handler + outgoing
842
- * request. If `super.init()` throws (unlikely but possible across Arize
843
- * versions), we gracefully degrade to protocol-only instrumentation.
844
- *
845
- * The cast at the end satisfies the parent's strongly-typed generic
846
- * without leaking the cast into call sites.
847
- */
848
- init() {
849
- let base;
850
- try {
851
- base = super.init() ?? [];
852
- } catch (error) {
853
- logger.warn(
854
- `Brizz MCP: base Arize init() failed \u2014 transport context propagation disabled: ${String(error)}`
855
- );
856
- base = [];
857
- }
858
- const baseArr = Array.isArray(base) ? base : [base];
859
- const brizzDef = new InstrumentationNodeModuleDefinition(
860
- PROTOCOL_MODULE_NAME,
861
- PROTOCOL_SUPPORTED_VERSIONS,
862
- (module2) => {
863
- this.patchProtocolModule(module2);
864
- return module2;
865
- },
866
- (module2) => {
867
- this.unpatchProtocolModule(module2);
868
- return module2;
869
- }
870
- );
871
- return [...baseArr, brizzDef];
872
- }
873
- /**
874
- * Manually instrument MCP modules for Next.js/Webpack where the
875
- * auto-instrumentation module-load hook doesn't fire.
876
- *
877
- * Forwards the six transport module fields to the inherited Arize
878
- * `manuallyInstrument(...)` (context propagation) and applies our
879
- * protocol patch if `protocolModule` is provided (SERVER/CLIENT spans).
880
- * Both legs are try/catch-guarded — a failure in one shouldn't prevent
881
- * the other from taking effect.
882
- */
883
- manuallyInstrument(modules) {
884
- const {
885
- clientSSEModule,
886
- serverSSEModule,
887
- clientStdioModule,
888
- serverStdioModule,
889
- clientStreamableHTTPModule,
890
- serverStreamableHTTPModule,
891
- protocolModule
892
- } = modules;
893
- try {
894
- super.manuallyInstrument({
895
- clientSSEModule,
896
- serverSSEModule,
897
- clientStdioModule,
898
- serverStdioModule,
899
- clientStreamableHTTPModule,
900
- serverStreamableHTTPModule
901
- });
902
- } catch (error) {
903
- logger.warn(`Brizz MCP: Arize manuallyInstrument(...) failed: ${String(error)}`);
904
- }
905
- if (protocolModule) {
906
- try {
907
- this.patchProtocolModule(protocolModule);
908
- } catch (error) {
909
- logger.warn(
910
- `Brizz MCP: failed to manually patch Protocol module: ${String(error)}`
911
- );
912
- }
913
- }
914
- }
915
- /**
916
- * Apply the SERVER + CLIENT patch to a loaded `protocol.js` module. Shared
917
- * by both the automatic module-load callback in `init()` and the manual
918
- * `manuallyInstrument(...)` path above so there's exactly one place that
919
- * calls `patchProtocolPrototype`.
920
- */
921
- patchProtocolModule(module2) {
922
- const proto = module2?.Protocol?.prototype;
923
- if (!proto) {
924
- logger.debug(
925
- "Brizz MCP: module does not expose Protocol.prototype \u2014 skipping protocol patches"
926
- );
927
- return;
928
- }
929
- const ok = patchProtocolPrototype(proto, this.brizzTracer);
930
- if (ok) {
931
- logger.debug("Brizz MCP: patched Protocol.prototype for SERVER+CLIENT spans");
932
- }
933
- }
934
- /**
935
- * Unpatch is intentionally a no-op.
936
- *
937
- * `patchProtocolPrototype` wraps methods in place and sets a PATCHED_FLAG
938
- * Symbol on the prototype to prevent double-patching. Restoring the
939
- * originals would require us to hold references across module unloads,
940
- * which isn't a pattern we need — instrumentation rarely gets torn down
941
- * at runtime, and a process reload is the canonical way to detach.
942
- */
943
- unpatchProtocolModule(_module) {
944
- logger.debug(
945
- "Brizz MCP: unpatch is a no-op \u2014 reload the process to cleanly detach"
946
- );
947
- }
948
- };
949
- }
950
- });
951
-
952
- // src/internal/instrumentation/mcp/index.ts
953
- var mcp_exports = {};
954
- __export(mcp_exports, {
955
- MCPInstrumentation: () => MCPInstrumentation,
956
- isMCPInstrumentation: () => isMCPInstrumentation
957
- });
958
- var init_mcp = __esm({
959
- "src/internal/instrumentation/mcp/index.ts"() {
960
- "use strict";
961
- init_instrumentation();
962
- }
963
- });
964
-
965
- // src/internal/instrumentation/vercel-ai/interrupt.ts
966
- var interrupt_exports = {};
967
- __export(interrupt_exports, {
968
- InterruptPropagator: () => InterruptPropagator,
969
- _resetInterruptState: () => _resetInterruptState,
970
- createInterruptIntegration: () => createInterruptIntegration
971
- });
972
- import { trace as trace3 } from "@opentelemetry/api";
973
- function isInnerLLMSpan(span) {
974
- if (INNER_OPERATION_IDS.has(span.name)) {
975
- return true;
976
- }
977
- const opId = span.attributes["ai.operationId"];
978
- return typeof opId === "string" && INNER_OPERATION_IDS.has(opId);
979
- }
980
- function setPending(parentSpanId, value) {
981
- pendingByParentSpanId.set(parentSpanId, value);
982
- while (pendingByParentSpanId.size > MAX_PENDING_ENTRIES) {
983
- const oldest = pendingByParentSpanId.keys().next().value;
984
- if (oldest === void 0) {
985
- break;
986
- }
987
- pendingByParentSpanId.delete(oldest);
988
- }
989
- }
990
- function extractInterruptTools(tools) {
991
- if (!tools || typeof tools !== "object") {
992
- return [];
993
- }
994
- return Object.entries(tools).filter(
995
- ([, t]) => !!t && typeof t === "object" && t.needsApproval
996
- ).map(([name]) => name);
997
- }
998
- function createInterruptIntegration() {
999
- const onStepStart = (event) => {
1000
- const names = extractInterruptTools(event.tools);
1001
- if (names.length === 0) {
1002
- return;
1003
- }
1004
- const value = JSON.stringify(names);
1005
- const span = trace3.getActiveSpan();
1006
- if (!span) {
1007
- return;
1008
- }
1009
- span.setAttribute(INTERRUPT_TOOLS, value);
1010
- setPending(span.spanContext().spanId, value);
1011
- };
1012
- return {
1013
- onStepStart
1014
- };
1015
- }
1016
- function _resetInterruptState() {
1017
- if (process.env["NODE_ENV"] !== "test") {
1018
- return;
1019
- }
1020
- pendingByParentSpanId.clear();
1021
- }
1022
- var INNER_OPERATION_IDS, MAX_PENDING_ENTRIES, pendingByParentSpanId, InterruptPropagator;
1023
- var init_interrupt = __esm({
1024
- "src/internal/instrumentation/vercel-ai/interrupt.ts"() {
1025
- "use strict";
1026
- init_semantic_conventions2();
1027
- INNER_OPERATION_IDS = /* @__PURE__ */ new Set([
1028
- "ai.generateText.doGenerate",
1029
- "ai.streamText.doStream"
1030
- ]);
1031
- MAX_PENDING_ENTRIES = 1024;
1032
- pendingByParentSpanId = /* @__PURE__ */ new Map();
1033
- InterruptPropagator = class {
1034
- onStart(span, _parentContext) {
1035
- if (!isInnerLLMSpan(span)) {
1036
- return;
1037
- }
1038
- const parentSpanId = span.parentSpanContext?.spanId;
1039
- if (!parentSpanId) {
1040
- return;
1041
- }
1042
- const value = pendingByParentSpanId.get(parentSpanId);
1043
- if (!value) {
1044
- return;
1045
- }
1046
- span.setAttribute(INTERRUPT_TOOLS, value);
1047
- pendingByParentSpanId.delete(parentSpanId);
1048
- }
1049
- onEnd() {
1050
- }
1051
- async shutdown() {
1052
- }
1053
- async forceFlush() {
1054
- }
1055
- };
1056
- }
1057
- });
1058
-
1059
- // src/internal/instrumentation/auto-init.ts
1060
- init_logger();
1061
- import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";
1062
- import { registerInstrumentations } from "@opentelemetry/instrumentation";
1063
- import { AnthropicInstrumentation } from "@traceloop/instrumentation-anthropic";
1064
- import { BedrockInstrumentation } from "@traceloop/instrumentation-bedrock";
1065
- import { ChromaDBInstrumentation } from "@traceloop/instrumentation-chromadb";
1066
- import { CohereInstrumentation } from "@traceloop/instrumentation-cohere";
1067
- import { LlamaIndexInstrumentation } from "@traceloop/instrumentation-llamaindex";
1068
- import { OpenAIInstrumentation } from "@traceloop/instrumentation-openai";
1069
- import { PineconeInstrumentation } from "@traceloop/instrumentation-pinecone";
1070
- import { QdrantInstrumentation } from "@traceloop/instrumentation-qdrant";
1071
- import { TogetherInstrumentation } from "@traceloop/instrumentation-together";
1072
- import { VertexAIInstrumentation } from "@traceloop/instrumentation-vertexai";
1073
- var autoInstrumentationsLoaded = false;
1074
- var exceptionLogger = (error) => {
1075
- logger.error(`Exception in instrumentation: ${String(error)}`);
1076
- };
1077
- function loadNodeAutoInstrumentations() {
1078
- try {
1079
- const nodeInstrumentations = getNodeAutoInstrumentations({
1080
- // Disabled because @traceloop/instrumentation-openai wraps the same OpenAI
1081
- // prototype with richer span attributes (gen_ai.input.messages /
1082
- // gen_ai.output.messages). Leaving both enabled lets the official one win
1083
- // and route content to log events instead of span attributes, leaving the
1084
- // Brizz backend parser with no payload to read.
1085
- "@opentelemetry/instrumentation-openai": { enabled: false }
1086
- });
1087
- registerInstrumentations({ instrumentations: nodeInstrumentations });
1088
- return nodeInstrumentations;
1089
- } catch (error) {
1090
- logger.error(`Failed to load Node.js auto-instrumentations: ${String(error)}`);
1091
- return [];
1092
- }
1093
- }
1094
- function loadGenAIInstrumentations() {
1095
- const instrumentations = [];
1096
- const genAIInstrumentationClasses = [
1097
- { class: OpenAIInstrumentation, name: "OpenAI" },
1098
- { class: AnthropicInstrumentation, name: "Anthropic" },
1099
- { class: CohereInstrumentation, name: "Cohere" },
1100
- { class: VertexAIInstrumentation, name: "Vertex AI" },
1101
- { class: BedrockInstrumentation, name: "Bedrock" },
1102
- { class: PineconeInstrumentation, name: "Pinecone" },
1103
- { class: LlamaIndexInstrumentation, name: "LlamaIndex" },
1104
- { class: ChromaDBInstrumentation, name: "ChromaDB" },
1105
- { class: QdrantInstrumentation, name: "Qdrant" },
1106
- { class: TogetherInstrumentation, name: "Together" }
1107
- ];
1108
- for (const config of genAIInstrumentationClasses) {
1109
- try {
1110
- const instrumentation = new config.class({ exceptionLogger });
1111
- instrumentations.push(instrumentation);
1112
- logger.debug(`Auto-loaded ${config.name} instrumentation`);
1113
- } catch (error) {
1114
- logger.error(`Failed to auto-load ${config.name} instrumentation: ${String(error)}`);
1115
- }
1116
- }
1117
- try {
1118
- registerInstrumentations({ instrumentations });
1119
- logger.info(`Auto-registered ${instrumentations.length} GenAI instrumentations`);
1120
- } catch (error) {
1121
- logger.error(`Failed to register GenAI instrumentations: ${String(error)}`);
1122
- }
1123
- return instrumentations;
1124
- }
1125
- function loadMCPInstrumentation() {
1126
- void (async () => {
1127
- try {
1128
- const { MCPInstrumentation: MCPInstrumentation2 } = await Promise.resolve().then(() => (init_mcp(), mcp_exports));
1129
- const mcp = new MCPInstrumentation2({ exceptionLogger });
1130
- registerInstrumentations({ instrumentations: [mcp] });
1131
- logger.debug("Auto-loaded MCP instrumentation");
1132
- } catch (error) {
1133
- logger.debug(
1134
- `MCP instrumentation not loaded (install @modelcontextprotocol/sdk and @arizeai/openinference-instrumentation-mcp if you want MCP support): ${String(error)}`
1135
- );
1136
- }
1137
- })();
1138
- }
1139
- function loadVercelAIInterruptIntegration() {
1140
- void (async () => {
1141
- try {
1142
- const ai = await import("ai");
1143
- if (typeof ai.registerTelemetryIntegration !== "function") {
1144
- logger.debug(
1145
- "AI SDK present but lacks registerTelemetryIntegration (needs ai@>=6); skipping interrupt bridge"
1146
- );
1147
- return;
1148
- }
1149
- const { createInterruptIntegration: createInterruptIntegration2 } = await Promise.resolve().then(() => (init_interrupt(), interrupt_exports));
1150
- ai.registerTelemetryIntegration(createInterruptIntegration2());
1151
- logger.debug("Auto-loaded Vercel AI interrupt bridge");
1152
- } catch (error) {
1153
- logger.debug(
1154
- `Vercel AI interrupt bridge not loaded (install ai@>=6 if you want HITL attribution): ${String(error)}`
1155
- );
1156
- }
1157
- })();
1158
- }
1159
- function autoInitializeInstrumentations() {
1160
- if (autoInstrumentationsLoaded) {
1161
- return;
1162
- }
1163
- try {
1164
- const nodeInstrumentations = loadNodeAutoInstrumentations();
1165
- const genAIInstrumentations = loadGenAIInstrumentations();
1166
- loadMCPInstrumentation();
1167
- loadVercelAIInterruptIntegration();
1168
- autoInstrumentationsLoaded = true;
1169
- logger.info(
1170
- `Auto-initialization complete: ${nodeInstrumentations.length} node + ${genAIInstrumentations.length} GenAI instrumentations`
1171
- );
1172
- } catch (error) {
1173
- logger.error(`Auto-initialization failed: ${String(error)}`);
1174
- autoInstrumentationsLoaded = false;
1175
- }
1176
- }
1177
- autoInitializeInstrumentations();
1178
-
1179
- // src/internal/sdk.ts
1180
- import { resourceFromAttributes as resourceFromAttributes3 } from "@opentelemetry/resources";
1181
- import { NodeSDK } from "@opentelemetry/sdk-node";
1182
-
1183
- // src/internal/dsn.ts
1184
- var PLACEHOLDER_SERVICE = "<service-name>";
1185
- var SERVICE_NAME_HEADER = "X-Brizz-Service-Name";
1186
- function parseDSN(dsn) {
1187
- let parsed;
1188
- try {
1189
- parsed = new globalThis.URL(dsn);
1190
- } catch {
1191
- return null;
1192
- }
1193
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:" || !parsed.username || !parsed.host) {
1194
- return null;
1195
- }
1196
- const scheme = parsed.protocol === "https:" ? "https" : "http";
1197
- let service;
1198
- try {
1199
- service = decodeURIComponent(parsed.pathname.replace(/^\//, ""));
1200
- } catch {
1201
- return null;
1202
- }
1203
- if (service === "" || service === PLACEHOLDER_SERVICE) {
1204
- return null;
1205
- }
1206
- return {
1207
- scheme,
1208
- host: parsed.host,
1209
- bearer: decodeURIComponent(parsed.username),
1210
- service,
1211
- baseUrl: `${scheme}://${parsed.host}`
1212
- };
1213
- }
1214
-
1215
- // src/internal/config.ts
1216
- init_logger();
1217
- function resolveConfig(options) {
1218
- const envLogLevel = process.env["BRIZZ_LOG_LEVEL"] || options.logLevel?.toString() || DEFAULT_LOG_LEVEL.toString();
1219
- let resolvedLogLevel;
1220
- if (envLogLevel) {
1221
- resolvedLogLevel = parseLogLevel(envLogLevel);
1222
- } else if (typeof options.logLevel === "string") {
1223
- resolvedLogLevel = parseLogLevel(options.logLevel);
1224
- } else {
1225
- resolvedLogLevel = options.logLevel || DEFAULT_LOG_LEVEL;
1226
- }
1227
- setLogLevel(resolvedLogLevel);
1228
- let maskingStatus;
1229
- if (options.masking === true) {
1230
- maskingStatus = "enabled";
1231
- } else if (options.masking === false) {
1232
- maskingStatus = "disabled";
1233
- } else if (typeof options.masking === "object") {
1234
- maskingStatus = "custom";
1235
- } else {
1236
- maskingStatus = "default-disabled";
1237
- }
1238
- logger.debug("Starting configuration resolution", {
1239
- appName: options.appName,
1240
- baseUrl: options.baseUrl,
1241
- hasApiKey: !!options.apiKey,
1242
- dsnProvided: !!(process.env["BRIZZ_DSN"] || options.dsn),
1243
- disableBatch: options.disableBatch,
1244
- logLevel: resolvedLogLevel,
1245
- headersCount: Object.keys(options.headers || {}).length,
1246
- masking: maskingStatus
1247
- });
1248
- let resolvedMasking;
1249
- if (options.masking === true) {
1250
- resolvedMasking = {
1251
- spanMasking: {},
1252
- eventMasking: {}
1253
- };
1254
- } else if (options.masking && typeof options.masking === "object") {
1255
- resolvedMasking = options.masking;
1256
- }
1257
- const resolvedConfig = {
1258
- ...options,
1259
- appName: process.env["BRIZZ_APP_NAME"] || options.appName || "unknown-app",
1260
- appVersion: process.env["BRIZZ_APP_VERSION"] || options.appVersion,
1261
- baseUrl: process.env["BRIZZ_BASE_URL"] || options.baseUrl || "https://telemetry.brizz.dev",
1262
- headers: { ...options.headers },
1263
- apiKey: process.env["BRIZZ_API_KEY"] || options.apiKey,
1264
- disableBatch: process.env["BRIZZ_DISABLE_BATCH"] === "true" || !!options.disableBatch,
1265
- disableSpanExporter: process.env["BRIZZ_DISABLE_SPAN_EXPORTER"] === "true" || !!options.disableSpanExporter,
1266
- environment: process.env["BRIZZ_ENVIRONMENT"] || options.environment,
1267
- logLevel: resolvedLogLevel,
1268
- masking: resolvedMasking
1269
- };
1270
- const dsnInput = process.env["BRIZZ_DSN"] || options.dsn;
1271
- let parsedDSN = null;
1272
- if (dsnInput) {
1273
- const kwargConflicts = [];
1274
- if (options.apiKey !== void 0) {
1275
- kwargConflicts.push("apiKey");
1276
- }
1277
- if (options.baseUrl !== void 0) {
1278
- kwargConflicts.push("baseUrl");
1279
- }
1280
- if (options.appName !== void 0) {
1281
- kwargConflicts.push("appName");
1282
- }
1283
- if (kwargConflicts.length > 0) {
1284
- throw new Error(
1285
- `dsn cannot be combined with kwargs ${kwargConflicts.join(", ")}. The DSN bundles bearer, gateway URL, and service name \u2014 choose one configuration style.`
1286
- );
1287
- }
1288
- const envConflicts = ["BRIZZ_API_KEY", "BRIZZ_BASE_URL", "BRIZZ_APP_NAME"].filter(
1289
- (name) => process.env[name] !== void 0
1290
- );
1291
- if (envConflicts.length > 0) {
1292
- logger.warn(
1293
- `Ignoring ${envConflicts.join(", ")} \u2014 dsn / BRIZZ_DSN takes precedence.`
1294
- );
1295
- }
1296
- resolvedConfig.apiKey = void 0;
1297
- resolvedConfig.baseUrl = "https://telemetry.brizz.dev";
1298
- resolvedConfig.appName = "unknown-app";
1299
- parsedDSN = parseDSN(dsnInput);
1300
- if (parsedDSN) {
1301
- resolvedConfig.appName = parsedDSN.service;
1302
- resolvedConfig.baseUrl = parsedDSN.baseUrl;
1303
- resolvedConfig.apiKey = parsedDSN.bearer;
1304
- }
1305
- } else if (resolvedConfig.apiKey) {
1306
- resolvedConfig.headers["Authorization"] = `Bearer ${resolvedConfig.apiKey}`;
1307
- }
1308
- if (process.env["BRIZZ_HEADERS"]) {
1309
- try {
1310
- const envHeaders = JSON.parse(process.env["BRIZZ_HEADERS"]);
1311
- Object.assign(resolvedConfig.headers, envHeaders);
1312
- logger.debug("Added headers from environment variable", {
1313
- headers: Object.keys(envHeaders)
1314
- });
1315
- } catch (error) {
1316
- logger.error("Failed to parse BRIZZ_HEADERS environment variable", { error });
1317
- throw new Error("Invalid JSON in BRIZZ_HEADERS environment variable", { cause: error });
1318
- }
1319
- }
1320
- if (dsnInput) {
1321
- const authHeaderKeys = /* @__PURE__ */ new Set(["authorization", SERVICE_NAME_HEADER.toLowerCase()]);
1322
- resolvedConfig.headers = Object.fromEntries(
1323
- Object.entries(resolvedConfig.headers).filter(
1324
- ([key]) => !authHeaderKeys.has(key.toLowerCase())
1325
- )
1326
- );
1327
- if (parsedDSN) {
1328
- resolvedConfig.headers["Authorization"] = `Bearer ${parsedDSN.bearer}`;
1329
- resolvedConfig.headers[SERVICE_NAME_HEADER] = parsedDSN.service;
1330
- }
1331
- }
1332
- logger.debug("Configuration resolved with environment variables", {
1333
- appName: resolvedConfig.appName,
1334
- baseUrl: resolvedConfig.baseUrl,
1335
- hasApiKey: !!resolvedConfig.apiKey,
1336
- dsnProvided: !!dsnInput,
1337
- disableBatch: resolvedConfig.disableBatch,
1338
- envOverrides: {
1339
- hasEnvApiKey: !!process.env["BRIZZ_API_KEY"],
1340
- hasEnvBaseUrl: !!process.env["BRIZZ_BASE_URL"],
1341
- hasEnvDsn: !!process.env["BRIZZ_DSN"],
1342
- hasEnvBatch: !!process.env["BRIZZ_DISABLE_BATCH"],
1343
- hasEnvHeaders: !!process.env["BRIZZ_HEADERS"]
1344
- }
1345
- });
1346
- return resolvedConfig;
1347
- }
1348
-
1349
- // src/internal/constants.ts
1350
- var BRIZZ_SDK_VERSION = "brizz.sdk.version";
1351
- var BRIZZ_SDK_LANGUAGE = "brizz.sdk.language";
1352
- var SDK_LANGUAGE = "typescript";
1353
-
1354
- // src/internal/instrumentation/registry.ts
1355
- init_logger();
1356
- init_mcp();
1357
- import { AnthropicInstrumentation as AnthropicInstrumentation2 } from "@traceloop/instrumentation-anthropic";
1358
- import { BedrockInstrumentation as BedrockInstrumentation2 } from "@traceloop/instrumentation-bedrock";
1359
- import { ChromaDBInstrumentation as ChromaDBInstrumentation2 } from "@traceloop/instrumentation-chromadb";
1360
- import { CohereInstrumentation as CohereInstrumentation2 } from "@traceloop/instrumentation-cohere";
1361
- import { LlamaIndexInstrumentation as LlamaIndexInstrumentation2 } from "@traceloop/instrumentation-llamaindex";
1362
- import { OpenAIInstrumentation as OpenAIInstrumentation2 } from "@traceloop/instrumentation-openai";
1363
- import { PineconeInstrumentation as PineconeInstrumentation2 } from "@traceloop/instrumentation-pinecone";
1364
- import { QdrantInstrumentation as QdrantInstrumentation2 } from "@traceloop/instrumentation-qdrant";
1365
- import { TogetherInstrumentation as TogetherInstrumentation2 } from "@traceloop/instrumentation-together";
1366
- import { VertexAIInstrumentation as VertexAIInstrumentation2 } from "@traceloop/instrumentation-vertexai";
1367
- var InstrumentationRegistry = class _InstrumentationRegistry {
1368
- static instance;
1369
- manualModules = null;
1370
- static getInstance() {
1371
- if (!_InstrumentationRegistry.instance) {
1372
- _InstrumentationRegistry.instance = new _InstrumentationRegistry();
1373
- }
1374
- return _InstrumentationRegistry.instance;
1375
- }
1376
- /**
1377
- * Set manual instrumentation modules for Next.js/Webpack environments
1378
- */
1379
- setManualModules(modules) {
1380
- this.manualModules = modules;
1381
- logger.info("Manual instrumentation modules configured for Next.js/Webpack compatibility");
1382
- }
1383
- /**
1384
- * Helper to load instrumentation with optional manual module
1385
- */
1386
- loadInstrumentation(InstrumentationClass, name, manualModule, exceptionLogger2) {
1387
- try {
1388
- const inst = new InstrumentationClass({
1389
- exceptionLogger: exceptionLogger2 || ((error) => logger.error(`Exception in instrumentation: ${String(error)}`))
1390
- });
1391
- if (manualModule) {
1392
- inst.manuallyInstrument(manualModule);
1393
- logger.debug(`Manual instrumentation enabled for ${name}`);
1394
- }
1395
- return inst;
1396
- } catch (error) {
1397
- logger.error(`Failed to load ${name} instrumentation: ${String(error)}`);
1398
- return null;
1399
- }
1400
- }
1401
- /**
1402
- * Get manual instrumentations only.
1403
- * Auto-instrumentations are handled at import time.
1404
- */
1405
- getManualInstrumentations() {
1406
- if (!this.manualModules || Object.keys(this.manualModules).length === 0) {
1407
- logger.debug("No manual instrumentation modules configured");
1408
- return [];
1409
- }
1410
- const instrumentations = [];
1411
- const exceptionLogger2 = (error) => {
1412
- logger.error(`Exception in manual instrumentation: ${String(error)}`);
1413
- };
1414
- this.loadManualInstrumentations(instrumentations, exceptionLogger2);
1415
- logger.info(`Loaded ${instrumentations.length} manual instrumentations`);
1416
- return instrumentations;
1417
- }
1418
- /**
1419
- * Load manual instrumentations only (with modules provided by user).
1420
- * @private
1421
- */
1422
- loadManualInstrumentations(instrumentations, exceptionLogger2) {
1423
- const instrumentationConfigs = [
1424
- { class: OpenAIInstrumentation2, name: "OpenAI", module: this.manualModules?.openAI },
1425
- { class: AnthropicInstrumentation2, name: "Anthropic", module: this.manualModules?.anthropic },
1426
- { class: CohereInstrumentation2, name: "Cohere", module: this.manualModules?.cohere },
1427
- {
1428
- class: VertexAIInstrumentation2,
1429
- name: "Vertex AI",
1430
- module: this.manualModules?.google_vertexai
1431
- },
1432
- { class: BedrockInstrumentation2, name: "Bedrock", module: this.manualModules?.bedrock },
1433
- { class: PineconeInstrumentation2, name: "Pinecone", module: this.manualModules?.pinecone },
1434
- {
1435
- class: LlamaIndexInstrumentation2,
1436
- name: "LlamaIndex",
1437
- module: this.manualModules?.llamaindex
1438
- },
1439
- { class: ChromaDBInstrumentation2, name: "ChromaDB", module: this.manualModules?.chromadb },
1440
- { class: QdrantInstrumentation2, name: "Qdrant", module: this.manualModules?.qdrant },
1441
- { class: TogetherInstrumentation2, name: "Together", module: this.manualModules?.together }
1442
- ];
1443
- for (const config of instrumentationConfigs) {
1444
- if (config.module) {
1445
- const instrumentation = this.loadInstrumentation(
1446
- config.class,
1447
- config.name,
1448
- config.module,
1449
- exceptionLogger2
1450
- );
1451
- if (instrumentation) {
1452
- instrumentations.push(instrumentation);
1453
- }
1454
- }
1455
- }
1456
- if (this.manualModules?.langchain?.callbackManagerModule) {
1457
- const callbackManagerModule = this.manualModules.langchain.callbackManagerModule;
1458
- void (async () => {
1459
- try {
1460
- const { LangChainInstrumentation } = await import("@arizeai/openinference-instrumentation-langchain");
1461
- const lcInst = new LangChainInstrumentation();
1462
- lcInst.manuallyInstrument(callbackManagerModule);
1463
- logger.debug("Manual instrumentation enabled for LangChain");
1464
- } catch (error) {
1465
- logger.error(
1466
- `Failed to load LangChain instrumentation. Ensure @langchain/core is installed: ${String(error)}`
1467
- );
1468
- }
1469
- })();
1470
- }
1471
- if (this.manualModules?.mcp) {
1472
- try {
1473
- new MCPInstrumentation({ exceptionLogger: exceptionLogger2 }).manuallyInstrument(this.manualModules.mcp);
1474
- logger.debug("Manual instrumentation enabled for MCP");
1475
- } catch (error) {
1476
- logger.error(`Failed to apply MCP instrumentation: ${String(error)}`);
1477
- }
1478
- }
1479
- }
1480
- };
1481
-
1482
- // src/internal/sdk.ts
1483
- init_interrupt();
1484
-
1485
- // src/internal/log/logging.ts
1486
- import { SeverityNumber } from "@opentelemetry/api-logs";
1487
- import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-http";
1488
- import { resourceFromAttributes } from "@opentelemetry/resources";
1489
- import {
1490
- LoggerProvider
1491
- } from "@opentelemetry/sdk-logs";
1492
- init_logger();
1493
-
1494
- // src/internal/trace/session.ts
1495
- import { context as context3, trace as trace4, SpanStatusCode as SpanStatusCode3 } from "@opentelemetry/api";
1496
- init_logger();
1497
- init_semantic_conventions2();
1498
- function setCurrentSpanCustomProperties(properties) {
1499
- const current = trace4.getActiveSpan();
1500
- if (!current || !current.isRecording()) {
1501
- return;
1502
- }
1503
- for (const [key, value] of Object.entries(properties)) {
1504
- try {
1505
- current.setAttribute(`${BRIZZ}.${key}`, value);
1506
- } catch {
1507
- }
1508
- }
1509
- }
1510
- function callWithProperties(properties, fn, thisArg, ...args) {
1511
- const base = context3.active();
1512
- const prev = base.getValue(PROPERTIES_CONTEXT_KEY);
1513
- const merged = prev ? { ...prev, ...properties } : properties;
1514
- const next = base.setValue(PROPERTIES_CONTEXT_KEY, merged);
1515
- return context3.with(next, fn, thisArg, ...args);
1516
- }
1517
- function withProperties(properties, fn, thisArg) {
1518
- return function wrapped(...args) {
1519
- return callWithProperties(
1520
- properties,
1521
- fn,
1522
- thisArg !== void 0 ? thisArg : this,
1523
- ...args
1524
- );
1525
- };
1526
- }
1527
- function muteProperties(options) {
1528
- const { input = true, output = true } = options;
1529
- const properties = {};
1530
- if (input) {
1531
- properties[MUTE_INPUT] = "true";
1532
- }
1533
- if (output) {
1534
- properties[MUTE_OUTPUT] = "true";
1535
- }
1536
- return properties;
1537
- }
1538
- function callWithMute(options, fn, thisArg, ...args) {
1539
- return callWithProperties(muteProperties(options), fn, thisArg, ...args);
1540
- }
1541
- function withMute(options, fn, thisArg) {
1542
- return withProperties(muteProperties(options), fn, thisArg);
1543
- }
1544
- function withSessionId(sessionId, fn, thisArg, extraProperties) {
1545
- const properties = { [SESSION_ID]: sessionId, ...extraProperties };
1546
- return withProperties(properties, fn, thisArg);
1547
- }
1548
- function callWithSessionId(sessionId, fn, thisArg, ...args) {
1549
- return callWithProperties({ [SESSION_ID]: sessionId }, fn, thisArg, ...args);
1550
- }
1551
- var Session = class {
1552
- sessionId;
1553
- span;
1554
- inputs = [];
1555
- outputs = [];
1556
- inputContexts = [];
1557
- outputContexts = [];
1558
- constructor(sessionId, span) {
1559
- this.sessionId = sessionId;
1560
- this.span = span;
1561
- }
1562
- /**
1563
- * Append a user turn to session input tracking.
1564
- *
1565
- * Each call appends one element to `brizz.session.input` (the text) AND one
1566
- * element to `brizz.session.input.context` (the per-turn context bag). The
1567
- * two arrays stay index-aligned — the ingestion pipeline zips them together
1568
- * so the i-th context bag lands on the i-th user_display conversation item's
1569
- * `span_attributes` map.
1570
- *
1571
- * @param text - Text to append (null becomes a null/"hide marker")
1572
- * @param context - Optional per-turn context bag to attach to this turn
1573
- */
1574
- setInput(text, context6) {
1575
- this.inputs.push(text);
1576
- this.inputContexts.push(context6 ?? {});
1577
- this.span.setAttribute(SESSION_INPUT, JSON.stringify(this.inputs));
1578
- this.span.setAttribute(SESSION_INPUT_CONTEXT, JSON.stringify(this.inputContexts));
1579
- }
1580
- /**
1581
- * Append an assistant turn to session output tracking.
1582
- *
1583
- * Symmetric to {@link setInput} — appends one text element and one
1584
- * context-bag element to the index-aligned `brizz.session.output` /
1585
- * `brizz.session.output.context` arrays.
1586
- *
1587
- * @param text - Text to append (null becomes a null/"hide marker")
1588
- * @param context - Optional per-turn context bag to attach to this turn
1589
- */
1590
- setOutput(text, context6) {
1591
- this.outputs.push(text);
1592
- this.outputContexts.push(context6 ?? {});
1593
- this.span.setAttribute(SESSION_OUTPUT, JSON.stringify(this.outputs));
1594
- this.span.setAttribute(SESSION_OUTPUT_CONTEXT, JSON.stringify(this.outputContexts));
1595
- }
1596
- /**
1597
- * Set the session title on the span.
1598
- *
1599
- * @param title - The generated title string
1600
- */
1601
- setTitle(title) {
1602
- this.span.setAttribute(SESSION_TITLE, title);
1603
- }
1604
- /**
1605
- * Update custom properties on the session span.
1606
- * Properties are prefixed with 'brizz.'.
1607
- *
1608
- * @param properties - Key-value properties to set on the session
1609
- */
1610
- updateProperties(properties) {
1611
- for (const [key, value] of Object.entries(properties)) {
1612
- this.span.setAttribute(`${BRIZZ}.${key}`, value);
1613
- }
1614
- }
1615
- /**
1616
- * Attach an external link (URL) to this session.
1617
- *
1618
- * The link surfaces on the session's detail panel in Brizz — use it to
1619
- * correlate a session with an external record such as a Datadog trace,
1620
- * Sentry issue, or internal dashboard. Re-sending the same URL is idempotent;
1621
- * distinct URLs add separate links.
1622
- *
1623
- * @param url - The link target
1624
- * @param options - Optional `title` (defaults to the URL host) and `linkType`
1625
- * (free-form category, defaults to `'generic'`)
1626
- */
1627
- addExternalLink(url, options) {
1628
- emitExternalLink(this.sessionId, url, options?.title, options?.linkType);
1629
- }
1630
- };
1631
- var SessionTitle = class {
1632
- span;
1633
- constructor(span) {
1634
- this.span = span;
1635
- }
1636
- /**
1637
- * Set the generated title on the wrapper span.
1638
- *
1639
- * @param title - The generated title string
1640
- */
1641
- setTitle(title) {
1642
- this.span.setAttribute(SESSION_TITLE, title);
1643
- }
1644
- };
1645
- function getActiveSession() {
1646
- return context3.active().getValue(SESSION_OBJECT_CONTEXT_KEY);
1647
- }
1648
- function resolveSessionIdFromContext() {
1649
- const active = getActiveSession();
1650
- if (active) {
1651
- return active.sessionId;
1652
- }
1653
- const props = context3.active().getValue(PROPERTIES_CONTEXT_KEY);
1654
- return props?.[SESSION_ID];
1655
- }
1656
- function emitExternalLink(sessionId, url, title, linkType) {
1657
- try {
1658
- emitEventWithSessionId(sessionId, EXTERNAL_LINK_EVENT_NAME, {
1659
- [EXTERNAL_LINK_URL]: url,
1660
- [EXTERNAL_LINK_TITLE]: title ?? "",
1661
- [EXTERNAL_LINK_TYPE]: linkType ?? "generic"
1662
- });
1663
- } catch (error) {
1664
- logger.warn("addExternalLink: failed to emit external link", error);
1665
- }
1666
- }
1667
- function addExternalLink(url, options) {
1668
- const sessionId = options?.sessionId ?? resolveSessionIdFromContext();
1669
- if (!sessionId) {
1670
- logger.warn(
1671
- "addExternalLink called without a resolvable session id; link dropped. Pass options.sessionId or call inside a startSession/callWithSessionId scope."
1672
- );
1673
- return;
1674
- }
1675
- emitExternalLink(sessionId, url, options?.title, options?.linkType);
1676
- }
1677
- function startSession(sessionId, callback, extraProperties, options) {
1678
- const isTitle = options?.mode === "title";
1679
- const spanName = isTitle ? SESSION_TITLE_SPAN_NAME : SESSION_SPAN_NAME;
1680
- const tracer = trace4.getTracer("@brizz/sdk");
1681
- return tracer.startActiveSpan(spanName, (span) => {
1682
- span.setAttribute(`${BRIZZ}.${SESSION_ID}`, sessionId);
1683
- if (extraProperties) {
1684
- for (const [key, value] of Object.entries(extraProperties)) {
1685
- span.setAttribute(`${BRIZZ}.${key}`, value);
1686
- }
1687
- }
1688
- const session = new Session(sessionId, span);
1689
- const contextProperties = { [SESSION_ID]: sessionId };
1690
- if (isTitle) {
1691
- contextProperties[SESSION_TITLE_GENERATION] = "true";
1692
- }
1693
- if (extraProperties) {
1694
- for (const [key, value] of Object.entries(extraProperties)) {
1695
- contextProperties[key] = String(value);
1696
- }
1697
- }
1698
- return callWithProperties(contextProperties, () => {
1699
- const sessionCtx = context3.active().setValue(SESSION_OBJECT_CONTEXT_KEY, session);
1700
- return context3.with(sessionCtx, () => {
1701
- try {
1702
- const result = callback(session);
1703
- if (result && typeof result.then === "function") {
1704
- return result.then((value) => {
1705
- span.end();
1706
- return value;
1707
- }).catch((error) => {
1708
- span.recordException(error);
1709
- span.setStatus({ code: SpanStatusCode3.ERROR });
1710
- span.end();
1711
- throw error;
1712
- });
1713
- }
1714
- span.end();
1715
- return result;
1716
- } catch (error) {
1717
- span.recordException(error);
1718
- span.setStatus({ code: SpanStatusCode3.ERROR });
1719
- span.end();
1720
- throw error;
1721
- }
1722
- });
1723
- });
1724
- });
1725
- }
1726
- function startSessionTitle(callback, options) {
1727
- const resolvedSessionId = options?.sessionId ?? getActiveSession()?.sessionId;
1728
- const tracer = trace4.getTracer("@brizz/sdk");
1729
- return tracer.startActiveSpan(SESSION_TITLE_SPAN_NAME, (span) => {
1730
- if (resolvedSessionId) {
1731
- span.setAttribute(`${BRIZZ}.${SESSION_ID}`, resolvedSessionId);
1732
- }
1733
- const sessionTitle = new SessionTitle(span);
1734
- const properties = { [SESSION_TITLE_GENERATION]: "true" };
1735
- if (resolvedSessionId) {
1736
- properties[SESSION_ID] = resolvedSessionId;
1737
- }
1738
- return callWithProperties(properties, () => {
1739
- try {
1740
- const result = callback(sessionTitle);
1741
- if (result && typeof result.then === "function") {
1742
- return result.then((value) => {
1743
- span.end();
1744
- return value;
1745
- }).catch((error) => {
1746
- span.recordException(error);
1747
- span.setStatus({ code: SpanStatusCode3.ERROR });
1748
- span.end();
1749
- throw error;
1750
- });
1751
- }
1752
- span.end();
1753
- return result;
1754
- } catch (error) {
1755
- span.recordException(error);
1756
- span.setStatus({ code: SpanStatusCode3.ERROR });
1757
- span.end();
1758
- throw error;
1759
- }
1760
- });
1761
- });
1762
- }
1763
-
1764
- // src/internal/log/logging.ts
1765
- init_version();
1766
-
1767
- // src/internal/log/processors/log-processor.ts
1768
- init_logger();
1769
- import { context as context4 } from "@opentelemetry/api";
1770
- import { BatchLogRecordProcessor, SimpleLogRecordProcessor } from "@opentelemetry/sdk-logs";
1771
-
1772
- // src/internal/masking/patterns.ts
1773
- var DEFAULT_PII_PATTERNS = [
1774
- // Phone numbers (US format)
1775
- {
1776
- name: "us_phone_numbers",
1777
- pattern: String.raw`(?:^|[\s])(?:\+?1[-.\s]*)?(?:\([0-9]{3}\)\s?[0-9]{3}[-.\s]?[0-9]{4}|[0-9]{3}[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}|[0-9]{10})(?=[\s]|$)`
1778
- },
1779
- // Credit card numbers
1780
- {
1781
- name: "credit_cards",
1782
- pattern: String.raw`\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|6(?:011|5[0-9]{2})[0-9]{12}|(?:2131|1800|35\\d{3})\\d{11})\b`
1783
- },
1784
- {
1785
- name: "credit_cards_with_separators",
1786
- pattern: String.raw`\b(?:4\\d{3}|5[1-5]\\d{2}|3[47]\\d{2})[-\s]?\\d{4}[-\s]?\\d{4}[-\s]?\\d{4}\b`
1787
- },
1788
- // IP addresses (IPv4)
1789
- {
1790
- name: "ipv4_addresses",
1791
- pattern: String.raw`\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?!\.[0-9])\b`
1792
- },
1793
- // API keys/tokens
1794
- {
1795
- name: "generic_api_keys",
1796
- pattern: String.raw`\b(?:[Aa][Pp][Ii][_-]?[Kk][Ee][Yy]|[Tt][Oo][Kk][Ee][Nn]|[Ss][Ee][Cc][Rr][Ee][Tt])[_-]?[=:]?\s*["']?(?:[a-zA-Z0-9\-_.]{20,})["']?\b`
1797
- },
1798
- {
1799
- name: "openai_keys",
1800
- pattern: String.raw`\bsk[-_][a-zA-Z0-9]{20,}\b`
1801
- },
1802
- // AWS Keys
1803
- {
1804
- name: "aws_access_keys",
1805
- pattern: String.raw`\b(?:AKIA|ABIA|ACCA|ASIA)[0-9A-Z]{16}\b`
1806
- },
1807
- // GitHub tokens
1808
- {
1809
- name: "github_tokens",
1810
- pattern: String.raw`\bghp_[a-zA-Z0-9]{36}\b`
1811
- },
1812
- // Slack tokens
1813
- {
1814
- name: "slack_tokens",
1815
- pattern: String.raw`\bxox[baprs]-[0-9]{10,13}-[0-9]{10,13}-[a-zA-Z0-9]{24,34}\b`
1816
- },
1817
- // Stripe keys
1818
- {
1819
- name: "stripe_keys",
1820
- pattern: String.raw`\b(?:sk|pk)_(?:test|live)_[a-zA-Z0-9]{24,}\b`
1821
- },
1822
- // JWT tokens
1823
- {
1824
- name: "jwt_tokens",
1825
- pattern: String.raw`\beyJ[A-Za-z0-9_-]{2,}\\.[A-Za-z0-9_-]{2,}\\.[A-Za-z0-9_-]{2,}\b`
1826
- },
1827
- // MAC addresses
1828
- {
1829
- name: "mac_addresses",
1830
- pattern: String.raw`\b(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b`
1831
- },
1832
- // IPv6 addresses
1833
- {
1834
- name: "ipv6_addresses",
1835
- pattern: String.raw`\b(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\b`
1836
- },
1837
- // Bitcoin addresses
1838
- {
1839
- name: "bitcoin_addresses",
1840
- pattern: String.raw`\b[13][a-km-zA-HJ-NP-Z1-9]{25,34}\b`
1841
- },
1842
- // Ethereum addresses
1843
- {
1844
- name: "ethereum_addresses",
1845
- pattern: String.raw`\b0x[a-fA-F0-9]{40}(?![a-fA-F0-9])\b`
1846
- },
1847
- // Database connection strings
1848
- {
1849
- name: "database_connections",
1850
- pattern: String.raw`\b(?:[Mm][Oo][Nn][Gg][Oo][Dd][Bb]|[Pp][Oo][Ss][Tt][Gg][Rr][Ee][Ss]|[Mm][Yy][Ss][Qq][Ll]|[Rr][Ee][Dd][Ii][Ss]|[Mm][Ss][Ss][Qq][Ll]|[Oo][Rr][Aa][Cc][Ll][Ee]):\\/\\/[^\\s]+\b`
1851
- },
1852
- // Private keys
1853
- {
1854
- name: "rsa_private_keys",
1855
- pattern: "-----BEGIN (?:RSA )?PRIVATE KEY-----"
1856
- },
1857
- {
1858
- name: "pgp_private_keys",
1859
- pattern: "-----BEGIN PGP PRIVATE KEY BLOCK-----"
1860
- },
1861
- // Additional API Keys and Tokens
1862
- {
1863
- name: "google_oauth",
1864
- pattern: String.raw`\bya29\\.[a-zA-Z0-9_-]{60,}\b`
1865
- },
1866
- {
1867
- name: "firebase_tokens",
1868
- pattern: String.raw`\bAAAA[A-Za-z0-9_-]{100,}\b`
1869
- },
1870
- {
1871
- name: "google_app_ids",
1872
- pattern: String.raw`\b[0-9]+-\w+\.apps\.googleusercontent\.com\b`
1873
- },
1874
- {
1875
- name: "facebook_secrets",
1876
- pattern: String.raw`\b(facebook_secret|FACEBOOK_SECRET|facebook_app_secret|FACEBOOK_APP_SECRET)[a-z_ =\\s"'\\:]{0,5}[^a-zA-Z0-9][a-f0-9]{32}[^a-zA-Z0-9]`
1877
- },
1878
- {
1879
- name: "github_keys",
1880
- pattern: String.raw`\b(GITHUB_SECRET|GITHUB_KEY|github_secret|github_key|github_token|GITHUB_TOKEN|github_api_key|GITHUB_API_KEY)[a-z_ =\\s\"'\\:]{0,10}[^a-zA-Z0-9][a-zA-Z0-9]{40}[^a-zA-Z0-9]`
1881
- },
1882
- {
1883
- name: "heroku_keys",
1884
- pattern: String.raw`\b(heroku_api_key|HEROKU_API_KEY|heroku_secret|HEROKU_SECRET)[a-z_ =\\s\"'\\:]{0,10}[^a-zA-Z0-9-]\\w{8}(?:-\\w{4}){3}-\\w{12}[^a-zA-Z0-9\\-]`
1885
- },
1886
- {
1887
- name: "slack_api_keys",
1888
- pattern: String.raw`\b(slack_api_key|SLACK_API_KEY|slack_key|SLACK_KEY)[a-z_ =\\s\"'\\:]{0,10}[^a-f0-9][a-f0-9]{32}[^a-f0-9]`
1889
- },
1890
- {
1891
- name: "slack_api_tokens",
1892
- pattern: String.raw`\b(xox[pb](?:-[a-zA-Z0-9]+){4,})\b`
1893
- },
1894
- // Extended Private Keys and Certificates
1895
- {
1896
- name: "dsa_private_keys",
1897
- pattern: String.raw`-----BEGIN DSA PRIVATE KEY-----(?:[a-zA-Z0-9\+\=\/"']|\s)+?-----END DSA PRIVATE KEY-----`
1898
- },
1899
- {
1900
- name: "ec_private_keys",
1901
- pattern: String.raw`-----BEGIN (?:EC|ECDSA) PRIVATE KEY-----(?:[a-zA-Z0-9\+\=\/"']|\s)+?-----END (?:EC|ECDSA) PRIVATE KEY-----`
1902
- },
1903
- {
1904
- name: "encrypted_private_keys",
1905
- pattern: String.raw`-----BEGIN ENCRYPTED PRIVATE KEY-----(?:.|\s)+?-----END ENCRYPTED PRIVATE KEY-----`
1906
- },
1907
- {
1908
- name: "ssl_certificates",
1909
- pattern: String.raw`-----BEGIN CERTIFICATE-----(?:.|\n)+?\s*-----END CERTIFICATE-----`
1910
- },
1911
- {
1912
- name: "ssh_dss_public",
1913
- pattern: String.raw`\bssh-dss [0-9A-Za-z+/]+[=]{2}\b`
1914
- },
1915
- {
1916
- name: "ssh_rsa_public",
1917
- pattern: String.raw`\bssh-rsa AAAA[0-9A-Za-z+/]+[=]{0,3} [^@]+@[^@]+\b`
1918
- },
1919
- {
1920
- name: "putty_ssh_keys",
1921
- pattern: String.raw`PuTTY-User-Key-File-2: ssh-(?:rsa|dss)\s*Encryption: none(?:.|\s?)*?Private-MAC:`
1922
- },
1923
- // Security and Network
1924
- {
1925
- name: "cve_numbers",
1926
- pattern: String.raw`\b[Cc][Vv][Ee]-\\d{4}-\\d{4,7}\b`
1927
- },
1928
- {
1929
- name: "microsoft_oauth",
1930
- pattern: String.raw`https://login\.microsoftonline\.com/common/oauth2/v2\.0/token|https://login\.windows\.net/common/oauth2/token`
1931
- },
1932
- {
1933
- name: "postgres_connections",
1934
- pattern: String.raw`\b(?:[Pp][Oo][Ss][Tt][Gg][Rr][Ee][Ss]|[Pp][Gg][Ss][Qq][Ll])\\:\\/\\/`
1935
- },
1936
- {
1937
- name: "box_links",
1938
- pattern: String.raw`https://app\.box\.com/[s|l]/\S+`
1939
- },
1940
- {
1941
- name: "dropbox_links",
1942
- pattern: String.raw`https://www\.dropbox\.com/(?:s|l)/\S+`
1943
- },
1944
- // Credit Card Variants
1945
- {
1946
- name: "amex_cards",
1947
- pattern: String.raw`\b3[47][0-9]{13}\b`
1948
- },
1949
- {
1950
- name: "visa_cards",
1951
- pattern: String.raw`\b4[0-9]{12}(?:[0-9]{3})?\b`
1952
- },
1953
- {
1954
- name: "discover_cards",
1955
- pattern: String.raw`\b65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}\b`
1956
- }
1957
- ];
1958
-
1959
- // src/internal/masking/utils.ts
1960
- init_logger();
1961
- function isValidPatternName(name) {
1962
- return /^[a-zA-Z0-9_]+$/.test(name);
1963
- }
1964
- function isLikelyReDoSPattern(pattern) {
1965
- const dangerousPatterns = [
1966
- // Nested quantifiers like (a+)+, (a*)+, (a+)*
1967
- /\([^)]*[+*]\)[+*]/,
1968
- // Overlapping alternation under an outer quantifier like (a|a)+, (\w|\d)+. Scoped to
1969
- // capturing groups so the lazy (?:…)+? built-ins aren't false-flagged.
1970
- /\((?!\?)[^)]*\|[^)]*\)[+*]/,
1971
- // Complex backtracking patterns - but more specific
1972
- /\([^)]*[+*][^)]*[+*][^)]*\)[+*]/
1973
- ];
1974
- return dangerousPatterns.some((dangerous) => dangerous.test(pattern));
1975
- }
1976
- function getGroupedPattern(patternEntry) {
1977
- let name = patternEntry.name;
1978
- if (!name || name === "") {
1979
- name = `pattern_${Math.random().toString(16).slice(2)}`;
1980
- }
1981
- if (!isValidPatternName(name)) {
1982
- throw new Error(
1983
- `Pattern name '${name}' must only contain alphanumeric characters and underscores`
1984
- );
1985
- }
1986
- if (isLikelyReDoSPattern(patternEntry.pattern)) {
1987
- throw new Error(`Potentially dangerous ReDoS pattern detected: '${patternEntry.pattern}'`);
1988
- }
1989
- try {
1990
- new RegExp(patternEntry.pattern);
1991
- } catch (error) {
1992
- throw new Error(`Invalid regex pattern '${patternEntry.pattern}': ${String(error)}`, {
1993
- cause: error
1994
- });
1995
- }
1996
- return `(?<${name}>${patternEntry.pattern})`;
1997
- }
1998
- function isIPatternEntry(obj) {
1999
- return typeof obj === "object" && obj !== null && typeof obj.pattern === "string" && (obj.name === void 0 || typeof obj.name === "string");
2000
- }
2001
- function isIEventMaskingRule(obj) {
2002
- return typeof obj === "object" && obj !== null && typeof obj.mode === "string" && Array.isArray(obj.patterns) && obj.patterns.every(
2003
- (p) => isIPatternEntry(p) || typeof p === "string"
2004
- ) && (obj.attributePattern === void 0 || typeof obj.attributePattern === "string");
2005
- }
2006
- function convertPatternsToPatternEntries(patterns) {
2007
- const patternEntries = [];
2008
- for (const pattern of patterns) {
2009
- if (typeof pattern === "string") {
2010
- patternEntries.push({ pattern, name: "" });
2011
- } else if (isIPatternEntry(pattern)) {
2012
- patternEntries.push(pattern);
2013
- } else {
2014
- throw new Error("Patterns must be either strings or PatternEntry instances");
2015
- }
2016
- }
2017
- return patternEntries;
2018
- }
2019
- function compilePatternEntries(patternEntries) {
2020
- const patternGroups = [];
2021
- for (const patternEntry of patternEntries) {
2022
- try {
2023
- patternGroups.push(getGroupedPattern(patternEntry));
2024
- } catch (error) {
2025
- logger.warn(`Invalid pattern '${patternEntry.name}': ${patternEntry.pattern}`, error);
2026
- continue;
2027
- }
2028
- }
2029
- if (patternGroups.length === 0) {
2030
- return null;
2031
- }
2032
- try {
2033
- return new RegExp(patternGroups.join("|"));
2034
- } catch (error) {
2035
- logger.warn("Failed to compile pattern entries into regex", error);
2036
- return null;
2037
- }
2038
- }
2039
- var compiledPatternCache = /* @__PURE__ */ new WeakMap();
2040
- function getCompiledPatternsForRule(rule) {
2041
- const key = rule.patterns;
2042
- if (compiledPatternCache.has(key)) {
2043
- return compiledPatternCache.get(key) ?? null;
2044
- }
2045
- const compiled = compilePatternEntries(convertPatternsToPatternEntries(rule.patterns));
2046
- compiledPatternCache.set(key, compiled);
2047
- return compiled;
2048
- }
2049
- function getCompiledAttributeNamePattern(rule) {
2050
- if (!rule.attributePattern) {
2051
- logger.debug("No attribute pattern provided, using default .*");
2052
- return /.*/;
2053
- }
2054
- let compiledPatternString = rule.attributePattern;
2055
- if (isIEventMaskingRule(rule) && rule.eventNamePattern) {
2056
- compiledPatternString = `(${compiledPatternString})|(${rule.eventNamePattern})`;
2057
- }
2058
- return new RegExp(compiledPatternString);
2059
- }
2060
- function shouldContinueExecution(startTime, iterations, timeoutMs) {
2061
- if (Date.now() - startTime > timeoutMs) {
2062
- logger.warn("Regex execution timed out - potential ReDoS pattern detected");
2063
- return false;
2064
- }
2065
- const maxIterations = 1e3;
2066
- if (iterations > maxIterations) {
2067
- logger.warn("Regex execution exceeded maximum iterations - potential ReDoS pattern detected");
2068
- return false;
2069
- }
2070
- return true;
2071
- }
2072
- function createGlobalPattern(pattern) {
2073
- return new RegExp(
2074
- pattern.source,
2075
- pattern.flags.includes("g") ? pattern.flags : pattern.flags + "g"
2076
- );
2077
- }
2078
- function executeRegexWithTimeout(pattern, value, timeoutMs = 100) {
2079
- const matches = [];
2080
- const globalPattern = createGlobalPattern(pattern);
2081
- const startTime = Date.now();
2082
- let match;
2083
- let iterations = 0;
2084
- while ((match = globalPattern.exec(value)) !== null) {
2085
- if (!shouldContinueExecution(startTime, ++iterations, timeoutMs)) {
2086
- break;
2087
- }
2088
- matches.push(match);
2089
- if (match[0].length === 0) {
2090
- globalPattern.lastIndex = match.index + 1;
2091
- }
2092
- }
2093
- return matches;
2094
- }
2095
- function maskStringByPattern(value, pattern, mode = "full") {
2096
- const matches = [];
2097
- try {
2098
- const regexMatches = executeRegexWithTimeout(pattern, value);
2099
- for (const match of regexMatches) {
2100
- matches.push({
2101
- start: match.index,
2102
- end: match.index + match[0].length,
2103
- text: match[0],
2104
- groups: match.groups
2105
- });
2106
- }
2107
- } catch (error) {
2108
- logger.warn("Regex execution failed, skipping masking", error);
2109
- return value;
2110
- }
2111
- for (const matchInfo of matches.toReversed()) {
2112
- let patternName = "unknown";
2113
- if (matchInfo.groups) {
2114
- for (const [groupName, groupValue] of Object.entries(matchInfo.groups)) {
2115
- if (groupValue !== void 0) {
2116
- if (groupName.includes("_") && /\d$/.test(groupName)) {
2117
- const parts = groupName.split("_");
2118
- patternName = parts[0] || groupName;
2119
- } else {
2120
- patternName = groupName;
2121
- }
2122
- break;
2123
- }
2124
- }
2125
- }
2126
- logger.info(`Masking detected: pattern '${patternName}' found match in value`);
2127
- const masked = mode === "partial" ? matchInfo.text[0] + "*****" : "*****";
2128
- value = value.slice(0, matchInfo.start) + masked + value.slice(matchInfo.end);
2129
- }
2130
- return value;
2131
- }
2132
- function maskStringByPatternBasedRule(value, rule) {
2133
- const patternEntries = convertPatternsToPatternEntries(rule.patterns);
2134
- if (patternEntries.length === 0) {
2135
- logger.warn("No patterns provided for masking rule, returning original value");
2136
- return value;
2137
- }
2138
- const mode = rule.mode;
2139
- if (!patternEntries || patternEntries.length === 0) {
2140
- return mode === "partial" && value ? value[0] + "*****" : "*****";
2141
- }
2142
- const compiledPatterns = getCompiledPatternsForRule(rule);
2143
- if (!compiledPatterns) {
2144
- return value;
2145
- }
2146
- return maskStringByPattern(value, compiledPatterns, mode);
2147
- }
2148
- function maskValue(value, rule) {
2149
- if (typeof value === "string") {
2150
- return maskStringByPatternBasedRule(value, rule);
2151
- } else if (typeof value === "boolean" || typeof value === "number") {
2152
- return maskStringByPatternBasedRule(String(value), rule);
2153
- } else if (Array.isArray(value)) {
2154
- return value.map((v) => maskStringByPatternBasedRule(String(v), rule));
2155
- } else if (value !== null && typeof value === "object") {
2156
- const result = {};
2157
- for (const [k, v] of Object.entries(value)) {
2158
- result[k] = maskValue(v, rule);
2159
- }
2160
- return result;
2161
- } else {
2162
- throw new Error(`Unsupported value type for masking: ${typeof value}`);
2163
- }
2164
- }
2165
- function maskAttributes(attributes, rules, outputOriginalValue = false) {
2166
- if (!attributes || Object.keys(attributes).length === 0) {
2167
- return {};
2168
- }
2169
- const maskedAttributes = { ...attributes };
2170
- for (const rule of rules) {
2171
- const compiledAttributeNamePattern = getCompiledAttributeNamePattern(rule);
2172
- const attributesToMask = compiledAttributeNamePattern ? Object.keys(maskedAttributes).filter((attr) => compiledAttributeNamePattern.test(attr)) : Object.keys(maskedAttributes);
2173
- for (const attribute of attributesToMask) {
2174
- const value = maskedAttributes[attribute];
2175
- if (value === null || value === void 0) {
2176
- continue;
2177
- }
2178
- if (outputOriginalValue) {
2179
- logger.debug(`Masking attribute '${attribute}' with original value`, { value });
2180
- }
2181
- maskedAttributes[attribute] = maskValue(value, rule);
2182
- }
2183
- }
2184
- return maskedAttributes;
2185
- }
1
+ import {
2
+ Brizz,
3
+ DEFAULT_PII_PATTERNS,
4
+ Session,
5
+ SessionTitle,
6
+ addExternalLink,
7
+ callWithMute,
8
+ callWithProperties,
9
+ callWithSessionId,
10
+ detectRuntime,
11
+ emitEvent,
12
+ emitEventWithSessionId,
13
+ getActiveSession,
14
+ getMetricsExporter,
15
+ getMetricsReader,
16
+ getSpanExporter,
17
+ getSpanProcessor,
18
+ maskAttributes,
19
+ maskValue,
20
+ setCurrentSpanCustomProperties,
21
+ startSession,
22
+ startSessionTitle,
23
+ withMute,
24
+ withProperties,
25
+ withSessionId
26
+ } from "./chunk-U474AL6K.js";
27
+ import "./chunk-7SUF4VVI.js";
28
+ import "./chunk-6M3CBP2N.js";
29
+ import {
30
+ LogLevel,
31
+ getLogLevel,
32
+ logger,
33
+ setLogLevel
34
+ } from "./chunk-Y4HNUX3Q.js";
35
+ import "./chunk-LTLONC6I.js";
36
+ import "./chunk-VGMJ3KUM.js";
37
+ import "./chunk-3RG5ZIWI.js";
2186
38
 
2187
- // src/internal/log/processors/log-processor.ts
2188
- init_semantic_conventions2();
2189
- var DEFAULT_LOG_MASKING_RULES = [
2190
- {
2191
- mode: "partial",
2192
- attributePattern: "event.name",
2193
- patterns: DEFAULT_PII_PATTERNS
2194
- }
2195
- ];
2196
- var BrizzSimpleLogRecordProcessor = class extends SimpleLogRecordProcessor {
2197
- config;
2198
- constructor(exporter, config) {
2199
- super(exporter);
2200
- this.config = config;
2201
- }
2202
- onEmit(logRecord) {
2203
- const maskingConfig = this.config.masking?.eventMasking;
2204
- if (maskingConfig) {
2205
- maskLog(logRecord, maskingConfig);
2206
- }
2207
- const associationProperties = context4.active().getValue(PROPERTIES_CONTEXT_KEY);
2208
- if (associationProperties) {
2209
- for (const [key, value] of Object.entries(associationProperties)) {
2210
- logRecord.setAttribute(`${BRIZZ}.${key}`, value);
2211
- }
2212
- }
2213
- super.onEmit(logRecord);
2214
- }
2215
- };
2216
- var BrizzBatchLogRecordProcessor = class extends BatchLogRecordProcessor {
2217
- config;
2218
- constructor(exporter, config) {
2219
- super(exporter);
2220
- this.config = config;
2221
- }
2222
- onEmit(logRecord) {
2223
- const maskingConfig = this.config.masking?.eventMasking;
2224
- if (maskingConfig) {
2225
- maskLog(logRecord, maskingConfig);
2226
- }
2227
- const associationProperties = context4.active().getValue(PROPERTIES_CONTEXT_KEY);
2228
- if (associationProperties) {
2229
- for (const [key, value] of Object.entries(associationProperties)) {
2230
- logRecord.setAttribute(`${BRIZZ}.${key}`, value);
2231
- }
2232
- }
2233
- super.onEmit(logRecord);
2234
- }
39
+ // src/internal/instrumentation/auto-init.ts
40
+ import { registerInstrumentations } from "@opentelemetry/instrumentation";
41
+ import { AnthropicInstrumentation } from "@traceloop/instrumentation-anthropic";
42
+ import { BedrockInstrumentation } from "@traceloop/instrumentation-bedrock";
43
+ import { ChromaDBInstrumentation } from "@traceloop/instrumentation-chromadb";
44
+ import { CohereInstrumentation } from "@traceloop/instrumentation-cohere";
45
+ import { LlamaIndexInstrumentation } from "@traceloop/instrumentation-llamaindex";
46
+ import { OpenAIInstrumentation } from "@traceloop/instrumentation-openai";
47
+ import { PineconeInstrumentation } from "@traceloop/instrumentation-pinecone";
48
+ import { QdrantInstrumentation } from "@traceloop/instrumentation-qdrant";
49
+ import { TogetherInstrumentation } from "@traceloop/instrumentation-together";
50
+ var exceptionLogger = (error) => {
51
+ logger.error(`Exception in instrumentation: ${String(error)}`);
2235
52
  };
2236
- function maskLog(logRecord, config) {
2237
- if (!logRecord.attributes) {
2238
- return logRecord;
2239
- }
2240
- let rules = config.rules || [];
2241
- if (!config.disableDefaultRules) {
2242
- rules = [...DEFAULT_LOG_MASKING_RULES, ...rules];
2243
- }
2244
- try {
2245
- if (logRecord.attributes && Object.keys(logRecord.attributes).length > 0) {
2246
- const attributesRecord = {};
2247
- for (const [key, value] of Object.entries(logRecord.attributes)) {
2248
- attributesRecord[key] = value;
2249
- }
2250
- const maskedAttributes = maskAttributes(attributesRecord, rules);
2251
- if (maskedAttributes) {
2252
- const newAttributes = {};
2253
- for (const [key, value] of Object.entries(maskedAttributes)) {
2254
- newAttributes[key] = value;
2255
- }
2256
- for (const [key, value] of Object.entries(logRecord.attributes)) {
2257
- if (key.startsWith(INTERNAL_EVENT_PREFIX)) {
2258
- newAttributes[key] = value;
2259
- }
2260
- }
2261
- logRecord.setAttributes(newAttributes);
2262
- }
2263
- }
2264
- if (config.maskBody && logRecord.body !== void 0 && logRecord.body !== null) {
2265
- let maskedBody = logRecord.body;
2266
- for (const rule of rules) {
2267
- maskedBody = maskValue(maskedBody, rule);
2268
- }
2269
- logRecord.setBody(maskedBody);
2270
- }
2271
- return logRecord;
2272
- } catch (error) {
2273
- logger.error("Error masking log record:", error);
2274
- return logRecord;
2275
- }
2276
- }
2277
-
2278
- // src/internal/log/logging.ts
2279
- var LoggingModule = class _LoggingModule {
2280
- static instance = null;
2281
- logExporter = null;
2282
- logProcessor = null;
2283
- loggerProvider = null;
2284
- static getInstance() {
2285
- if (!_LoggingModule.instance) {
2286
- throw new Error("Brizz must be initialized before accessing LoggingModule");
2287
- }
2288
- return _LoggingModule.instance;
2289
- }
2290
- /**
2291
- * Initialize the logging module with the provided configuration
2292
- */
2293
- setup(config) {
2294
- logger.info("Setting up logging module");
2295
- this.initLogExporter(config);
2296
- this.initLogProcessor(config);
2297
- this.initLoggerProvider(config);
2298
- _LoggingModule.instance = this;
2299
- logger.info("Logging module setup completed");
2300
- }
2301
- /**
2302
- * Initialize the log exporter
2303
- */
2304
- initLogExporter(config) {
2305
- if (this.logExporter) {
2306
- logger.debug("Log exporter already initialized, skipping re-initialization");
2307
- return;
2308
- }
2309
- if (config.customLogExporter) {
2310
- logger.debug("Using custom log exporter");
2311
- this.logExporter = config.customLogExporter;
2312
- logger.debug("Custom log exporter initialized successfully");
2313
- return;
2314
- }
2315
- const logsUrl = config.baseUrl.replace(/\/$/, "") + "/v1/logs";
2316
- logger.debug("Initializing default OTLP log exporter", { url: logsUrl });
2317
- const headers = { ...config.headers };
2318
- this.logExporter = new OTLPLogExporter({
2319
- url: logsUrl,
2320
- headers
2321
- });
2322
- logger.debug("OTLP log exporter initialized successfully");
2323
- }
2324
- /**
2325
- * Initialize the log processor with masking support
2326
- */
2327
- initLogProcessor(config) {
2328
- if (this.logProcessor) {
2329
- logger.debug("Log processor already initialized, skipping re-initialization");
2330
- return;
2331
- }
2332
- if (!this.logExporter) {
2333
- throw new Error("Log exporter must be initialized before processor");
2334
- }
2335
- logger.debug("Initializing log processor", {
2336
- disableBatch: config.disableBatch,
2337
- hasMasking: !!config.masking?.eventMasking
2338
- });
2339
- this.logProcessor = config.disableBatch ? new BrizzSimpleLogRecordProcessor(this.logExporter, config) : new BrizzBatchLogRecordProcessor(this.logExporter, config);
2340
- logger.debug("Log processor initialized successfully");
2341
- }
2342
- /**
2343
- * Initialize the logger provider
2344
- */
2345
- initLoggerProvider(config) {
2346
- if (this.loggerProvider) {
2347
- logger.debug("Logger provider already initialized, skipping re-initialization");
2348
- return;
2349
- }
2350
- if (!this.logProcessor) {
2351
- throw new Error("Log processor must be initialized before logger provider");
2352
- }
2353
- logger.debug("Creating resource with service name", {
2354
- serviceName: config.appName
2355
- });
2356
- const resourceAttributes = {
2357
- ...config.resourceAttributes,
2358
- "service.name": config.appName,
2359
- [BRIZZ_SDK_VERSION]: getSDKVersion(),
2360
- [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE
2361
- };
2362
- if (config.environment) {
2363
- resourceAttributes["deployment.environment"] = config.environment;
2364
- }
2365
- if (config.appVersion) {
2366
- resourceAttributes["service.version"] = config.appVersion;
2367
- }
2368
- const resource = resourceFromAttributes(resourceAttributes);
2369
- logger.debug("Creating logger provider with resource");
2370
- this.loggerProvider = new LoggerProvider({
2371
- resource,
2372
- processors: [this.logProcessor]
2373
- });
2374
- logger.debug("Logger provider initialization completed");
2375
- }
2376
- /**
2377
- * Emit a custom event to the telemetry pipeline
2378
- */
2379
- emitEvent(name, attributes, body, severityNumber = SeverityNumber.INFO) {
2380
- logger.debug("Attempting to emit event", {
2381
- name,
2382
- hasAttributes: !!attributes,
2383
- attributesCount: attributes ? Object.keys(attributes).length : 0,
2384
- hasBody: !!body,
2385
- severityNumber
2386
- });
2387
- if (!this.loggerProvider) {
2388
- logger.error("Cannot emit event: Logger provider not initialized");
2389
- throw new Error("Logging module not initialized");
2390
- }
2391
- const logAttributes = { "event.name": name };
2392
- if (attributes) {
2393
- Object.assign(logAttributes, attributes);
2394
- logger.debug("Combined log attributes", { attributes: Object.keys(logAttributes) });
2395
- }
2396
- logger.debug("Getting logger instance for brizz_events");
2397
- const eventLogger = this.loggerProvider.getLogger("brizz.events");
2398
- logger.debug("Emitting log record with eventName", { eventName: name });
53
+ function loadGenAIInstrumentations() {
54
+ const instrumentations = [];
55
+ const genAIInstrumentationClasses = [
56
+ { class: OpenAIInstrumentation, name: "OpenAI" },
57
+ { class: AnthropicInstrumentation, name: "Anthropic" },
58
+ { class: CohereInstrumentation, name: "Cohere" },
59
+ { class: BedrockInstrumentation, name: "Bedrock" },
60
+ { class: PineconeInstrumentation, name: "Pinecone" },
61
+ { class: LlamaIndexInstrumentation, name: "LlamaIndex" },
62
+ { class: ChromaDBInstrumentation, name: "ChromaDB" },
63
+ { class: QdrantInstrumentation, name: "Qdrant" },
64
+ { class: TogetherInstrumentation, name: "Together" }
65
+ ];
66
+ for (const config of genAIInstrumentationClasses) {
2399
67
  try {
2400
- eventLogger.emit({
2401
- eventName: name,
2402
- attributes: logAttributes,
2403
- severityNumber,
2404
- body
2405
- });
2406
- logger.debug("Event successfully emitted", { eventName: name });
68
+ const instrumentation = new config.class({ exceptionLogger });
69
+ instrumentations.push(instrumentation);
70
+ logger.debug(`Auto-loaded ${config.name} instrumentation`);
2407
71
  } catch (error) {
2408
- logger.error(`Failed to emit event '${name}'`, { error, eventName: name });
2409
- logger.error("Log record that failed", {
2410
- eventName: name,
2411
- hasAttributes: logAttributes,
2412
- severityNumber,
2413
- hasBody: body
2414
- });
2415
- throw error instanceof Error ? error : new Error(String(error));
2416
- }
2417
- }
2418
- /**
2419
- * Check if the module is initialized
2420
- */
2421
- isInitialized() {
2422
- return this.loggerProvider !== null;
2423
- }
2424
- /**
2425
- * Get the logger provider
2426
- */
2427
- getLoggerProvider() {
2428
- return this.loggerProvider;
2429
- }
2430
- /**
2431
- * Shutdown the logging module
2432
- */
2433
- async shutdown() {
2434
- logger.debug("Shutting down logging module");
2435
- if (this.loggerProvider) {
2436
- await this.loggerProvider.shutdown();
2437
- this.loggerProvider = null;
2438
- }
2439
- this.logProcessor = null;
2440
- this.logExporter = null;
2441
- if (_LoggingModule.instance === this) {
2442
- _LoggingModule.instance = null;
2443
- }
2444
- logger.debug("Logging module shutdown completed");
2445
- }
2446
- };
2447
- function emitEvent(name, attributes, body, severityNumber = SeverityNumber.INFO) {
2448
- return LoggingModule.getInstance().emitEvent(name, attributes, body, severityNumber);
2449
- }
2450
- function emitEventWithSessionId(sessionId, name, attributes, body, severityNumber = SeverityNumber.INFO) {
2451
- return callWithSessionId(sessionId, () => {
2452
- LoggingModule.getInstance().emitEvent(name, attributes, body, severityNumber);
2453
- });
2454
- }
2455
-
2456
- // src/internal/sdk.ts
2457
- init_logger();
2458
-
2459
- // src/internal/metric/metrics.ts
2460
- init_logger();
2461
- import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
2462
- import { PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
2463
- var MetricsModule = class _MetricsModule {
2464
- static instance = null;
2465
- metricsExporter = null;
2466
- metricsReader = null;
2467
- static getInstance() {
2468
- if (!_MetricsModule.instance) {
2469
- throw new Error("Brizz must be initialized before accessing MetricsModule");
2470
- }
2471
- return _MetricsModule.instance;
2472
- }
2473
- /**
2474
- * Initialize the metrics module with the provided configuration
2475
- */
2476
- setup(config) {
2477
- logger.info("Setting up metrics module");
2478
- this.initMetricsReader(config);
2479
- _MetricsModule.instance = this;
2480
- logger.info("Metrics module setup completed");
2481
- }
2482
- /**
2483
- * Initialize the metrics exporter
2484
- */
2485
- initMetricsExporter(config) {
2486
- if (this.metricsExporter) {
2487
- logger.debug("Metrics exporter already initialized, skipping re-initialization");
2488
- return;
2489
- }
2490
- const metricsUrl = config.baseUrl.replace(/\/$/, "") + "/v1/metrics";
2491
- logger.debug("Initializing metrics exporter", { url: metricsUrl });
2492
- this.metricsExporter = new OTLPMetricExporter({
2493
- url: metricsUrl,
2494
- headers: config.headers
2495
- });
2496
- logger.debug("Metrics exporter initialized successfully");
2497
- }
2498
- /**
2499
- * Initialize the metrics reader
2500
- */
2501
- initMetricsReader(config) {
2502
- if (this.metricsReader) {
2503
- logger.debug("Metrics reader already initialized, skipping re-initialization");
2504
- return;
2505
- }
2506
- if (config.customMetricReader) {
2507
- logger.debug("Using custom metric reader");
2508
- this.metricsReader = config.customMetricReader;
2509
- logger.debug("Custom metric reader initialized successfully");
2510
- return;
2511
- }
2512
- logger.debug(
2513
- "Using default metrics flow - creating OTLP exporter and PeriodicExportingMetricReader"
2514
- );
2515
- this.initMetricsExporter(config);
2516
- if (!this.metricsExporter) {
2517
- throw new Error("Failed to initialize metrics exporter");
2518
- }
2519
- this.metricsReader = new PeriodicExportingMetricReader({
2520
- exporter: this.metricsExporter
2521
- });
2522
- logger.debug("Default metrics reader initialized successfully");
2523
- }
2524
- /**
2525
- * Get the metrics exporter
2526
- */
2527
- getMetricsExporter() {
2528
- if (!this.metricsExporter) {
2529
- throw new Error("Metrics module not initialized");
2530
- }
2531
- return this.metricsExporter;
2532
- }
2533
- /**
2534
- * Get the metrics reader
2535
- */
2536
- getMetricsReader() {
2537
- if (!this.metricsReader) {
2538
- throw new Error("Metrics module not initialized");
2539
- }
2540
- return this.metricsReader;
2541
- }
2542
- /**
2543
- * Shutdown the metrics module
2544
- */
2545
- shutdown() {
2546
- logger.debug("Shutting down metrics module");
2547
- this.metricsReader = null;
2548
- this.metricsExporter = null;
2549
- if (_MetricsModule.instance === this) {
2550
- _MetricsModule.instance = null;
2551
- }
2552
- logger.debug("Metrics module shutdown completed");
2553
- }
2554
- };
2555
- function getMetricsExporter() {
2556
- return MetricsModule.getInstance().getMetricsExporter();
2557
- }
2558
- function getMetricsReader() {
2559
- return MetricsModule.getInstance().getMetricsReader();
2560
- }
2561
-
2562
- // src/internal/trace/tracing.ts
2563
- init_logger();
2564
- import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
2565
-
2566
- // src/internal/trace/exporters/span-exporter.ts
2567
- import { ExportResultCode } from "@opentelemetry/core";
2568
- import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
2569
- init_logger();
2570
- init_version();
2571
- var BrizzSpanExporter = class {
2572
- _delegate;
2573
- _brizzResource;
2574
- _beforeSendSpan;
2575
- constructor(delegate, config) {
2576
- this._delegate = delegate;
2577
- const resourceAttrs = {
2578
- ...config.resourceAttributes,
2579
- "service.name": config.appName,
2580
- [BRIZZ_SDK_VERSION]: getSDKVersion(),
2581
- [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE
2582
- };
2583
- if (config.environment) {
2584
- resourceAttrs["deployment.environment"] = config.environment;
2585
- }
2586
- if (config.appVersion) {
2587
- resourceAttrs["service.version"] = config.appVersion;
2588
- }
2589
- this._brizzResource = resourceFromAttributes2(resourceAttrs);
2590
- this._beforeSendSpan = config.beforeSendSpan;
2591
- }
2592
- export(spans, resultCallback) {
2593
- if (spans.length === 0) {
2594
- resultCallback({ code: ExportResultCode.SUCCESS });
2595
- return;
2596
- }
2597
- const patchedSpans = spans.map((span) => ({
2598
- ...span,
2599
- resource: span.resource.merge(this._brizzResource),
2600
- spanContext: span.spanContext.bind(span)
2601
- }));
2602
- const filter = this._beforeSendSpan;
2603
- if (!filter) {
2604
- this._delegate.export(patchedSpans, resultCallback);
2605
- return;
2606
- }
2607
- const verdicts = patchedSpans.map((span) => {
2608
- try {
2609
- return Promise.resolve(filter(span));
2610
- } catch (error) {
2611
- logger.warn("beforeSendSpan threw; span will be kept", { error });
2612
- return Promise.resolve(true);
2613
- }
2614
- });
2615
- Promise.all(verdicts).then((keep) => {
2616
- const filtered = patchedSpans.filter((_, i) => keep[i] !== false);
2617
- if (filtered.length === 0) {
2618
- resultCallback({ code: ExportResultCode.SUCCESS });
2619
- return;
2620
- }
2621
- this._delegate.export(filtered, resultCallback);
2622
- return;
2623
- }).catch((error) => {
2624
- logger.warn("beforeSendSpan rejected; all spans will be kept", { error });
2625
- this._delegate.export(patchedSpans, resultCallback);
2626
- });
2627
- }
2628
- async shutdown() {
2629
- return this._delegate.shutdown();
2630
- }
2631
- async forceFlush() {
2632
- return this._delegate.forceFlush?.();
2633
- }
2634
- };
2635
-
2636
- // src/internal/trace/processors/span-processor.ts
2637
- init_logger();
2638
- import { context as context5 } from "@opentelemetry/api";
2639
- import {
2640
- BatchSpanProcessor,
2641
- SimpleSpanProcessor
2642
- } from "@opentelemetry/sdk-trace-base";
2643
- init_semantic_conventions2();
2644
- function applyContextAttributes(span) {
2645
- const sessionProperties = context5.active().getValue(PROPERTIES_CONTEXT_KEY);
2646
- if (sessionProperties) {
2647
- for (const [key, value] of Object.entries(sessionProperties)) {
2648
- span.setAttribute(`${BRIZZ}.${key}`, value);
2649
- }
2650
- }
2651
- }
2652
- var DEFAULT_MASKING_RULES = [
2653
- {
2654
- mode: "partial",
2655
- patterns: DEFAULT_PII_PATTERNS
2656
- }
2657
- ];
2658
- var BrizzSimpleSpanProcessor = class extends SimpleSpanProcessor {
2659
- config;
2660
- constructor(spanExporter, config) {
2661
- super(spanExporter);
2662
- this.config = config;
2663
- }
2664
- onStart(span, parentContext) {
2665
- applyContextAttributes(span);
2666
- super.onStart(span, parentContext);
2667
- }
2668
- onEnd(span) {
2669
- const maskingConfig = this.config.masking?.spanMasking;
2670
- if (maskingConfig) {
2671
- maskReadableSpan(span, maskingConfig);
2672
- }
2673
- super.onEnd(span);
2674
- }
2675
- };
2676
- var BrizzBatchSpanProcessor = class extends BatchSpanProcessor {
2677
- config;
2678
- constructor(spanExporter, config) {
2679
- super(spanExporter);
2680
- this.config = config;
2681
- }
2682
- onStart(span, parentContext) {
2683
- applyContextAttributes(span);
2684
- super.onStart(span, parentContext);
2685
- }
2686
- onEnd(span) {
2687
- const maskingConfig = this.config.masking?.spanMasking;
2688
- if (maskingConfig) {
2689
- maskReadableSpan(span, maskingConfig);
72
+ logger.error(`Failed to auto-load ${config.name} instrumentation: ${String(error)}`);
2690
73
  }
2691
- super.onEnd(span);
2692
- }
2693
- };
2694
- function maskReadableSpan(span, config) {
2695
- const attrs = span.attributes;
2696
- if (!attrs || Object.keys(attrs).length === 0) {
2697
- return;
2698
- }
2699
- let rules = config.rules ? [...config.rules] : [];
2700
- if (!config.disableDefaultRules) {
2701
- rules = [...rules, ...DEFAULT_MASKING_RULES];
2702
74
  }
2703
75
  try {
2704
- const input = {};
2705
- for (const [k, v] of Object.entries(attrs)) {
2706
- input[k] = v;
2707
- }
2708
- const masked = maskAttributes(input, rules);
2709
- for (const [k, v] of Object.entries(masked ?? {})) {
2710
- if (attrs[k] !== v) {
2711
- attrs[k] = v;
2712
- }
2713
- }
76
+ registerInstrumentations({ instrumentations });
77
+ logger.info(`Auto-registered ${instrumentations.length} GenAI instrumentations`);
2714
78
  } catch (error) {
2715
- logger.error("Error masking span", { err: error });
2716
- }
2717
- }
2718
-
2719
- // src/internal/trace/tracing.ts
2720
- var TracingModule = class _TracingModule {
2721
- static instance = null;
2722
- spanExporter = null;
2723
- spanProcessor = null;
2724
- static getInstance() {
2725
- if (!_TracingModule.instance) {
2726
- throw new Error("Brizz must be initialized before accessing TracingModule");
2727
- }
2728
- return _TracingModule.instance;
2729
- }
2730
- /**
2731
- * Initialize the tracing module with the provided configuration
2732
- */
2733
- setup(config) {
2734
- logger.info("Setting up tracing module");
2735
- if (config.disableSpanExporter) {
2736
- logger.info(
2737
- "Span exporter disabled via disableSpanExporter; skipping exporter and processor setup"
2738
- );
2739
- this.spanExporter = null;
2740
- this.spanProcessor = null;
2741
- _TracingModule.instance = this;
2742
- return;
2743
- }
2744
- this.initSpanExporter(config);
2745
- this.initSpanProcessor(config);
2746
- _TracingModule.instance = this;
2747
- logger.info("Tracing module setup completed");
2748
- }
2749
- /**
2750
- * Initialize the span exporter
2751
- */
2752
- initSpanExporter(config) {
2753
- if (this.spanExporter) {
2754
- logger.debug("Span exporter already initialized, skipping re-initialization");
2755
- return;
2756
- }
2757
- if (config.customSpanExporter) {
2758
- logger.debug("Using custom span exporter");
2759
- this.spanExporter = new BrizzSpanExporter(config.customSpanExporter, config);
2760
- logger.debug("Custom span exporter initialized successfully");
2761
- return;
2762
- }
2763
- const tracesUrl = config.baseUrl.replace(/\/$/, "") + "/v1/traces";
2764
- logger.debug("Initializing default OTLP span exporter", { url: tracesUrl });
2765
- const otlpExporter = new OTLPTraceExporter({
2766
- url: tracesUrl,
2767
- headers: config.headers
2768
- });
2769
- this.spanExporter = new BrizzSpanExporter(otlpExporter, config);
2770
- logger.debug("OTLP span exporter initialized successfully");
2771
- }
2772
- /**
2773
- * Initialize the span processor with masking support
2774
- */
2775
- initSpanProcessor(config) {
2776
- if (this.spanProcessor) {
2777
- logger.debug("Span processor already initialized, skipping re-initialization");
2778
- return;
2779
- }
2780
- if (!this.spanExporter) {
2781
- throw new Error("Span exporter must be initialized before processor");
2782
- }
2783
- logger.debug("Initializing span processor", {
2784
- disableBatch: config.disableBatch,
2785
- hasMasking: !!config.masking?.spanMasking
2786
- });
2787
- const spanProcessor = config.disableBatch ? new BrizzSimpleSpanProcessor(this.spanExporter, config) : new BrizzBatchSpanProcessor(this.spanExporter, config);
2788
- logger.debug("Span processor initialized successfully");
2789
- this.spanProcessor = spanProcessor;
2790
- }
2791
- /**
2792
- * Get the span exporter
2793
- */
2794
- getSpanExporter() {
2795
- if (!this.spanExporter) {
2796
- throw new Error("Tracing module not initialized");
2797
- }
2798
- return this.spanExporter;
2799
- }
2800
- /**
2801
- * Get the span processor
2802
- */
2803
- getSpanProcessor() {
2804
- if (!this.spanProcessor) {
2805
- throw new Error("Tracing module not initialized");
2806
- }
2807
- return this.spanProcessor;
2808
- }
2809
- async shutdown() {
2810
- logger.debug("Shutting down tracing module");
2811
- if (this.spanProcessor) {
2812
- await this.spanProcessor.shutdown();
2813
- this.spanProcessor = null;
2814
- }
2815
- if (this.spanExporter) {
2816
- await this.spanExporter.shutdown();
2817
- this.spanExporter = null;
2818
- }
2819
- _TracingModule.instance = null;
2820
- logger.debug("Tracing module shutdown completed");
79
+ logger.error(`Failed to register GenAI instrumentations: ${String(error)}`);
2821
80
  }
2822
- };
2823
- function getSpanExporter() {
2824
- return TracingModule.getInstance().getSpanExporter();
2825
- }
2826
- function getSpanProcessor() {
2827
- return TracingModule.getInstance().getSpanProcessor();
81
+ return instrumentations;
2828
82
  }
2829
-
2830
- // src/internal/sdk.ts
2831
- init_version();
2832
- var _Brizz = class __Brizz {
2833
- static instance = null;
2834
- /** Flag indicating if SDK initialization has completed successfully */
2835
- _initialized = false;
2836
- /** OpenTelemetry sdk instance */
2837
- _sdk = null;
2838
- static getInstance() {
2839
- if (!__Brizz.instance) {
2840
- throw new Error("Brizz must be initialized before accessing TracingModule");
2841
- }
2842
- return __Brizz.instance;
2843
- }
2844
- /**
2845
- * Initialize the Brizz SDK with the provided configuration.
2846
- *
2847
- * @param {IBrizzInitializeOptions} options - Configuration options for the SDK
2848
- * @throws {Error} - If initialization fails
2849
- *
2850
- * @example
2851
- * ```typescript
2852
- * Brizz.initialize({
2853
- * appName: 'my-app',
2854
- * baseUrl: 'http://localhost:4318',
2855
- * apiKey: 'your-api-key'
2856
- * });
2857
- * ```
2858
- */
2859
- initialize(options) {
2860
- if (this._initialized) {
2861
- logger.warn("Brizz SDK already initialized");
2862
- return;
2863
- }
2864
- logger.info("Starting Brizz SDK initialization");
83
+ function loadMCPInstrumentation() {
84
+ void (async () => {
2865
85
  try {
2866
- const resolvedConfig = resolveConfig(options);
2867
- this.initializeModules(resolvedConfig);
2868
- this.setupInstrumentation(options);
2869
- this.createAndStartNodeSDK(options, resolvedConfig);
2870
- this._initialized = true;
2871
- logger.info("Brizz SDK initialization completed successfully", {
2872
- moduleSystem: this.detectModuleSystem()
2873
- });
86
+ const { MCPInstrumentation } = await import("./mcp-3YERODPL.js");
87
+ const mcp = new MCPInstrumentation({ exceptionLogger });
88
+ registerInstrumentations({ instrumentations: [mcp] });
89
+ logger.debug("Auto-loaded MCP instrumentation");
2874
90
  } catch (error) {
2875
- logger.error("Failed to initialize Brizz SDK", { error });
2876
- throw new Error(`Failed to initialize SDK: ${String(error)}`, { cause: error });
2877
- }
2878
- }
2879
- /**
2880
- * Set up instrumentation registry and configure manual modules.
2881
- * @private
2882
- */
2883
- setupInstrumentation(options) {
2884
- const registry = InstrumentationRegistry.getInstance();
2885
- if (options.instrumentModules && Object.keys(options.instrumentModules).length > 0) {
2886
- registry.setManualModules(options.instrumentModules);
2887
- }
2888
- }
2889
- /**
2890
- * Create and start NodeSDK if not disabled.
2891
- * Only handles manual instrumentations now - auto instrumentations are loaded at import time.
2892
- * @private
2893
- */
2894
- createAndStartNodeSDK(options, resolvedConfig) {
2895
- if (options.disableNodeSdk) {
2896
- logger.info("NodeSDK disabled - only telemetry modules initialized");
2897
- return;
2898
- }
2899
- const registry = InstrumentationRegistry.getInstance();
2900
- const manualInstrumentations = registry.getManualInstrumentations();
2901
- const resourceAttributes = {
2902
- ...resolvedConfig.resourceAttributes,
2903
- "service.name": resolvedConfig.appName,
2904
- [BRIZZ_SDK_VERSION]: getSDKVersion(),
2905
- [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE
2906
- };
2907
- if (resolvedConfig.environment) {
2908
- resourceAttributes["deployment.environment"] = resolvedConfig.environment;
2909
- }
2910
- if (resolvedConfig.appVersion) {
2911
- resourceAttributes["service.version"] = resolvedConfig.appVersion;
2912
- }
2913
- this._sdk = new NodeSDK({
2914
- spanProcessors: resolvedConfig.disableSpanExporter ? [] : [new InterruptPropagator(), getSpanProcessor()],
2915
- metricReader: getMetricsReader(),
2916
- resource: resourceFromAttributes3(resourceAttributes),
2917
- instrumentations: manualInstrumentations
2918
- });
2919
- this._sdk.start();
2920
- if (manualInstrumentations.length > 0) {
2921
- logger.info(`NodeSDK started with ${manualInstrumentations.length} manual instrumentations`);
2922
- } else {
2923
- logger.info("NodeSDK started - using auto-instrumentations loaded at import time");
2924
- }
2925
- }
2926
- /**
2927
- * Initialize telemetry modules.
2928
- *
2929
- * Sets up the tracing, metrics, and logging modules with their
2930
- * respective exporters and processors.
2931
- *
2932
- * @param {IResolvedBrizzConfig} config - Resolved configuration
2933
- * @private
2934
- */
2935
- initializeModules(config) {
2936
- logger.info("Initializing telemetry modules");
2937
- logger.debug("Initializing tracing module");
2938
- const tracingModule = new TracingModule();
2939
- tracingModule.setup(config);
2940
- logger.debug("Initializing metrics module");
2941
- const metricsModule = new MetricsModule();
2942
- metricsModule.setup(config);
2943
- logger.debug("Initializing logging module");
2944
- const loggingModule = new LoggingModule();
2945
- loggingModule.setup(config);
2946
- logger.info("All telemetry modules initialized successfully");
2947
- }
2948
- /**
2949
- * Detect the current module system (ESM or CJS) using reliable indicators
2950
- *
2951
- * @returns {string} - 'ESM' or 'CJS'
2952
- * @private
2953
- */
2954
- detectModuleSystem() {
2955
- const inCJS = typeof module !== "undefined" && typeof exports !== "undefined" && typeof __require === "function" && typeof __filename === "string" && typeof __dirname === "string" && this === (typeof exports !== "undefined" ? exports : void 0);
2956
- return inCJS ? "CJS" : "ESM";
2957
- }
2958
- /**
2959
- * Gracefully shutdown the Brizz SDK.
2960
- *
2961
- * This method stops all telemetry collection, flushes any pending data,
2962
- * and releases resources. Should be called before application termination.
2963
- *
2964
- * @returns {Promise<void>} - Resolves when shutdown is complete
2965
- * @throws {Error} - If shutdown fails
2966
- *
2967
- * @example
2968
- * ```typescript
2969
- * // Shutdown before app exit
2970
- * await Brizz.shutdown();
2971
- * ```
2972
- */
2973
- async shutdown() {
2974
- if (!this._initialized) {
2975
- logger.warn("Brizz SDK not initialized");
2976
- return;
91
+ logger.debug(
92
+ `MCP instrumentation not loaded (install @modelcontextprotocol/sdk and @arizeai/openinference-instrumentation-mcp if you want MCP support): ${String(error)}`
93
+ );
2977
94
  }
95
+ })();
96
+ }
97
+ function loadVertexAIInstrumentation() {
98
+ void (async () => {
2978
99
  try {
2979
- await this.shutdownModules();
2980
- await this._sdk?.shutdown();
2981
- this._initialized = false;
2982
- this._sdk = null;
2983
- __Brizz.instance = null;
2984
- logger.info("Brizz SDK shut down successfully");
100
+ const { VertexAIInstrumentation } = await import("@traceloop/instrumentation-vertexai");
101
+ const vertexAI = new VertexAIInstrumentation({ exceptionLogger });
102
+ registerInstrumentations({ instrumentations: [vertexAI] });
103
+ logger.debug("Auto-loaded Vertex AI instrumentation");
2985
104
  } catch (error) {
2986
- if (error instanceof Error && error.message.includes("ENOTFOUND")) {
2987
- logger.debug(`Network error during shutdown (expected in tests): ${error.message}`);
2988
- } else {
2989
- logger.error(`Failed to shutdown Brizz SDK: ${String(error)}`);
2990
- throw error;
2991
- }
105
+ logger.debug(
106
+ `Vertex AI instrumentation not loaded (install @traceloop/instrumentation-vertexai if you want Vertex AI support): ${String(error)}`
107
+ );
2992
108
  }
2993
- }
2994
- /**
2995
- * Shutdown all telemetry modules.
2996
- * @private
2997
- */
2998
- async shutdownModules() {
2999
- logger.info("Shutting down telemetry modules");
109
+ })();
110
+ }
111
+ function selectTelemetryRegister(ai) {
112
+ const register = ai.registerTelemetry ?? ai.registerTelemetryIntegration;
113
+ return typeof register === "function" ? register : void 0;
114
+ }
115
+ function loadVercelAITelemetry() {
116
+ void (async () => {
3000
117
  try {
3001
- try {
3002
- const tracingModule = TracingModule.getInstance();
3003
- await tracingModule.shutdown();
3004
- } catch {
3005
- logger.debug("Tracing module already shut down or not initialized");
118
+ const ai = await import("ai");
119
+ const register = selectTelemetryRegister(ai);
120
+ if (!register) {
121
+ logger.debug(
122
+ "AI SDK present but lacks a telemetry-registration hook (needs ai@>=6); skipping"
123
+ );
124
+ return;
3006
125
  }
126
+ const isV7 = typeof ai.registerTelemetry === "function";
127
+ const integrations = [];
128
+ const { createInterruptIntegration } = await import("./interrupt-VMUSMALH.js");
129
+ integrations.push(createInterruptIntegration());
130
+ let otelCollectorLoaded = false;
3007
131
  try {
3008
- const metricsModule = MetricsModule.getInstance();
3009
- metricsModule.shutdown();
132
+ const otel = await import("@ai-sdk/otel");
133
+ if (typeof otel.LegacyOpenTelemetry === "function") {
134
+ integrations.push(new otel.LegacyOpenTelemetry());
135
+ otelCollectorLoaded = true;
136
+ }
3010
137
  } catch {
3011
- logger.debug("Metrics module already shut down or not initialized");
3012
138
  }
3013
- try {
3014
- const loggingModule = LoggingModule.getInstance();
3015
- await loggingModule.shutdown();
3016
- } catch {
3017
- logger.debug("Logging module already shut down or not initialized");
139
+ if (!otelCollectorLoaded) {
140
+ const message = "AI SDK present but @ai-sdk/otel is missing or unusable; install it (npm install @ai-sdk/otel) to capture AI SDK spans on ai@>=7";
141
+ if (isV7) {
142
+ logger.warn(message);
143
+ } else {
144
+ logger.debug(message);
145
+ }
3018
146
  }
3019
- logger.info("All telemetry modules shut down successfully");
147
+ register(...integrations);
148
+ logger.debug("Auto-loaded Vercel AI telemetry");
3020
149
  } catch (error) {
3021
- logger.error("Error shutting down modules", { error });
3022
- throw error;
150
+ logger.debug(
151
+ `Vercel AI telemetry not loaded (install ai@>=6 to capture AI SDK telemetry): ${String(error)}`
152
+ );
3023
153
  }
154
+ })();
155
+ }
156
+ function autoInitializeInstrumentations() {
157
+ try {
158
+ const genAIInstrumentations = loadGenAIInstrumentations();
159
+ loadMCPInstrumentation();
160
+ loadVertexAIInstrumentation();
161
+ loadVercelAITelemetry();
162
+ logger.info(
163
+ `Auto-initialization complete: ${genAIInstrumentations.length} GenAI instrumentations`
164
+ );
165
+ return true;
166
+ } catch (error) {
167
+ logger.error(`Auto-initialization failed: ${String(error)}`);
168
+ return false;
3024
169
  }
3025
- };
3026
- var Brizz = new _Brizz();
170
+ }
171
+ var autoInstrumentationsLoaded = autoInitializeInstrumentations();
3027
172
 
3028
173
  // src/index.ts
3029
- init_logger();
3030
- import { SeverityNumber as SeverityNumber2 } from "@opentelemetry/api-logs";
3031
-
3032
- // src/node/runtime.ts
3033
- init_logger();
3034
- function detectRuntime() {
3035
- const [major, minor] = process.versions.node.split(".").map(Number);
3036
- const noNodeJSGlobals = typeof __filename === "undefined" && typeof __dirname === "undefined";
3037
- const noModuleSystem = typeof module === "undefined" && typeof exports === "undefined";
3038
- const hasRequire = typeof __require === "function";
3039
- const isESM = noNodeJSGlobals && noModuleSystem;
3040
- const isCJS = hasRequire && typeof module !== "undefined" && typeof exports !== "undefined" && typeof __filename === "string" && typeof __dirname === "string";
3041
- const supportsLoaderAPI = (major ?? 0) >= 21 || (major ?? 0) === 20 && (minor ?? 0) >= 6 || (major ?? 0) === 18 && (minor ?? 0) >= 19;
3042
- const supportsRegister = (
3043
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
3044
- !!process.features?.typescript || !!globalThis.module?.register
3045
- );
3046
- logger.debug("Runtime detection results:", {
3047
- nodeVersion: `${major ?? 0}.${minor ?? 0}`,
3048
- isESM,
3049
- isCJS,
3050
- supportsLoaderAPI,
3051
- supportsRegister,
3052
- detectionLogic: {
3053
- noNodeJSGlobals,
3054
- noModuleSystem,
3055
- hasRequire,
3056
- esmCondition: `${noNodeJSGlobals} && ${noModuleSystem} = ${isESM}`,
3057
- cjsCondition: `require && module && exports && __filename && __dirname = ${isCJS}`
3058
- },
3059
- checks: {
3060
- __filename: typeof __filename,
3061
- __dirname: typeof __dirname,
3062
- require: typeof __require,
3063
- module: typeof module,
3064
- exports: typeof exports,
3065
- "process.features": process.features,
3066
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
3067
- "globalThis.module": globalThis.module
3068
- }
3069
- });
3070
- return {
3071
- isESM,
3072
- isCJS,
3073
- nodeVersion: process.versions.node,
3074
- supportsLoaderAPI,
3075
- supportsRegister
3076
- };
3077
- }
174
+ import { SeverityNumber } from "@opentelemetry/api-logs";
3078
175
 
3079
176
  // src/init.ts
3080
177
  var init_exports = {};
@@ -3084,7 +181,7 @@ export {
3084
181
  LogLevel,
3085
182
  Session,
3086
183
  SessionTitle,
3087
- SeverityNumber2 as SeverityNumber,
184
+ SeverityNumber,
3088
185
  addExternalLink,
3089
186
  callWithMute,
3090
187
  callWithProperties,