@brizz/sdk 0.1.57 → 0.1.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +52 -3
  2. package/dist/chunk-4QNEI7VZ.cjs +984 -0
  3. package/dist/{chunk-DCXOK7PX.cjs → chunk-5QZM5EVP.cjs} +8 -8
  4. package/dist/{chunk-O2IBZJOJ.cjs → chunk-6QXPHZEO.cjs} +4 -4
  5. package/dist/chunk-EZCNPWKM.js +984 -0
  6. package/dist/{chunk-7PRTTYWM.js → chunk-GABRGNAU.js} +1 -1
  7. package/dist/{chunk-GUKWVI53.js → chunk-GISL4K6Z.js} +27 -1
  8. package/dist/{chunk-RV7JIIDG.cjs → chunk-NF52RMLW.cjs} +27 -1
  9. package/dist/{chunk-42KYS2LU.js → chunk-ZGX52S4U.js} +2 -2
  10. package/dist/index.cjs +280 -966
  11. package/dist/index.js +238 -924
  12. package/dist/interrupt-36U5562Z.cjs +12 -0
  13. package/dist/{interrupt-UKJK5WOA.js → interrupt-6BSXUK3O.js} +2 -2
  14. package/dist/{mcp-FBTQYIOL.js → mcp-TTECBPGZ.js} +4 -3
  15. package/dist/{mcp-WHXEBLRI.cjs → mcp-UPBKSTB7.cjs} +19 -18
  16. package/dist/session.cjs +78 -0
  17. package/dist/session.js +78 -0
  18. package/dist/types/cjs/index.d.ts +2 -2
  19. package/dist/types/cjs/internal/error-type.d.ts +1 -0
  20. package/dist/types/cjs/internal/instrumentation/mcp/semantic-conventions.d.ts +1 -1
  21. package/dist/types/cjs/internal/instrumentation/typesafe.d.ts +0 -8
  22. package/dist/types/cjs/internal/log/emit.d.ts +8 -0
  23. package/dist/types/cjs/internal/log/logging.d.ts +2 -2
  24. package/dist/types/cjs/internal/semantic-conventions.d.ts +13 -0
  25. package/dist/types/cjs/internal/serialization.d.ts +2 -0
  26. package/dist/types/cjs/internal/trace/decision-call.d.ts +24 -0
  27. package/dist/types/cjs/internal/trace/index.d.ts +2 -0
  28. package/dist/types/cjs/internal/trace/session.d.ts +2 -1
  29. package/dist/types/cjs/session.d.ts +6 -0
  30. package/dist/types/esm/index.d.ts +2 -2
  31. package/dist/types/esm/internal/error-type.d.ts +1 -0
  32. package/dist/types/esm/internal/instrumentation/mcp/semantic-conventions.d.ts +1 -1
  33. package/dist/types/esm/internal/instrumentation/typesafe.d.ts +0 -8
  34. package/dist/types/esm/internal/log/emit.d.ts +8 -0
  35. package/dist/types/esm/internal/log/logging.d.ts +2 -2
  36. package/dist/types/esm/internal/semantic-conventions.d.ts +13 -0
  37. package/dist/types/esm/internal/serialization.d.ts +2 -0
  38. package/dist/types/esm/internal/trace/decision-call.d.ts +24 -0
  39. package/dist/types/esm/internal/trace/index.d.ts +2 -0
  40. package/dist/types/esm/internal/trace/session.d.ts +2 -1
  41. package/dist/types/esm/session.d.ts +6 -0
  42. package/package.json +29 -18
  43. package/dist/interrupt-BYLSBXTV.cjs +0 -12
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-EZCNPWKM.js";
5
43
  import {
6
44
  configure,
7
45
  getSDKVersion
8
- } from "./chunk-42KYS2LU.js";
46
+ } from "./chunk-ZGX52S4U.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";
@@ -26,68 +62,31 @@ import {
26
62
  } from "./chunk-Y4HNUX3Q.js";
27
63
  import {
28
64
  InterruptPropagator
29
- } from "./chunk-7PRTTYWM.js";
65
+ } from "./chunk-GABRGNAU.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,
68
+ ERROR_TYPE,
69
+ GEN_AI_CONVERSATION_ID,
70
+ GEN_AI_INPUT_MESSAGES,
71
+ GEN_AI_OPERATION_CLASSIFY,
72
+ GEN_AI_OPERATION_NAME,
73
+ GEN_AI_OUTPUT_MESSAGES,
74
+ GEN_AI_OUTPUT_TYPE,
75
+ GEN_AI_PROVIDER_NAME,
76
+ GEN_AI_REQUEST_MODEL,
77
+ GEN_AI_RESPONSE_MODEL,
78
+ GEN_AI_USAGE_COST_USD,
79
+ GEN_AI_USAGE_INPUT_TOKENS,
80
+ GEN_AI_USAGE_OUTPUT_TOKENS,
46
81
  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
82
  ORGANIZATION_DOMAIN,
68
- ORGANIZATION_ID,
69
83
  ORGANIZATION_NAME,
70
- ORGANIZATION_PLAN,
71
84
  PROPERTIES_CONTEXT_KEY,
72
- RESERVED_METRIC_NAMES,
73
- SERVICE_NAME,
74
85
  SERVICE_NAME_ATTRIBUTE,
75
86
  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
87
  USER_EMAIL,
86
- USER_ID,
87
- USER_NAME,
88
- USER_PLAN,
89
- USER_ROLE
90
- } from "./chunk-GUKWVI53.js";
88
+ USER_NAME
89
+ } from "./chunk-GISL4K6Z.js";
91
90
  import {
92
91
  __require
93
92
  } from "./chunk-3RG5ZIWI.js";
@@ -451,19 +450,34 @@ import {
451
450
  InstrumentationBase as InstrumentationBase2,
452
451
  InstrumentationNodeModuleDefinition as InstrumentationNodeModuleDefinition2
453
452
  } from "@opentelemetry/instrumentation";
453
+
454
+ // src/internal/error-type.ts
455
+ function errorType(error) {
456
+ if (!(error instanceof Error)) {
457
+ return "_OTHER";
458
+ }
459
+ return error.constructor?.name || error.name || "_OTHER";
460
+ }
461
+
462
+ // src/internal/serialization.ts
463
+ function toJson(value) {
464
+ try {
465
+ return JSON.stringify(value);
466
+ } catch (error) {
467
+ logger.debug(`Brizz: value is not JSON-serializable: ${String(error)}`);
468
+ return void 0;
469
+ }
470
+ }
471
+ function text(value) {
472
+ return typeof value === "string" ? value : toJson(value) ?? "";
473
+ }
474
+
475
+ // src/internal/instrumentation/typesafe.ts
454
476
  var INSTRUMENTATION_NAME2 = "@brizz/sdk/typesafe";
455
477
  var MODULE_NAME2 = "@typesafe-ai/sdk";
456
478
  var SUPPORTED_VERSIONS2 = [">=0.5.7 <1"];
457
479
  var SPAN_NAME = "typesafe.system_one";
458
480
  var PROVIDER_NAME = "typesafe";
459
- var OPERATION_NAME = "classify";
460
- var ATTR_OPERATION_NAME = "gen_ai.operation.name";
461
- var ATTR_PROVIDER_NAME = "gen_ai.provider.name";
462
- var ATTR_REQUEST_MODEL = "gen_ai.request.model";
463
- var ATTR_RESPONSE_MODEL = "gen_ai.response.model";
464
- var ATTR_INPUT_TOKENS = "gen_ai.usage.input_tokens";
465
- var ATTR_OUTPUT_TOKENS = "gen_ai.usage.output_tokens";
466
- var ATTR_INPUT_MESSAGES = "gen_ai.input.messages";
467
481
  var ATTR_QUESTIONS = "typesafe.questions";
468
482
  var ATTR_ANSWERS = "typesafe.answers";
469
483
  var PATCHED_FLAG2 = /* @__PURE__ */ Symbol.for("brizz.typesafe.patched");
@@ -605,14 +619,14 @@ function startSpan(getTracer, request) {
605
619
  try {
606
620
  const model = typeof request?.model === "string" && request.model !== "" ? request.model : void 0;
607
621
  const attributes = {
608
- [ATTR_OPERATION_NAME]: OPERATION_NAME,
609
- [ATTR_PROVIDER_NAME]: PROVIDER_NAME,
610
- [ATTR_INPUT_MESSAGES]: JSON.stringify([
622
+ [GEN_AI_OPERATION_NAME]: GEN_AI_OPERATION_CLASSIFY,
623
+ [GEN_AI_PROVIDER_NAME]: PROVIDER_NAME,
624
+ [GEN_AI_INPUT_MESSAGES]: JSON.stringify([
611
625
  { role: "user", parts: [{ type: "text", content: text(request?.state) }] }
612
626
  ])
613
627
  };
614
628
  if (model) {
615
- attributes[ATTR_REQUEST_MODEL] = model;
629
+ attributes[GEN_AI_REQUEST_MODEL] = model;
616
630
  }
617
631
  if (request?.questions !== void 0) {
618
632
  attributes[ATTR_QUESTIONS] = JSON.stringify(request.questions);
@@ -627,13 +641,13 @@ function recordResult(span, result) {
627
641
  try {
628
642
  const { model, usage, answers } = result ?? {};
629
643
  if (typeof model === "string" && model) {
630
- span.setAttribute(ATTR_RESPONSE_MODEL, model);
644
+ span.setAttribute(GEN_AI_RESPONSE_MODEL, model);
631
645
  }
632
646
  if (typeof usage?.input_tokens === "number") {
633
- span.setAttribute(ATTR_INPUT_TOKENS, usage.input_tokens);
647
+ span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, usage.input_tokens);
634
648
  }
635
649
  if (typeof usage?.output_tokens === "number") {
636
- span.setAttribute(ATTR_OUTPUT_TOKENS, usage.output_tokens);
650
+ span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, usage.output_tokens);
637
651
  }
638
652
  if (answers !== void 0) {
639
653
  span.setAttribute(ATTR_ANSWERS, JSON.stringify(answers));
@@ -649,12 +663,10 @@ function endSpan(span, error) {
649
663
  if (error !== void 0) {
650
664
  span.recordException(error instanceof Error ? error : new Error(String(error)));
651
665
  span.setStatus({ code: SpanStatusCode2.ERROR, message: String(error) });
666
+ span.setAttribute(ERROR_TYPE, errorType(error));
652
667
  }
653
668
  span.end();
654
669
  }
655
- function text(value) {
656
- return typeof value === "string" ? value : JSON.stringify(value) ?? "";
657
- }
658
670
 
659
671
  // src/internal/instrumentation/auto-init.ts
660
672
  var exceptionLogger = (error) => {
@@ -698,7 +710,7 @@ function loadGenAIInstrumentations() {
698
710
  function loadMCPInstrumentation() {
699
711
  void (async () => {
700
712
  try {
701
- const { MCPInstrumentation } = await import("./mcp-FBTQYIOL.js");
713
+ const { MCPInstrumentation } = await import("./mcp-TTECBPGZ.js");
702
714
  const mcp = new MCPInstrumentation({ exceptionLogger });
703
715
  registerInstrumentations({ instrumentations: [mcp], tracerProvider: brizzTracerProvider });
704
716
  logger.debug("Auto-loaded MCP instrumentation");
@@ -782,7 +794,7 @@ function loadVercelAITelemetry() {
782
794
  }
783
795
  const isV7 = typeof ai.registerTelemetry === "function";
784
796
  const integrations = [];
785
- const { createInterruptIntegration } = await import("./interrupt-UKJK5WOA.js");
797
+ const { createInterruptIntegration } = await import("./interrupt-6BSXUK3O.js");
786
798
  integrations.push(createInterruptIntegration());
787
799
  let otelCollectorLoaded = false;
788
800
  try {
@@ -1075,21 +1087,21 @@ function patchCallbackManagerModule(module2) {
1075
1087
  return true;
1076
1088
  }
1077
1089
  function patchTracer(handler) {
1078
- const tracer = handler;
1079
- if (typeof tracer !== "object" || tracer === null || tracer[TRACER_PATCHED_MARKER] === true) {
1090
+ const tracer2 = handler;
1091
+ if (typeof tracer2 !== "object" || tracer2 === null || tracer2[TRACER_PATCHED_MARKER] === true) {
1080
1092
  return;
1081
1093
  }
1082
- const addRunToRunMap = tracer["_addRunToRunMap"];
1083
- const onRunCreate = tracer["onRunCreate"];
1084
- const endTrace = tracer["_endTrace"];
1094
+ const addRunToRunMap = tracer2["_addRunToRunMap"];
1095
+ const onRunCreate = tracer2["onRunCreate"];
1096
+ const endTrace = tracer2["_endTrace"];
1085
1097
  if (typeof addRunToRunMap !== "function" || typeof onRunCreate !== "function" || typeof endTrace !== "function") {
1086
1098
  return;
1087
1099
  }
1088
- tracer[TRACER_PATCHED_MARKER] = true;
1089
- tracer["onRunCreate"] = inRunContext(onRunCreate);
1090
- tracer["_endTrace"] = inRunContext(endTrace);
1100
+ tracer2[TRACER_PATCHED_MARKER] = true;
1101
+ tracer2["onRunCreate"] = inRunContext(onRunCreate);
1102
+ tracer2["_endTrace"] = inRunContext(endTrace);
1091
1103
  const addRun = addRunToRunMap;
1092
- tracer["_addRunToRunMap"] = function(...args) {
1104
+ tracer2["_addRunToRunMap"] = function(...args) {
1093
1105
  const run = addRun.apply(this, args);
1094
1106
  if (typeof run === "object" && run !== null) {
1095
1107
  runContexts.set(run, context3.active());
@@ -1309,7 +1321,7 @@ var InstrumentationRegistry = class _InstrumentationRegistry {
1309
1321
  const mcpModules = this.manualModules.mcp;
1310
1322
  void (async () => {
1311
1323
  try {
1312
- const { MCPInstrumentation } = await import("./mcp-FBTQYIOL.js");
1324
+ const { MCPInstrumentation } = await import("./mcp-TTECBPGZ.js");
1313
1325
  const instrumentation = new MCPInstrumentation({ exceptionLogger: exceptionLogger2 });
1314
1326
  instrumentation.manuallyInstrument(mcpModules);
1315
1327
  logger.debug("Manual instrumentation enabled for MCP");
@@ -1351,724 +1363,8 @@ import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-http";
1351
1363
  import { resourceFromAttributes } from "@opentelemetry/resources";
1352
1364
  import { LoggerProvider } from "@opentelemetry/sdk-logs";
1353
1365
 
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
1366
  // src/internal/log/processors/log-processor.ts
2071
- import { context as context5 } from "@opentelemetry/api";
1367
+ import { context as context4 } from "@opentelemetry/api";
2072
1368
  import { BatchLogRecordProcessor, SimpleLogRecordProcessor } from "@opentelemetry/sdk-logs";
2073
1369
 
2074
1370
  // src/internal/masking/patterns.ts
@@ -2508,7 +1804,7 @@ var BrizzSimpleLogRecordProcessor = class extends SimpleLogRecordProcessor {
2508
1804
  if (maskingConfig) {
2509
1805
  maskLog(logRecord, maskingConfig);
2510
1806
  }
2511
- const associationProperties = context5.active().getValue(PROPERTIES_CONTEXT_KEY);
1807
+ const associationProperties = context4.active().getValue(PROPERTIES_CONTEXT_KEY);
2512
1808
  if (associationProperties) {
2513
1809
  for (const [key, value] of Object.entries(associationProperties)) {
2514
1810
  logRecord.setAttribute(`${BRIZZ}.${key}`, value);
@@ -2528,7 +1824,7 @@ var BrizzBatchLogRecordProcessor = class extends BatchLogRecordProcessor {
2528
1824
  if (maskingConfig) {
2529
1825
  maskLog(logRecord, maskingConfig);
2530
1826
  }
2531
- const associationProperties = context5.active().getValue(PROPERTIES_CONTEXT_KEY);
1827
+ const associationProperties = context4.active().getValue(PROPERTIES_CONTEXT_KEY);
2532
1828
  if (associationProperties) {
2533
1829
  for (const [key, value] of Object.entries(associationProperties)) {
2534
1830
  logRecord.setAttribute(`${BRIZZ}.${key}`, value);
@@ -2674,6 +1970,7 @@ var LoggingModule = class _LoggingModule {
2674
1970
  this.loggerProvider = this.createLoggerProvider(config, config.appName);
2675
1971
  }
2676
1972
  _LoggingModule.instance = this;
1973
+ setEventSink(this);
2677
1974
  logger.info("Logging module setup completed");
2678
1975
  }
2679
1976
  /**
@@ -2751,17 +2048,10 @@ var LoggingModule = class _LoggingModule {
2751
2048
  if (_LoggingModule.instance === this) {
2752
2049
  _LoggingModule.instance = null;
2753
2050
  }
2051
+ clearEventSink(this);
2754
2052
  logger.debug("Logging module shutdown completed");
2755
2053
  }
2756
2054
  };
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
2055
 
2766
2056
  // src/internal/metric/metrics.ts
2767
2057
  import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
@@ -3023,13 +2313,13 @@ var BrizzSpanExporter = class {
3023
2313
  };
3024
2314
 
3025
2315
  // src/internal/trace/processors/span-processor.ts
3026
- import { context as context6 } from "@opentelemetry/api";
2316
+ import { context as context5 } from "@opentelemetry/api";
3027
2317
  import {
3028
2318
  BatchSpanProcessor,
3029
2319
  SimpleSpanProcessor
3030
2320
  } from "@opentelemetry/sdk-trace";
3031
2321
  function applyContextAttributes(span) {
3032
- const sessionProperties = context6.active().getValue(PROPERTIES_CONTEXT_KEY);
2322
+ const sessionProperties = context5.active().getValue(PROPERTIES_CONTEXT_KEY);
3033
2323
  if (sessionProperties) {
3034
2324
  for (const [key, value] of Object.entries(sessionProperties)) {
3035
2325
  span.setAttribute(`${BRIZZ}.${key}`, value);
@@ -3250,131 +2540,153 @@ function getSpanProcessor() {
3250
2540
  return TracingModule.getInstance().getSpanProcessor();
3251
2541
  }
3252
2542
 
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");
2543
+ // src/internal/trace/decision-call.ts
2544
+ import { SpanKind as SpanKind2, SpanStatusCode as SpanStatusCode3, context as context6, trace as trace3 } from "@opentelemetry/api";
2545
+ import { suppressTracing } from "@opentelemetry/core";
2546
+ var tracer = brizzTracerProvider.getTracer("@brizz/sdk/decision-call", getSDKVersion());
2547
+ function decisionCall(options, callback) {
2548
+ const span = startDecisionSpan(options);
2549
+ if (!span) {
2550
+ return callback(describeResultOn(void 0, options.provider));
2551
+ }
2552
+ const callbackContext = suppressTracing(trace3.setSpan(context6.active(), span));
2553
+ let result;
2554
+ try {
2555
+ result = context6.with(
2556
+ callbackContext,
2557
+ callback,
2558
+ void 0,
2559
+ describeResultOn(span, options.provider)
2560
+ );
2561
+ } catch (error) {
2562
+ endWithError(span, error);
2563
+ throw error;
2564
+ }
2565
+ return endWhenSettled(span, result);
3271
2566
  }
3272
- function currentTraceparent() {
3273
- const carrier = {};
2567
+ function recordDecisionCall(record) {
3274
2568
  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);
2569
+ const span = startDecisionSpan(record, record.startTime ?? record.endTime);
2570
+ if (!span) {
2571
+ return;
3292
2572
  }
3293
- };
2573
+ const call = describeResultOn(span, record.provider);
2574
+ if (record.answers !== void 0) {
2575
+ call.setAnswers(record.answers);
2576
+ }
2577
+ call.setUsage(record);
2578
+ if (record.costUsd !== void 0) {
2579
+ call.setCost(record.costUsd);
2580
+ }
2581
+ span.end(record.endTime);
2582
+ } catch (error) {
2583
+ logger.debug(`Brizz decision call: could not record the call: ${String(error)}`);
2584
+ }
3294
2585
  }
3295
- function decodeToken(token) {
2586
+ function startDecisionSpan(options, startTime) {
3296
2587
  try {
3297
- const payload = JSON.parse(Buffer.from(token, "base64url").toString("utf8"));
3298
- return payload.id ? payload : void 0;
3299
- } catch {
2588
+ const requestModel = options.requestModel || options.model;
2589
+ const attributes = {
2590
+ [GEN_AI_OPERATION_NAME]: GEN_AI_OPERATION_CLASSIFY,
2591
+ [GEN_AI_PROVIDER_NAME]: options.provider,
2592
+ [GEN_AI_REQUEST_MODEL]: requestModel,
2593
+ [GEN_AI_RESPONSE_MODEL]: options.model,
2594
+ [GEN_AI_OUTPUT_TYPE]: "json"
2595
+ };
2596
+ const inputMessages = toJson([
2597
+ {
2598
+ role: "user",
2599
+ parts: [
2600
+ { type: "text", content: text(options.state) },
2601
+ { type: `${options.provider}.questions`, content: options.questions }
2602
+ ]
2603
+ }
2604
+ ]);
2605
+ if (inputMessages !== void 0) {
2606
+ attributes[GEN_AI_INPUT_MESSAGES] = inputMessages;
2607
+ }
2608
+ const sessionId = currentSessionId();
2609
+ if (sessionId) {
2610
+ attributes[GEN_AI_CONVERSATION_ID] = sessionId;
2611
+ }
2612
+ return tracer.startSpan(`${GEN_AI_OPERATION_CLASSIFY} ${requestModel}`, {
2613
+ kind: SpanKind2.CLIENT,
2614
+ attributes,
2615
+ startTime
2616
+ });
2617
+ } catch (error) {
2618
+ logger.debug(`Brizz decision call: could not start span: ${String(error)}`);
3300
2619
  return void 0;
3301
2620
  }
3302
2621
  }
3303
- function unreadableAgent(agent) {
3304
- return {
3305
- id: "",
3306
- parentId: "",
3307
- name: "",
3308
- traceparent: "",
3309
- sessionId: "",
3310
- token: typeof agent === "string" ? "" : agent.token ?? ""
3311
- };
2622
+ function currentSessionId() {
2623
+ const properties = context6.active().getValue(PROPERTIES_CONTEXT_KEY);
2624
+ return properties?.[SESSION_ID];
3312
2625
  }
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;
2626
+ function describeResultOn(span, provider) {
2627
+ const set = (key, value) => {
2628
+ if (!span || value === void 0) {
2629
+ return;
3329
2630
  }
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
- }
2631
+ try {
2632
+ span.setAttribute(key, value);
2633
+ } catch (error) {
2634
+ logger.debug(`Brizz decision call: could not set ${key}: ${String(error)}`);
3339
2635
  }
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 };
2636
+ };
2637
+ return {
2638
+ setAnswers(answers) {
2639
+ set(
2640
+ GEN_AI_OUTPUT_MESSAGES,
2641
+ toJson([
2642
+ {
2643
+ role: "assistant",
2644
+ parts: [{ type: `${provider}.answers`, content: answers }],
2645
+ finish_reason: "stop"
2646
+ }
2647
+ ])
2648
+ );
2649
+ },
2650
+ setUsage(usage) {
2651
+ set(GEN_AI_USAGE_INPUT_TOKENS, finiteNumber(usage?.inputTokens));
2652
+ set(GEN_AI_USAGE_OUTPUT_TOKENS, finiteNumber(usage?.outputTokens));
2653
+ },
2654
+ setCost(costUsd) {
2655
+ set(GEN_AI_USAGE_COST_USD, finiteNumber(costUsd));
2656
+ }
2657
+ };
3349
2658
  }
3350
- function startAgent(agent, callback) {
3351
- const resolved = resolveAgent(agent);
3352
- if (!resolved) {
3353
- return callback(unreadableAgent(agent));
2659
+ function endWhenSettled(span, result) {
2660
+ if (typeof result?.then !== "function") {
2661
+ span.end();
2662
+ return result;
3354
2663
  }
3355
- const { id, parentId, name, properties, parentContext } = resolved;
3356
- return context7.with(
3357
- parentContext,
3358
- () => callWithProperties(properties, () => callback(agentHandle(id, parentId, name)))
2664
+ return Promise.resolve(result).then(
2665
+ (value) => {
2666
+ span.end();
2667
+ return value;
2668
+ },
2669
+ (error) => {
2670
+ endWithError(span, error);
2671
+ throw error;
2672
+ }
3359
2673
  );
3360
2674
  }
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);
2675
+ function endWithError(span, error) {
2676
+ try {
2677
+ span.recordException(error instanceof Error ? error : String(error));
2678
+ span.setStatus({
2679
+ code: SpanStatusCode3.ERROR,
2680
+ message: error instanceof Error ? error.message : String(error)
2681
+ });
2682
+ span.setAttribute(ERROR_TYPE, errorType(error));
2683
+ } catch (describeError) {
2684
+ logger.debug(`Brizz decision call: could not record the error: ${String(describeError)}`);
3373
2685
  }
3374
- const { id, parentId, name, properties, parentContext } = resolved;
3375
- setCurrentSpanCustomProperties(properties);
3376
- propagatePropertiesImperatively(properties, parentContext);
3377
- return agentHandle(id, parentId, name);
2686
+ span.end();
2687
+ }
2688
+ function finiteNumber(value) {
2689
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
3378
2690
  }
3379
2691
 
3380
2692
  // src/internal/sdk.ts
@@ -3728,6 +3040,7 @@ export {
3728
3040
  callWithServiceName,
3729
3041
  callWithSessionId,
3730
3042
  callWithUser,
3043
+ decisionCall,
3731
3044
  emitEvent,
3732
3045
  emitEventWithSessionId,
3733
3046
  getActiveSession,
@@ -3740,6 +3053,7 @@ export {
3740
3053
  logger,
3741
3054
  maskAttributes,
3742
3055
  maskValue,
3056
+ recordDecisionCall,
3743
3057
  recordFeedback,
3744
3058
  recordMetric,
3745
3059
  setAgent,