@brizz/sdk 0.2.0 → 0.2.2

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 (49) hide show
  1. package/CHANGELOG.md +436 -0
  2. package/LICENSE +194 -20
  3. package/README.md +36 -1
  4. package/dist/{chunk-WC573FCI.cjs → chunk-C5OT6GAQ.cjs} +10 -2
  5. package/dist/{chunk-5HCG3JKU.js → chunk-CNEZA3WB.js} +5 -5
  6. package/dist/{chunk-Y4HNUX3Q.js → chunk-CZDPIJTO.js} +8 -0
  7. package/dist/{chunk-B5IY6O4N.js → chunk-DIOULRY4.js} +3 -2
  8. package/dist/{chunk-EZCNPWKM.js → chunk-GITAPIVL.js} +9 -9
  9. package/dist/{chunk-NF52RMLW.cjs → chunk-IWSFMCHH.cjs} +5 -1
  10. package/dist/{chunk-GISL4K6Z.js → chunk-JMX23OHO.js} +4 -0
  11. package/dist/{chunk-RD4XCYKT.cjs → chunk-PUOXH4CD.cjs} +6 -5
  12. package/dist/{chunk-CNVK5RA3.cjs → chunk-STMZ73NM.cjs} +13 -13
  13. package/dist/{chunk-4QNEI7VZ.cjs → chunk-UF4GMVEY.cjs} +142 -142
  14. package/dist/eve.cjs +2 -3
  15. package/dist/eve.js +1 -2
  16. package/dist/google-genai-KDEYFHTK.cjs +12 -0
  17. package/dist/{google-genai-3ERJNC7Q.js → google-genai-ZKKWSBVY.js} +4 -3
  18. package/dist/google-genai.cjs +3 -4
  19. package/dist/google-genai.js +2 -3
  20. package/dist/index.cjs +629 -306
  21. package/dist/index.js +410 -87
  22. package/dist/{mcp-5ERVMLSA.cjs → mcp-E5TPIVFI.cjs} +39 -40
  23. package/dist/{mcp-EJAJTGIC.js → mcp-SZSGMNBB.js} +5 -6
  24. package/dist/session.cjs +4 -5
  25. package/dist/session.js +3 -4
  26. package/dist/types/cjs/internal/instrumentation/auto-init.d.ts +0 -7
  27. package/dist/types/cjs/internal/instrumentation/google-genai.d.ts +1 -0
  28. package/dist/types/cjs/internal/instrumentation/registry.d.ts +2 -0
  29. package/dist/types/cjs/internal/instrumentation/vercel-ai/index.d.ts +28 -0
  30. package/dist/types/cjs/internal/instrumentation/vercel-ai/model-call-end.d.ts +1 -0
  31. package/dist/types/cjs/internal/masking/utils.d.ts +1 -1
  32. package/dist/types/cjs/internal/sdk.d.ts +1 -0
  33. package/dist/types/cjs/internal/semantic-conventions.d.ts +2 -0
  34. package/dist/types/esm/internal/instrumentation/auto-init.d.ts +0 -7
  35. package/dist/types/esm/internal/instrumentation/google-genai.d.ts +1 -0
  36. package/dist/types/esm/internal/instrumentation/registry.d.ts +2 -0
  37. package/dist/types/esm/internal/instrumentation/vercel-ai/index.d.ts +28 -0
  38. package/dist/types/esm/internal/instrumentation/vercel-ai/model-call-end.d.ts +1 -0
  39. package/dist/types/esm/internal/masking/utils.d.ts +1 -1
  40. package/dist/types/esm/internal/sdk.d.ts +1 -0
  41. package/dist/types/esm/internal/semantic-conventions.d.ts +2 -0
  42. package/package.json +36 -29
  43. package/dist/chunk-3RG5ZIWI.js +0 -10
  44. package/dist/chunk-6QXPHZEO.cjs +0 -130
  45. package/dist/chunk-GABRGNAU.js +0 -130
  46. package/dist/chunk-OBGZSXTJ.cjs +0 -10
  47. package/dist/google-genai-GVCKSJMR.cjs +0 -11
  48. package/dist/interrupt-36U5562Z.cjs +0 -12
  49. package/dist/interrupt-6BSXUK3O.js +0 -12
package/dist/index.js CHANGED
@@ -39,31 +39,14 @@ import {
39
39
  withServiceName,
40
40
  withSessionId,
41
41
  withUser
42
- } from "./chunk-EZCNPWKM.js";
42
+ } from "./chunk-GITAPIVL.js";
43
43
  import {
44
44
  configure,
45
45
  getSDKVersion
46
- } from "./chunk-5HCG3JKU.js";
47
- import {
48
- bindToBrizz,
49
- brizzTracerProvider,
50
- ensureContextManager,
51
- getTracerProvider,
52
- registerTracerProvider,
53
- setPrivateTracerProvider
54
- } from "./chunk-TDPQDITP.js";
55
- import {
56
- DEFAULT_LOG_LEVEL,
57
- LogLevel,
58
- getLogLevel,
59
- logger,
60
- parseLogLevel,
61
- setLogLevel
62
- } from "./chunk-Y4HNUX3Q.js";
63
- import {
64
- InterruptPropagator
65
- } from "./chunk-GABRGNAU.js";
46
+ } from "./chunk-CNEZA3WB.js";
66
47
  import {
48
+ AI_SDK_OTEL_SCOPE,
49
+ APPROVALS,
67
50
  BRIZZ,
68
51
  ERROR_TYPE,
69
52
  GEN_AI_CONVERSATION_ID,
@@ -79,6 +62,7 @@ import {
79
62
  GEN_AI_USAGE_INPUT_TOKENS,
80
63
  GEN_AI_USAGE_OUTPUT_TOKENS,
81
64
  INTERNAL_EVENT_PREFIX,
65
+ INTERRUPT_TOOLS,
82
66
  ORGANIZATION_DOMAIN,
83
67
  ORGANIZATION_NAME,
84
68
  PROPERTIES_CONTEXT_KEY,
@@ -86,10 +70,24 @@ import {
86
70
  SESSION_ID,
87
71
  USER_EMAIL,
88
72
  USER_NAME
89
- } from "./chunk-GISL4K6Z.js";
73
+ } from "./chunk-JMX23OHO.js";
74
+ import {
75
+ bindToBrizz,
76
+ brizzTracerProvider,
77
+ ensureContextManager,
78
+ getTracerProvider,
79
+ registerTracerProvider,
80
+ setPrivateTracerProvider
81
+ } from "./chunk-TDPQDITP.js";
90
82
  import {
91
- __require
92
- } from "./chunk-3RG5ZIWI.js";
83
+ DEFAULT_LOG_LEVEL,
84
+ LogLevel,
85
+ __require,
86
+ getLogLevel,
87
+ logger,
88
+ parseLogLevel,
89
+ setLogLevel
90
+ } from "./chunk-CZDPIJTO.js";
93
91
 
94
92
  // src/internal/instrumentation/auto-init.ts
95
93
  import { registerInstrumentations } from "@opentelemetry/instrumentation";
@@ -710,7 +708,7 @@ function loadGenAIInstrumentations() {
710
708
  function loadMCPInstrumentation() {
711
709
  void (async () => {
712
710
  try {
713
- const { MCPInstrumentation } = await import("./mcp-EJAJTGIC.js");
711
+ const { MCPInstrumentation } = await import("./mcp-SZSGMNBB.js");
714
712
  const mcp = new MCPInstrumentation({ exceptionLogger });
715
713
  registerInstrumentations({ instrumentations: [mcp], tracerProvider: brizzTracerProvider });
716
714
  logger.debug("Auto-loaded MCP instrumentation");
@@ -763,7 +761,7 @@ function loadVertexAIInstrumentation() {
763
761
  function loadGoogleGenAIInstrumentation() {
764
762
  void (async () => {
765
763
  try {
766
- const { GoogleGenAIInstrumentation } = await import("./google-genai-3ERJNC7Q.js");
764
+ const { GoogleGenAIInstrumentation } = await import("./google-genai-ZKKWSBVY.js");
767
765
  const googleGenAI = new GoogleGenAIInstrumentation({ exceptionLogger });
768
766
  registerInstrumentations({
769
767
  instrumentations: [googleGenAI],
@@ -777,53 +775,6 @@ function loadGoogleGenAIInstrumentation() {
777
775
  }
778
776
  })();
779
777
  }
780
- function selectTelemetryRegister(ai) {
781
- const register = ai.registerTelemetry ?? ai.registerTelemetryIntegration;
782
- return typeof register === "function" ? register : void 0;
783
- }
784
- function loadVercelAITelemetry() {
785
- void (async () => {
786
- try {
787
- const ai = await import("ai");
788
- const register = selectTelemetryRegister(ai);
789
- if (!register) {
790
- logger.debug(
791
- "AI SDK present but lacks a telemetry-registration hook (needs ai@>=6); skipping"
792
- );
793
- return;
794
- }
795
- const isV7 = typeof ai.registerTelemetry === "function";
796
- const integrations = [];
797
- const { createInterruptIntegration } = await import("./interrupt-6BSXUK3O.js");
798
- integrations.push(createInterruptIntegration());
799
- let otelCollectorLoaded = false;
800
- try {
801
- const otel = await import("@ai-sdk/otel");
802
- if (typeof otel.LegacyOpenTelemetry === "function") {
803
- integrations.push(
804
- new otel.LegacyOpenTelemetry({ tracer: brizzTracerProvider.getTracer("ai") })
805
- );
806
- otelCollectorLoaded = true;
807
- }
808
- } catch {
809
- }
810
- if (!otelCollectorLoaded) {
811
- const message = "AI SDK present but @ai-sdk/otel is missing or unusable; install it (npm install @ai-sdk/otel) to capture AI SDK spans on ai@>=7";
812
- if (isV7) {
813
- logger.warn(message);
814
- } else {
815
- logger.debug(message);
816
- }
817
- }
818
- register(...integrations);
819
- logger.debug("Auto-loaded Vercel AI telemetry");
820
- } catch (error) {
821
- logger.debug(
822
- `Vercel AI telemetry not loaded (install ai@>=6 to capture AI SDK telemetry): ${String(error)}`
823
- );
824
- }
825
- })();
826
- }
827
778
  function autoInitializeInstrumentations() {
828
779
  try {
829
780
  const genAIInstrumentations = loadGenAIInstrumentations();
@@ -832,7 +783,6 @@ function autoInitializeInstrumentations() {
832
783
  loadTypeSafeInstrumentation();
833
784
  loadVertexAIInstrumentation();
834
785
  loadGoogleGenAIInstrumentation();
835
- loadVercelAITelemetry();
836
786
  logger.info(
837
787
  `Auto-initialization complete: ${genAIInstrumentations.length} GenAI instrumentations`
838
788
  );
@@ -845,7 +795,7 @@ function autoInitializeInstrumentations() {
845
795
  var autoInstrumentationsLoaded = autoInitializeInstrumentations();
846
796
 
847
797
  // src/internal/sdk.ts
848
- import { metrics, trace as trace4 } from "@opentelemetry/api";
798
+ import { metrics, trace as trace5 } from "@opentelemetry/api";
849
799
  import { registerInstrumentations as registerInstrumentations2 } from "@opentelemetry/instrumentation";
850
800
  import {
851
801
  defaultResource,
@@ -1306,7 +1256,7 @@ var InstrumentationRegistry = class _InstrumentationRegistry {
1306
1256
  const genaiModule = this.manualModules.google_genai;
1307
1257
  void (async () => {
1308
1258
  try {
1309
- const { GoogleGenAIInstrumentation } = await import("./google-genai-3ERJNC7Q.js");
1259
+ const { GoogleGenAIInstrumentation } = await import("./google-genai-ZKKWSBVY.js");
1310
1260
  const genaiInst = new GoogleGenAIInstrumentation({ exceptionLogger: exceptionLogger2 });
1311
1261
  genaiInst.manuallyInstrument(genaiModule);
1312
1262
  logger.debug("Manual instrumentation enabled for Google GenAI");
@@ -1321,7 +1271,7 @@ var InstrumentationRegistry = class _InstrumentationRegistry {
1321
1271
  const mcpModules = this.manualModules.mcp;
1322
1272
  void (async () => {
1323
1273
  try {
1324
- const { MCPInstrumentation } = await import("./mcp-EJAJTGIC.js");
1274
+ const { MCPInstrumentation } = await import("./mcp-SZSGMNBB.js");
1325
1275
  const instrumentation = new MCPInstrumentation({ exceptionLogger: exceptionLogger2 });
1326
1276
  instrumentation.manuallyInstrument(mcpModules);
1327
1277
  logger.debug("Manual instrumentation enabled for MCP");
@@ -1357,6 +1307,184 @@ var InstrumentationRegistry = class _InstrumentationRegistry {
1357
1307
  }
1358
1308
  };
1359
1309
 
1310
+ // src/internal/instrumentation/vercel-ai/interrupt.ts
1311
+ import { trace as trace3 } from "@opentelemetry/api";
1312
+ var INNER_OPERATION_IDS = /* @__PURE__ */ new Set([
1313
+ "ai.generateText.doGenerate",
1314
+ "ai.streamText.doStream"
1315
+ ]);
1316
+ function isLegacyModelCallSpan(span) {
1317
+ if (INNER_OPERATION_IDS.has(span.name)) {
1318
+ return true;
1319
+ }
1320
+ const opId = span.attributes["ai.operationId"];
1321
+ return typeof opId === "string" && INNER_OPERATION_IDS.has(opId);
1322
+ }
1323
+ function isGenAIModelCallSpan(span) {
1324
+ return span.instrumentationScope?.name === AI_SDK_OTEL_SCOPE && span.attributes["gen_ai.operation.name"] === "chat";
1325
+ }
1326
+ var MAX_PENDING_ENTRIES = 1024;
1327
+ var pendingByParentSpanId = /* @__PURE__ */ new Map();
1328
+ var needsApprovalToolNames = /* @__PURE__ */ new Set();
1329
+ var versionState = { sawActiveSpan: false };
1330
+ function setPending(parentSpanId, value) {
1331
+ pendingByParentSpanId.set(parentSpanId, value);
1332
+ evictOldest(pendingByParentSpanId);
1333
+ }
1334
+ function extractInterruptTools(tools) {
1335
+ if (!tools || typeof tools !== "object") {
1336
+ return [];
1337
+ }
1338
+ return Object.entries(tools).filter(
1339
+ ([, t]) => !!t && typeof t === "object" && t.needsApproval
1340
+ ).map(([name]) => name);
1341
+ }
1342
+ function parsePromptToolNames(raw) {
1343
+ if (!Array.isArray(raw)) {
1344
+ return null;
1345
+ }
1346
+ const names = [];
1347
+ for (const element of raw) {
1348
+ if (typeof element !== "string") {
1349
+ continue;
1350
+ }
1351
+ try {
1352
+ const parsed = JSON.parse(element);
1353
+ if (parsed && typeof parsed.name === "string") {
1354
+ names.push(parsed.name);
1355
+ }
1356
+ } catch {
1357
+ }
1358
+ }
1359
+ return names.length > 0 ? names : null;
1360
+ }
1361
+ var verdictsByToolCallId = /* @__PURE__ */ new Map();
1362
+ function recordVerdicts(messages) {
1363
+ if (!Array.isArray(messages)) {
1364
+ return;
1365
+ }
1366
+ const parts = messages.flatMap((message) => {
1367
+ const content = message?.content;
1368
+ return Array.isArray(content) ? content : [];
1369
+ });
1370
+ const askedOf = /* @__PURE__ */ new Map();
1371
+ for (const part of parts) {
1372
+ if (part?.type === "tool-approval-request" && part.isAutomatic !== true) {
1373
+ askedOf.set(part.approvalId, part.toolCallId);
1374
+ }
1375
+ }
1376
+ for (const part of parts) {
1377
+ const toolCallId = part?.type === "tool-approval-response" && askedOf.get(part.approvalId);
1378
+ if (typeof toolCallId === "string" && typeof part.approved === "boolean") {
1379
+ verdictsByToolCallId.set(toolCallId, part.approved);
1380
+ evictOldest(verdictsByToolCallId);
1381
+ }
1382
+ }
1383
+ }
1384
+ function verdictsForRequest(inputMessages) {
1385
+ if (typeof inputMessages !== "string" || verdictsByToolCallId.size === 0) {
1386
+ return void 0;
1387
+ }
1388
+ let messages;
1389
+ try {
1390
+ messages = JSON.parse(inputMessages);
1391
+ } catch {
1392
+ return void 0;
1393
+ }
1394
+ if (!Array.isArray(messages)) {
1395
+ return void 0;
1396
+ }
1397
+ const verdicts = {};
1398
+ for (const message of [...messages].reverse()) {
1399
+ const { role, parts } = message ?? {};
1400
+ if (role === "assistant" || role === "system") {
1401
+ break;
1402
+ }
1403
+ for (const part of Array.isArray(parts) ? parts : []) {
1404
+ const approved = part?.type === "tool_call_response" && typeof part.id === "string" ? verdictsByToolCallId.get(part.id) : void 0;
1405
+ if (approved !== void 0) {
1406
+ verdicts[part.id] = approved;
1407
+ }
1408
+ }
1409
+ }
1410
+ return Object.keys(verdicts).length > 0 ? JSON.stringify(verdicts) : void 0;
1411
+ }
1412
+ function evictOldest(map) {
1413
+ while (map.size > MAX_PENDING_ENTRIES) {
1414
+ const oldest = map.keys().next().value;
1415
+ if (oldest === void 0) {
1416
+ break;
1417
+ }
1418
+ map.delete(oldest);
1419
+ }
1420
+ }
1421
+ function createInterruptIntegration() {
1422
+ const onStart = (event) => {
1423
+ recordVerdicts(event.messages);
1424
+ for (const name of extractInterruptTools(event.tools)) {
1425
+ needsApprovalToolNames.add(name);
1426
+ }
1427
+ };
1428
+ const onStepStart = (event) => {
1429
+ const span = trace3.getActiveSpan();
1430
+ if (span) {
1431
+ versionState.sawActiveSpan = true;
1432
+ }
1433
+ const names = extractInterruptTools(event.tools);
1434
+ if (names.length === 0) {
1435
+ return;
1436
+ }
1437
+ for (const name of names) {
1438
+ needsApprovalToolNames.add(name);
1439
+ }
1440
+ if (!span) {
1441
+ return;
1442
+ }
1443
+ const value = JSON.stringify(names);
1444
+ span.setAttribute(INTERRUPT_TOOLS, value);
1445
+ setPending(span.spanContext().spanId, value);
1446
+ };
1447
+ return {
1448
+ onStart,
1449
+ onStepStart
1450
+ };
1451
+ }
1452
+ var InterruptPropagator = class {
1453
+ onStart(span, _parentContext) {
1454
+ if (isGenAIModelCallSpan(span)) {
1455
+ const verdicts = verdictsForRequest(span.attributes["gen_ai.input.messages"]);
1456
+ if (verdicts) {
1457
+ span.setAttribute(APPROVALS, verdicts);
1458
+ }
1459
+ return;
1460
+ }
1461
+ if (!isLegacyModelCallSpan(span)) {
1462
+ return;
1463
+ }
1464
+ const parentSpanId = span.parentSpanContext?.spanId;
1465
+ const stashed = parentSpanId && pendingByParentSpanId.get(parentSpanId);
1466
+ if (stashed) {
1467
+ span.setAttribute(INTERRUPT_TOOLS, stashed);
1468
+ pendingByParentSpanId.delete(parentSpanId);
1469
+ return;
1470
+ }
1471
+ if (versionState.sawActiveSpan || needsApprovalToolNames.size === 0) {
1472
+ return;
1473
+ }
1474
+ const scoped = parsePromptToolNames(span.attributes["ai.prompt.tools"]);
1475
+ const names = scoped === null ? [...needsApprovalToolNames] : scoped.filter((n) => needsApprovalToolNames.has(n));
1476
+ if (names.length > 0) {
1477
+ span.setAttribute(INTERRUPT_TOOLS, JSON.stringify(names));
1478
+ }
1479
+ }
1480
+ onEnd() {
1481
+ }
1482
+ async shutdown() {
1483
+ }
1484
+ async forceFlush() {
1485
+ }
1486
+ };
1487
+
1360
1488
  // src/internal/log/logging.ts
1361
1489
  import { SeverityNumber } from "@opentelemetry/api";
1362
1490
  import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-http";
@@ -1636,10 +1764,13 @@ function compilePatternEntries(patternEntries) {
1636
1764
  var compiledPatternCache = /* @__PURE__ */ new WeakMap();
1637
1765
  function getCompiledPatternsForRule(rule) {
1638
1766
  const key = rule.patterns;
1639
- if (compiledPatternCache.has(key)) {
1640
- return compiledPatternCache.get(key) ?? null;
1767
+ const cached = compiledPatternCache.get(key);
1768
+ if (cached) {
1769
+ return cached;
1641
1770
  }
1642
- const compiled = compilePatternEntries(convertPatternsToPatternEntries(rule.patterns));
1771
+ const entries = convertPatternsToPatternEntries(rule.patterns);
1772
+ const pattern = compilePatternEntries(entries);
1773
+ const compiled = { pattern, custom: pattern && compileCustomEntries(entries) };
1643
1774
  compiledPatternCache.set(key, compiled);
1644
1775
  return compiled;
1645
1776
  }
@@ -1689,11 +1820,40 @@ function executeRegexWithTimeout(pattern, value, timeoutMs = 100) {
1689
1820
  }
1690
1821
  return matches;
1691
1822
  }
1692
- function maskStringByPattern(value, pattern, mode = "full") {
1823
+ var BUILTIN_ENTRIES = new Set(DEFAULT_PII_PATTERNS);
1824
+ function compileCustomEntries(patternEntries) {
1825
+ const groups = patternEntries.filter((entry) => !BUILTIN_ENTRIES.has(entry)).flatMap((entry) => {
1826
+ try {
1827
+ return [getGroupedPattern(entry)];
1828
+ } catch {
1829
+ return [];
1830
+ }
1831
+ });
1832
+ return groups.length > 0 ? new RegExp(groups.join("|")) : null;
1833
+ }
1834
+ function isDecimalPart(value, match) {
1835
+ const start = match.index;
1836
+ const end = start + match[0].length;
1837
+ if (!/^[0-9]+$/.test(match[0])) {
1838
+ return false;
1839
+ }
1840
+ const afterPoint = value.charAt(start - 1) === "." && /^[0-9]$/.test(value.charAt(start - 2));
1841
+ const beforePoint = value.charAt(end) === "." && /^[0-9]$/.test(value.charAt(end + 1));
1842
+ return afterPoint || beforePoint;
1843
+ }
1844
+ function overlapsAny(match, others) {
1845
+ const end = match.index + match[0].length;
1846
+ return others.some((other) => other.index < end && match.index < other.index + other[0].length);
1847
+ }
1848
+ function maskStringByPattern(value, pattern, mode = "full", custom = pattern) {
1693
1849
  const matches = [];
1694
1850
  try {
1695
1851
  const regexMatches = executeRegexWithTimeout(pattern, value);
1852
+ const customMatches = custom && regexMatches.some((match) => isDecimalPart(value, match)) ? executeRegexWithTimeout(custom, value) : [];
1696
1853
  for (const match of regexMatches) {
1854
+ if (isDecimalPart(value, match) && !overlapsAny(match, customMatches)) {
1855
+ continue;
1856
+ }
1697
1857
  matches.push({
1698
1858
  start: match.index,
1699
1859
  end: match.index + match[0].length,
@@ -1737,11 +1897,11 @@ function maskStringByPatternBasedRule(value, rule) {
1737
1897
  if (!patternEntries || patternEntries.length === 0) {
1738
1898
  return mode === "partial" && value ? value.at(0) + "*****" : "*****";
1739
1899
  }
1740
- const compiledPatterns = getCompiledPatternsForRule(rule);
1741
- if (!compiledPatterns) {
1900
+ const { pattern, custom } = getCompiledPatternsForRule(rule);
1901
+ if (!pattern) {
1742
1902
  return value;
1743
1903
  }
1744
- return maskStringByPattern(value, compiledPatterns, mode);
1904
+ return maskStringByPattern(value, pattern, mode, custom);
1745
1905
  }
1746
1906
  function maskValue(value, rule) {
1747
1907
  if (typeof value === "string") {
@@ -2158,6 +2318,165 @@ function getMetricsReader() {
2158
2318
  return MetricsModule.getInstance().getMetricsReader();
2159
2319
  }
2160
2320
 
2321
+ // src/internal/instrumentation/vercel-ai/model-call-end.ts
2322
+ var NO_USAGE = {
2323
+ inputTokens: void 0,
2324
+ inputTokenDetails: {
2325
+ noCacheTokens: void 0,
2326
+ cacheReadTokens: void 0,
2327
+ cacheWriteTokens: void 0
2328
+ },
2329
+ outputTokens: void 0,
2330
+ outputTokenDetails: { textTokens: void 0, reasoningTokens: void 0 },
2331
+ totalTokens: void 0
2332
+ };
2333
+ function endUnreportedModelCalls(collector) {
2334
+ const hooks = collector;
2335
+ if (!hasModelCallHooks(hooks)) {
2336
+ logger.debug("@ai-sdk/otel lacks the model-call hooks; failed streamed calls stay untraced");
2337
+ return collector;
2338
+ }
2339
+ const { onStepEnd, onLanguageModelCallStart, onLanguageModelCallEnd } = hooks;
2340
+ hooks.onStepEnd = (event) => {
2341
+ if (!event.durableContext) {
2342
+ onLanguageModelCallEnd.call(hooks, modelCallEndOf(event));
2343
+ }
2344
+ return onStepEnd.call(hooks, event);
2345
+ };
2346
+ hooks.onLanguageModelCallStart = (event) => {
2347
+ if (!event.durableContext) {
2348
+ onLanguageModelCallEnd.call(hooks, failedAttemptBefore(event));
2349
+ }
2350
+ return onLanguageModelCallStart.call(hooks, event);
2351
+ };
2352
+ return collector;
2353
+ }
2354
+ function hasModelCallHooks(hooks) {
2355
+ return typeof hooks.onStepEnd === "function" && typeof hooks.onLanguageModelCallStart === "function" && typeof hooks.onLanguageModelCallEnd === "function";
2356
+ }
2357
+ function modelCallEndOf(step) {
2358
+ return {
2359
+ callId: step.callId,
2360
+ provider: step.model.provider,
2361
+ modelId: step.response.modelId,
2362
+ finishReason: step.finishReason,
2363
+ usage: step.usage,
2364
+ content: step.content,
2365
+ responseId: step.response.id,
2366
+ providerMetadata: step.providerMetadata,
2367
+ request: { url: step.request.url },
2368
+ performance: { ...step.performance, timeToFirstOutputMs: void 0 },
2369
+ timestamp: step.timestamp
2370
+ };
2371
+ }
2372
+ function failedAttemptBefore(retry) {
2373
+ return {
2374
+ callId: retry.callId,
2375
+ provider: retry.provider,
2376
+ modelId: retry.modelId,
2377
+ finishReason: "error",
2378
+ usage: NO_USAGE,
2379
+ content: [],
2380
+ responseId: "",
2381
+ performance: {
2382
+ responseTimeMs: 0,
2383
+ effectiveOutputTokensPerSecond: 0,
2384
+ outputTokensPerSecond: void 0,
2385
+ inputTokensPerSecond: void 0,
2386
+ effectiveTotalTokensPerSecond: 0,
2387
+ timeToFirstOutputMs: void 0
2388
+ },
2389
+ timestamp: retry.timestamp
2390
+ };
2391
+ }
2392
+
2393
+ // src/internal/instrumentation/vercel-ai/index.ts
2394
+ var importInstalled = {
2395
+ ai: () => import("ai").catch(() => void 0),
2396
+ otel: () => import("@ai-sdk/otel").catch(() => void 0)
2397
+ };
2398
+ var registration = { done: false };
2399
+ function registerAISdkTelemetry({ collector, modules }, load = importInstalled) {
2400
+ if (registration.done) {
2401
+ return;
2402
+ }
2403
+ const ai = modules?.ai;
2404
+ const otel = modules?.aiOtel;
2405
+ if (ai && (otel || !collector || typeof ai.registerTelemetry !== "function")) {
2406
+ registerIntegrations(ai, otel, collector);
2407
+ return;
2408
+ }
2409
+ if (ai) {
2410
+ logger.debug(
2411
+ "instrumentModules has ai but not aiOtel; pass aiOtel too to trace a call made right after Brizz.initialize()"
2412
+ );
2413
+ }
2414
+ return registerInstalled(collector, load, ai, otel);
2415
+ }
2416
+ async function registerInstalled(collector, load, suppliedAi, suppliedOtel) {
2417
+ try {
2418
+ const ai = suppliedAi ?? await load.ai();
2419
+ const otel = collector && typeof ai?.registerTelemetry === "function" ? suppliedOtel ?? await load.otel() : void 0;
2420
+ registerIntegrations(ai, otel, collector);
2421
+ } catch (error) {
2422
+ logger.debug(`Vercel AI telemetry not registered: ${String(error)}`);
2423
+ }
2424
+ }
2425
+ function registerIntegrations(ai, otel, collector) {
2426
+ try {
2427
+ if (registration.done) {
2428
+ return;
2429
+ }
2430
+ if (!ai) {
2431
+ logger.debug("AI SDK not installed; install ai@>=6 to capture AI SDK telemetry");
2432
+ return;
2433
+ }
2434
+ const register = callable(ai.registerTelemetry) ?? callable(ai.registerTelemetryIntegration);
2435
+ if (!register) {
2436
+ logger.debug(
2437
+ "AI SDK present but lacks a telemetry-registration hook (needs ai@>=6); skipping"
2438
+ );
2439
+ return;
2440
+ }
2441
+ const integrations = [createInterruptIntegration()];
2442
+ if (register === ai.registerTelemetry && collector) {
2443
+ const openTelemetry = createCollector(otel?.OpenTelemetry);
2444
+ if (openTelemetry) {
2445
+ integrations.push(openTelemetry);
2446
+ } else {
2447
+ logger.warn(
2448
+ "AI SDK present but @ai-sdk/otel is missing or unusable; install it (npm install @ai-sdk/otel) to capture AI SDK spans on ai@>=7"
2449
+ );
2450
+ }
2451
+ }
2452
+ register(...integrations);
2453
+ registration.done = true;
2454
+ } catch (error) {
2455
+ logger.debug(`Vercel AI telemetry not registered: ${String(error)}`);
2456
+ }
2457
+ }
2458
+ function createCollector(OpenTelemetry) {
2459
+ if (typeof OpenTelemetry !== "function") {
2460
+ return void 0;
2461
+ }
2462
+ try {
2463
+ return endUnreportedModelCalls(
2464
+ new OpenTelemetry({
2465
+ tracer: brizzTracerProvider.getTracer(AI_SDK_OTEL_SCOPE),
2466
+ // Records the model's tool-choice decisions (`ai.decision.*`).
2467
+ experimental_decision: true,
2468
+ // Carries the price the Vercel AI Gateway billed.
2469
+ providerMetadata: true
2470
+ })
2471
+ );
2472
+ } catch {
2473
+ return void 0;
2474
+ }
2475
+ }
2476
+ function callable(hook) {
2477
+ return typeof hook === "function" ? hook : void 0;
2478
+ }
2479
+
2161
2480
  // src/internal/trace/tracing.ts
2162
2481
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
2163
2482
 
@@ -2541,7 +2860,7 @@ function getSpanProcessor() {
2541
2860
  }
2542
2861
 
2543
2862
  // src/internal/trace/decision-call.ts
2544
- import { SpanKind as SpanKind2, SpanStatusCode as SpanStatusCode3, context as context6, trace as trace3 } from "@opentelemetry/api";
2863
+ import { SpanKind as SpanKind2, SpanStatusCode as SpanStatusCode3, context as context6, trace as trace4 } from "@opentelemetry/api";
2545
2864
  import { suppressTracing } from "@opentelemetry/core";
2546
2865
  var tracer = brizzTracerProvider.getTracer("@brizz/sdk/decision-call", getSDKVersion());
2547
2866
  function decisionCall(options, callback) {
@@ -2549,7 +2868,7 @@ function decisionCall(options, callback) {
2549
2868
  if (!span) {
2550
2869
  return callback(describeResultOn(void 0, options.provider));
2551
2870
  }
2552
- const callbackContext = suppressTracing(trace3.setSpan(context6.active(), span));
2871
+ const callbackContext = suppressTracing(trace4.setSpan(context6.active(), span));
2553
2872
  let result;
2554
2873
  try {
2555
2874
  result = context6.with(
@@ -2700,7 +3019,7 @@ function resolveMcpSessionTracking(configured) {
2700
3019
  }
2701
3020
  var BRIZZ_OWNED = /* @__PURE__ */ Symbol.for("brizz.sdk.ownedTracerProvider");
2702
3021
  function globalTracerDelegate() {
2703
- const global = trace4.getTracerProvider();
3022
+ const global = trace5.getTracerProvider();
2704
3023
  return typeof global.getDelegate === "function" ? global.getDelegate() : global;
2705
3024
  }
2706
3025
  var _Brizz = class __Brizz {
@@ -2915,6 +3234,10 @@ var _Brizz = class __Brizz {
2915
3234
  this.initializeModules(resolvedConfig);
2916
3235
  this.setupInstrumentation(options);
2917
3236
  this.createAndStartProviders(options, resolvedConfig);
3237
+ void registerAISdkTelemetry({
3238
+ collector: !options.disableAiSdkCollector,
3239
+ modules: options.instrumentModules
3240
+ });
2918
3241
  this._initialized = true;
2919
3242
  logger.info("Brizz SDK initialization completed successfully", {
2920
3243
  moduleSystem: this.detectModuleSystem()