@osfactory/otel-hook 0.13.1 → 0.14.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 (41) hide show
  1. package/README.md +94 -3
  2. package/dist/{adapter-DyCb7y1N.d.ts → adapter-D5R8lhfl.d.ts} +1 -1
  3. package/dist/cli.js +1240 -200
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +32 -4
  6. package/dist/config.js +200 -14
  7. package/dist/config.js.map +1 -1
  8. package/dist/{destinations-DvqsPulb.d.ts → destinations-2KrcRslo.d.ts} +92 -2
  9. package/dist/{export-destinations-DUeQKr_C.d.ts → export-destinations-DvoH4QOe.d.ts} +135 -11
  10. package/dist/{hook-D5imE0Qc.d.ts → hook-DVK8Don-.d.ts} +4 -4
  11. package/dist/index.d.ts +11 -11
  12. package/dist/index.js +1262 -228
  13. package/dist/index.js.map +1 -1
  14. package/dist/install.d.ts +3 -3
  15. package/dist/install.js +1 -0
  16. package/dist/install.js.map +1 -1
  17. package/dist/integration.d.ts +16 -9
  18. package/dist/integration.js +1298 -205
  19. package/dist/integration.js.map +1 -1
  20. package/dist/lifecycle.js +1 -1
  21. package/dist/lifecycle.js.map +1 -1
  22. package/dist/{payload-CdDKeRpH.d.ts → payload-D4r71EL-.d.ts} +18 -2
  23. package/dist/privacy.d.ts +2 -2
  24. package/dist/privacy.js +42 -1
  25. package/dist/privacy.js.map +1 -1
  26. package/dist/providers.d.ts +94 -9
  27. package/dist/providers.js +300 -2
  28. package/dist/providers.js.map +1 -1
  29. package/dist/{registry-BKQhhIO3.d.ts → registry-DOJh9mzB.d.ts} +2 -2
  30. package/dist/runtime.d.ts +5 -5
  31. package/dist/runtime.js +151 -5
  32. package/dist/runtime.js.map +1 -1
  33. package/dist/{schema-SpFM6YQY.d.ts → schema-oRsbo7WO.d.ts} +77 -3
  34. package/dist/{service-CbI9CObT.d.ts → service-DySC7KQM.d.ts} +6 -1
  35. package/dist/telemetry.d.ts +5 -4
  36. package/dist/telemetry.js +1076 -476
  37. package/dist/telemetry.js.map +1 -1
  38. package/dist/testing.d.ts +5 -5
  39. package/dist/testing.js +178 -21
  40. package/dist/testing.js.map +1 -1
  41. 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.13.1";
21
+ var VERSION = "0.14.0";
22
22
 
23
23
  // src/telemetry/export-identity.ts
24
24
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -1378,6 +1378,17 @@ var planGroup = (group, correlation, correlationAvailable) => {
1378
1378
  };
1379
1379
  var runDiscriminatorOf = (correlation) => correlation?.runSpanIdDiscriminator === void 0 ? void 0 : `run:${correlation.runSpanIdDiscriminator}`;
1380
1380
  var resumedSessionParent = (ref, correlation) => ref.family === "session" && correlation?.runSpanIdDiscriminator !== void 0 ? ref : void 0;
1381
+ var spanEndEdgesOf = (events) => {
1382
+ const layout = layoutBatch(events);
1383
+ const ends = /* @__PURE__ */ new Map();
1384
+ for (const [eventId, groupKey] of layout.groupOf) {
1385
+ const end = layout.groups.get(groupKey)?.end;
1386
+ if (end !== void 0) {
1387
+ ends.set(eventId, end);
1388
+ }
1389
+ }
1390
+ return ends;
1391
+ };
1381
1392
  var canonicalEventTraceIdentities = (events, options = {}) => {
1382
1393
  const layout = layoutBatch(events);
1383
1394
  const correlations = indexCorrelations(options.correlations);
@@ -1431,7 +1442,7 @@ var canonicalEventsToReadableSpans = (events, options) => {
1431
1442
 
1432
1443
  // src/telemetry/spool-queue.ts
1433
1444
  import { randomBytes } from "crypto";
1434
- import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "fs/promises";
1445
+ import { mkdir, open, readFile, readdir, rename, stat, unlink, writeFile } from "fs/promises";
1435
1446
  import * as path from "path";
1436
1447
 
1437
1448
  // src/state/keys.ts
@@ -1508,7 +1519,8 @@ var readSpoolQueueStats = async (queueDir) => {
1508
1519
  };
1509
1520
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
1510
1521
  var SPOOL_CLAIM_STALE_MILLIS = 5 * 60 * 1e3;
1511
- var CLAIM_MARKER = ".claimed-";
1522
+ var CLAIM_SUFFIX = ".claim";
1523
+ var RELEASING_SUFFIX = ".releasing";
1512
1524
  var isClaimOwnerAlive = (pid) => {
1513
1525
  if (!Number.isSafeInteger(pid) || pid <= 0) {
1514
1526
  return true;
@@ -1524,6 +1536,34 @@ var isClaimOwnerAlive = (pid) => {
1524
1536
  }
1525
1537
  };
1526
1538
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
1539
+ var readClaim = async (claimPath) => {
1540
+ try {
1541
+ const parsed = JSON.parse(await readFile(claimPath, "utf8"));
1542
+ return typeof parsed.token === "string" && typeof parsed.pid === "number" && typeof parsed.claimedAt === "number" ? { token: parsed.token, pid: parsed.pid, claimedAt: parsed.claimedAt } : void 0;
1543
+ } catch {
1544
+ return void 0;
1545
+ }
1546
+ };
1547
+ var releaseClaim = async (claimPath, token) => {
1548
+ const tombstone = `${claimPath}.${token ?? "untokened"}-${randomBytes(4).toString("hex")}${RELEASING_SUFFIX}`;
1549
+ for (let attempt = 1; ; attempt += 1) {
1550
+ try {
1551
+ await rename(claimPath, tombstone);
1552
+ break;
1553
+ } catch (thrown) {
1554
+ if (isErrnoException(thrown, "ENOENT") || attempt >= 3) {
1555
+ return;
1556
+ }
1557
+ await new Promise((resolve) => setTimeout(resolve, 10 * attempt));
1558
+ }
1559
+ }
1560
+ const captured = await readClaim(tombstone);
1561
+ if (captured !== void 0 && captured.token !== token) {
1562
+ await rename(tombstone, claimPath).catch(() => void 0);
1563
+ return;
1564
+ }
1565
+ await unlink(tombstone).catch(() => void 0);
1566
+ };
1527
1567
  var createSpoolQueue = (options) => {
1528
1568
  const [providerSegment, installationSegment] = namespaceSegments(options);
1529
1569
  const queueDir = path.join(options.rootDir, providerSegment, installationSegment, options.queueName);
@@ -1672,6 +1712,19 @@ var createSpoolQueue = (options) => {
1672
1712
  await rename(tmp, target);
1673
1713
  return { spooled: true };
1674
1714
  };
1715
+ const claimStaleMillis = options.claimStaleMillis ?? SPOOL_CLAIM_STALE_MILLIS;
1716
+ const staleClaim = async (claimPath) => {
1717
+ const claim = await readClaim(claimPath);
1718
+ const now = Date.now();
1719
+ if (claim !== void 0) {
1720
+ return !isClaimOwnerAlive(claim.pid) || now - claim.claimedAt > claimStaleMillis ? { stale: true, token: claim.token } : { stale: false };
1721
+ }
1722
+ try {
1723
+ return now - (await stat(claimPath)).mtimeMs > claimStaleMillis ? { stale: true, token: void 0 } : { stale: false };
1724
+ } catch {
1725
+ return { stale: false };
1726
+ }
1727
+ };
1675
1728
  const releaseStaleClaims = async () => {
1676
1729
  let entries;
1677
1730
  try {
@@ -1681,18 +1734,35 @@ var createSpoolQueue = (options) => {
1681
1734
  }
1682
1735
  const now = Date.now();
1683
1736
  for (const entry of entries) {
1684
- const marker = entry.lastIndexOf(CLAIM_MARKER);
1685
- if (marker <= 0) {
1686
- continue;
1737
+ const entryPath = path.join(queueDir, entry);
1738
+ if (entry.endsWith(CLAIM_SUFFIX)) {
1739
+ const staleness = await staleClaim(entryPath);
1740
+ if (staleness.stale) {
1741
+ await releaseClaim(entryPath, staleness.token);
1742
+ }
1743
+ } else if (entry.endsWith(RELEASING_SUFFIX)) {
1744
+ try {
1745
+ if (now - (await stat(entryPath)).mtimeMs > claimStaleMillis) {
1746
+ await unlink(entryPath);
1747
+ }
1748
+ } catch {
1749
+ }
1687
1750
  }
1688
- const claimPath = path.join(queueDir, entry);
1689
- const owner = Number.parseInt(entry.slice(marker + CLAIM_MARKER.length), 10);
1751
+ }
1752
+ };
1753
+ const claimBatch = async (claimPath) => {
1754
+ const token = randomBytes(16).toString("hex");
1755
+ try {
1756
+ const handle = await open(claimPath, "wx");
1690
1757
  try {
1691
- if (!isClaimOwnerAlive(owner) || now - (await stat(claimPath)).ctimeMs > (options.claimStaleMillis ?? SPOOL_CLAIM_STALE_MILLIS)) {
1692
- await rename(claimPath, path.join(queueDir, entry.slice(0, marker)));
1693
- }
1694
- } catch {
1758
+ const contents = { token, pid: process.pid, claimedAt: Date.now() };
1759
+ await handle.writeFile(JSON.stringify(contents), "utf8");
1760
+ } finally {
1761
+ await handle.close();
1695
1762
  }
1763
+ return token;
1764
+ } catch {
1765
+ return void 0;
1696
1766
  }
1697
1767
  };
1698
1768
  const drain = async (send, drainOptions) => {
@@ -1716,21 +1786,7 @@ var createSpoolQueue = (options) => {
1716
1786
  let failed = 0;
1717
1787
  let quarantined = 0;
1718
1788
  let index = 0;
1719
- for (; index < files.length && index < cap; index += 1) {
1720
- const fileName = files[index];
1721
- if (fileName === void 0) {
1722
- break;
1723
- }
1724
- const queuedPath = path.join(queueDir, fileName);
1725
- const filePath = path.join(
1726
- queueDir,
1727
- `${fileName}${CLAIM_MARKER}${String(process.pid)}-${randomBytes(4).toString("hex")}`
1728
- );
1729
- try {
1730
- await rename(queuedPath, filePath);
1731
- } catch {
1732
- continue;
1733
- }
1789
+ const sendClaimed = async (fileName, filePath, claimPath, token) => {
1734
1790
  const quarantine = async (rejection) => {
1735
1791
  quarantined += 1;
1736
1792
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -1749,17 +1805,17 @@ var createSpoolQueue = (options) => {
1749
1805
  text = await readFile(filePath, "utf8");
1750
1806
  } catch (thrown) {
1751
1807
  if (thrown?.code === "ENOENT") {
1752
- continue;
1808
+ return "next";
1753
1809
  }
1754
1810
  await quarantine("unreadable");
1755
- continue;
1811
+ return "next";
1756
1812
  }
1757
1813
  let parsed;
1758
1814
  try {
1759
1815
  parsed = JSON.parse(text);
1760
1816
  } catch {
1761
1817
  await quarantine("unparseable-json");
1762
- continue;
1818
+ return "next";
1763
1819
  }
1764
1820
  const validation = options.validate(parsed, {
1765
1821
  providerId: options.providerId,
@@ -1767,7 +1823,10 @@ var createSpoolQueue = (options) => {
1767
1823
  });
1768
1824
  if ("rejection" in validation) {
1769
1825
  await quarantine(validation.rejection);
1770
- continue;
1826
+ return "next";
1827
+ }
1828
+ if ((await readClaim(claimPath))?.token !== token) {
1829
+ return "next";
1771
1830
  }
1772
1831
  let delivered;
1773
1832
  try {
@@ -1779,14 +1838,34 @@ var createSpoolQueue = (options) => {
1779
1838
  if (await unlink(filePath).then(() => true, () => false)) {
1780
1839
  await recordDrops("rejected", 1);
1781
1840
  }
1782
- continue;
1841
+ return "next";
1783
1842
  }
1784
1843
  if (delivered) {
1785
1844
  await unlink(filePath).catch(() => void 0);
1786
1845
  drained += 1;
1787
- } else {
1788
- await rename(filePath, queuedPath).catch(() => void 0);
1789
- failed += 1;
1846
+ return "next";
1847
+ }
1848
+ failed += 1;
1849
+ return "stop";
1850
+ };
1851
+ for (; index < files.length && index < cap; index += 1) {
1852
+ const fileName = files[index];
1853
+ if (fileName === void 0) {
1854
+ break;
1855
+ }
1856
+ const filePath = path.join(queueDir, fileName);
1857
+ const claimPath = `${filePath}${CLAIM_SUFFIX}`;
1858
+ const token = await claimBatch(claimPath);
1859
+ if (token === void 0) {
1860
+ continue;
1861
+ }
1862
+ let outcome;
1863
+ try {
1864
+ outcome = await sendClaimed(fileName, filePath, claimPath, token);
1865
+ } finally {
1866
+ await releaseClaim(claimPath, token);
1867
+ }
1868
+ if (outcome === "stop") {
1790
1869
  break;
1791
1870
  }
1792
1871
  }
@@ -1900,7 +1979,7 @@ var createFileDurableSpool = (options) => createSpoolQueue({
1900
1979
  });
1901
1980
 
1902
1981
  // src/telemetry/otlp-sink.ts
1903
- import { ExportResultCode } from "@opentelemetry/core";
1982
+ import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
1904
1983
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
1905
1984
 
1906
1985
  // src/errors/index.ts
@@ -2010,11 +2089,17 @@ var isPermanentExportFailure = (result) => {
2010
2089
  return typeof code === "number" && Number.isInteger(code) && code >= 400 && code < 600 && !RETRYABLE_HTTP_STATUSES.has(code);
2011
2090
  };
2012
2091
 
2013
- // src/telemetry/exporter-resource.ts
2014
- import { resourceFromAttributes } from "@opentelemetry/resources";
2092
+ // src/telemetry/endpoint-health.ts
2093
+ import { createHash as createHash3, randomBytes as randomBytes2 } from "crypto";
2094
+ import { mkdir as mkdir2, readFile as readFile2, rename as rename2, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
2095
+ import * as http from "http";
2096
+ import * as https from "https";
2097
+ import path2 from "path";
2098
+ import { ExportResultCode } from "@opentelemetry/core";
2015
2099
 
2016
- // src/config/resource-attributes.ts
2017
- import { z as z12 } from "zod";
2100
+ // src/config/schema.ts
2101
+ import { isAbsolute } from "path";
2102
+ import { z as z14 } from "zod";
2018
2103
 
2019
2104
  // src/privacy/policy.ts
2020
2105
  import { z as z11 } from "zod";
@@ -2093,7 +2178,296 @@ var DEFAULT_PRIVACY_POLICY = Object.freeze({
2093
2178
  limits: DEFAULT_PRIVACY_LIMITS
2094
2179
  });
2095
2180
 
2181
+ // src/config/destinations.ts
2182
+ import { z as z12 } from "zod";
2183
+
2184
+ // src/config/header-value.ts
2185
+ var isUnsafeHeaderValue = (value) => [...value].some((char) => {
2186
+ const code = char.codePointAt(0) ?? 0;
2187
+ return code < 32 && code !== 9 || code === 127 || code > 255;
2188
+ });
2189
+
2190
+ // src/config/otlp-headers.ts
2191
+ var MAX_OTLP_HEADERS = 32;
2192
+ var OTLP_HEADER_VARIABLES = Object.freeze({
2193
+ generic: "OTEL_EXPORTER_OTLP_HEADERS",
2194
+ traces: "OTEL_EXPORTER_OTLP_TRACES_HEADERS",
2195
+ logs: "OTEL_EXPORTER_OTLP_LOGS_HEADERS"
2196
+ });
2197
+
2198
+ // src/config/repository-key.ts
2199
+ var ATTR_VCS_REPOSITORY_URL_FULL = "vcs.repository.url.full";
2200
+ var MAX_REPOSITORY_REFERENCE_LENGTH = 2048;
2201
+ var SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;
2202
+ var SCP_LIKE_PATTERN = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/\/)(.+)$/;
2203
+ var trimTrailingSlashes = (value) => {
2204
+ let end = value.length;
2205
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
2206
+ return value.slice(0, end);
2207
+ };
2208
+ var keyOf = (host, pathname) => {
2209
+ const withoutSlashes = trimTrailingSlashes(pathname);
2210
+ const cleanedPath = trimTrailingSlashes(
2211
+ withoutSlashes.toLowerCase().endsWith(".git") ? withoutSlashes.slice(0, -4) : withoutSlashes
2212
+ );
2213
+ if (host.length === 0 || cleanedPath.length === 0 || cleanedPath === "/") {
2214
+ return void 0;
2215
+ }
2216
+ const withSlash = cleanedPath.startsWith("/") ? cleanedPath : `/${cleanedPath}`;
2217
+ return `${host}${withSlash}`.toLowerCase();
2218
+ };
2219
+ var normalizeRepositoryKey = (reference) => {
2220
+ const trimmed = reference.trim();
2221
+ if (trimmed.length === 0 || trimmed.length > MAX_REPOSITORY_REFERENCE_LENGTH) {
2222
+ return void 0;
2223
+ }
2224
+ if (SCHEME_PATTERN.test(trimmed)) {
2225
+ let url;
2226
+ try {
2227
+ url = new URL(trimmed);
2228
+ } catch {
2229
+ return void 0;
2230
+ }
2231
+ if (url.protocol === "file:") {
2232
+ return void 0;
2233
+ }
2234
+ return keyOf(url.hostname, url.pathname);
2235
+ }
2236
+ if (trimmed.startsWith("/") || trimmed.startsWith(".") || trimmed.includes("\\")) {
2237
+ return void 0;
2238
+ }
2239
+ const scp = SCP_LIKE_PATTERN.exec(trimmed);
2240
+ if (scp !== null && !trimmed.split(":")[0]?.includes("/")) {
2241
+ const [, host, pathPart] = scp;
2242
+ return host === void 0 || pathPart === void 0 ? void 0 : keyOf(host, pathPart);
2243
+ }
2244
+ try {
2245
+ const url = new URL(`https://${trimmed}`);
2246
+ return keyOf(url.hostname, url.pathname);
2247
+ } catch {
2248
+ return void 0;
2249
+ }
2250
+ };
2251
+
2252
+ // src/config/destinations.ts
2253
+ var DEFAULT_DESTINATION_NAME = "default";
2254
+ var DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;
2255
+ var MAX_EXPORT_DESTINATIONS = 16;
2256
+ var MAX_DESTINATION_HEADERS = MAX_OTLP_HEADERS;
2257
+ var HEADER_ENV_REFERENCE_PREFIX = "env:";
2258
+ var HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
2259
+ var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
2260
+ var MAX_HEADER_VALUE_LENGTH = 8192;
2261
+ var exportSignalSchema = z12.enum(["traces", "logs", "metrics"]);
2262
+ var headerValueSchema = z12.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
2263
+ (value) => !isUnsafeHeaderValue(value),
2264
+ "header values may not contain line breaks, control characters, or characters beyond Latin-1"
2265
+ ).refine(
2266
+ (value) => !value.startsWith(HEADER_ENV_REFERENCE_PREFIX) || ENV_VARIABLE_NAME_PATTERN.test(value.slice(HEADER_ENV_REFERENCE_PREFIX.length)),
2267
+ "an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN"
2268
+ );
2269
+ var endpointSchema = z12.string().url().max(2048);
2270
+ var MAX_DESTINATION_SCOPES = 64;
2271
+ var MAX_SCOPE_REPOSITORIES = 256;
2272
+ var ALL_REPOSITORIES = "*";
2273
+ var repositoryReferenceSchema = z12.string().min(1).max(MAX_REPOSITORY_REFERENCE_LENGTH).refine(
2274
+ (value) => normalizeRepositoryKey(value) !== void 0,
2275
+ "not a repository URL: use https://host/owner/repo, git@host:owner/repo.git, or host/owner/repo"
2276
+ );
2277
+ var destinationScopeSchema = z12.strictObject({
2278
+ /**
2279
+ * Repository URLs (any spelling of the remote; compared by host and path,
2280
+ * case-insensitively, without `.git`), or `"*"` for every record that names
2281
+ * a repository. A record that names none never matches a scope.
2282
+ */
2283
+ repositories: z12.union([
2284
+ z12.literal(ALL_REPOSITORIES),
2285
+ z12.array(repositoryReferenceSchema).min(1).max(MAX_SCOPE_REPOSITORIES).readonly()
2286
+ ]),
2287
+ /** Signals sent for these repositories. Default: every signal the destination takes. */
2288
+ signals: z12.array(exportSignalSchema).min(1).max(3).readonly().optional(),
2289
+ /** Content disclosure for these repositories, never above `privacy.contentMode`. Default: unchanged. */
2290
+ contentMode: contentModeSchema.optional(),
2291
+ /** False leaves `session.id` off metric data points for these repositories. Default true. */
2292
+ includeSessionId: z12.boolean().optional()
2293
+ });
2294
+ var exportDestinationSchema = z12.strictObject({
2295
+ /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */
2296
+ name: z12.string().regex(DESTINATION_NAME_PATTERN, "destination names are lowercase letters, digits, _ and -"),
2297
+ /** Default true. A disabled destination is neither sent to nor drained. */
2298
+ enabled: z12.boolean().optional(),
2299
+ /**
2300
+ * Traces URL, with the same meaning as `exporter.endpoint`: the logs URL is
2301
+ * derived from it (`/v1/traces` becomes `/v1/logs`) unless `logsEndpoint` is set.
2302
+ */
2303
+ endpoint: endpointSchema.optional(),
2304
+ /** Per-signal override of `endpoint` for traces. */
2305
+ tracesEndpoint: endpointSchema.optional(),
2306
+ /** Per-signal override of the derived logs URL. */
2307
+ logsEndpoint: endpointSchema.optional(),
2308
+ /** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */
2309
+ metricsEndpoint: endpointSchema.optional(),
2310
+ /** Defaults to `exporter.protocol`. */
2311
+ protocol: z12.enum(["http/protobuf", "http/json", "none"]).optional(),
2312
+ /**
2313
+ * Header name to value. A value of the form `env:NAME` is read from that
2314
+ * environment variable at send time, so a credential never has to be written
2315
+ * into the file. Values never appear in a snapshot, a diagnostic, or `doctor`.
2316
+ */
2317
+ headers: z12.record(z12.string().regex(HEADER_NAME_PATTERN, "not a valid header name"), headerValueSchema).refine(
2318
+ (headers) => Object.keys(headers).length <= MAX_DESTINATION_HEADERS,
2319
+ `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
2320
+ ).optional(),
2321
+ /**
2322
+ * Which signals this destination receives. Default: traces and logs. The logs
2323
+ * signal is still governed by `exporter.logs.enabled`, which stays the one
2324
+ * opt-in for content-bearing records leaving the host. `metrics` is never on by
2325
+ * default: a destination receives hook-derived metrics only when it lists them.
2326
+ */
2327
+ signals: z12.array(exportSignalSchema).min(1).max(3).readonly().optional(),
2328
+ /**
2329
+ * Per-repository filter. Absent: every record goes to this destination, as
2330
+ * before scopes existed. Present: a record goes only when its repository
2331
+ * (`vcs.repository.url.full`) matches a scope — the first matching scope
2332
+ * decides its signals, content mode, and session id — and a record that
2333
+ * names no repository is not sent here at all.
2334
+ */
2335
+ scopes: z12.array(destinationScopeSchema).min(1).max(MAX_DESTINATION_SCOPES).readonly().optional()
2336
+ }).refine(
2337
+ (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
2338
+ "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
2339
+ );
2340
+ var DEFAULT_DESTINATION_SIGNALS = Object.freeze(["traces", "logs"]);
2341
+ var exportDestinationsSchema = z12.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
2342
+ const seen = /* @__PURE__ */ new Set();
2343
+ destinations.forEach((destination, index) => {
2344
+ if (destination.name === DEFAULT_DESTINATION_NAME) {
2345
+ context.addIssue({
2346
+ code: "custom",
2347
+ path: [index, "name"],
2348
+ message: 'the name "default" is reserved for exporter.endpoint and the OTEL_EXPORTER_OTLP_* variables'
2349
+ });
2350
+ }
2351
+ if (seen.has(destination.name)) {
2352
+ context.addIssue({
2353
+ code: "custom",
2354
+ path: [index, "name"],
2355
+ message: `duplicate destination name "${destination.name}"`
2356
+ });
2357
+ }
2358
+ seen.add(destination.name);
2359
+ });
2360
+ });
2361
+ var spoolPolicySchema = z12.strictObject({
2362
+ /** Total bytes of queued batches. Default 16 MiB. */
2363
+ maxBytes: z12.number().int().min(1024).max(1073741824),
2364
+ /** A batch older than this is dropped instead of sent. Default 72 hours. */
2365
+ maxAgeMillis: z12.number().int().min(1e3).max(30 * 24 * 60 * 60 * 1e3),
2366
+ /** Number of queued batches. Default 500. */
2367
+ maxBatches: z12.number().int().min(1).max(65536)
2368
+ });
2369
+ var DEFAULT_SPOOL_POLICY = Object.freeze({
2370
+ maxBytes: 16 * 1024 * 1024,
2371
+ maxAgeMillis: 72 * 60 * 60 * 1e3,
2372
+ maxBatches: 500
2373
+ });
2374
+ var effectiveSpoolPolicy = (exporter) => ({
2375
+ maxBytes: exporter.spool?.maxBytes ?? DEFAULT_SPOOL_POLICY.maxBytes,
2376
+ maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,
2377
+ maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches
2378
+ });
2379
+ var resolveDestinationScopes = (scopes, destinationSignals) => scopes.map((scope) => {
2380
+ const listed = scope.signals ?? exportSignalSchema.options;
2381
+ return {
2382
+ repositories: scope.repositories === ALL_REPOSITORIES ? ALL_REPOSITORIES : new Set(
2383
+ scope.repositories.flatMap((reference) => {
2384
+ const key = normalizeRepositoryKey(reference);
2385
+ return key === void 0 ? [] : [key];
2386
+ })
2387
+ ),
2388
+ signals: {
2389
+ traces: destinationSignals.traces && listed.includes("traces"),
2390
+ logs: destinationSignals.logs && listed.includes("logs"),
2391
+ metrics: destinationSignals.metrics && listed.includes("metrics")
2392
+ },
2393
+ ...scope.contentMode === void 0 ? {} : { contentMode: scope.contentMode },
2394
+ includeSessionId: scope.includeSessionId ?? true
2395
+ };
2396
+ });
2397
+ var matchDestinationScope = (scopes, repositoryKey) => {
2398
+ if (repositoryKey === void 0) {
2399
+ return void 0;
2400
+ }
2401
+ return scopes.find(
2402
+ (scope) => scope.repositories === ALL_REPOSITORIES || scope.repositories.has(repositoryKey)
2403
+ );
2404
+ };
2405
+ var legacyDestination = (exporter) => ({
2406
+ name: DEFAULT_DESTINATION_NAME,
2407
+ source: "exporter",
2408
+ protocol: exporter.protocol,
2409
+ ...exporter.endpoint === void 0 ? {} : { endpoint: exporter.endpoint },
2410
+ ...exporter.logs.endpoint === void 0 ? {} : { logsEndpoint: exporter.logs.endpoint },
2411
+ ...exporter.metrics?.endpoint === void 0 ? {} : { metricsEndpoint: exporter.metrics.endpoint },
2412
+ signals: { traces: true, logs: exporter.logs.enabled, metrics: exporter.metrics?.enabled === true },
2413
+ headers: {}
2414
+ });
2415
+ var hasConfiguredDestinations = (exporter) => exporter.destinations !== void 0 && exporter.destinations.length > 0;
2416
+ var resolveExportDestinations = (exporter) => {
2417
+ if (!hasConfiguredDestinations(exporter)) {
2418
+ return [legacyDestination(exporter)];
2419
+ }
2420
+ const resolved = [];
2421
+ if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0 || exporter.metrics?.endpoint !== void 0) {
2422
+ resolved.push(legacyDestination(exporter));
2423
+ }
2424
+ for (const destination of exporter.destinations ?? []) {
2425
+ if (destination.enabled === false) {
2426
+ continue;
2427
+ }
2428
+ const signals = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;
2429
+ const flags = {
2430
+ traces: signals.includes("traces"),
2431
+ logs: exporter.logs.enabled && signals.includes("logs"),
2432
+ metrics: signals.includes("metrics")
2433
+ };
2434
+ resolved.push({
2435
+ name: destination.name,
2436
+ source: "destinations",
2437
+ protocol: destination.protocol ?? exporter.protocol,
2438
+ ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
2439
+ ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
2440
+ ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
2441
+ ...destination.metricsEndpoint === void 0 ? {} : { metricsEndpoint: destination.metricsEndpoint },
2442
+ signals: flags,
2443
+ headers: { ...destination.headers ?? {} },
2444
+ ...destination.scopes === void 0 ? {} : { scopes: resolveDestinationScopes(destination.scopes, flags) }
2445
+ });
2446
+ }
2447
+ return resolved;
2448
+ };
2449
+ var parseHeaderValueReference = (value) => value.startsWith(HEADER_ENV_REFERENCE_PREFIX) ? { kind: "env", variable: value.slice(HEADER_ENV_REFERENCE_PREFIX.length) } : { kind: "literal" };
2450
+ var resolveDestinationHeaders = (headers, environment) => {
2451
+ const values = {};
2452
+ const missing = [];
2453
+ for (const [name, value] of Object.entries(headers)) {
2454
+ const reference = parseHeaderValueReference(value);
2455
+ if (reference.kind === "literal") {
2456
+ values[name] = value;
2457
+ continue;
2458
+ }
2459
+ const resolved = environment?.[reference.variable];
2460
+ if (resolved === void 0 || resolved === "") {
2461
+ missing.push(reference.variable);
2462
+ continue;
2463
+ }
2464
+ values[name] = resolved;
2465
+ }
2466
+ return { values, missingVariables: [...new Set(missing)].sort() };
2467
+ };
2468
+
2096
2469
  // src/config/resource-attributes.ts
2470
+ import { z as z13 } from "zod";
2097
2471
  var MAX_RESOURCE_ATTRIBUTES = 64;
2098
2472
  var MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH = 255;
2099
2473
  var MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH = 2048;
@@ -2130,54 +2504,452 @@ var checkResourceAttributeKey = (key) => {
2130
2504
  if (!RESOURCE_ATTRIBUTE_KEY_PATTERN.test(key)) {
2131
2505
  return "malformed";
2132
2506
  }
2133
- if (isReservedResourceAttributeKey(key)) {
2134
- return "reserved";
2507
+ if (isReservedResourceAttributeKey(key)) {
2508
+ return "reserved";
2509
+ }
2510
+ if (isSecretResourceAttributeKey(key)) {
2511
+ return "secret-like";
2512
+ }
2513
+ return void 0;
2514
+ };
2515
+ var resourceAttributeValueSchema = z13.union([
2516
+ z13.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),
2517
+ z13.number().finite(),
2518
+ z13.boolean()
2519
+ ]);
2520
+ var resourceAttributesSchema = z13.record(z13.string(), resourceAttributeValueSchema).superRefine((value, ctx) => {
2521
+ const keys = Object.keys(value);
2522
+ if (keys.length > MAX_RESOURCE_ATTRIBUTES) {
2523
+ ctx.addIssue({
2524
+ code: "custom",
2525
+ message: `at most ${String(MAX_RESOURCE_ATTRIBUTES)} resource attributes are accepted`
2526
+ });
2527
+ }
2528
+ for (const key of keys) {
2529
+ const rejection = checkResourceAttributeKey(key);
2530
+ if (rejection !== void 0) {
2531
+ ctx.addIssue({
2532
+ code: "custom",
2533
+ path: [key],
2534
+ message: RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL[rejection]
2535
+ });
2536
+ }
2537
+ }
2538
+ }).readonly();
2539
+ var EMPTY_RESOURCE_ATTRIBUTES = Object.freeze({});
2540
+ var sanitizeResourceAttributes = (attributes) => {
2541
+ const safe = {};
2542
+ for (const [key, value] of Object.entries(attributes)) {
2543
+ if (checkResourceAttributeKey(key) !== void 0) {
2544
+ continue;
2545
+ }
2546
+ if (Object.keys(safe).length >= MAX_RESOURCE_ATTRIBUTES) {
2547
+ break;
2548
+ }
2549
+ safe[key] = value;
2550
+ }
2551
+ return safe;
2552
+ };
2553
+
2554
+ // src/config/schema.ts
2555
+ var logsPolicySchema = z14.strictObject({
2556
+ enabled: z14.boolean(),
2557
+ /**
2558
+ * Full URL for the logs signal.
2559
+ *
2560
+ * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes
2561
+ * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.
2562
+ */
2563
+ endpoint: z14.string().url().max(2048).optional(),
2564
+ includeContent: z14.boolean(),
2565
+ maxBatchSize: z14.number().int().min(1).max(4096)
2566
+ });
2567
+ var DEFAULT_LOGS_POLICY = Object.freeze({
2568
+ enabled: false,
2569
+ includeContent: false,
2570
+ maxBatchSize: 128
2571
+ });
2572
+ var metricsPolicySchema = z14.strictObject({
2573
+ enabled: z14.boolean(),
2574
+ /** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */
2575
+ endpoint: z14.string().url().max(2048).optional(),
2576
+ temporality: z14.enum(["cumulative", "delta"]),
2577
+ includeSessionId: z14.boolean()
2578
+ });
2579
+ var DEFAULT_METRICS_POLICY = Object.freeze({
2580
+ enabled: false,
2581
+ temporality: "cumulative",
2582
+ includeSessionId: true
2583
+ });
2584
+ var exporterPolicySchema = z14.strictObject({
2585
+ enabled: z14.boolean(),
2586
+ protocol: z14.enum(["http/protobuf", "http/json", "none"]),
2587
+ endpoint: z14.string().url().max(2048).optional(),
2588
+ /**
2589
+ * Header names only. Values are supplied separately at construction time and
2590
+ * are never part of a resolved-config snapshot, which is logged and exported.
2591
+ */
2592
+ headerNames: z14.array(nonEmptyStringSchema).max(32).readonly(),
2593
+ timeoutMillis: z14.number().int().min(1).max(6e5),
2594
+ maxBatchSize: z14.number().int().min(1).max(4096),
2595
+ maxQueueSize: z14.number().int().min(1).max(65536),
2596
+ maxRetryAttempts: z14.number().int().min(0).max(10),
2597
+ serviceName: nonEmptyStringSchema,
2598
+ serviceNamespace: nonEmptyStringSchema.optional(),
2599
+ /**
2600
+ * Custom attributes merged into the exported OTLP Resource.
2601
+ *
2602
+ * Bounded and validated, and refusing `service.name`/`service.namespace`,
2603
+ * which are the two fields above. Distinct from an invocation's
2604
+ * `consumerAttributes`: this describes the emitting deployment, carries no
2605
+ * identity, and is the same for every span this process exports.
2606
+ */
2607
+ resourceAttributes: resourceAttributesSchema,
2608
+ /**
2609
+ * The logs signal. Nested under the exporter because it shares the endpoint,
2610
+ * headers, timeout, protocol, service identity, and resource attributes above —
2611
+ * a second top-level section would invite two of each to drift apart.
2612
+ */
2613
+ logs: logsPolicySchema,
2614
+ /**
2615
+ * Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before
2616
+ * metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.
2617
+ */
2618
+ metrics: metricsPolicySchema.optional(),
2619
+ /**
2620
+ * Additional OTLP destinations, each sent every batch in parallel.
2621
+ *
2622
+ * Absent (the default), the exporter has exactly one destination — the
2623
+ * single-endpoint settings above, named `default` — and behaves exactly as it
2624
+ * did before this list existed. See `destinations.ts`.
2625
+ *
2626
+ * Merged as one leaf: a higher layer that sets the list replaces it whole,
2627
+ * because "the union of two partial lists" has no answer an operator could
2628
+ * predict.
2629
+ */
2630
+ destinations: exportDestinationsSchema.optional(),
2631
+ /**
2632
+ * Per-destination retry spool bounds, each optional and merged per leaf; any
2633
+ * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.
2634
+ */
2635
+ spool: spoolPolicySchema.partial().optional(),
2636
+ /**
2637
+ * The most time one hook invocation spends trying to reach one endpoint, in
2638
+ * milliseconds: caps `timeoutMillis` for every OTLP request (connection setup
2639
+ * included) and the exporter's own retries inside it. A batch that does not
2640
+ * get through in time is spooled. Default {@link DEFAULT_EXPORT_BUDGET_MILLIS}:
2641
+ * the host agent waits for its hooks, so a down collector must not stall it.
2642
+ */
2643
+ exportBudgetMillis: z14.number().int().min(50).max(6e5).optional(),
2644
+ /**
2645
+ * After an endpoint was unreachable (refused, timed out, or answered a
2646
+ * retryable status), every hook spools for it without trying for this long,
2647
+ * in milliseconds; then one hook probes it again. 0 disables the window.
2648
+ * Default {@link DEFAULT_ENDPOINT_DOWN_MILLIS}.
2649
+ */
2650
+ endpointDownMillis: z14.number().int().min(0).max(36e5).optional()
2651
+ });
2652
+ var DEFAULT_EXPORT_BUDGET_MILLIS = 1500;
2653
+ var DEFAULT_ENDPOINT_DOWN_MILLIS = 3e4;
2654
+ var effectiveExportTimeoutMillis = (exporter) => Math.min(exporter.timeoutMillis, exporter.exportBudgetMillis ?? DEFAULT_EXPORT_BUDGET_MILLIS);
2655
+ var detectionPolicySchema = z14.strictObject({
2656
+ /** Detections below this confidence resolve to the unknown provider. */
2657
+ minimumConfidence: detectionConfidenceSchema,
2658
+ /** When false, an ambiguous detection is an error rather than unknown. */
2659
+ allowAmbiguousFallback: z14.boolean(),
2660
+ /** Optional allow-list of provider ids; empty means "any registered". */
2661
+ allowedProviderIds: z14.array(nonEmptyStringSchema).max(32).readonly()
2662
+ });
2663
+ var diagnosticsPolicySchema = z14.strictObject({
2664
+ logLevel: z14.enum(["silent", "error", "warn", "info", "debug"]),
2665
+ /** Emit `error.raised` events for contained failures. */
2666
+ emitErrorEvents: z14.boolean()
2667
+ });
2668
+ var providersPolicySchema = z14.strictObject({
2669
+ claudeCode: z14.strictObject({
2670
+ readTranscriptUsage: z14.boolean()
2671
+ }).optional(),
2672
+ codex: z14.strictObject({
2673
+ readRolloutUsage: z14.boolean()
2674
+ }).optional()
2675
+ });
2676
+ var sessionContextPolicySchema = z14.strictObject({
2677
+ /** Absolute path of the context directory. */
2678
+ dir: z14.string().min(1).max(4096).refine((value) => isAbsolute(value), { message: "must be an absolute path" })
2679
+ });
2680
+ var otelHookConfigSchema = z14.strictObject({
2681
+ exporter: exporterPolicySchema,
2682
+ privacy: privacyPolicySchema,
2683
+ detection: detectionPolicySchema,
2684
+ diagnostics: diagnosticsPolicySchema,
2685
+ /** Optional so a hand-built configuration from before it existed stays valid. */
2686
+ providers: providersPolicySchema.optional(),
2687
+ /** Optional: absent means no session context is read. */
2688
+ sessionContext: sessionContextPolicySchema.optional()
2689
+ });
2690
+ var otelHookConfigPatchSchema = z14.strictObject({
2691
+ // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
2692
+ // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
2693
+ // without also restating the endpoint and the batch size.
2694
+ exporter: exporterPolicySchema.omit({ logs: true, metrics: true, spool: true }).partial().extend({
2695
+ logs: logsPolicySchema.partial().optional(),
2696
+ metrics: metricsPolicySchema.partial().optional(),
2697
+ spool: spoolPolicySchema.partial().optional()
2698
+ }).optional(),
2699
+ privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
2700
+ detection: detectionPolicySchema.partial().optional(),
2701
+ diagnostics: diagnosticsPolicySchema.partial().optional(),
2702
+ providers: z14.strictObject({
2703
+ claudeCode: z14.strictObject({ readTranscriptUsage: z14.boolean() }).partial().optional(),
2704
+ codex: z14.strictObject({ readRolloutUsage: z14.boolean() }).partial().optional()
2705
+ }).partial().optional(),
2706
+ sessionContext: sessionContextPolicySchema.partial().optional()
2707
+ });
2708
+ var DEFAULT_EXPORTER_POLICY = Object.freeze({
2709
+ enabled: true,
2710
+ protocol: "http/protobuf",
2711
+ headerNames: Object.freeze([]),
2712
+ timeoutMillis: 1e4,
2713
+ maxBatchSize: 128,
2714
+ maxQueueSize: 2048,
2715
+ maxRetryAttempts: 2,
2716
+ serviceName: "coding-agent",
2717
+ resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
2718
+ logs: DEFAULT_LOGS_POLICY,
2719
+ metrics: DEFAULT_METRICS_POLICY
2720
+ });
2721
+ var DEFAULT_DETECTION_POLICY = Object.freeze({
2722
+ minimumConfidence: "strong",
2723
+ allowAmbiguousFallback: true,
2724
+ allowedProviderIds: Object.freeze([])
2725
+ });
2726
+ var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
2727
+ logLevel: "warn",
2728
+ emitErrorEvents: true
2729
+ });
2730
+ var DEFAULT_PROVIDERS_POLICY = Object.freeze({
2731
+ claudeCode: Object.freeze({ readTranscriptUsage: false }),
2732
+ codex: Object.freeze({ readRolloutUsage: false })
2733
+ });
2734
+ var DEFAULT_CONFIG = Object.freeze({
2735
+ exporter: DEFAULT_EXPORTER_POLICY,
2736
+ privacy: DEFAULT_PRIVACY_POLICY,
2737
+ detection: DEFAULT_DETECTION_POLICY,
2738
+ diagnostics: DEFAULT_DIAGNOSTICS_POLICY,
2739
+ providers: DEFAULT_PROVIDERS_POLICY
2740
+ });
2741
+ var effectiveMetricsPolicy = (exporter) => ({
2742
+ ...DEFAULT_METRICS_POLICY,
2743
+ ...exporter.metrics ?? {}
2744
+ });
2745
+
2746
+ // src/telemetry/endpoint-health.ts
2747
+ var ENDPOINT_DOWN_ERROR_CODE = "OTEL_HOOK_ENDPOINT_DOWN";
2748
+ var UNREACHABLE_NETWORK_CODES = /* @__PURE__ */ new Set([
2749
+ "ECONNREFUSED",
2750
+ "ECONNRESET",
2751
+ "ETIMEDOUT",
2752
+ "EPIPE",
2753
+ "EHOSTUNREACH",
2754
+ "ENETUNREACH",
2755
+ "EHOSTDOWN",
2756
+ "ENETDOWN",
2757
+ "EAI_AGAIN",
2758
+ "ENOTFOUND",
2759
+ ENDPOINT_DOWN_ERROR_CODE
2760
+ ]);
2761
+ var isUnreachableExportFailure = (result) => {
2762
+ if (result.code === ExportResultCode.SUCCESS) {
2763
+ return false;
2764
+ }
2765
+ const error = result.error;
2766
+ const code = error?.code;
2767
+ if (typeof code === "string") {
2768
+ return UNREACHABLE_NETWORK_CODES.has(code);
2769
+ }
2770
+ if (code !== void 0) {
2771
+ return false;
2772
+ }
2773
+ return typeof error?.message === "string" && /timed out/i.test(error.message);
2774
+ };
2775
+ var withConnectTimeout = (agent, connectTimeoutMillis) => {
2776
+ const target = agent;
2777
+ const original = target.createConnection.bind(agent);
2778
+ target.createConnection = (options, callback) => {
2779
+ const socket = original(options, callback);
2780
+ if (socket !== void 0 && socket.connecting) {
2781
+ const timer = setTimeout(() => {
2782
+ const error = Object.assign(new Error("connect timed out"), { code: "ETIMEDOUT" });
2783
+ socket.destroy(error);
2784
+ }, connectTimeoutMillis);
2785
+ timer.unref();
2786
+ const clear = () => {
2787
+ clearTimeout(timer);
2788
+ };
2789
+ socket.once("connect", clear);
2790
+ socket.once("close", clear);
2791
+ }
2792
+ return socket;
2793
+ };
2794
+ return agent;
2795
+ };
2796
+ var boundedExporterOptions = (exporter) => {
2797
+ const timeoutMillis = effectiveExportTimeoutMillis(exporter);
2798
+ let agents = {};
2799
+ return {
2800
+ timeoutMillis,
2801
+ httpAgentOptions: (protocol) => {
2802
+ if (protocol === "https:") {
2803
+ agents = { ...agents, https: agents.https ?? withConnectTimeout(new https.Agent({ keepAlive: true }), timeoutMillis) };
2804
+ return agents.https;
2805
+ }
2806
+ agents = { ...agents, http: agents.http ?? withConnectTimeout(new http.Agent({ keepAlive: true }), timeoutMillis) };
2807
+ return agents.http;
2808
+ }
2809
+ };
2810
+ };
2811
+ var parseMark = (raw) => {
2812
+ try {
2813
+ const parsed = JSON.parse(raw);
2814
+ return typeof parsed.downUntil === "number" && Number.isFinite(parsed.downUntil) ? {
2815
+ downUntil: parsed.downUntil,
2816
+ failures: typeof parsed.failures === "number" && Number.isInteger(parsed.failures) ? parsed.failures : 1
2817
+ } : void 0;
2818
+ } catch {
2819
+ return void 0;
2820
+ }
2821
+ };
2822
+ var originOf = (url) => {
2823
+ if (url === void 0) {
2824
+ return void 0;
2135
2825
  }
2136
- if (isSecretResourceAttributeKey(key)) {
2137
- return "secret-like";
2826
+ try {
2827
+ return new URL(url).origin;
2828
+ } catch {
2829
+ return void 0;
2138
2830
  }
2139
- return void 0;
2140
2831
  };
2141
- var resourceAttributeValueSchema = z12.union([
2142
- z12.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),
2143
- z12.number().finite(),
2144
- z12.boolean()
2145
- ]);
2146
- var resourceAttributesSchema = z12.record(z12.string(), resourceAttributeValueSchema).superRefine((value, ctx) => {
2147
- const keys = Object.keys(value);
2148
- if (keys.length > MAX_RESOURCE_ATTRIBUTES) {
2149
- ctx.addIssue({
2150
- code: "custom",
2151
- message: `at most ${String(MAX_RESOURCE_ATTRIBUTES)} resource attributes are accepted`
2152
- });
2153
- }
2154
- for (const key of keys) {
2155
- const rejection = checkResourceAttributeKey(key);
2156
- if (rejection !== void 0) {
2157
- ctx.addIssue({
2158
- code: "custom",
2159
- path: [key],
2160
- message: RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL[rejection]
2161
- });
2832
+ var createEndpointHealth = (options) => {
2833
+ const downMillis = options.downMillis ?? DEFAULT_ENDPOINT_DOWN_MILLIS;
2834
+ const gates = /* @__PURE__ */ new Map();
2835
+ const createGate = (origin) => {
2836
+ const digest = createHash3("sha256").update(origin, "utf8").digest("hex").slice(0, 32);
2837
+ const dir = options.rootDir === void 0 ? void 0 : path2.join(options.rootDir, "endpoint-health");
2838
+ const file = dir === void 0 ? void 0 : path2.join(dir, `${digest}.json`);
2839
+ let downUntil = 0;
2840
+ let failures = 0;
2841
+ let marked = false;
2842
+ let loaded;
2843
+ let warned = false;
2844
+ const write = async (mark) => {
2845
+ if (file === void 0 || dir === void 0) {
2846
+ return;
2847
+ }
2848
+ try {
2849
+ await mkdir2(dir, { recursive: true });
2850
+ const tmp = path2.join(dir, `.tmp-${randomBytes2(6).toString("hex")}.json`);
2851
+ await writeFile2(tmp, `${JSON.stringify(mark)}
2852
+ `);
2853
+ await rename2(tmp, file);
2854
+ marked = true;
2855
+ } catch {
2856
+ }
2857
+ };
2858
+ const load = () => {
2859
+ loaded ??= (async () => {
2860
+ if (file === void 0) {
2861
+ return;
2862
+ }
2863
+ let raw;
2864
+ try {
2865
+ raw = await readFile2(file, "utf8");
2866
+ } catch {
2867
+ return;
2868
+ }
2869
+ marked = true;
2870
+ const mark = parseMark(raw);
2871
+ if (mark === void 0) {
2872
+ return;
2873
+ }
2874
+ failures = mark.failures;
2875
+ const now = options.clock.now();
2876
+ if (mark.downUntil > now) {
2877
+ downUntil = mark.downUntil;
2878
+ return;
2879
+ }
2880
+ await write({ downUntil: now + options.probeMillis, failures });
2881
+ })();
2882
+ return loaded;
2883
+ };
2884
+ return {
2885
+ available: async () => {
2886
+ if (downMillis === 0) {
2887
+ return true;
2888
+ }
2889
+ await load();
2890
+ return options.clock.now() >= downUntil;
2891
+ },
2892
+ record: async (result) => {
2893
+ if (downMillis === 0) {
2894
+ return;
2895
+ }
2896
+ if (!isUnreachableExportFailure(result)) {
2897
+ if (!marked && downUntil === 0) {
2898
+ return;
2899
+ }
2900
+ downUntil = 0;
2901
+ failures = 0;
2902
+ marked = false;
2903
+ if (file !== void 0) {
2904
+ await unlink2(file).catch(() => void 0);
2905
+ }
2906
+ return;
2907
+ }
2908
+ failures += 1;
2909
+ downUntil = options.clock.now() + downMillis;
2910
+ if (!warned) {
2911
+ warned = true;
2912
+ options.logger?.warn("export endpoint unreachable; hooks spool for it without trying until it is probed again", {
2913
+ "export.endpoint_down_millis": downMillis,
2914
+ "export.endpoint_failures": failures
2915
+ });
2916
+ }
2917
+ await write({ downUntil, failures });
2918
+ }
2919
+ };
2920
+ };
2921
+ return {
2922
+ gateFor: (url) => {
2923
+ const origin = originOf(url);
2924
+ if (origin === void 0) {
2925
+ return void 0;
2926
+ }
2927
+ let gate = gates.get(origin);
2928
+ if (gate === void 0) {
2929
+ gate = createGate(origin);
2930
+ gates.set(origin, gate);
2931
+ }
2932
+ return gate;
2162
2933
  }
2934
+ };
2935
+ };
2936
+ var guardExport = async (gate, send) => {
2937
+ if (gate === void 0) {
2938
+ return send();
2163
2939
  }
2164
- }).readonly();
2165
- var EMPTY_RESOURCE_ATTRIBUTES = Object.freeze({});
2166
- var sanitizeResourceAttributes = (attributes) => {
2167
- const safe = {};
2168
- for (const [key, value] of Object.entries(attributes)) {
2169
- if (checkResourceAttributeKey(key) !== void 0) {
2170
- continue;
2171
- }
2172
- if (Object.keys(safe).length >= MAX_RESOURCE_ATTRIBUTES) {
2173
- break;
2174
- }
2175
- safe[key] = value;
2940
+ if (!await gate.available()) {
2941
+ return {
2942
+ code: ExportResultCode.FAILED,
2943
+ error: Object.assign(new Error("endpoint marked down; batch not sent"), { code: ENDPOINT_DOWN_ERROR_CODE })
2944
+ };
2176
2945
  }
2177
- return safe;
2946
+ const result = await send();
2947
+ await gate.record(result).catch(() => void 0);
2948
+ return result;
2178
2949
  };
2179
2950
 
2180
2951
  // src/telemetry/exporter-resource.ts
2952
+ import { resourceFromAttributes } from "@opentelemetry/resources";
2181
2953
  var resourceFromExporterPolicy = (policy) => resourceFromAttributes({
2182
2954
  ...sanitizeResourceAttributes(policy.resourceAttributes),
2183
2955
  "service.name": policy.serviceName,
@@ -2315,12 +3087,16 @@ var createOtlpTraceSink = (options) => {
2315
3087
  const exporter = new OTLPTraceExporter({
2316
3088
  url: options.exporter.endpoint,
2317
3089
  headers: { ...options.headers },
2318
- timeoutMillis: options.exporter.timeoutMillis
3090
+ ...boundedExporterOptions(options.exporter)
2319
3091
  });
3092
+ const gate = options.endpointHealth?.gateFor(options.exporter.endpoint);
2320
3093
  let shutdownCompleted = false;
2321
- const exportSpans = (spans) => new Promise((resolve) => {
2322
- exporter.export([...spans], (result) => resolve(result));
2323
- });
3094
+ const exportSpans = (spans) => guardExport(
3095
+ gate,
3096
+ () => new Promise((resolve) => {
3097
+ exporter.export([...spans], (result) => resolve(result));
3098
+ })
3099
+ );
2324
3100
  const toSpoolBatch = (spans, batchResource) => ({
2325
3101
  providerId: options.providerId,
2326
3102
  installationId: options.installationId,
@@ -2333,7 +3109,7 @@ var createOtlpTraceSink = (options) => {
2333
3109
  const batchResource = replayResource(batch.resourceAttributes, options.exporter);
2334
3110
  const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));
2335
3111
  const result = await exportSpans(spans);
2336
- if (result.code === ExportResultCode.SUCCESS) {
3112
+ if (result.code === ExportResultCode2.SUCCESS) {
2337
3113
  return true;
2338
3114
  }
2339
3115
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -2372,9 +3148,9 @@ var createOtlpTraceSink = (options) => {
2372
3148
  try {
2373
3149
  result = await exportSpans(batch);
2374
3150
  } catch (thrown) {
2375
- result = { code: ExportResultCode.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
3151
+ result = { code: ExportResultCode2.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
2376
3152
  }
2377
- if (result.code === ExportResultCode.SUCCESS) {
3153
+ if (result.code === ExportResultCode2.SUCCESS) {
2378
3154
  accepted += batch.length;
2379
3155
  health.recordSuccess(batch.length, options.clock.now());
2380
3156
  continue;
@@ -2411,6 +3187,9 @@ var createOtlpTraceSink = (options) => {
2411
3187
  if (options.spool === void 0) {
2412
3188
  return { drained: 0, remaining: 0, failed: 0 };
2413
3189
  }
3190
+ if (gate !== void 0 && !await gate.available()) {
3191
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
3192
+ }
2414
3193
  const result = await options.spool.drain(sendSerializedBatch, { ...maxBatches === void 0 ? {} : { maxBatches } });
2415
3194
  if (result.drained > 0) {
2416
3195
  health.recordSuccess(result.drained, options.clock.now());
@@ -2968,7 +3747,7 @@ var createFileDurableLogSpool = (options) => createSpoolQueue({
2968
3747
 
2969
3748
  // src/telemetry/otlp-log-sink.ts
2970
3749
  import { TraceFlags as TraceFlags3 } from "@opentelemetry/api";
2971
- import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
3750
+ import { ExportResultCode as ExportResultCode3 } from "@opentelemetry/core";
2972
3751
  import { millisToHrTime as millisToHrTime3 } from "@opentelemetry/core";
2973
3752
  import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
2974
3753
 
@@ -3147,12 +3926,16 @@ var createOtlpLogSink = (options) => {
3147
3926
  const exporter = new OTLPLogExporter({
3148
3927
  url: deliverability.endpoint,
3149
3928
  headers: { ...options.headers },
3150
- timeoutMillis: options.exporter.timeoutMillis
3929
+ ...boundedExporterOptions(options.exporter)
3151
3930
  });
3931
+ const gate = options.endpointHealth?.gateFor(deliverability.endpoint);
3152
3932
  let shutdownCompleted = false;
3153
- const exportRecords = (records) => new Promise((resolve) => {
3154
- exporter.export([...records], (result) => resolve(result));
3155
- });
3933
+ const exportRecords = (records) => guardExport(
3934
+ gate,
3935
+ () => new Promise((resolve) => {
3936
+ exporter.export([...records], (result) => resolve(result));
3937
+ })
3938
+ );
3156
3939
  const toSpoolBatch = (records, batchResource) => ({
3157
3940
  providerId: options.providerId,
3158
3941
  installationId: options.installationId,
@@ -3170,7 +3953,7 @@ var createOtlpLogSink = (options) => {
3170
3953
  (record) => deserializeRecord(record, batchResource, batch.instrumentationScope)
3171
3954
  );
3172
3955
  const result = await exportRecords(records);
3173
- if (result.code === ExportResultCode2.SUCCESS) {
3956
+ if (result.code === ExportResultCode3.SUCCESS) {
3174
3957
  return true;
3175
3958
  }
3176
3959
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -3216,11 +3999,11 @@ var createOtlpLogSink = (options) => {
3216
3999
  result = await exportRecords(batch);
3217
4000
  } catch (thrown) {
3218
4001
  result = {
3219
- code: ExportResultCode2.FAILED,
4002
+ code: ExportResultCode3.FAILED,
3220
4003
  error: thrown instanceof Error ? thrown : new Error("export threw")
3221
4004
  };
3222
4005
  }
3223
- if (result.code === ExportResultCode2.SUCCESS) {
4006
+ if (result.code === ExportResultCode3.SUCCESS) {
3224
4007
  accepted += batch.length;
3225
4008
  health.recordSuccess(batch.length, options.clock.now());
3226
4009
  continue;
@@ -3261,6 +4044,9 @@ var createOtlpLogSink = (options) => {
3261
4044
  if (options.spool === void 0) {
3262
4045
  return { drained: 0, remaining: 0, failed: 0 };
3263
4046
  }
4047
+ if (gate !== void 0 && !await gate.available()) {
4048
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
4049
+ }
3264
4050
  const result = await options.spool.drain(sendSerializedBatch, {
3265
4051
  ...maxBatches === void 0 ? {} : { maxBatches }
3266
4052
  });
@@ -3306,383 +4092,44 @@ var createSignalFanout = (options) => {
3306
4092
  accepted: traces.accepted + logs.accepted,
3307
4093
  rejected: traces.rejected + logs.rejected,
3308
4094
  errors
3309
- };
3310
- };
3311
- const flush = async () => {
3312
- await options.traces.flush().catch(() => void 0);
3313
- await options.logs.flush().catch(() => void 0);
3314
- };
3315
- const shutdown = async () => {
3316
- await options.traces.shutdown().catch(() => void 0);
3317
- await options.logs.shutdown().catch(() => void 0);
3318
- };
3319
- return {
3320
- emit,
3321
- flush,
3322
- shutdown,
3323
- health: () => [
3324
- options.traces.health(),
3325
- options.logs.health()
3326
- ]
3327
- };
3328
- };
3329
- var shareCorrelationPerBatch = (correlate) => {
3330
- let pending;
3331
- return (events) => {
3332
- if (pending?.events === events) {
3333
- return pending.result;
3334
- }
3335
- const result = correlate(events);
3336
- pending = { events, result };
3337
- return result;
3338
- };
3339
- };
3340
-
3341
- // src/config/destinations.ts
3342
- import { z as z13 } from "zod";
3343
-
3344
- // src/config/header-value.ts
3345
- var isUnsafeHeaderValue = (value) => [...value].some((char) => {
3346
- const code = char.codePointAt(0) ?? 0;
3347
- return code < 32 && code !== 9 || code === 127 || code > 255;
3348
- });
3349
-
3350
- // src/config/otlp-headers.ts
3351
- var MAX_OTLP_HEADERS = 32;
3352
- var OTLP_HEADER_VARIABLES = Object.freeze({
3353
- generic: "OTEL_EXPORTER_OTLP_HEADERS",
3354
- traces: "OTEL_EXPORTER_OTLP_TRACES_HEADERS",
3355
- logs: "OTEL_EXPORTER_OTLP_LOGS_HEADERS"
3356
- });
3357
-
3358
- // src/config/destinations.ts
3359
- var DEFAULT_DESTINATION_NAME = "default";
3360
- var DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;
3361
- var MAX_EXPORT_DESTINATIONS = 16;
3362
- var MAX_DESTINATION_HEADERS = MAX_OTLP_HEADERS;
3363
- var HEADER_ENV_REFERENCE_PREFIX = "env:";
3364
- var HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
3365
- var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
3366
- var MAX_HEADER_VALUE_LENGTH = 8192;
3367
- var exportSignalSchema = z13.enum(["traces", "logs", "metrics"]);
3368
- var headerValueSchema = z13.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
3369
- (value) => !isUnsafeHeaderValue(value),
3370
- "header values may not contain line breaks, control characters, or characters beyond Latin-1"
3371
- ).refine(
3372
- (value) => !value.startsWith(HEADER_ENV_REFERENCE_PREFIX) || ENV_VARIABLE_NAME_PATTERN.test(value.slice(HEADER_ENV_REFERENCE_PREFIX.length)),
3373
- "an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN"
3374
- );
3375
- var endpointSchema = z13.string().url().max(2048);
3376
- var exportDestinationSchema = z13.strictObject({
3377
- /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */
3378
- name: z13.string().regex(DESTINATION_NAME_PATTERN, "destination names are lowercase letters, digits, _ and -"),
3379
- /** Default true. A disabled destination is neither sent to nor drained. */
3380
- enabled: z13.boolean().optional(),
3381
- /**
3382
- * Traces URL, with the same meaning as `exporter.endpoint`: the logs URL is
3383
- * derived from it (`/v1/traces` becomes `/v1/logs`) unless `logsEndpoint` is set.
3384
- */
3385
- endpoint: endpointSchema.optional(),
3386
- /** Per-signal override of `endpoint` for traces. */
3387
- tracesEndpoint: endpointSchema.optional(),
3388
- /** Per-signal override of the derived logs URL. */
3389
- logsEndpoint: endpointSchema.optional(),
3390
- /** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */
3391
- metricsEndpoint: endpointSchema.optional(),
3392
- /** Defaults to `exporter.protocol`. */
3393
- protocol: z13.enum(["http/protobuf", "http/json", "none"]).optional(),
3394
- /**
3395
- * Header name to value. A value of the form `env:NAME` is read from that
3396
- * environment variable at send time, so a credential never has to be written
3397
- * into the file. Values never appear in a snapshot, a diagnostic, or `doctor`.
3398
- */
3399
- headers: z13.record(z13.string().regex(HEADER_NAME_PATTERN, "not a valid header name"), headerValueSchema).refine(
3400
- (headers) => Object.keys(headers).length <= MAX_DESTINATION_HEADERS,
3401
- `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
3402
- ).optional(),
3403
- /**
3404
- * Which signals this destination receives. Default: traces and logs. The logs
3405
- * signal is still governed by `exporter.logs.enabled`, which stays the one
3406
- * opt-in for content-bearing records leaving the host. `metrics` is never on by
3407
- * default: a destination receives hook-derived metrics only when it lists them.
3408
- */
3409
- signals: z13.array(exportSignalSchema).min(1).max(3).readonly().optional()
3410
- }).refine(
3411
- (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
3412
- "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
3413
- );
3414
- var DEFAULT_DESTINATION_SIGNALS = Object.freeze(["traces", "logs"]);
3415
- var exportDestinationsSchema = z13.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
3416
- const seen = /* @__PURE__ */ new Set();
3417
- destinations.forEach((destination, index) => {
3418
- if (destination.name === DEFAULT_DESTINATION_NAME) {
3419
- context.addIssue({
3420
- code: "custom",
3421
- path: [index, "name"],
3422
- message: 'the name "default" is reserved for exporter.endpoint and the OTEL_EXPORTER_OTLP_* variables'
3423
- });
3424
- }
3425
- if (seen.has(destination.name)) {
3426
- context.addIssue({
3427
- code: "custom",
3428
- path: [index, "name"],
3429
- message: `duplicate destination name "${destination.name}"`
3430
- });
3431
- }
3432
- seen.add(destination.name);
3433
- });
3434
- });
3435
- var spoolPolicySchema = z13.strictObject({
3436
- /** Total bytes of queued batches. Default 16 MiB. */
3437
- maxBytes: z13.number().int().min(1024).max(1073741824),
3438
- /** A batch older than this is dropped instead of sent. Default 72 hours. */
3439
- maxAgeMillis: z13.number().int().min(1e3).max(30 * 24 * 60 * 60 * 1e3),
3440
- /** Number of queued batches. Default 500. */
3441
- maxBatches: z13.number().int().min(1).max(65536)
3442
- });
3443
- var DEFAULT_SPOOL_POLICY = Object.freeze({
3444
- maxBytes: 16 * 1024 * 1024,
3445
- maxAgeMillis: 72 * 60 * 60 * 1e3,
3446
- maxBatches: 500
3447
- });
3448
- var effectiveSpoolPolicy = (exporter) => ({
3449
- maxBytes: exporter.spool?.maxBytes ?? DEFAULT_SPOOL_POLICY.maxBytes,
3450
- maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,
3451
- maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches
3452
- });
3453
- var legacyDestination = (exporter) => ({
3454
- name: DEFAULT_DESTINATION_NAME,
3455
- source: "exporter",
3456
- protocol: exporter.protocol,
3457
- ...exporter.endpoint === void 0 ? {} : { endpoint: exporter.endpoint },
3458
- ...exporter.logs.endpoint === void 0 ? {} : { logsEndpoint: exporter.logs.endpoint },
3459
- ...exporter.metrics?.endpoint === void 0 ? {} : { metricsEndpoint: exporter.metrics.endpoint },
3460
- signals: { traces: true, logs: exporter.logs.enabled, metrics: exporter.metrics?.enabled === true },
3461
- headers: {}
3462
- });
3463
- var hasConfiguredDestinations = (exporter) => exporter.destinations !== void 0 && exporter.destinations.length > 0;
3464
- var resolveExportDestinations = (exporter) => {
3465
- if (!hasConfiguredDestinations(exporter)) {
3466
- return [legacyDestination(exporter)];
3467
- }
3468
- const resolved = [];
3469
- if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0 || exporter.metrics?.endpoint !== void 0) {
3470
- resolved.push(legacyDestination(exporter));
3471
- }
3472
- for (const destination of exporter.destinations ?? []) {
3473
- if (destination.enabled === false) {
3474
- continue;
3475
- }
3476
- const signals = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;
3477
- resolved.push({
3478
- name: destination.name,
3479
- source: "destinations",
3480
- protocol: destination.protocol ?? exporter.protocol,
3481
- ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
3482
- ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
3483
- ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
3484
- ...destination.metricsEndpoint === void 0 ? {} : { metricsEndpoint: destination.metricsEndpoint },
3485
- signals: {
3486
- traces: signals.includes("traces"),
3487
- logs: exporter.logs.enabled && signals.includes("logs"),
3488
- metrics: signals.includes("metrics")
3489
- },
3490
- headers: { ...destination.headers ?? {} }
3491
- });
3492
- }
3493
- return resolved;
4095
+ };
4096
+ };
4097
+ const flush = async () => {
4098
+ await options.traces.flush().catch(() => void 0);
4099
+ await options.logs.flush().catch(() => void 0);
4100
+ };
4101
+ const shutdown = async () => {
4102
+ await options.traces.shutdown().catch(() => void 0);
4103
+ await options.logs.shutdown().catch(() => void 0);
4104
+ };
4105
+ return {
4106
+ emit,
4107
+ flush,
4108
+ shutdown,
4109
+ health: () => [
4110
+ options.traces.health(),
4111
+ options.logs.health()
4112
+ ]
4113
+ };
3494
4114
  };
3495
- var parseHeaderValueReference = (value) => value.startsWith(HEADER_ENV_REFERENCE_PREFIX) ? { kind: "env", variable: value.slice(HEADER_ENV_REFERENCE_PREFIX.length) } : { kind: "literal" };
3496
- var resolveDestinationHeaders = (headers, environment) => {
3497
- const values = {};
3498
- const missing = [];
3499
- for (const [name, value] of Object.entries(headers)) {
3500
- const reference = parseHeaderValueReference(value);
3501
- if (reference.kind === "literal") {
3502
- values[name] = value;
3503
- continue;
4115
+ var shareCorrelationPerBatch = (correlate) => {
4116
+ let pending;
4117
+ const resolve = (events) => {
4118
+ if (pending !== void 0 && (pending.events === events || pending.aliases.has(events))) {
4119
+ return pending.result;
3504
4120
  }
3505
- const resolved = environment?.[reference.variable];
3506
- if (resolved === void 0 || resolved === "") {
3507
- missing.push(reference.variable);
3508
- continue;
4121
+ const result = correlate(events);
4122
+ pending = { events, aliases: /* @__PURE__ */ new Set(), result };
4123
+ return result;
4124
+ };
4125
+ const alias = (subset, batch) => {
4126
+ if (pending?.events === batch && subset !== batch) {
4127
+ pending.aliases.add(subset);
3509
4128
  }
3510
- values[name] = resolved;
3511
- }
3512
- return { values, missingVariables: [...new Set(missing)].sort() };
4129
+ };
4130
+ return Object.assign(resolve, { alias });
3513
4131
  };
3514
4132
 
3515
- // src/config/schema.ts
3516
- import { isAbsolute } from "path";
3517
- import { z as z14 } from "zod";
3518
- var logsPolicySchema = z14.strictObject({
3519
- enabled: z14.boolean(),
3520
- /**
3521
- * Full URL for the logs signal.
3522
- *
3523
- * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes
3524
- * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.
3525
- */
3526
- endpoint: z14.string().url().max(2048).optional(),
3527
- includeContent: z14.boolean(),
3528
- maxBatchSize: z14.number().int().min(1).max(4096)
3529
- });
3530
- var DEFAULT_LOGS_POLICY = Object.freeze({
3531
- enabled: false,
3532
- includeContent: false,
3533
- maxBatchSize: 128
3534
- });
3535
- var metricsPolicySchema = z14.strictObject({
3536
- enabled: z14.boolean(),
3537
- /** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */
3538
- endpoint: z14.string().url().max(2048).optional(),
3539
- temporality: z14.enum(["cumulative", "delta"]),
3540
- includeSessionId: z14.boolean()
3541
- });
3542
- var DEFAULT_METRICS_POLICY = Object.freeze({
3543
- enabled: false,
3544
- temporality: "cumulative",
3545
- includeSessionId: true
3546
- });
3547
- var exporterPolicySchema = z14.strictObject({
3548
- enabled: z14.boolean(),
3549
- protocol: z14.enum(["http/protobuf", "http/json", "none"]),
3550
- endpoint: z14.string().url().max(2048).optional(),
3551
- /**
3552
- * Header names only. Values are supplied separately at construction time and
3553
- * are never part of a resolved-config snapshot, which is logged and exported.
3554
- */
3555
- headerNames: z14.array(nonEmptyStringSchema).max(32).readonly(),
3556
- timeoutMillis: z14.number().int().min(1).max(6e5),
3557
- maxBatchSize: z14.number().int().min(1).max(4096),
3558
- maxQueueSize: z14.number().int().min(1).max(65536),
3559
- maxRetryAttempts: z14.number().int().min(0).max(10),
3560
- serviceName: nonEmptyStringSchema,
3561
- serviceNamespace: nonEmptyStringSchema.optional(),
3562
- /**
3563
- * Custom attributes merged into the exported OTLP Resource.
3564
- *
3565
- * Bounded and validated, and refusing `service.name`/`service.namespace`,
3566
- * which are the two fields above. Distinct from an invocation's
3567
- * `consumerAttributes`: this describes the emitting deployment, carries no
3568
- * identity, and is the same for every span this process exports.
3569
- */
3570
- resourceAttributes: resourceAttributesSchema,
3571
- /**
3572
- * The logs signal. Nested under the exporter because it shares the endpoint,
3573
- * headers, timeout, protocol, service identity, and resource attributes above —
3574
- * a second top-level section would invite two of each to drift apart.
3575
- */
3576
- logs: logsPolicySchema,
3577
- /**
3578
- * Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before
3579
- * metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.
3580
- */
3581
- metrics: metricsPolicySchema.optional(),
3582
- /**
3583
- * Additional OTLP destinations, each sent every batch in parallel.
3584
- *
3585
- * Absent (the default), the exporter has exactly one destination — the
3586
- * single-endpoint settings above, named `default` — and behaves exactly as it
3587
- * did before this list existed. See `destinations.ts`.
3588
- *
3589
- * Merged as one leaf: a higher layer that sets the list replaces it whole,
3590
- * because "the union of two partial lists" has no answer an operator could
3591
- * predict.
3592
- */
3593
- destinations: exportDestinationsSchema.optional(),
3594
- /**
3595
- * Per-destination retry spool bounds, each optional and merged per leaf; any
3596
- * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.
3597
- */
3598
- spool: spoolPolicySchema.partial().optional()
3599
- });
3600
- var detectionPolicySchema = z14.strictObject({
3601
- /** Detections below this confidence resolve to the unknown provider. */
3602
- minimumConfidence: detectionConfidenceSchema,
3603
- /** When false, an ambiguous detection is an error rather than unknown. */
3604
- allowAmbiguousFallback: z14.boolean(),
3605
- /** Optional allow-list of provider ids; empty means "any registered". */
3606
- allowedProviderIds: z14.array(nonEmptyStringSchema).max(32).readonly()
3607
- });
3608
- var diagnosticsPolicySchema = z14.strictObject({
3609
- logLevel: z14.enum(["silent", "error", "warn", "info", "debug"]),
3610
- /** Emit `error.raised` events for contained failures. */
3611
- emitErrorEvents: z14.boolean()
3612
- });
3613
- var providersPolicySchema = z14.strictObject({
3614
- claudeCode: z14.strictObject({
3615
- readTranscriptUsage: z14.boolean()
3616
- }).optional()
3617
- });
3618
- var sessionContextPolicySchema = z14.strictObject({
3619
- /** Absolute path of the context directory. */
3620
- dir: z14.string().min(1).max(4096).refine((value) => isAbsolute(value), { message: "must be an absolute path" })
3621
- });
3622
- var otelHookConfigSchema = z14.strictObject({
3623
- exporter: exporterPolicySchema,
3624
- privacy: privacyPolicySchema,
3625
- detection: detectionPolicySchema,
3626
- diagnostics: diagnosticsPolicySchema,
3627
- /** Optional so a hand-built configuration from before it existed stays valid. */
3628
- providers: providersPolicySchema.optional(),
3629
- /** Optional: absent means no session context is read. */
3630
- sessionContext: sessionContextPolicySchema.optional()
3631
- });
3632
- var otelHookConfigPatchSchema = z14.strictObject({
3633
- // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
3634
- // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
3635
- // without also restating the endpoint and the batch size.
3636
- exporter: exporterPolicySchema.omit({ logs: true, metrics: true, spool: true }).partial().extend({
3637
- logs: logsPolicySchema.partial().optional(),
3638
- metrics: metricsPolicySchema.partial().optional(),
3639
- spool: spoolPolicySchema.partial().optional()
3640
- }).optional(),
3641
- privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
3642
- detection: detectionPolicySchema.partial().optional(),
3643
- diagnostics: diagnosticsPolicySchema.partial().optional(),
3644
- providers: z14.strictObject({
3645
- claudeCode: z14.strictObject({ readTranscriptUsage: z14.boolean() }).partial().optional()
3646
- }).partial().optional(),
3647
- sessionContext: sessionContextPolicySchema.partial().optional()
3648
- });
3649
- var DEFAULT_EXPORTER_POLICY = Object.freeze({
3650
- enabled: true,
3651
- protocol: "http/protobuf",
3652
- headerNames: Object.freeze([]),
3653
- timeoutMillis: 1e4,
3654
- maxBatchSize: 128,
3655
- maxQueueSize: 2048,
3656
- maxRetryAttempts: 2,
3657
- serviceName: "coding-agent",
3658
- resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
3659
- logs: DEFAULT_LOGS_POLICY,
3660
- metrics: DEFAULT_METRICS_POLICY
3661
- });
3662
- var DEFAULT_DETECTION_POLICY = Object.freeze({
3663
- minimumConfidence: "strong",
3664
- allowAmbiguousFallback: true,
3665
- allowedProviderIds: Object.freeze([])
3666
- });
3667
- var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
3668
- logLevel: "warn",
3669
- emitErrorEvents: true
3670
- });
3671
- var DEFAULT_PROVIDERS_POLICY = Object.freeze({
3672
- claudeCode: Object.freeze({ readTranscriptUsage: false })
3673
- });
3674
- var DEFAULT_CONFIG = Object.freeze({
3675
- exporter: DEFAULT_EXPORTER_POLICY,
3676
- privacy: DEFAULT_PRIVACY_POLICY,
3677
- detection: DEFAULT_DETECTION_POLICY,
3678
- diagnostics: DEFAULT_DIAGNOSTICS_POLICY,
3679
- providers: DEFAULT_PROVIDERS_POLICY
3680
- });
3681
- var effectiveMetricsPolicy = (exporter) => ({
3682
- ...DEFAULT_METRICS_POLICY,
3683
- ...exporter.metrics ?? {}
3684
- });
3685
-
3686
4133
  // src/telemetry/metric-model.ts
3687
4134
  var TOKEN_USAGE_BUCKETS = Object.freeze([
3688
4135
  1,
@@ -4040,7 +4487,7 @@ var createFileDurableMetricSpool = (options) => createSpoolQueue({
4040
4487
 
4041
4488
  // src/telemetry/otlp-metric-sink.ts
4042
4489
  import { ValueType } from "@opentelemetry/api";
4043
- import { ExportResultCode as ExportResultCode3, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
4490
+ import { ExportResultCode as ExportResultCode4, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
4044
4491
  import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
4045
4492
  import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
4046
4493
  import {
@@ -4184,10 +4631,12 @@ var createOtlpMetricSink = (options) => {
4184
4631
  const exporter = new OTLPMetricExporter({
4185
4632
  url: deliverability.endpoint,
4186
4633
  headers: { ...options.headers },
4187
- timeoutMillis: options.exporter.timeoutMillis
4634
+ ...boundedExporterOptions(options.exporter)
4188
4635
  });
4636
+ const gate = options.endpointHealth?.gateFor(deliverability.endpoint);
4189
4637
  let shutdownCompleted = false;
4190
- const exportResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve) => {
4638
+ const exportResourceMetrics = (points, batchResource, batchScope) => guardExport(gate, () => sendResourceMetrics(points, batchResource, batchScope));
4639
+ const sendResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve) => {
4191
4640
  const payload = {
4192
4641
  resource: batchResource,
4193
4642
  scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }]
@@ -4196,7 +4645,7 @@ var createOtlpMetricSink = (options) => {
4196
4645
  exporter.export(payload, (result) => resolve(result));
4197
4646
  } catch (thrown) {
4198
4647
  resolve({
4199
- code: ExportResultCode3.FAILED,
4648
+ code: ExportResultCode4.FAILED,
4200
4649
  error: thrown instanceof Error ? thrown : new Error("export threw")
4201
4650
  });
4202
4651
  }
@@ -4217,7 +4666,7 @@ var createOtlpMetricSink = (options) => {
4217
4666
  withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes)
4218
4667
  );
4219
4668
  const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);
4220
- if (result.code === ExportResultCode3.SUCCESS) {
4669
+ if (result.code === ExportResultCode4.SUCCESS) {
4221
4670
  return true;
4222
4671
  }
4223
4672
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -4228,7 +4677,7 @@ var createOtlpMetricSink = (options) => {
4228
4677
  }
4229
4678
  const batchResource = context === void 0 ? resource : resourceWithContext(resource, context);
4230
4679
  const result = await exportResourceMetrics(points, batchResource, scope);
4231
- if (result.code === ExportResultCode3.SUCCESS) {
4680
+ if (result.code === ExportResultCode4.SUCCESS) {
4232
4681
  health.recordSuccess(points.length, options.clock.now());
4233
4682
  return { accepted: points.length, rejected: 0, errors: [] };
4234
4683
  }
@@ -4268,6 +4717,9 @@ var createOtlpMetricSink = (options) => {
4268
4717
  if (options.spool === void 0) {
4269
4718
  return { drained: 0, remaining: 0, failed: 0 };
4270
4719
  }
4720
+ if (gate !== void 0 && !await gate.available()) {
4721
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
4722
+ }
4271
4723
  const result = await options.spool.drain(sendSerializedBatch, {
4272
4724
  ...maxBatches === void 0 ? {} : { maxBatches }
4273
4725
  });
@@ -4304,6 +4756,101 @@ var createOtlpMetricSink = (options) => {
4304
4756
  };
4305
4757
  };
4306
4758
 
4759
+ // src/telemetry/destination-scope.ts
4760
+ var DISCLOSURE_RANK = Object.freeze({
4761
+ omitted: 0,
4762
+ masked: 1,
4763
+ redacted: 2,
4764
+ raw: 3
4765
+ });
4766
+ var omitRestrictedContent = (fact, mode) => {
4767
+ if (fact.text === void 0 || DISCLOSURE_RANK[fact.disclosure] <= DISCLOSURE_RANK[CONTENT_MODE_DISCLOSURE[mode]]) {
4768
+ return fact;
4769
+ }
4770
+ const { text, ...rest } = fact;
4771
+ void text;
4772
+ return { ...rest, disclosure: "omitted", truncated: false };
4773
+ };
4774
+ var keyOfValue = (value) => typeof value === "string" ? normalizeRepositoryKey(value) : void 0;
4775
+ var resourceRepositoryKey = (attributes) => keyOfValue(attributes[ATTR_VCS_REPOSITORY_URL_FULL]);
4776
+ var eventRepositoryKey = (event2, fallbackKey) => {
4777
+ const stamped = event2.contextAttributes?.[ATTR_VCS_REPOSITORY_URL_FULL];
4778
+ return stamped === void 0 ? fallbackKey : keyOfValue(stamped);
4779
+ };
4780
+ var pointRepositoryKey = (point, fallbackKey) => {
4781
+ const stamped = point.attributes[ATTR_VCS_REPOSITORY_URL_FULL];
4782
+ return stamped === void 0 ? fallbackKey : keyOfValue(stamped);
4783
+ };
4784
+ var restrictFacts = (facts, mode, restrict) => facts?.map((fact) => restrict(fact, mode));
4785
+ var restrictEventContent = (event2, mode, restrict) => {
4786
+ switch (event2.type) {
4787
+ case "prompt.submitted":
4788
+ return event2.content === void 0 ? event2 : { ...event2, content: restrict(event2.content, mode) };
4789
+ case "generation.start": {
4790
+ const inputContent = restrictFacts(event2.inputContent, mode, restrict);
4791
+ return inputContent === void 0 ? event2 : { ...event2, inputContent };
4792
+ }
4793
+ case "generation.end": {
4794
+ const outputContent = restrictFacts(event2.outputContent, mode, restrict);
4795
+ return outputContent === void 0 ? event2 : { ...event2, outputContent };
4796
+ }
4797
+ case "tool.start":
4798
+ return event2.input === void 0 ? event2 : { ...event2, input: restrict(event2.input, mode) };
4799
+ case "tool.end":
4800
+ return event2.output === void 0 ? event2 : { ...event2, output: restrict(event2.output, mode) };
4801
+ case "error.raised":
4802
+ return event2.message === void 0 ? event2 : { ...event2, message: restrict(event2.message, mode) };
4803
+ default:
4804
+ return event2;
4805
+ }
4806
+ };
4807
+ var routeEventsToScopes = (events, scopes, options) => {
4808
+ const ends = spanEndEdgesOf(events);
4809
+ const traces = [];
4810
+ const logs = [];
4811
+ let unchanged = true;
4812
+ for (const event2 of events) {
4813
+ const anchor = ends.get(event2.eventId) ?? event2;
4814
+ const scope = matchDestinationScope(scopes, eventRepositoryKey(anchor, options.resourceRepositoryKey));
4815
+ if (scope === void 0 || !scope.signals.traces || !scope.signals.logs) {
4816
+ unchanged = false;
4817
+ }
4818
+ if (scope === void 0) {
4819
+ continue;
4820
+ }
4821
+ const restricted = scope.contentMode === void 0 ? event2 : restrictEventContent(event2, scope.contentMode, options.restrict);
4822
+ if (restricted !== event2) {
4823
+ unchanged = false;
4824
+ }
4825
+ if (scope.signals.traces) {
4826
+ traces.push(restricted);
4827
+ }
4828
+ if (scope.signals.logs) {
4829
+ logs.push(restricted);
4830
+ }
4831
+ }
4832
+ return unchanged ? { traces: events, logs: events } : { traces, logs };
4833
+ };
4834
+ var routePointsToScopes = (scopes, pointsFor, options) => {
4835
+ const effective = (scope) => options.includeSessionId && scope.includeSessionId;
4836
+ const kept = [];
4837
+ for (const variant of [true, false]) {
4838
+ if (!scopes.some((scope) => scope.signals.metrics && effective(scope) === variant)) {
4839
+ continue;
4840
+ }
4841
+ for (const point of pointsFor(variant) ?? []) {
4842
+ const scope = matchDestinationScope(scopes, pointRepositoryKey(point, options.fallbackKey));
4843
+ if (scope?.signals.metrics === true && effective(scope) === variant) {
4844
+ kept.push(point);
4845
+ }
4846
+ }
4847
+ }
4848
+ return kept;
4849
+ };
4850
+ var sessionIdVariantsFor = (scopes, includeSessionId) => new Set(
4851
+ scopes.filter((scope) => scope.signals.metrics).map((scope) => includeSessionId && scope.includeSessionId)
4852
+ );
4853
+
4307
4854
  // src/telemetry/export-destinations.ts
4308
4855
  var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs", metrics: "spool-metrics" } : {
4309
4856
  traces: `destinations/${destination}/spool`,
@@ -4363,6 +4910,15 @@ var createExportDestinationSinks = (options) => {
4363
4910
  const spoolPolicy = effectiveSpoolPolicy(options.exporter);
4364
4911
  const destinations = [];
4365
4912
  const skipped = [];
4913
+ const endpointHealth = options.endpointHealth ?? createEndpointHealth({
4914
+ ...options.spoolRootDir === void 0 ? {} : { rootDir: options.spoolRootDir },
4915
+ clock: options.clock,
4916
+ ...options.logger === void 0 ? {} : { logger: options.logger },
4917
+ ...options.exporter.endpointDownMillis === void 0 ? {} : { downMillis: options.exporter.endpointDownMillis },
4918
+ probeMillis: effectiveExportTimeoutMillis(options.exporter) + 1e3
4919
+ });
4920
+ const scopedResourceKey = resourceRepositoryKey(resourceFromExporterPolicy(options.exporter).attributes);
4921
+ const restrict = options.restrictContent ?? omitRestrictedContent;
4366
4922
  for (const destination of resolveExportDestinations(options.exporter)) {
4367
4923
  let headers;
4368
4924
  let logHeaders;
@@ -4422,6 +4978,7 @@ var createExportDestinationSinks = (options) => {
4422
4978
  const sinkShared = {
4423
4979
  exporter: policy,
4424
4980
  ...shared,
4981
+ endpointHealth,
4425
4982
  ...options.correlate === void 0 ? {} : { correlate: options.correlate },
4426
4983
  ...label === void 0 ? {} : { destination: label }
4427
4984
  };
@@ -4439,6 +4996,7 @@ var createExportDestinationSinks = (options) => {
4439
4996
  const metrics = destination.signals.metrics ? createOtlpMetricSink({
4440
4997
  exporter: policy,
4441
4998
  ...shared,
4999
+ endpointHealth,
4442
5000
  ...label === void 0 ? {} : { destination: label },
4443
5001
  ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
4444
5002
  ...metricSpool === void 0 ? {} : { spool: metricSpool }
@@ -4450,17 +5008,51 @@ var createExportDestinationSinks = (options) => {
4450
5008
  metrics,
4451
5009
  ...spool === void 0 ? {} : { spool },
4452
5010
  ...logSpool === void 0 ? {} : { logSpool },
4453
- ...metricSpool === void 0 ? {} : { metricSpool }
5011
+ ...metricSpool === void 0 ? {} : { metricSpool },
5012
+ ...destination.scopes === void 0 ? {} : {
5013
+ scopes: destination.scopes,
5014
+ route: (events) => routeEventsToScopes(events, destination.scopes ?? [], {
5015
+ ...scopedResourceKey === void 0 ? {} : { resourceRepositoryKey: scopedResourceKey },
5016
+ restrict
5017
+ })
5018
+ }
4454
5019
  });
4455
5020
  }
4456
5021
  return { destinations, skipped };
4457
5022
  };
4458
- var createDestinationFanout = (destinations) => {
5023
+ var createScopedFanout = (destination, correlate) => {
5024
+ const route = destination.route;
5025
+ const unscoped = createSignalFanout({ traces: destination.traces, logs: destination.logs });
5026
+ if (route === void 0) {
5027
+ return unscoped;
5028
+ }
5029
+ const none = { accepted: 0, rejected: 0, errors: [] };
5030
+ return {
5031
+ ...unscoped,
5032
+ emit: async (events) => {
5033
+ const batch = route(events);
5034
+ if (correlate !== void 0 && (batch.traces.length > 0 || batch.logs.length > 0)) {
5035
+ await correlate(events);
5036
+ correlate.alias(batch.traces, events);
5037
+ correlate.alias(batch.logs, events);
5038
+ }
5039
+ const traces = batch.traces.length === 0 ? none : await destination.traces.emit(batch.traces);
5040
+ const logs = batch.logs.length === 0 ? none : await destination.logs.emit(batch.logs);
5041
+ return {
5042
+ accepted: traces.accepted + logs.accepted,
5043
+ rejected: traces.rejected + logs.rejected,
5044
+ errors: [...traces.errors, ...logs.errors]
5045
+ };
5046
+ }
5047
+ };
5048
+ };
5049
+ var createDestinationFanout = (destinations, options = {}) => {
4459
5050
  const fanouts = destinations.map((destination) => ({
4460
5051
  name: destination.name,
4461
- sink: createSignalFanout({ traces: destination.traces, logs: destination.logs })
5052
+ sink: createScopedFanout(destination, options.correlate)
4462
5053
  }));
4463
- const only = fanouts.length === 1 ? fanouts[0] : void 0;
5054
+ const scoped = destinations.some((destination) => destination.route !== void 0);
5055
+ const only = fanouts.length === 1 && !scoped ? fanouts[0] : void 0;
4464
5056
  if (only !== void 0) {
4465
5057
  return only.sink;
4466
5058
  }
@@ -4529,13 +5121,21 @@ export {
4529
5121
  deriveMetricObservations,
4530
5122
  describeLogsDeliverability,
4531
5123
  describeMetricsDeliverability,
5124
+ eventRepositoryKey,
4532
5125
  exporterPolicyForDestination,
4533
5126
  isPermanentExportFailure,
4534
5127
  logSignalOf,
4535
5128
  logSignalsForLifecycleEvents,
5129
+ omitRestrictedContent,
4536
5130
  parentScopeRefOf,
5131
+ pointRepositoryKey,
4537
5132
  resolveLogsEndpoint,
4538
5133
  resolveMetricsEndpoint,
5134
+ resourceRepositoryKey,
5135
+ restrictEventContent,
5136
+ routeEventsToScopes,
5137
+ routePointsToScopes,
5138
+ sessionIdVariantsFor,
4539
5139
  shareCorrelationPerBatch,
4540
5140
  spanScopeRefOf,
4541
5141
  spoolQueueNamesFor,