@osfactory/otel-hook 0.8.0 → 0.10.0

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 (52) hide show
  1. package/README.md +159 -2
  2. package/dist/{adapter-BJiz6lqM.d.ts → adapter-B9RwW6TO.d.ts} +14 -2
  3. package/dist/cli.js +2514 -1238
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +5 -2
  6. package/dist/config.js +479 -169
  7. package/dist/config.js.map +1 -1
  8. package/dist/destinations-DWOkVxV1.d.ts +169 -0
  9. package/dist/diagnostics.d.ts +8 -0
  10. package/dist/diagnostics.js +2 -1
  11. package/dist/diagnostics.js.map +1 -1
  12. package/dist/{events-B3MHoJTD.d.ts → events-CSD_YiJ2.d.ts} +2 -0
  13. package/dist/{otlp-log-sink-zuHojHSP.d.ts → export-destinations-lORbe25J.d.ts} +241 -9
  14. package/dist/{filesystem-store-r-nNA3BA.d.ts → filesystem-store-DX3dGIgu.d.ts} +1 -1
  15. package/dist/{hook-Dh8OO4Wa.d.ts → hook-BAxXoKsp.d.ts} +10 -5
  16. package/dist/index.d.ts +15 -14
  17. package/dist/index.js +1936 -730
  18. package/dist/index.js.map +1 -1
  19. package/dist/install.d.ts +4 -4
  20. package/dist/install.js +31 -2
  21. package/dist/install.js.map +1 -1
  22. package/dist/integration.d.ts +37 -12
  23. package/dist/integration.js +1942 -617
  24. package/dist/integration.js.map +1 -1
  25. package/dist/lifecycle.d.ts +3 -3
  26. package/dist/lifecycle.js +8 -1
  27. package/dist/lifecycle.js.map +1 -1
  28. package/dist/{memory-Bl9ANVff.d.ts → memory-aJilVG4R.d.ts} +2 -2
  29. package/dist/model.d.ts +1 -1
  30. package/dist/model.js +7 -0
  31. package/dist/model.js.map +1 -1
  32. package/dist/{payload-Ci8_ERm6.d.ts → payload-D7gc0-WQ.d.ts} +41 -2
  33. package/dist/{ports-n7KFOpKo.d.ts → ports-plO5MKrY.d.ts} +63 -2
  34. package/dist/providers.d.ts +146 -10
  35. package/dist/providers.js +397 -13
  36. package/dist/providers.js.map +1 -1
  37. package/dist/{registry-CIVvRlVK.d.ts → registry-C7XO4DzD.d.ts} +2 -2
  38. package/dist/runtime.d.ts +8 -8
  39. package/dist/runtime.js +1426 -1163
  40. package/dist/runtime.js.map +1 -1
  41. package/dist/{schema-Cn0-xz8L.d.ts → schema-CHb3GU1r.d.ts} +98 -3
  42. package/dist/{semconv-fPRb-dpU.d.ts → semconv-Dw7gcQcg.d.ts} +1 -1
  43. package/dist/state.d.ts +4 -4
  44. package/dist/state.js +607 -39
  45. package/dist/state.js.map +1 -1
  46. package/dist/telemetry.d.ts +23 -66
  47. package/dist/telemetry.js +637 -34
  48. package/dist/telemetry.js.map +1 -1
  49. package/dist/testing.d.ts +10 -8
  50. package/dist/testing.js +868 -560
  51. package/dist/testing.js.map +1 -1
  52. package/package.json +1 -1
package/dist/telemetry.js CHANGED
@@ -18,7 +18,7 @@ import {
18
18
  } from "@opentelemetry/semantic-conventions/incubating";
19
19
 
20
20
  // src/version.ts
21
- var VERSION = "0.8.0";
21
+ var VERSION = "0.10.0";
22
22
 
23
23
  // src/telemetry/export-identity.ts
24
24
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -706,6 +706,13 @@ var generationEndEventSchema = event({
706
706
  stopReason: nonEmptyStringSchema.optional(),
707
707
  durationMillis: durationMillisSchema.optional(),
708
708
  usage: canonicalUsageSchema.optional(),
709
+ /**
710
+ * True when `usage` is known to cover only part of the generation (for
711
+ * example the last model request of a multi-request turn); false when the
712
+ * provider or harness said it is the whole. Absent: not stated. Meaningless
713
+ * without `usage`.
714
+ */
715
+ usagePartial: z9.boolean().optional(),
709
716
  cost: costFactsSchema.optional(),
710
717
  outputContent: contentFactsSchema.optional()
711
718
  });
@@ -887,6 +894,7 @@ var ATTR_OTELHOOK_SPAN_PAIRING = "otelhook.span.pairing";
887
894
  var ATTR_OTELHOOK_SPAN_ORPHAN = "otelhook.span.orphan";
888
895
  var ATTR_OTELHOOK_OUTCOME = "otelhook.outcome";
889
896
  var ATTR_OTELHOOK_RESET_DETECTED = "otelhook.usage.reset_detected";
897
+ var ATTR_OTELHOOK_USAGE_PARTIAL = "otelhook.usage.partial";
890
898
  var ATTR_OTELHOOK_TOOL_KIND = "otelhook.tool.kind";
891
899
  var ATTR_OTELHOOK_DELEGATION_DEPTH = "otelhook.delegation_depth";
892
900
  var ATTR_OTELHOOK_COMPACTION_TRIGGER = "otelhook.compaction.trigger";
@@ -1159,7 +1167,8 @@ var buildLifecycleSpan = (plan, resource, scope) => {
1159
1167
  // Codex turn): the key a consumer stores a usage observation under.
1160
1168
  [ATTR_OTELHOOK_GENERATION_ID]: group.ref.scopeKey,
1161
1169
  ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
1162
- ...usageAttributes(end?.usage, false)
1170
+ ...usageAttributes(end?.usage, false),
1171
+ ...end?.usage === void 0 || end.usagePartial === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_PARTIAL]: end.usagePartial }
1163
1172
  };
1164
1173
  status = outcomeStatus(end?.outcome);
1165
1174
  break;
@@ -1405,7 +1414,7 @@ var canonicalEventsToReadableSpans = (events, options) => {
1405
1414
 
1406
1415
  // src/telemetry/spool-queue.ts
1407
1416
  import { randomBytes } from "crypto";
1408
- import { mkdir, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
1417
+ import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "fs/promises";
1409
1418
  import * as path from "path";
1410
1419
 
1411
1420
  // src/state/keys.ts
@@ -1424,6 +1433,62 @@ var namespaceSegments = (namespace) => [
1424
1433
  ];
1425
1434
 
1426
1435
  // src/telemetry/spool-queue.ts
1436
+ var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
1437
+ total: 0,
1438
+ age: 0,
1439
+ size: 0,
1440
+ count: 0,
1441
+ rejected: 0
1442
+ });
1443
+ var SPOOL_DROPS_FILE = ".drops";
1444
+ var enqueuedAtOf = (fileName) => {
1445
+ const match = /^(\d{16})-/.exec(fileName);
1446
+ return match?.[1] === void 0 ? void 0 : Number(match[1]);
1447
+ };
1448
+ var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
1449
+ var readSpoolDropCounts = async (queueDir) => {
1450
+ try {
1451
+ const parsed = JSON.parse(await readFile(path.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
1452
+ if (typeof parsed !== "object" || parsed === null) {
1453
+ return EMPTY_SPOOL_DROP_COUNTS;
1454
+ }
1455
+ const record = parsed;
1456
+ const field = (name) => isCount(record[name]) ? record[name] : 0;
1457
+ return {
1458
+ total: field("total"),
1459
+ age: field("age"),
1460
+ size: field("size"),
1461
+ count: field("count"),
1462
+ rejected: field("rejected"),
1463
+ ...isCount(record.lastDroppedAt) ? { lastDroppedAt: record.lastDroppedAt } : {}
1464
+ };
1465
+ } catch {
1466
+ return EMPTY_SPOOL_DROP_COUNTS;
1467
+ }
1468
+ };
1469
+ var readSpoolQueueStats = async (queueDir) => {
1470
+ let entries;
1471
+ try {
1472
+ entries = await readdir(queueDir);
1473
+ } catch {
1474
+ return { batches: 0, bytes: 0, dropped: await readSpoolDropCounts(queueDir) };
1475
+ }
1476
+ const files = entries.filter((entry) => entry.endsWith(".json") && !entry.startsWith(".tmp-")).sort();
1477
+ let bytes = 0;
1478
+ for (const file of files) {
1479
+ try {
1480
+ bytes += (await stat(path.join(queueDir, file))).size;
1481
+ } catch {
1482
+ }
1483
+ }
1484
+ const oldest = files[0] === void 0 ? void 0 : enqueuedAtOf(files[0]);
1485
+ return {
1486
+ batches: files.length,
1487
+ bytes,
1488
+ ...oldest === void 0 ? {} : { oldestEnqueuedAt: oldest },
1489
+ dropped: await readSpoolDropCounts(queueDir)
1490
+ };
1491
+ };
1427
1492
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
1428
1493
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
1429
1494
  var createSpoolQueue = (options) => {
@@ -1464,27 +1529,132 @@ var createSpoolQueue = (options) => {
1464
1529
  }
1465
1530
  return entries.filter((entry) => entry.endsWith(".json") && !entry.startsWith(".tmp-")).sort();
1466
1531
  };
1532
+ const recordDrops = async (reason, dropped) => {
1533
+ if (dropped <= 0) {
1534
+ return;
1535
+ }
1536
+ try {
1537
+ const current = await readSpoolDropCounts(queueDir);
1538
+ const next = {
1539
+ ...current,
1540
+ total: current.total + dropped,
1541
+ [reason]: current[reason] + dropped,
1542
+ lastDroppedAt: options.clock.now()
1543
+ };
1544
+ const tmp = path.join(queueDir, `.tmp-${randomBytes(6).toString("hex")}.drops`);
1545
+ await writeFile(tmp, JSON.stringify(next), "utf8");
1546
+ await rename(tmp, path.join(queueDir, SPOOL_DROPS_FILE));
1547
+ } catch {
1548
+ }
1549
+ options.logger?.warn("durable spool dropped batches", {
1550
+ "spool.queue": options.queueName,
1551
+ "spool.drop_reason": reason,
1552
+ "spool.dropped": dropped
1553
+ });
1554
+ };
1555
+ const listWithSizes = async () => {
1556
+ const names = await listSorted();
1557
+ const files = [];
1558
+ for (const name of names) {
1559
+ let bytes = 0;
1560
+ if (options.maxBytes !== void 0) {
1561
+ try {
1562
+ bytes = (await stat(path.join(queueDir, name))).size;
1563
+ } catch {
1564
+ continue;
1565
+ }
1566
+ }
1567
+ const enqueuedAt = enqueuedAtOf(name);
1568
+ files.push({ name, bytes, ...enqueuedAt === void 0 ? {} : { enqueuedAt } });
1569
+ }
1570
+ return files;
1571
+ };
1572
+ const evict = async (files) => {
1573
+ let removed = 0;
1574
+ for (const file of files) {
1575
+ try {
1576
+ await unlink(path.join(queueDir, file.name));
1577
+ removed += 1;
1578
+ } catch {
1579
+ }
1580
+ }
1581
+ return removed;
1582
+ };
1583
+ const isExpired = (file, now) => options.maxAgeMillis !== void 0 && file.enqueuedAt !== void 0 && now - file.enqueuedAt > options.maxAgeMillis;
1467
1584
  const enqueue = async (batch) => {
1468
1585
  await ensureDirs();
1469
- const existing = await listSorted();
1470
- if (existing.length >= options.maxFiles) {
1586
+ const serialized = JSON.stringify(batch);
1587
+ const bytes = Buffer.byteLength(serialized, "utf8");
1588
+ const refuse = async (reason) => {
1471
1589
  options.logger?.warn("durable spool at capacity; batch dropped", {
1472
1590
  "spool.max_files": options.maxFiles,
1591
+ ...options.maxBytes === void 0 ? {} : { "spool.max_bytes": options.maxBytes },
1473
1592
  "spool.queue": options.queueName
1474
1593
  });
1594
+ await recordDrops(reason, 1);
1475
1595
  return { spooled: false, reason: "capacity-exceeded" };
1596
+ };
1597
+ if (options.maxBytes !== void 0 && bytes > options.maxBytes) {
1598
+ return refuse("size");
1476
1599
  }
1477
- const fileName = `${String(options.clock.now()).padStart(16, "0")}-${randomBytes(6).toString("hex")}.json`;
1600
+ let queued = await listWithSizes();
1601
+ const now = options.clock.now();
1602
+ const expired = queued.filter((file) => isExpired(file, now));
1603
+ if (expired.length > 0) {
1604
+ await recordDrops("age", await evict(expired));
1605
+ queued = queued.filter((file) => !isExpired(file, now));
1606
+ }
1607
+ const overflow = options.overflow ?? "refuse-new";
1608
+ const totalBytes = () => queued.reduce((sum, file) => sum + file.bytes, 0);
1609
+ if (overflow === "refuse-new") {
1610
+ if (queued.length >= options.maxFiles) {
1611
+ return refuse("count");
1612
+ }
1613
+ if (options.maxBytes !== void 0 && totalBytes() + bytes > options.maxBytes) {
1614
+ return refuse("size");
1615
+ }
1616
+ } else {
1617
+ const overCount = Math.max(0, queued.length + 1 - options.maxFiles);
1618
+ if (overCount > 0) {
1619
+ await recordDrops("count", await evict(queued.slice(0, overCount)));
1620
+ queued = queued.slice(overCount);
1621
+ }
1622
+ if (options.maxBytes !== void 0) {
1623
+ let excess = totalBytes() + bytes - options.maxBytes;
1624
+ let cut = 0;
1625
+ while (excess > 0 && cut < queued.length) {
1626
+ excess -= queued[cut]?.bytes ?? 0;
1627
+ cut += 1;
1628
+ }
1629
+ if (cut > 0) {
1630
+ await recordDrops("size", await evict(queued.slice(0, cut)));
1631
+ queued = queued.slice(cut);
1632
+ }
1633
+ }
1634
+ }
1635
+ const fileName = `${String(now).padStart(16, "0")}-${randomBytes(6).toString("hex")}.json`;
1478
1636
  const target = path.join(queueDir, fileName);
1479
1637
  const tmp = path.join(queueDir, `.tmp-${randomBytes(6).toString("hex")}.json`);
1480
- await writeFile(tmp, JSON.stringify(batch), "utf8");
1638
+ await writeFile(tmp, serialized, "utf8");
1481
1639
  await rename(tmp, target);
1482
1640
  return { spooled: true };
1483
1641
  };
1484
1642
  const drain = async (send, drainOptions) => {
1485
1643
  await ensureDirs();
1486
1644
  const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;
1487
- const files = await listSorted();
1645
+ let files = await listSorted();
1646
+ if (options.maxAgeMillis !== void 0) {
1647
+ const now = options.clock.now();
1648
+ const expired = files.map((name) => {
1649
+ const enqueuedAt = enqueuedAtOf(name);
1650
+ return { name, bytes: 0, ...enqueuedAt === void 0 ? {} : { enqueuedAt } };
1651
+ }).filter((file) => isExpired(file, now));
1652
+ if (expired.length > 0) {
1653
+ await recordDrops("age", await evict(expired));
1654
+ const gone = new Set(expired.map((file) => file.name));
1655
+ files = files.filter((name) => !gone.has(name));
1656
+ }
1657
+ }
1488
1658
  let drained = 0;
1489
1659
  let failed = 0;
1490
1660
  let quarantined = 0;
@@ -1529,6 +1699,12 @@ var createSpoolQueue = (options) => {
1529
1699
  } catch {
1530
1700
  delivered = false;
1531
1701
  }
1702
+ if (delivered === "discard") {
1703
+ if (await unlink(filePath).then(() => true, () => false)) {
1704
+ await recordDrops("rejected", 1);
1705
+ }
1706
+ continue;
1707
+ }
1532
1708
  if (delivered) {
1533
1709
  await unlink(filePath).catch(() => void 0);
1534
1710
  drained += 1;
@@ -1546,7 +1722,8 @@ var createSpoolQueue = (options) => {
1546
1722
  size: async () => {
1547
1723
  await ensureDirs();
1548
1724
  return (await listSorted()).length;
1549
- }
1725
+ },
1726
+ stats: () => readSpoolQueueStats(queueDir)
1550
1727
  };
1551
1728
  };
1552
1729
 
@@ -1638,7 +1815,10 @@ var createFileDurableSpool = (options) => createSpoolQueue({
1638
1815
  clock: options.clock,
1639
1816
  ...options.logger === void 0 ? {} : { logger: options.logger },
1640
1817
  maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_SPOOL_FILES,
1641
- queueName: "spool",
1818
+ queueName: options.queueName ?? "spool",
1819
+ ...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
1820
+ ...options.maxAgeMillis === void 0 ? {} : { maxAgeMillis: options.maxAgeMillis },
1821
+ ...options.overflow === void 0 ? {} : { overflow: options.overflow },
1642
1822
  validate: validateSpoolBatch
1643
1823
  });
1644
1824
 
@@ -1672,6 +1852,40 @@ var createErrorInfo = (input) => {
1672
1852
  ...input.occurredAt === void 0 ? {} : { occurredAt: input.occurredAt }
1673
1853
  });
1674
1854
  };
1855
+ var OtelHookError = class _OtelHookError extends Error {
1856
+ info;
1857
+ constructor(info) {
1858
+ super(info.message);
1859
+ this.name = "OtelHookError";
1860
+ this.info = info;
1861
+ }
1862
+ static of(input) {
1863
+ return new _OtelHookError(createErrorInfo(input));
1864
+ }
1865
+ };
1866
+ var isOtelHookError = (value) => value instanceof OtelHookError;
1867
+ var describeThrown = (thrown) => {
1868
+ if (thrown instanceof Error) {
1869
+ return {
1870
+ errorName: thrown.name.slice(0, 64) || "Error",
1871
+ hasMessage: typeof thrown.message === "string" && thrown.message.length > 0
1872
+ };
1873
+ }
1874
+ return { errorName: typeof thrown, hasMessage: false };
1875
+ };
1876
+ var errorInfoFromThrown = (thrown, input) => {
1877
+ if (isOtelHookError(thrown)) {
1878
+ return thrown.info;
1879
+ }
1880
+ const described = describeThrown(thrown);
1881
+ return createErrorInfo({
1882
+ code: input.code ?? "internal-error",
1883
+ phase: input.phase,
1884
+ detail: `contained ${described.errorName}`,
1885
+ details: { "error.name": described.errorName, "error.has_message": described.hasMessage },
1886
+ ...input.occurredAt === void 0 ? {} : { occurredAt: input.occurredAt }
1887
+ });
1888
+ };
1675
1889
 
1676
1890
  // src/diagnostics/health.ts
1677
1891
  var createHealthTracker = (subsystem, options = {}) => {
@@ -1706,11 +1920,19 @@ var createHealthTracker = (subsystem, options = {}) => {
1706
1920
  consecutiveFailures,
1707
1921
  ...lastSuccessAt === void 0 ? {} : { lastSuccessAt },
1708
1922
  ...lastFailureAt === void 0 ? {} : { lastFailureAt },
1709
- ...lastErrorCode === void 0 ? {} : { lastErrorCode }
1923
+ ...lastErrorCode === void 0 ? {} : { lastErrorCode },
1924
+ ...options.destination === void 0 ? {} : { destination: options.destination }
1710
1925
  })
1711
1926
  };
1712
1927
  };
1713
1928
 
1929
+ // src/telemetry/export-failure.ts
1930
+ var RETRYABLE_HTTP_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
1931
+ var isPermanentExportFailure = (result) => {
1932
+ const code = result.error?.code;
1933
+ return typeof code === "number" && Number.isInteger(code) && code >= 400 && code < 600 && !RETRYABLE_HTTP_STATUSES.has(code);
1934
+ };
1935
+
1714
1936
  // src/telemetry/exporter-resource.ts
1715
1937
  import { resourceFromAttributes } from "@opentelemetry/resources";
1716
1938
 
@@ -1948,8 +2170,11 @@ var deserializeSpan = (serialized, resource, scope) => assembleReadableSpan({
1948
2170
  resource,
1949
2171
  instrumentationScope: scope
1950
2172
  });
1951
- var createDisabledSink = () => {
1952
- const health = createHealthTracker("telemetry-sink");
2173
+ var createDisabledSink = (destination) => {
2174
+ const health = createHealthTracker(
2175
+ "telemetry-sink",
2176
+ destination === void 0 ? {} : { destination }
2177
+ );
1953
2178
  return {
1954
2179
  emit: (events) => {
1955
2180
  health.recordSuccess(events.length);
@@ -1962,22 +2187,27 @@ var createDisabledSink = () => {
1962
2187
  };
1963
2188
  };
1964
2189
  var createOtlpTraceSink = (options) => {
2190
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
1965
2191
  if (!options.exporter.enabled || options.exporter.protocol === "none") {
1966
- return createDisabledSink();
2192
+ return createDisabledSink(options.destination);
1967
2193
  }
1968
2194
  if (options.exporter.endpoint === void 0) {
1969
- options.logger?.warn("otlp sink disabled: no endpoint configured", {});
1970
- return createDisabledSink();
2195
+ options.logger?.warn("otlp sink disabled: no endpoint configured", destinationFields);
2196
+ return createDisabledSink(options.destination);
1971
2197
  }
1972
2198
  if (options.exporter.protocol !== "http/protobuf") {
1973
2199
  options.logger?.warn("otlp sink: protocol not supported by this build, falling back to disabled", {
1974
- "exporter.protocol": options.exporter.protocol
2200
+ "exporter.protocol": options.exporter.protocol,
2201
+ ...destinationFields
1975
2202
  });
1976
- return createDisabledSink();
2203
+ return createDisabledSink(options.destination);
1977
2204
  }
1978
2205
  const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
1979
2206
  const resource = resourceFromExporterPolicy(options.exporter);
1980
- const health = createHealthTracker("telemetry-sink");
2207
+ const health = createHealthTracker(
2208
+ "telemetry-sink",
2209
+ options.destination === void 0 ? {} : { destination: options.destination }
2210
+ );
1981
2211
  const exporter = new OTLPTraceExporter({
1982
2212
  url: options.exporter.endpoint,
1983
2213
  headers: { ...options.headers },
@@ -1999,7 +2229,10 @@ var createOtlpTraceSink = (options) => {
1999
2229
  const batchResource = replayResource(batch.resourceAttributes, options.exporter);
2000
2230
  const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));
2001
2231
  const result = await exportSpans(spans);
2002
- return result.code === ExportResultCode.SUCCESS;
2232
+ if (result.code === ExportResultCode.SUCCESS) {
2233
+ return true;
2234
+ }
2235
+ return isPermanentExportFailure(result) ? "discard" : false;
2003
2236
  };
2004
2237
  const resolveCorrelations = async (events) => {
2005
2238
  if (options.correlate === void 0) {
@@ -2027,6 +2260,9 @@ var createOtlpTraceSink = (options) => {
2027
2260
  let accepted = 0;
2028
2261
  let rejected = 0;
2029
2262
  for (const batch of chunk(spans, options.exporter.maxBatchSize)) {
2263
+ if (batch.length === 0) {
2264
+ continue;
2265
+ }
2030
2266
  let result;
2031
2267
  try {
2032
2268
  result = await exportSpans(batch);
@@ -2039,13 +2275,18 @@ var createOtlpTraceSink = (options) => {
2039
2275
  continue;
2040
2276
  }
2041
2277
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
2042
- if (options.spool !== void 0) {
2278
+ const permanent = isPermanentExportFailure(result);
2279
+ if (options.spool !== void 0 && !permanent) {
2043
2280
  const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
2044
2281
  spooled: false,
2045
2282
  reason: "capacity-exceeded"
2046
2283
  }));
2047
2284
  if (spoolResult.spooled) {
2048
2285
  accepted += batch.length;
2286
+ options.logger?.warn("span batch not delivered; spooled for the next invocation", {
2287
+ "export.batch_size": batch.length,
2288
+ ...destinationFields
2289
+ });
2049
2290
  continue;
2050
2291
  }
2051
2292
  }
@@ -2054,8 +2295,8 @@ var createOtlpTraceSink = (options) => {
2054
2295
  createErrorInfo({
2055
2296
  code: "telemetry-export-failure",
2056
2297
  phase: "export",
2057
- detail: "collector rejected or was unreachable for a span batch",
2058
- details: { "export.batch_size": batch.length }
2298
+ detail: permanent ? "collector refused a span batch with a non-retryable status" : "collector rejected or was unreachable for a span batch",
2299
+ details: { "export.batch_size": batch.length, ...destinationFields }
2059
2300
  })
2060
2301
  );
2061
2302
  }
@@ -2320,7 +2561,8 @@ var eventAttributes = (event2) => {
2320
2561
  ...event2.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event2.model.vendor },
2321
2562
  [ATTR_OTELHOOK_OUTCOME2]: event2.outcome,
2322
2563
  ...event2.stopReason === void 0 ? {} : { [ATTR_OTELHOOK_STOP_REASON]: event2.stopReason },
2323
- ...usageAttributes2(event2.usage)
2564
+ ...usageAttributes2(event2.usage),
2565
+ ...event2.usage === void 0 || event2.usagePartial === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_PARTIAL]: event2.usagePartial }
2324
2566
  };
2325
2567
  case "tool.start":
2326
2568
  return {
@@ -2612,7 +2854,10 @@ var createFileDurableLogSpool = (options) => createSpoolQueue({
2612
2854
  clock: options.clock,
2613
2855
  ...options.logger === void 0 ? {} : { logger: options.logger },
2614
2856
  maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_LOG_SPOOL_FILES,
2615
- queueName: "spool-logs",
2857
+ queueName: options.queueName ?? "spool-logs",
2858
+ ...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
2859
+ ...options.maxAgeMillis === void 0 ? {} : { maxAgeMillis: options.maxAgeMillis },
2860
+ ...options.overflow === void 0 ? {} : { overflow: options.overflow },
2616
2861
  validate: validateLogSpoolBatch
2617
2862
  });
2618
2863
 
@@ -2715,8 +2960,11 @@ var chunk2 = (items, size) => {
2715
2960
  }
2716
2961
  return chunks;
2717
2962
  };
2718
- var createDisabledSink2 = () => {
2719
- const health = createHealthTracker("telemetry-log-sink");
2963
+ var createDisabledSink2 = (destination) => {
2964
+ const health = createHealthTracker(
2965
+ "telemetry-log-sink",
2966
+ destination === void 0 ? {} : { destination }
2967
+ );
2720
2968
  return {
2721
2969
  emit: (events) => {
2722
2970
  health.recordSuccess(events.length);
@@ -2755,19 +3003,24 @@ var DISABLED_DETAIL = Object.freeze({
2755
3003
  "no-endpoint": "otlp log sink disabled: no logs endpoint configured and none could be derived"
2756
3004
  });
2757
3005
  var createOtlpLogSink = (options) => {
3006
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
2758
3007
  const deliverability = describeLogsDeliverability(options.exporter);
2759
3008
  if (deliverability.status === "disabled") {
2760
3009
  if (deliverability.reason !== "logs-disabled") {
2761
3010
  options.logger?.warn(DISABLED_DETAIL[deliverability.reason], {
2762
- "exporter.protocol": options.exporter.protocol
3011
+ "exporter.protocol": options.exporter.protocol,
3012
+ ...destinationFields
2763
3013
  });
2764
3014
  }
2765
- return createDisabledSink2();
3015
+ return createDisabledSink2(options.destination);
2766
3016
  }
2767
3017
  const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
2768
3018
  const resource = resourceFromExporterPolicy(options.exporter);
2769
3019
  const content = options.content ?? NO_LOG_CONTENT;
2770
- const health = createHealthTracker("telemetry-log-sink");
3020
+ const health = createHealthTracker(
3021
+ "telemetry-log-sink",
3022
+ options.destination === void 0 ? {} : { destination: options.destination }
3023
+ );
2771
3024
  const exporter = new OTLPLogExporter({
2772
3025
  url: deliverability.endpoint,
2773
3026
  headers: { ...options.headers },
@@ -2794,7 +3047,10 @@ var createOtlpLogSink = (options) => {
2794
3047
  (record) => deserializeRecord(record, batchResource, batch.instrumentationScope)
2795
3048
  );
2796
3049
  const result = await exportRecords(records);
2797
- return result.code === ExportResultCode2.SUCCESS;
3050
+ if (result.code === ExportResultCode2.SUCCESS) {
3051
+ return true;
3052
+ }
3053
+ return isPermanentExportFailure(result) ? "discard" : false;
2798
3054
  };
2799
3055
  const resolveCorrelations = async (events) => {
2800
3056
  if (options.correlate === void 0) {
@@ -2846,13 +3102,18 @@ var createOtlpLogSink = (options) => {
2846
3102
  continue;
2847
3103
  }
2848
3104
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
2849
- if (options.spool !== void 0) {
3105
+ const permanent = isPermanentExportFailure(result);
3106
+ if (options.spool !== void 0 && !permanent) {
2850
3107
  const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
2851
3108
  spooled: false,
2852
3109
  reason: "capacity-exceeded"
2853
3110
  }));
2854
3111
  if (spoolResult.spooled) {
2855
3112
  accepted += batch.length;
3113
+ options.logger?.warn("log record batch not delivered; spooled for the next invocation", {
3114
+ "export.batch_size": batch.length,
3115
+ ...destinationFields
3116
+ });
2856
3117
  continue;
2857
3118
  }
2858
3119
  }
@@ -2861,8 +3122,12 @@ var createOtlpLogSink = (options) => {
2861
3122
  createErrorInfo({
2862
3123
  code: "telemetry-export-failure",
2863
3124
  phase: "export",
2864
- detail: "collector rejected or was unreachable for a log record batch",
2865
- details: { "export.batch_size": batch.length, "export.signal": "logs" }
3125
+ detail: permanent ? "collector refused a log record batch with a non-retryable status" : "collector rejected or was unreachable for a log record batch",
3126
+ details: {
3127
+ "export.batch_size": batch.length,
3128
+ "export.signal": "logs",
3129
+ ...destinationFields
3130
+ }
2866
3131
  })
2867
3132
  );
2868
3133
  }
@@ -2948,6 +3213,339 @@ var shareCorrelationPerBatch = (correlate) => {
2948
3213
  return result;
2949
3214
  };
2950
3215
  };
3216
+
3217
+ // src/config/destinations.ts
3218
+ import { z as z13 } from "zod";
3219
+
3220
+ // src/config/header-value.ts
3221
+ var isUnsafeHeaderValue = (value) => [...value].some((char) => {
3222
+ const code = char.codePointAt(0) ?? 0;
3223
+ return code < 32 && code !== 9 || code === 127 || code > 255;
3224
+ });
3225
+
3226
+ // src/config/otlp-headers.ts
3227
+ var MAX_OTLP_HEADERS = 32;
3228
+ var OTLP_HEADER_VARIABLES = Object.freeze({
3229
+ generic: "OTEL_EXPORTER_OTLP_HEADERS",
3230
+ traces: "OTEL_EXPORTER_OTLP_TRACES_HEADERS",
3231
+ logs: "OTEL_EXPORTER_OTLP_LOGS_HEADERS"
3232
+ });
3233
+
3234
+ // src/config/destinations.ts
3235
+ var DEFAULT_DESTINATION_NAME = "default";
3236
+ var DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;
3237
+ var MAX_EXPORT_DESTINATIONS = 16;
3238
+ var MAX_DESTINATION_HEADERS = MAX_OTLP_HEADERS;
3239
+ var HEADER_ENV_REFERENCE_PREFIX = "env:";
3240
+ var HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
3241
+ var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
3242
+ var MAX_HEADER_VALUE_LENGTH = 8192;
3243
+ var exportSignalSchema = z13.enum(["traces", "logs"]);
3244
+ var headerValueSchema = z13.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
3245
+ (value) => !isUnsafeHeaderValue(value),
3246
+ "header values may not contain line breaks, control characters, or characters beyond Latin-1"
3247
+ ).refine(
3248
+ (value) => !value.startsWith(HEADER_ENV_REFERENCE_PREFIX) || ENV_VARIABLE_NAME_PATTERN.test(value.slice(HEADER_ENV_REFERENCE_PREFIX.length)),
3249
+ "an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN"
3250
+ );
3251
+ var endpointSchema = z13.string().url().max(2048);
3252
+ var exportDestinationSchema = z13.strictObject({
3253
+ /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */
3254
+ name: z13.string().regex(DESTINATION_NAME_PATTERN, "destination names are lowercase letters, digits, _ and -"),
3255
+ /** Default true. A disabled destination is neither sent to nor drained. */
3256
+ enabled: z13.boolean().optional(),
3257
+ /**
3258
+ * Traces URL, with the same meaning as `exporter.endpoint`: the logs URL is
3259
+ * derived from it (`/v1/traces` becomes `/v1/logs`) unless `logsEndpoint` is set.
3260
+ */
3261
+ endpoint: endpointSchema.optional(),
3262
+ /** Per-signal override of `endpoint` for traces. */
3263
+ tracesEndpoint: endpointSchema.optional(),
3264
+ /** Per-signal override of the derived logs URL. */
3265
+ logsEndpoint: endpointSchema.optional(),
3266
+ /** Defaults to `exporter.protocol`. */
3267
+ protocol: z13.enum(["http/protobuf", "http/json", "none"]).optional(),
3268
+ /**
3269
+ * Header name to value. A value of the form `env:NAME` is read from that
3270
+ * environment variable at send time, so a credential never has to be written
3271
+ * into the file. Values never appear in a snapshot, a diagnostic, or `doctor`.
3272
+ */
3273
+ headers: z13.record(z13.string().regex(HEADER_NAME_PATTERN, "not a valid header name"), headerValueSchema).refine(
3274
+ (headers) => Object.keys(headers).length <= MAX_DESTINATION_HEADERS,
3275
+ `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
3276
+ ).optional(),
3277
+ /**
3278
+ * Which signals this destination receives. Default: both. The logs signal is
3279
+ * still governed by `exporter.logs.enabled`, which stays the one opt-in for a
3280
+ * second stream leaving the host.
3281
+ */
3282
+ signals: z13.array(exportSignalSchema).min(1).max(2).readonly().optional()
3283
+ }).refine(
3284
+ (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0,
3285
+ "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint"
3286
+ );
3287
+ var exportDestinationsSchema = z13.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
3288
+ const seen = /* @__PURE__ */ new Set();
3289
+ destinations.forEach((destination, index) => {
3290
+ if (destination.name === DEFAULT_DESTINATION_NAME) {
3291
+ context.addIssue({
3292
+ code: "custom",
3293
+ path: [index, "name"],
3294
+ message: 'the name "default" is reserved for exporter.endpoint and the OTEL_EXPORTER_OTLP_* variables'
3295
+ });
3296
+ }
3297
+ if (seen.has(destination.name)) {
3298
+ context.addIssue({
3299
+ code: "custom",
3300
+ path: [index, "name"],
3301
+ message: `duplicate destination name "${destination.name}"`
3302
+ });
3303
+ }
3304
+ seen.add(destination.name);
3305
+ });
3306
+ });
3307
+ var spoolPolicySchema = z13.strictObject({
3308
+ /** Total bytes of queued batches. Default 16 MiB. */
3309
+ maxBytes: z13.number().int().min(1024).max(1073741824),
3310
+ /** A batch older than this is dropped instead of sent. Default 72 hours. */
3311
+ maxAgeMillis: z13.number().int().min(1e3).max(30 * 24 * 60 * 60 * 1e3),
3312
+ /** Number of queued batches. Default 500. */
3313
+ maxBatches: z13.number().int().min(1).max(65536)
3314
+ });
3315
+ var DEFAULT_SPOOL_POLICY = Object.freeze({
3316
+ maxBytes: 16 * 1024 * 1024,
3317
+ maxAgeMillis: 72 * 60 * 60 * 1e3,
3318
+ maxBatches: 500
3319
+ });
3320
+ var effectiveSpoolPolicy = (exporter) => ({
3321
+ maxBytes: exporter.spool?.maxBytes ?? DEFAULT_SPOOL_POLICY.maxBytes,
3322
+ maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,
3323
+ maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches
3324
+ });
3325
+ var legacyDestination = (exporter) => ({
3326
+ name: DEFAULT_DESTINATION_NAME,
3327
+ source: "exporter",
3328
+ protocol: exporter.protocol,
3329
+ ...exporter.endpoint === void 0 ? {} : { endpoint: exporter.endpoint },
3330
+ ...exporter.logs.endpoint === void 0 ? {} : { logsEndpoint: exporter.logs.endpoint },
3331
+ signals: { traces: true, logs: exporter.logs.enabled },
3332
+ headers: {}
3333
+ });
3334
+ var hasConfiguredDestinations = (exporter) => exporter.destinations !== void 0 && exporter.destinations.length > 0;
3335
+ var resolveExportDestinations = (exporter) => {
3336
+ if (!hasConfiguredDestinations(exporter)) {
3337
+ return [legacyDestination(exporter)];
3338
+ }
3339
+ const resolved = [];
3340
+ if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0) {
3341
+ resolved.push(legacyDestination(exporter));
3342
+ }
3343
+ for (const destination of exporter.destinations ?? []) {
3344
+ if (destination.enabled === false) {
3345
+ continue;
3346
+ }
3347
+ const signals = destination.signals ?? exportSignalSchema.options;
3348
+ resolved.push({
3349
+ name: destination.name,
3350
+ source: "destinations",
3351
+ protocol: destination.protocol ?? exporter.protocol,
3352
+ ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
3353
+ ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
3354
+ ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
3355
+ signals: {
3356
+ traces: signals.includes("traces"),
3357
+ logs: exporter.logs.enabled && signals.includes("logs")
3358
+ },
3359
+ headers: { ...destination.headers ?? {} }
3360
+ });
3361
+ }
3362
+ return resolved;
3363
+ };
3364
+ var parseHeaderValueReference = (value) => value.startsWith(HEADER_ENV_REFERENCE_PREFIX) ? { kind: "env", variable: value.slice(HEADER_ENV_REFERENCE_PREFIX.length) } : { kind: "literal" };
3365
+ var resolveDestinationHeaders = (headers, environment) => {
3366
+ const values = {};
3367
+ const missing = [];
3368
+ for (const [name, value] of Object.entries(headers)) {
3369
+ const reference = parseHeaderValueReference(value);
3370
+ if (reference.kind === "literal") {
3371
+ values[name] = value;
3372
+ continue;
3373
+ }
3374
+ const resolved = environment?.[reference.variable];
3375
+ if (resolved === void 0 || resolved === "") {
3376
+ missing.push(reference.variable);
3377
+ continue;
3378
+ }
3379
+ values[name] = resolved;
3380
+ }
3381
+ return { values, missingVariables: [...new Set(missing)].sort() };
3382
+ };
3383
+
3384
+ // src/telemetry/export-destinations.ts
3385
+ var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs" } : { traces: `destinations/${destination}/spool`, logs: `destinations/${destination}/spool-logs` };
3386
+ var exporterPolicyForDestination = (exporter, destination) => {
3387
+ if (destination.source === "exporter") {
3388
+ return exporter;
3389
+ }
3390
+ const { destinations, endpoint, logs, ...shared } = exporter;
3391
+ void destinations;
3392
+ void endpoint;
3393
+ const tracesEndpoint = destination.tracesEndpoint ?? destination.endpoint;
3394
+ const derivedLogs = destination.logsEndpoint ?? (destination.endpoint === void 0 ? void 0 : (() => {
3395
+ const derived = resolveLogsEndpoint({
3396
+ ...exporter,
3397
+ endpoint: destination.endpoint,
3398
+ logs: { enabled: true, includeContent: false, maxBatchSize: logs.maxBatchSize }
3399
+ });
3400
+ return "endpoint" in derived ? derived.endpoint : void 0;
3401
+ })());
3402
+ return {
3403
+ ...shared,
3404
+ protocol: destination.protocol,
3405
+ ...tracesEndpoint === void 0 ? {} : { endpoint: tracesEndpoint },
3406
+ headerNames: Object.keys(destination.headers).sort(),
3407
+ logs: {
3408
+ ...logs,
3409
+ enabled: destination.signals.logs,
3410
+ ...derivedLogs === void 0 ? {} : { endpoint: derivedLogs }
3411
+ }
3412
+ };
3413
+ };
3414
+ var createOptedOutTraceSink = (destination) => {
3415
+ const health = createHealthTracker(
3416
+ "telemetry-sink",
3417
+ destination === void 0 ? {} : { destination }
3418
+ );
3419
+ return {
3420
+ emit: () => Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),
3421
+ flush: () => Promise.resolve(),
3422
+ shutdown: () => Promise.resolve(),
3423
+ health: () => health.snapshot(),
3424
+ drainSpool: () => Promise.resolve({ drained: 0, remaining: 0, failed: 0 })
3425
+ };
3426
+ };
3427
+ var createExportDestinationSinks = (options) => {
3428
+ const labelled = hasConfiguredDestinations(options.exporter);
3429
+ const spoolPolicy = effectiveSpoolPolicy(options.exporter);
3430
+ const destinations = [];
3431
+ const skipped = [];
3432
+ for (const destination of resolveExportDestinations(options.exporter)) {
3433
+ let headers;
3434
+ let logHeaders;
3435
+ if (destination.source === "exporter") {
3436
+ headers = options.defaultHeaders;
3437
+ logHeaders = options.defaultLogHeaders ?? options.defaultHeaders;
3438
+ } else {
3439
+ const resolved = resolveDestinationHeaders(destination.headers, options.headerEnvironment);
3440
+ if (resolved.missingVariables.length > 0) {
3441
+ options.logger?.warn("export destination skipped: a header references an unset environment variable", {
3442
+ "export.destination": destination.name,
3443
+ "config.variables": [...resolved.missingVariables]
3444
+ });
3445
+ skipped.push({
3446
+ name: destination.name,
3447
+ reason: "header-variable-missing",
3448
+ missingVariables: resolved.missingVariables
3449
+ });
3450
+ continue;
3451
+ }
3452
+ headers = resolved.values;
3453
+ logHeaders = resolved.values;
3454
+ }
3455
+ const label = labelled ? destination.name : void 0;
3456
+ const policy = exporterPolicyForDestination(options.exporter, destination);
3457
+ const queues = spoolQueueNamesFor(destination.name);
3458
+ const bounds = {
3459
+ maxSpoolFiles: spoolPolicy.maxBatches,
3460
+ maxBytes: spoolPolicy.maxBytes,
3461
+ maxAgeMillis: spoolPolicy.maxAgeMillis,
3462
+ overflow: "drop-oldest"
3463
+ };
3464
+ const shared = {
3465
+ providerId: options.providerId,
3466
+ installationId: options.installationId,
3467
+ clock: options.clock,
3468
+ ...options.logger === void 0 ? {} : { logger: options.logger }
3469
+ };
3470
+ const spool = options.spoolRootDir === void 0 || !destination.signals.traces ? void 0 : createFileDurableSpool({
3471
+ rootDir: options.spoolRootDir,
3472
+ ...shared,
3473
+ ...bounds,
3474
+ queueName: queues.traces
3475
+ });
3476
+ const logSpool = options.spoolRootDir === void 0 || !destination.signals.logs ? void 0 : createFileDurableLogSpool({
3477
+ rootDir: options.spoolRootDir,
3478
+ ...shared,
3479
+ ...bounds,
3480
+ queueName: queues.logs
3481
+ });
3482
+ const sinkShared = {
3483
+ exporter: policy,
3484
+ ...shared,
3485
+ ...options.correlate === void 0 ? {} : { correlate: options.correlate },
3486
+ ...label === void 0 ? {} : { destination: label }
3487
+ };
3488
+ const traces = destination.signals.traces ? createOtlpTraceSink({
3489
+ ...sinkShared,
3490
+ ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
3491
+ ...spool === void 0 ? {} : { spool }
3492
+ }) : createOptedOutTraceSink(label);
3493
+ const logs = createOtlpLogSink({
3494
+ ...sinkShared,
3495
+ ...logHeaders === void 0 || Object.keys(logHeaders).length === 0 ? {} : { headers: logHeaders },
3496
+ ...logSpool === void 0 ? {} : { spool: logSpool },
3497
+ content: options.logContent
3498
+ });
3499
+ destinations.push({
3500
+ name: destination.name,
3501
+ traces,
3502
+ logs,
3503
+ ...spool === void 0 ? {} : { spool },
3504
+ ...logSpool === void 0 ? {} : { logSpool }
3505
+ });
3506
+ }
3507
+ return { destinations, skipped };
3508
+ };
3509
+ var createDestinationFanout = (destinations) => {
3510
+ const fanouts = destinations.map((destination) => ({
3511
+ name: destination.name,
3512
+ sink: createSignalFanout({ traces: destination.traces, logs: destination.logs })
3513
+ }));
3514
+ const only = fanouts.length === 1 ? fanouts[0] : void 0;
3515
+ if (only !== void 0) {
3516
+ return only.sink;
3517
+ }
3518
+ const emit = async (events) => {
3519
+ const results = await Promise.all(
3520
+ fanouts.map(
3521
+ (fanout) => fanout.sink.emit(events).catch(
3522
+ (thrown) => ({
3523
+ accepted: 0,
3524
+ rejected: events.length,
3525
+ errors: [errorInfoFromThrown(thrown, { code: "telemetry-export-failure", phase: "export" })]
3526
+ })
3527
+ )
3528
+ )
3529
+ );
3530
+ const errors = results.flatMap((result) => result.errors);
3531
+ return {
3532
+ accepted: results.reduce((sum, result) => sum + result.accepted, 0),
3533
+ rejected: results.reduce((sum, result) => sum + result.rejected, 0),
3534
+ errors
3535
+ };
3536
+ };
3537
+ const settleAll = async (run) => {
3538
+ await Promise.all(fanouts.map((fanout) => run(fanout.sink).catch(() => void 0)));
3539
+ };
3540
+ return {
3541
+ emit,
3542
+ // Each destination drains its own spool in its flush; in parallel, so one
3543
+ // unreachable destination's drain cannot use up the others' flush window.
3544
+ flush: () => settleAll((sink) => sink.flush()),
3545
+ shutdown: () => settleAll((sink) => sink.shutdown()),
3546
+ health: () => fanouts.flatMap((fanout) => fanout.sink.health())
3547
+ };
3548
+ };
2951
3549
  export {
2952
3550
  DEFAULT_INSTRUMENTATION_SCOPE,
2953
3551
  LOG_MAPPING_VERSION,
@@ -2961,18 +3559,23 @@ export {
2961
3559
  canonicalEventTraceIdentities,
2962
3560
  canonicalEventsToLogRecords,
2963
3561
  canonicalEventsToReadableSpans,
3562
+ createDestinationFanout,
3563
+ createExportDestinationSinks,
2964
3564
  createFileDurableLogSpool,
2965
3565
  createFileDurableSpool,
2966
3566
  createOtlpLogSink,
2967
3567
  createOtlpTraceSink,
2968
3568
  createSignalFanout,
2969
3569
  describeLogsDeliverability,
3570
+ exporterPolicyForDestination,
3571
+ isPermanentExportFailure,
2970
3572
  logSignalOf,
2971
3573
  logSignalsForLifecycleEvents,
2972
3574
  parentScopeRefOf,
2973
3575
  resolveLogsEndpoint,
2974
3576
  shareCorrelationPerBatch,
2975
3577
  spanScopeRefOf,
3578
+ spoolQueueNamesFor,
2976
3579
  startOnlySpanAttributes
2977
3580
  };
2978
3581
  //# sourceMappingURL=telemetry.js.map