@brizz/sdk 0.1.56 → 0.1.58

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
@@ -2,17 +2,53 @@ import {
2
2
  SERVICE_NAME_HEADER,
3
3
  parseDSN
4
4
  } from "./chunk-7SUF4VVI.js";
5
+ import {
6
+ Session,
7
+ SessionTitle,
8
+ addExternalLink,
9
+ callWithMessageId,
10
+ callWithMute,
11
+ callWithOrganization,
12
+ callWithProperties,
13
+ callWithServiceName,
14
+ callWithSessionId,
15
+ callWithUser,
16
+ clearEventSink,
17
+ emitEvent,
18
+ emitEventWithSessionId,
19
+ getActiveSession,
20
+ recordFeedback,
21
+ recordMetric,
22
+ resolveServiceNameFromContext,
23
+ setAgent,
24
+ setCurrentSpanCustomProperties,
25
+ setEventSink,
26
+ setMessageId,
27
+ setOrganization,
28
+ setServiceName,
29
+ setSessionId,
30
+ setUser,
31
+ startAgent,
32
+ startSession,
33
+ startSessionTitle,
34
+ withAgent,
35
+ withMessageId,
36
+ withMute,
37
+ withOrganization,
38
+ withProperties,
39
+ withServiceName,
40
+ withSessionId,
41
+ withUser
42
+ } from "./chunk-MXKQQ6AU.js";
5
43
  import {
6
44
  configure,
7
45
  getSDKVersion
8
- } from "./chunk-AWYGZM6I.js";
46
+ } from "./chunk-LXRU77IM.js";
9
47
  import {
10
48
  bindToBrizz,
11
49
  brizzTracerProvider,
12
50
  ensureContextManager,
13
- extractTraceContext,
14
51
  getTracerProvider,
15
- injectTraceContext,
16
52
  registerTracerProvider,
17
53
  setPrivateTracerProvider
18
54
  } from "./chunk-TDPQDITP.js";
@@ -28,65 +64,14 @@ import {
28
64
  InterruptPropagator
29
65
  } from "./chunk-7PRTTYWM.js";
30
66
  import {
31
- AGENT_ID,
32
- AGENT_NAME,
33
- AGENT_PARENT_ID,
34
67
  BRIZZ,
35
- EXTERNAL_LINK_EVENT_NAME,
36
- EXTERNAL_LINK_TITLE,
37
- EXTERNAL_LINK_TYPE,
38
- EXTERNAL_LINK_URL,
39
- FEEDBACK_ATTR_PREFIX,
40
- FEEDBACK_COMMENT,
41
- FEEDBACK_EVENT_NAME,
42
- FEEDBACK_REASON,
43
- FEEDBACK_SCORE,
44
- FEEDBACK_SOURCE,
45
- FEEDBACK_TYPE,
46
68
  INTERNAL_EVENT_PREFIX,
47
- MESSAGE_ID,
48
- METRIC_ATTRIBUTE_PREFIX,
49
- METRIC_COMMENT,
50
- METRIC_EVENT_NAME,
51
- METRIC_MAX,
52
- METRIC_MIN,
53
- METRIC_NAME,
54
- METRIC_POLARITY,
55
- METRIC_POLARITY_NEGATIVE,
56
- METRIC_POLARITY_POSITIVE,
57
- METRIC_SCOPE,
58
- METRIC_SCOPE_SESSION,
59
- METRIC_SCOPE_TRACE,
60
- METRIC_TIMESTAMP,
61
- METRIC_TRACE_ID,
62
- METRIC_UNIT,
63
- METRIC_VALUE,
64
- MUTE_INPUT,
65
- MUTE_OUTPUT,
66
- MUTE_TOOLS,
67
69
  ORGANIZATION_DOMAIN,
68
- ORGANIZATION_ID,
69
70
  ORGANIZATION_NAME,
70
- ORGANIZATION_PLAN,
71
71
  PROPERTIES_CONTEXT_KEY,
72
- RESERVED_METRIC_NAMES,
73
- SERVICE_NAME,
74
72
  SERVICE_NAME_ATTRIBUTE,
75
- SESSION_ID,
76
- SESSION_INPUT,
77
- SESSION_INPUT_CONTEXT,
78
- SESSION_OBJECT_CONTEXT_KEY,
79
- SESSION_OUTPUT,
80
- SESSION_OUTPUT_CONTEXT,
81
- SESSION_SPAN_NAME,
82
- SESSION_TITLE,
83
- SESSION_TITLE_GENERATION,
84
- SESSION_TITLE_SPAN_NAME,
85
73
  USER_EMAIL,
86
- USER_ID,
87
- USER_NAME,
88
- USER_PLAN,
89
- USER_ROLE
74
+ USER_NAME
90
75
  } from "./chunk-GUKWVI53.js";
91
76
  import {
92
77
  __require
@@ -698,7 +683,7 @@ function loadGenAIInstrumentations() {
698
683
  function loadMCPInstrumentation() {
699
684
  void (async () => {
700
685
  try {
701
- const { MCPInstrumentation } = await import("./mcp-WIKXDZIJ.js");
686
+ const { MCPInstrumentation } = await import("./mcp-2JWY4GGY.js");
702
687
  const mcp = new MCPInstrumentation({ exceptionLogger });
703
688
  registerInstrumentations({ instrumentations: [mcp], tracerProvider: brizzTracerProvider });
704
689
  logger.debug("Auto-loaded MCP instrumentation");
@@ -833,7 +818,7 @@ function autoInitializeInstrumentations() {
833
818
  var autoInstrumentationsLoaded = autoInitializeInstrumentations();
834
819
 
835
820
  // src/internal/sdk.ts
836
- import { metrics, trace as trace4 } from "@opentelemetry/api";
821
+ import { metrics, trace as trace3 } from "@opentelemetry/api";
837
822
  import { registerInstrumentations as registerInstrumentations2 } from "@opentelemetry/instrumentation";
838
823
  import {
839
824
  defaultResource,
@@ -1309,7 +1294,7 @@ var InstrumentationRegistry = class _InstrumentationRegistry {
1309
1294
  const mcpModules = this.manualModules.mcp;
1310
1295
  void (async () => {
1311
1296
  try {
1312
- const { MCPInstrumentation } = await import("./mcp-WIKXDZIJ.js");
1297
+ const { MCPInstrumentation } = await import("./mcp-2JWY4GGY.js");
1313
1298
  const instrumentation = new MCPInstrumentation({ exceptionLogger: exceptionLogger2 });
1314
1299
  instrumentation.manuallyInstrument(mcpModules);
1315
1300
  logger.debug("Manual instrumentation enabled for MCP");
@@ -1351,724 +1336,8 @@ import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-http";
1351
1336
  import { resourceFromAttributes } from "@opentelemetry/resources";
1352
1337
  import { LoggerProvider } from "@opentelemetry/sdk-logs";
1353
1338
 
1354
- // src/internal/trace/session.ts
1355
- import { context as context4, isSpanContextValid, trace as trace3, SpanStatusCode as SpanStatusCode3 } from "@opentelemetry/api";
1356
- var sessionTracer = brizzTracerProvider.getTracer("@brizz/sdk");
1357
- function setCurrentSpanCustomProperties(properties) {
1358
- const current = trace3.getActiveSpan();
1359
- if (!current || !current.isRecording()) {
1360
- return;
1361
- }
1362
- for (const [key, value] of Object.entries(properties)) {
1363
- try {
1364
- current.setAttribute(`${BRIZZ}.${key}`, value);
1365
- } catch {
1366
- }
1367
- }
1368
- }
1369
- function callWithProperties(properties, fn, thisArg, ...args) {
1370
- const base = context4.active();
1371
- const prev = base.getValue(PROPERTIES_CONTEXT_KEY);
1372
- const merged = prev ? { ...prev, ...properties } : properties;
1373
- const next = base.setValue(PROPERTIES_CONTEXT_KEY, merged);
1374
- return context4.with(next, fn, thisArg, ...args);
1375
- }
1376
- function withProperties(properties, fn, thisArg) {
1377
- return function wrapped(...args) {
1378
- return callWithProperties(
1379
- properties,
1380
- fn,
1381
- thisArg !== void 0 ? thisArg : this,
1382
- ...args
1383
- );
1384
- };
1385
- }
1386
- function propagatePropertiesImperatively(properties, base = context4.active()) {
1387
- try {
1388
- const manager = context4;
1389
- const mgr = manager._getContextManager?.();
1390
- const store = mgr?._asyncLocalStorage;
1391
- if (!store || typeof store.enterWith !== "function") {
1392
- return;
1393
- }
1394
- const prev = base.getValue(PROPERTIES_CONTEXT_KEY);
1395
- const merged = prev ? { ...prev, ...properties } : properties;
1396
- store.enterWith(base.setValue(PROPERTIES_CONTEXT_KEY, merged));
1397
- } catch {
1398
- }
1399
- }
1400
- function setUser(user) {
1401
- const properties = { [USER_ID]: user.id };
1402
- if (user.email !== void 0) {
1403
- properties[USER_EMAIL] = user.email;
1404
- }
1405
- if (user.name !== void 0) {
1406
- properties[USER_NAME] = user.name;
1407
- }
1408
- if (user.role !== void 0) {
1409
- properties[USER_ROLE] = user.role;
1410
- }
1411
- if (user.plan !== void 0) {
1412
- properties[USER_PLAN] = user.plan;
1413
- }
1414
- if (user.traits) {
1415
- for (const [key, value] of Object.entries(user.traits)) {
1416
- const k = `user.${key}`;
1417
- if (properties[k] === void 0) {
1418
- properties[k] = value;
1419
- }
1420
- }
1421
- }
1422
- setCurrentSpanCustomProperties(properties);
1423
- propagatePropertiesImperatively(properties);
1424
- }
1425
- function setOrganization(org) {
1426
- const properties = { [ORGANIZATION_ID]: org.id };
1427
- if (org.name !== void 0) {
1428
- properties[ORGANIZATION_NAME] = org.name;
1429
- }
1430
- if (org.plan !== void 0) {
1431
- properties[ORGANIZATION_PLAN] = org.plan;
1432
- }
1433
- if (org.domain !== void 0) {
1434
- properties[ORGANIZATION_DOMAIN] = org.domain;
1435
- }
1436
- if (org.traits) {
1437
- for (const [key, value] of Object.entries(org.traits)) {
1438
- const k = `organization.${key}`;
1439
- if (properties[k] === void 0) {
1440
- properties[k] = value;
1441
- }
1442
- }
1443
- }
1444
- setCurrentSpanCustomProperties(properties);
1445
- propagatePropertiesImperatively(properties);
1446
- }
1447
- function setMessageId(id) {
1448
- const properties = { [MESSAGE_ID]: id };
1449
- setCurrentSpanCustomProperties(properties);
1450
- propagatePropertiesImperatively(properties);
1451
- }
1452
- function setSessionId(id) {
1453
- const properties = { [SESSION_ID]: id };
1454
- setCurrentSpanCustomProperties(properties);
1455
- propagatePropertiesImperatively(properties);
1456
- }
1457
- var SERVICE_NAME_MAX_BYTES = 256;
1458
- function serviceNameProblem(name) {
1459
- if (typeof name !== "string" || name === "") {
1460
- return "must be a non-empty string";
1461
- }
1462
- if (/[\r\n\0]/.test(name)) {
1463
- return `${JSON.stringify(name)} contains CR, LF, or NUL`;
1464
- }
1465
- const byteLength = new globalThis.TextEncoder().encode(name).length;
1466
- if (byteLength > SERVICE_NAME_MAX_BYTES) {
1467
- return `is ${byteLength} bytes, over the ${SERVICE_NAME_MAX_BYTES}-byte limit`;
1468
- }
1469
- return void 0;
1470
- }
1471
- function serviceNameProperties(name) {
1472
- const problem = serviceNameProblem(name);
1473
- if (problem !== void 0) {
1474
- logger.warn(`Service name ${problem}; keeping the configured appName.`);
1475
- return {};
1476
- }
1477
- return { [SERVICE_NAME]: name };
1478
- }
1479
- function setServiceName(name) {
1480
- const properties = serviceNameProperties(name);
1481
- setCurrentSpanCustomProperties(properties);
1482
- propagatePropertiesImperatively(properties);
1483
- }
1484
- function callWithServiceName(name, fn, thisArg, ...args) {
1485
- return callWithProperties(serviceNameProperties(name), fn, thisArg, ...args);
1486
- }
1487
- function withServiceName(name, fn, thisArg) {
1488
- return withProperties(serviceNameProperties(name), fn, thisArg);
1489
- }
1490
- function resolveServiceNameFromContext() {
1491
- const props = context4.active().getValue(PROPERTIES_CONTEXT_KEY);
1492
- return props?.[SERVICE_NAME];
1493
- }
1494
- function userProperties(user) {
1495
- const properties = { [USER_ID]: user.id };
1496
- if (user.email !== void 0) {
1497
- properties[USER_EMAIL] = user.email;
1498
- }
1499
- if (user.name !== void 0) {
1500
- properties[USER_NAME] = user.name;
1501
- }
1502
- if (user.role !== void 0) {
1503
- properties[USER_ROLE] = user.role;
1504
- }
1505
- if (user.plan !== void 0) {
1506
- properties[USER_PLAN] = user.plan;
1507
- }
1508
- if (user.traits) {
1509
- for (const [key, value] of Object.entries(user.traits)) {
1510
- const k = `user.${key}`;
1511
- if (properties[k] === void 0) {
1512
- properties[k] = value;
1513
- }
1514
- }
1515
- }
1516
- return properties;
1517
- }
1518
- function organizationProperties(org) {
1519
- const properties = { [ORGANIZATION_ID]: org.id };
1520
- if (org.name !== void 0) {
1521
- properties[ORGANIZATION_NAME] = org.name;
1522
- }
1523
- if (org.plan !== void 0) {
1524
- properties[ORGANIZATION_PLAN] = org.plan;
1525
- }
1526
- if (org.domain !== void 0) {
1527
- properties[ORGANIZATION_DOMAIN] = org.domain;
1528
- }
1529
- if (org.traits) {
1530
- for (const [key, value] of Object.entries(org.traits)) {
1531
- const k = `organization.${key}`;
1532
- if (properties[k] === void 0) {
1533
- properties[k] = value;
1534
- }
1535
- }
1536
- }
1537
- return properties;
1538
- }
1539
- function callWithUser(user, fn, thisArg, ...args) {
1540
- return callWithProperties(userProperties(user), fn, thisArg, ...args);
1541
- }
1542
- function withUser(user, fn, thisArg) {
1543
- return withProperties(userProperties(user), fn, thisArg);
1544
- }
1545
- function callWithOrganization(org, fn, thisArg, ...args) {
1546
- return callWithProperties(organizationProperties(org), fn, thisArg, ...args);
1547
- }
1548
- function withOrganization(org, fn, thisArg) {
1549
- return withProperties(organizationProperties(org), fn, thisArg);
1550
- }
1551
- function callWithMessageId(id, fn, thisArg, ...args) {
1552
- return callWithProperties({ [MESSAGE_ID]: id }, fn, thisArg, ...args);
1553
- }
1554
- function withMessageId(id, fn, thisArg) {
1555
- return withProperties({ [MESSAGE_ID]: id }, fn, thisArg);
1556
- }
1557
- function inheritedMuteTools() {
1558
- const properties = context4.active().getValue(PROPERTIES_CONTEXT_KEY);
1559
- return properties?.[MUTE_TOOLS];
1560
- }
1561
- function muteProperties(options) {
1562
- const { input = true, output = true, tools = output } = options;
1563
- const properties = {};
1564
- if (input) {
1565
- properties[MUTE_INPUT] = "true";
1566
- }
1567
- if (output) {
1568
- properties[MUTE_OUTPUT] = "true";
1569
- }
1570
- if (tools !== output) {
1571
- properties[MUTE_TOOLS] = String(tools);
1572
- } else {
1573
- const inherited = inheritedMuteTools();
1574
- if (tools && inherited === "false") {
1575
- properties[MUTE_TOOLS] = "true";
1576
- } else if (options.tools === false && inherited === "true") {
1577
- properties[MUTE_TOOLS] = "false";
1578
- }
1579
- }
1580
- return properties;
1581
- }
1582
- function callWithMute(options, fn, thisArg, ...args) {
1583
- return callWithProperties(muteProperties(options), fn, thisArg, ...args);
1584
- }
1585
- function withMute(options, fn, thisArg) {
1586
- return withProperties(muteProperties(options), fn, thisArg);
1587
- }
1588
- function withSessionId(sessionId, fn, thisArg, extraProperties) {
1589
- const properties = { [SESSION_ID]: sessionId, ...extraProperties };
1590
- return withProperties(properties, fn, thisArg);
1591
- }
1592
- function callWithSessionId(sessionId, fn, thisArg, ...args) {
1593
- return callWithProperties({ [SESSION_ID]: sessionId }, fn, thisArg, ...args);
1594
- }
1595
- var Session = class {
1596
- span;
1597
- inputs = [];
1598
- outputs = [];
1599
- inputContexts = [];
1600
- outputContexts = [];
1601
- sessionId;
1602
- constructor(sessionId, span) {
1603
- this.sessionId = sessionId;
1604
- this.span = span;
1605
- }
1606
- /**
1607
- * Append a user turn to session input tracking.
1608
- *
1609
- * Each call appends one element to `brizz.session.input` (the text) AND one
1610
- * element to `brizz.session.input.context` (the per-turn context bag). The
1611
- * two arrays stay index-aligned — the ingestion pipeline zips them together
1612
- * so the i-th context bag lands on the i-th user_display conversation item's
1613
- * `span_attributes` map.
1614
- *
1615
- * @param text - Text to append (null becomes a null/"hide marker")
1616
- * @param context - Optional per-turn context bag to attach to this turn
1617
- */
1618
- setInput(text2, context8) {
1619
- this.inputs.push(text2);
1620
- this.inputContexts.push(context8 ?? {});
1621
- this.span.setAttribute(SESSION_INPUT, JSON.stringify(this.inputs));
1622
- this.span.setAttribute(SESSION_INPUT_CONTEXT, JSON.stringify(this.inputContexts));
1623
- }
1624
- /**
1625
- * Append an assistant turn to session output tracking.
1626
- *
1627
- * Symmetric to {@link setInput} — appends one text element and one
1628
- * context-bag element to the index-aligned `brizz.session.output` /
1629
- * `brizz.session.output.context` arrays.
1630
- *
1631
- * @param text - Text to append (null becomes a null/"hide marker")
1632
- * @param context - Optional per-turn context bag to attach to this turn
1633
- */
1634
- setOutput(text2, context8) {
1635
- this.outputs.push(text2);
1636
- this.outputContexts.push(context8 ?? {});
1637
- this.span.setAttribute(SESSION_OUTPUT, JSON.stringify(this.outputs));
1638
- this.span.setAttribute(SESSION_OUTPUT_CONTEXT, JSON.stringify(this.outputContexts));
1639
- }
1640
- /**
1641
- * Set the session title on the span.
1642
- *
1643
- * @param title - The generated title string
1644
- */
1645
- setTitle(title) {
1646
- this.span.setAttribute(SESSION_TITLE, title);
1647
- }
1648
- /**
1649
- * Update custom properties on the session span.
1650
- * Properties are prefixed with 'brizz.'.
1651
- *
1652
- * @param properties - Key-value properties to set on the session
1653
- */
1654
- updateProperties(properties) {
1655
- for (const [key, value] of Object.entries(properties)) {
1656
- this.span.setAttribute(`${BRIZZ}.${key}`, value);
1657
- }
1658
- }
1659
- /**
1660
- * Set end-user identity on the session span: `brizz.user.id` and, when
1661
- * provided, `brizz.user.email` / `brizz.user.name`. Undefined fields are omitted.
1662
- *
1663
- * @param user - User identity (`id` required; `email` / `name` optional)
1664
- */
1665
- setUser(user) {
1666
- if (user.traits) {
1667
- for (const [key, value] of Object.entries(user.traits)) {
1668
- this.span.setAttribute(`${BRIZZ}.user.${key}`, value);
1669
- }
1670
- }
1671
- this.span.setAttribute(`${BRIZZ}.${USER_ID}`, user.id);
1672
- if (user.email !== void 0) {
1673
- this.span.setAttribute(`${BRIZZ}.${USER_EMAIL}`, user.email);
1674
- }
1675
- if (user.name !== void 0) {
1676
- this.span.setAttribute(`${BRIZZ}.${USER_NAME}`, user.name);
1677
- }
1678
- if (user.role !== void 0) {
1679
- this.span.setAttribute(`${BRIZZ}.${USER_ROLE}`, user.role);
1680
- }
1681
- if (user.plan !== void 0) {
1682
- this.span.setAttribute(`${BRIZZ}.${USER_PLAN}`, user.plan);
1683
- }
1684
- }
1685
- /**
1686
- * Set organization identity on the session span: `brizz.organization.id` and,
1687
- * when provided, `brizz.organization.name`. Undefined fields are omitted.
1688
- *
1689
- * @param org - Organization identity (`id` required; `name` optional)
1690
- */
1691
- setOrganization(org) {
1692
- if (org.traits) {
1693
- for (const [key, value] of Object.entries(org.traits)) {
1694
- this.span.setAttribute(`${BRIZZ}.organization.${key}`, value);
1695
- }
1696
- }
1697
- this.span.setAttribute(`${BRIZZ}.${ORGANIZATION_ID}`, org.id);
1698
- if (org.name !== void 0) {
1699
- this.span.setAttribute(`${BRIZZ}.${ORGANIZATION_NAME}`, org.name);
1700
- }
1701
- if (org.plan !== void 0) {
1702
- this.span.setAttribute(`${BRIZZ}.${ORGANIZATION_PLAN}`, org.plan);
1703
- }
1704
- if (org.domain !== void 0) {
1705
- this.span.setAttribute(`${BRIZZ}.${ORGANIZATION_DOMAIN}`, org.domain);
1706
- }
1707
- }
1708
- /**
1709
- * Attach an external link (URL) to this session.
1710
- *
1711
- * The link surfaces on the session's detail panel in Brizz — use it to
1712
- * correlate a session with an external record such as a Datadog trace,
1713
- * Sentry issue, or internal dashboard. Re-sending the same URL is idempotent;
1714
- * distinct URLs add separate links.
1715
- *
1716
- * @param url - The link target
1717
- * @param options - Optional `title` (defaults to the URL host) and `linkType`
1718
- * (free-form category, defaults to `'generic'`)
1719
- */
1720
- addExternalLink(url, options) {
1721
- emitExternalLink(this.sessionId, url, options?.title, options?.linkType);
1722
- }
1723
- };
1724
- var SessionTitle = class {
1725
- span;
1726
- constructor(span) {
1727
- this.span = span;
1728
- }
1729
- /**
1730
- * Set the generated title on the wrapper span.
1731
- *
1732
- * @param title - The generated title string
1733
- */
1734
- setTitle(title) {
1735
- this.span.setAttribute(SESSION_TITLE, title);
1736
- }
1737
- };
1738
- function getActiveSession() {
1739
- return context4.active().getValue(SESSION_OBJECT_CONTEXT_KEY);
1740
- }
1741
- function resolveSessionIdFromContext() {
1742
- const active = getActiveSession();
1743
- if (active) {
1744
- return active.sessionId;
1745
- }
1746
- const props = context4.active().getValue(PROPERTIES_CONTEXT_KEY);
1747
- return props?.[SESSION_ID];
1748
- }
1749
- function resolveMessageIdFromContext() {
1750
- const props = context4.active().getValue(PROPERTIES_CONTEXT_KEY);
1751
- return props?.[MESSAGE_ID];
1752
- }
1753
- function emitExternalLink(sessionId, url, title, linkType) {
1754
- try {
1755
- emitEventWithSessionId(sessionId, EXTERNAL_LINK_EVENT_NAME, {
1756
- [EXTERNAL_LINK_URL]: url,
1757
- [EXTERNAL_LINK_TITLE]: title ?? "",
1758
- [EXTERNAL_LINK_TYPE]: linkType ?? "generic"
1759
- });
1760
- } catch (error) {
1761
- logger.warn("addExternalLink: failed to emit external link", error);
1762
- }
1763
- }
1764
- function addExternalLink(url, options) {
1765
- const sessionId = options?.sessionId ?? resolveSessionIdFromContext();
1766
- if (!sessionId) {
1767
- logger.warn(
1768
- "addExternalLink called without a resolvable session id; link dropped. Pass options.sessionId or call inside a startSession/callWithSessionId scope."
1769
- );
1770
- return;
1771
- }
1772
- emitExternalLink(sessionId, url, options?.title, options?.linkType);
1773
- }
1774
- function recordFeedback(type, options) {
1775
- const eventAttributes = { [FEEDBACK_TYPE]: type };
1776
- if (options?.score !== void 0) {
1777
- eventAttributes[FEEDBACK_SCORE] = options.score;
1778
- }
1779
- if (options?.reason !== void 0) {
1780
- eventAttributes[FEEDBACK_REASON] = options.reason;
1781
- }
1782
- if (options?.comment !== void 0) {
1783
- eventAttributes[FEEDBACK_COMMENT] = options.comment;
1784
- }
1785
- if (options?.source !== void 0) {
1786
- eventAttributes[FEEDBACK_SOURCE] = options.source;
1787
- }
1788
- if (options?.attributes) {
1789
- for (const [key, value] of Object.entries(options.attributes)) {
1790
- const k = `${FEEDBACK_ATTR_PREFIX}${key}`;
1791
- if (eventAttributes[k] === void 0) {
1792
- eventAttributes[k] = value;
1793
- }
1794
- }
1795
- }
1796
- const messageId = options?.messageId ?? resolveMessageIdFromContext();
1797
- const sessionId = options?.sessionId ?? resolveSessionIdFromContext();
1798
- if (messageId === void 0 && sessionId === void 0) {
1799
- logger.warn(
1800
- "recordFeedback called with no resolvable message id or session id; the feedback cannot be attributed to a message or conversation. Pass options.messageId / options.sessionId or call inside a startSession/callWithMessageId scope."
1801
- );
1802
- }
1803
- const anchor = {};
1804
- if (messageId !== void 0) {
1805
- anchor[MESSAGE_ID] = messageId;
1806
- }
1807
- if (sessionId !== void 0) {
1808
- anchor[SESSION_ID] = sessionId;
1809
- }
1810
- try {
1811
- if (Object.keys(anchor).length === 0) {
1812
- emitEvent(FEEDBACK_EVENT_NAME, eventAttributes);
1813
- } else {
1814
- callWithProperties(anchor, () => emitEvent(FEEDBACK_EVENT_NAME, eventAttributes));
1815
- }
1816
- } catch (error) {
1817
- logger.warn("recordFeedback: failed to emit feedback event", error);
1818
- }
1819
- }
1820
- var METRIC_NAME_PATTERN = /^[a-z][a-z0-9_.-]{0,63}$/;
1821
- var METRIC_COMMENT_MAX_LEN = 4096;
1822
- var METRIC_ATTRIBUTES_MAX = 20;
1823
- var METRIC_ATTRIBUTE_VALUE_MAX_LEN = 256;
1824
- function recordMetric(options) {
1825
- try {
1826
- recordMetricImpl(options);
1827
- } catch (error) {
1828
- logger.warn(`recordMetric(${JSON.stringify(options?.name)}) failed; metric dropped.`, error);
1829
- }
1830
- }
1831
- function recordMetricImpl(options) {
1832
- const name = typeof options.name === "string" ? options.name.toLowerCase() : "";
1833
- if (!METRIC_NAME_PATTERN.test(name)) {
1834
- logger.warn(
1835
- `recordMetric called with an invalid name ${JSON.stringify(options.name)}; metric dropped. Names must match ${METRIC_NAME_PATTERN.source} after lowercasing.`
1836
- );
1837
- return;
1838
- }
1839
- if (RESERVED_METRIC_NAMES.has(name)) {
1840
- logger.warn(
1841
- `recordMetric called with the reserved name ${JSON.stringify(name)}; metric dropped. Brizz computes this metric itself \u2014 pick a different name.`
1842
- );
1843
- return;
1844
- }
1845
- const { value } = options;
1846
- let numericValue;
1847
- if (typeof value === "boolean") {
1848
- numericValue = value ? 1 : 0;
1849
- } else if (typeof value === "number" && Number.isFinite(value)) {
1850
- numericValue = value;
1851
- } else {
1852
- logger.warn(
1853
- `recordMetric(${name}) called with a non-finite or non-numeric value ${JSON.stringify(value)}; metric dropped.`
1854
- );
1855
- return;
1856
- }
1857
- if (options.serviceName !== void 0) {
1858
- const problem = serviceNameProblem(options.serviceName);
1859
- if (problem !== void 0) {
1860
- logger.warn(`recordMetric(${name}) service name ${problem}; metric dropped.`);
1861
- return;
1862
- }
1863
- }
1864
- const scope = options.scope ?? METRIC_SCOPE_SESSION;
1865
- if (scope !== METRIC_SCOPE_SESSION && scope !== METRIC_SCOPE_TRACE) {
1866
- logger.warn(
1867
- `recordMetric(${name}) called with an invalid scope ${JSON.stringify(scope)}; expected '${METRIC_SCOPE_SESSION}' or '${METRIC_SCOPE_TRACE}'. Metric dropped.`
1868
- );
1869
- return;
1870
- }
1871
- const eventAttributes = {
1872
- [METRIC_NAME]: name,
1873
- [METRIC_VALUE]: numericValue
1874
- };
1875
- if (options.scope !== void 0) {
1876
- eventAttributes[METRIC_SCOPE] = scope;
1877
- }
1878
- if (options.unit !== void 0) {
1879
- eventAttributes[METRIC_UNIT] = options.unit;
1880
- }
1881
- if (options.minValue !== void 0) {
1882
- eventAttributes[METRIC_MIN] = options.minValue;
1883
- }
1884
- if (options.maxValue !== void 0) {
1885
- eventAttributes[METRIC_MAX] = options.maxValue;
1886
- }
1887
- if (options.comment !== void 0) {
1888
- let comment = options.comment;
1889
- if (comment.length > METRIC_COMMENT_MAX_LEN) {
1890
- logger.warn(
1891
- `recordMetric(${name}) comment exceeds ${METRIC_COMMENT_MAX_LEN} characters; truncated.`
1892
- );
1893
- comment = comment.slice(0, METRIC_COMMENT_MAX_LEN);
1894
- }
1895
- eventAttributes[METRIC_COMMENT] = comment;
1896
- }
1897
- if (options.polarity !== void 0) {
1898
- const polarity = options.polarity;
1899
- if (polarity === METRIC_POLARITY_POSITIVE || polarity === METRIC_POLARITY_NEGATIVE) {
1900
- eventAttributes[METRIC_POLARITY] = polarity;
1901
- } else {
1902
- logger.warn(
1903
- `recordMetric(${name}) called with an invalid polarity ${JSON.stringify(polarity)}; expected '${METRIC_POLARITY_POSITIVE}' or '${METRIC_POLARITY_NEGATIVE}'. Emitting the metric without it.`
1904
- );
1905
- }
1906
- }
1907
- if (options.timestamp !== void 0) {
1908
- if (Number.isFinite(options.timestamp.getTime())) {
1909
- eventAttributes[METRIC_TIMESTAMP] = options.timestamp.toISOString();
1910
- } else {
1911
- logger.warn(
1912
- `recordMetric(${name}) called with an invalid timestamp; emitting the metric without it.`
1913
- );
1914
- }
1915
- }
1916
- if (options.attributes) {
1917
- let accepted = 0;
1918
- for (const [key, attrValue] of Object.entries(options.attributes)) {
1919
- if (accepted >= METRIC_ATTRIBUTES_MAX) {
1920
- logger.warn(
1921
- `recordMetric(${name}) called with more than ${METRIC_ATTRIBUTES_MAX} attributes; the excess was dropped.`
1922
- );
1923
- break;
1924
- }
1925
- const normalizedKey = key.toLowerCase();
1926
- if (!METRIC_NAME_PATTERN.test(normalizedKey)) {
1927
- logger.warn(
1928
- `recordMetric(${name}) called with an invalid attribute key ${JSON.stringify(key)}; that attribute was dropped. Keys must match ${METRIC_NAME_PATTERN.source} after lowercasing.`
1929
- );
1930
- continue;
1931
- }
1932
- let text2 = typeof attrValue === "string" ? attrValue : String(attrValue);
1933
- if (text2.length > METRIC_ATTRIBUTE_VALUE_MAX_LEN) {
1934
- logger.warn(
1935
- `recordMetric(${name}) attribute ${JSON.stringify(normalizedKey)} exceeds ${METRIC_ATTRIBUTE_VALUE_MAX_LEN} characters; truncated.`
1936
- );
1937
- text2 = text2.slice(0, METRIC_ATTRIBUTE_VALUE_MAX_LEN);
1938
- }
1939
- eventAttributes[`${METRIC_ATTRIBUTE_PREFIX}${normalizedKey}`] = text2;
1940
- accepted += 1;
1941
- }
1942
- }
1943
- const traceId = typeof options.traceId === "string" && options.traceId !== "" ? options.traceId : void 0;
1944
- if (traceId !== void 0) {
1945
- eventAttributes[METRIC_TRACE_ID] = traceId;
1946
- }
1947
- if (scope === METRIC_SCOPE_TRACE && traceId === void 0) {
1948
- const spanContext = trace3.getActiveSpan()?.spanContext();
1949
- if (!spanContext || !isSpanContextValid(spanContext)) {
1950
- logger.warn(
1951
- `recordMetric(${name}) called with scope 'trace' but no trace; metric dropped. Pass options.traceId, or call inside the span of the trace being scored.`
1952
- );
1953
- return;
1954
- }
1955
- eventAttributes[METRIC_TRACE_ID] = spanContext.traceId;
1956
- }
1957
- const sessionId = options.sessionId ?? (traceId === void 0 ? resolveSessionIdFromContext() : void 0);
1958
- if (sessionId === void 0 && traceId === void 0) {
1959
- logger.warn(
1960
- `recordMetric(${name}) called with no resolvable session id or trace id; the metric cannot be attributed to a conversation and is dropped. Pass options.sessionId or options.traceId, or call inside a startSession/callWithSessionId scope.`
1961
- );
1962
- return;
1963
- }
1964
- const base = context4.active();
1965
- const ambient = base.getValue(PROPERTIES_CONTEXT_KEY);
1966
- const properties = { ...ambient };
1967
- if (sessionId === void 0) {
1968
- delete properties[SESSION_ID];
1969
- delete properties[MESSAGE_ID];
1970
- } else {
1971
- properties[SESSION_ID] = sessionId;
1972
- }
1973
- if (options.serviceName !== void 0) {
1974
- properties[SERVICE_NAME] = options.serviceName;
1975
- }
1976
- try {
1977
- context4.with(
1978
- base.setValue(PROPERTIES_CONTEXT_KEY, properties),
1979
- () => emitEvent(METRIC_EVENT_NAME, eventAttributes)
1980
- );
1981
- } catch (error) {
1982
- logger.warn("recordMetric: failed to emit metric event", error);
1983
- }
1984
- }
1985
- function startSession(sessionId, callback, extraProperties, options) {
1986
- const isTitle = options?.mode === "title";
1987
- const spanName = isTitle ? SESSION_TITLE_SPAN_NAME : SESSION_SPAN_NAME;
1988
- return sessionTracer.startActiveSpan(spanName, (span) => {
1989
- span.setAttribute(`${BRIZZ}.${SESSION_ID}`, sessionId);
1990
- if (extraProperties) {
1991
- for (const [key, value] of Object.entries(extraProperties)) {
1992
- span.setAttribute(`${BRIZZ}.${key}`, value);
1993
- }
1994
- }
1995
- const session = new Session(sessionId, span);
1996
- const contextProperties = { [SESSION_ID]: sessionId };
1997
- if (isTitle) {
1998
- contextProperties[SESSION_TITLE_GENERATION] = "true";
1999
- }
2000
- if (extraProperties) {
2001
- for (const [key, value] of Object.entries(extraProperties)) {
2002
- contextProperties[key] = String(value);
2003
- }
2004
- }
2005
- return callWithProperties(contextProperties, () => {
2006
- const sessionCtx = context4.active().setValue(SESSION_OBJECT_CONTEXT_KEY, session);
2007
- return context4.with(sessionCtx, () => {
2008
- try {
2009
- const result = callback(session);
2010
- if (result && typeof result.then === "function") {
2011
- return result.then((value) => {
2012
- span.end();
2013
- return value;
2014
- }).catch((error) => {
2015
- span.recordException(error);
2016
- span.setStatus({ code: SpanStatusCode3.ERROR });
2017
- span.end();
2018
- throw error;
2019
- });
2020
- }
2021
- span.end();
2022
- return result;
2023
- } catch (error) {
2024
- span.recordException(error);
2025
- span.setStatus({ code: SpanStatusCode3.ERROR });
2026
- span.end();
2027
- throw error;
2028
- }
2029
- });
2030
- });
2031
- });
2032
- }
2033
- function startSessionTitle(callback, options) {
2034
- const resolvedSessionId = options?.sessionId ?? getActiveSession()?.sessionId;
2035
- return sessionTracer.startActiveSpan(SESSION_TITLE_SPAN_NAME, (span) => {
2036
- if (resolvedSessionId) {
2037
- span.setAttribute(`${BRIZZ}.${SESSION_ID}`, resolvedSessionId);
2038
- }
2039
- const sessionTitle = new SessionTitle(span);
2040
- const properties = { [SESSION_TITLE_GENERATION]: "true" };
2041
- if (resolvedSessionId) {
2042
- properties[SESSION_ID] = resolvedSessionId;
2043
- }
2044
- return callWithProperties(properties, () => {
2045
- try {
2046
- const result = callback(sessionTitle);
2047
- if (result && typeof result.then === "function") {
2048
- return result.then((value) => {
2049
- span.end();
2050
- return value;
2051
- }).catch((error) => {
2052
- span.recordException(error);
2053
- span.setStatus({ code: SpanStatusCode3.ERROR });
2054
- span.end();
2055
- throw error;
2056
- });
2057
- }
2058
- span.end();
2059
- return result;
2060
- } catch (error) {
2061
- span.recordException(error);
2062
- span.setStatus({ code: SpanStatusCode3.ERROR });
2063
- span.end();
2064
- throw error;
2065
- }
2066
- });
2067
- });
2068
- }
2069
-
2070
1339
  // src/internal/log/processors/log-processor.ts
2071
- import { context as context5 } from "@opentelemetry/api";
1340
+ import { context as context4 } from "@opentelemetry/api";
2072
1341
  import { BatchLogRecordProcessor, SimpleLogRecordProcessor } from "@opentelemetry/sdk-logs";
2073
1342
 
2074
1343
  // src/internal/masking/patterns.ts
@@ -2254,7 +1523,7 @@ var DEFAULT_PII_PATTERNS = [
2254
1523
  },
2255
1524
  {
2256
1525
  name: "discover_cards",
2257
- pattern: String.raw`\b65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}\b`
1526
+ pattern: String.raw`\b(?:65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12})\b`
2258
1527
  }
2259
1528
  ];
2260
1529
 
@@ -2508,7 +1777,7 @@ var BrizzSimpleLogRecordProcessor = class extends SimpleLogRecordProcessor {
2508
1777
  if (maskingConfig) {
2509
1778
  maskLog(logRecord, maskingConfig);
2510
1779
  }
2511
- const associationProperties = context5.active().getValue(PROPERTIES_CONTEXT_KEY);
1780
+ const associationProperties = context4.active().getValue(PROPERTIES_CONTEXT_KEY);
2512
1781
  if (associationProperties) {
2513
1782
  for (const [key, value] of Object.entries(associationProperties)) {
2514
1783
  logRecord.setAttribute(`${BRIZZ}.${key}`, value);
@@ -2528,7 +1797,7 @@ var BrizzBatchLogRecordProcessor = class extends BatchLogRecordProcessor {
2528
1797
  if (maskingConfig) {
2529
1798
  maskLog(logRecord, maskingConfig);
2530
1799
  }
2531
- const associationProperties = context5.active().getValue(PROPERTIES_CONTEXT_KEY);
1800
+ const associationProperties = context4.active().getValue(PROPERTIES_CONTEXT_KEY);
2532
1801
  if (associationProperties) {
2533
1802
  for (const [key, value] of Object.entries(associationProperties)) {
2534
1803
  logRecord.setAttribute(`${BRIZZ}.${key}`, value);
@@ -2674,6 +1943,7 @@ var LoggingModule = class _LoggingModule {
2674
1943
  this.loggerProvider = this.createLoggerProvider(config, config.appName);
2675
1944
  }
2676
1945
  _LoggingModule.instance = this;
1946
+ setEventSink(this);
2677
1947
  logger.info("Logging module setup completed");
2678
1948
  }
2679
1949
  /**
@@ -2751,17 +2021,10 @@ var LoggingModule = class _LoggingModule {
2751
2021
  if (_LoggingModule.instance === this) {
2752
2022
  _LoggingModule.instance = null;
2753
2023
  }
2024
+ clearEventSink(this);
2754
2025
  logger.debug("Logging module shutdown completed");
2755
2026
  }
2756
2027
  };
2757
- function emitEvent(name, attributes, body, severityNumber = SeverityNumber.INFO) {
2758
- return LoggingModule.getInstance().emitEvent(name, attributes, body, severityNumber);
2759
- }
2760
- function emitEventWithSessionId(sessionId, name, attributes, body, severityNumber = SeverityNumber.INFO) {
2761
- return callWithSessionId(sessionId, () => {
2762
- LoggingModule.getInstance().emitEvent(name, attributes, body, severityNumber);
2763
- });
2764
- }
2765
2028
 
2766
2029
  // src/internal/metric/metrics.ts
2767
2030
  import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
@@ -3023,13 +2286,13 @@ var BrizzSpanExporter = class {
3023
2286
  };
3024
2287
 
3025
2288
  // src/internal/trace/processors/span-processor.ts
3026
- import { context as context6 } from "@opentelemetry/api";
2289
+ import { context as context5 } from "@opentelemetry/api";
3027
2290
  import {
3028
2291
  BatchSpanProcessor,
3029
2292
  SimpleSpanProcessor
3030
2293
  } from "@opentelemetry/sdk-trace";
3031
2294
  function applyContextAttributes(span) {
3032
- const sessionProperties = context6.active().getValue(PROPERTIES_CONTEXT_KEY);
2295
+ const sessionProperties = context5.active().getValue(PROPERTIES_CONTEXT_KEY);
3033
2296
  if (sessionProperties) {
3034
2297
  for (const [key, value] of Object.entries(sessionProperties)) {
3035
2298
  span.setAttribute(`${BRIZZ}.${key}`, value);
@@ -3250,133 +2513,6 @@ function getSpanProcessor() {
3250
2513
  return TracingModule.getInstance().getSpanProcessor();
3251
2514
  }
3252
2515
 
3253
- // src/internal/trace/agent.ts
3254
- import { randomUUID } from "crypto";
3255
- import { context as context7 } from "@opentelemetry/api";
3256
- function newInstanceId() {
3257
- return randomUUID().replaceAll("-", "").slice(0, 8);
3258
- }
3259
- function activeProperties() {
3260
- return context7.active().getValue(PROPERTIES_CONTEXT_KEY) ?? {};
3261
- }
3262
- function encodeToken(agent) {
3263
- const payload = {
3264
- id: agent.id,
3265
- parentId: agent.parentId,
3266
- name: agent.name,
3267
- traceparent: agent.traceparent,
3268
- sessionId: agent.sessionId
3269
- };
3270
- return Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
3271
- }
3272
- function currentTraceparent() {
3273
- const carrier = {};
3274
- try {
3275
- injectTraceContext(context7.active(), carrier);
3276
- } catch {
3277
- }
3278
- return carrier["traceparent"] ?? "";
3279
- }
3280
- function agentHandle(id, parentId, name) {
3281
- const opened = {
3282
- id,
3283
- parentId,
3284
- name,
3285
- traceparent: currentTraceparent(),
3286
- sessionId: activeProperties()[SESSION_ID] ?? ""
3287
- };
3288
- return {
3289
- ...opened,
3290
- get token() {
3291
- return encodeToken(opened);
3292
- }
3293
- };
3294
- }
3295
- function decodeToken(token) {
3296
- try {
3297
- const payload = JSON.parse(Buffer.from(token, "base64url").toString("utf8"));
3298
- return payload.id ? payload : void 0;
3299
- } catch {
3300
- return void 0;
3301
- }
3302
- }
3303
- function unreadableAgent(agent) {
3304
- return {
3305
- id: "",
3306
- parentId: "",
3307
- name: "",
3308
- traceparent: "",
3309
- sessionId: "",
3310
- token: typeof agent === "string" ? "" : agent.token ?? ""
3311
- };
3312
- }
3313
- function resolveAgent(agent) {
3314
- const options = typeof agent === "string" ? { name: agent } : agent;
3315
- let id;
3316
- let parentId;
3317
- let name;
3318
- let sessionId = "";
3319
- let parentContext = context7.active();
3320
- if (options.token === void 0) {
3321
- id = options.id || newInstanceId();
3322
- parentId = options.parentId || activeProperties()[AGENT_ID] || "";
3323
- name = options.name ?? "";
3324
- } else {
3325
- const decoded = decodeToken(options.token);
3326
- if (!decoded) {
3327
- logger.warn("Brizz: ignoring an unreadable agent token");
3328
- return void 0;
3329
- }
3330
- id = decoded.id;
3331
- parentId = decoded.parentId;
3332
- name = decoded.name;
3333
- sessionId = decoded.sessionId;
3334
- if (decoded.traceparent) {
3335
- try {
3336
- parentContext = extractTraceContext(parentContext, { traceparent: decoded.traceparent });
3337
- } catch {
3338
- }
3339
- }
3340
- }
3341
- const properties = { [AGENT_ID]: id, [AGENT_NAME]: name };
3342
- if (parentId) {
3343
- properties[AGENT_PARENT_ID] = parentId;
3344
- }
3345
- if (sessionId) {
3346
- properties[SESSION_ID] = sessionId;
3347
- }
3348
- return { id, parentId, name, properties, parentContext };
3349
- }
3350
- function startAgent(agent, callback) {
3351
- const resolved = resolveAgent(agent);
3352
- if (!resolved) {
3353
- return callback(unreadableAgent(agent));
3354
- }
3355
- const { id, parentId, name, properties, parentContext } = resolved;
3356
- return context7.with(
3357
- parentContext,
3358
- () => callWithProperties(properties, () => callback(agentHandle(id, parentId, name)))
3359
- );
3360
- }
3361
- function withAgent(agent, fn, thisArg) {
3362
- return function wrapped(...args) {
3363
- return startAgent(
3364
- agent,
3365
- () => fn.apply(thisArg !== void 0 ? thisArg : this, args)
3366
- );
3367
- };
3368
- }
3369
- function setAgent(agent) {
3370
- const resolved = resolveAgent(agent);
3371
- if (!resolved) {
3372
- return unreadableAgent(agent);
3373
- }
3374
- const { id, parentId, name, properties, parentContext } = resolved;
3375
- setCurrentSpanCustomProperties(properties);
3376
- propagatePropertiesImperatively(properties, parentContext);
3377
- return agentHandle(id, parentId, name);
3378
- }
3379
-
3380
2516
  // src/internal/sdk.ts
3381
2517
  function resolveMcpSessionTracking(configured) {
3382
2518
  const fromEnv = process.env["BRIZZ_MCP_SESSION_TRACKING"];
@@ -3388,7 +2524,7 @@ function resolveMcpSessionTracking(configured) {
3388
2524
  }
3389
2525
  var BRIZZ_OWNED = /* @__PURE__ */ Symbol.for("brizz.sdk.ownedTracerProvider");
3390
2526
  function globalTracerDelegate() {
3391
- const global = trace4.getTracerProvider();
2527
+ const global = trace3.getTracerProvider();
3392
2528
  return typeof global.getDelegate === "function" ? global.getDelegate() : global;
3393
2529
  }
3394
2530
  var _Brizz = class __Brizz {