@osfactory/otel-hook 0.13.0 → 0.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +51 -3
  2. package/dist/cli.js +907 -164
  3. package/dist/cli.js.map +1 -1
  4. package/dist/config.d.ts +5 -3
  5. package/dist/config.js +39 -5
  6. package/dist/config.js.map +1 -1
  7. package/dist/{destinations-DvqsPulb.d.ts → destinations-C4sSKjDO.d.ts} +1 -1
  8. package/dist/{export-destinations-Bey2djRk.d.ts → export-destinations-BjRXDots.d.ts} +37 -5
  9. package/dist/{hook-D5imE0Qc.d.ts → hook-CKLpgrYP.d.ts} +2 -2
  10. package/dist/index.d.ts +9 -9
  11. package/dist/index.js +921 -182
  12. package/dist/index.js.map +1 -1
  13. package/dist/install.d.ts +1 -1
  14. package/dist/install.js +5 -1
  15. package/dist/install.js.map +1 -1
  16. package/dist/integration.d.ts +15 -8
  17. package/dist/integration.js +998 -160
  18. package/dist/integration.js.map +1 -1
  19. package/dist/lifecycle.d.ts +8 -1
  20. package/dist/lifecycle.js +10 -3
  21. package/dist/lifecycle.js.map +1 -1
  22. package/dist/{metric-model-CFIeUwqd.d.ts → metric-model-B4lIuk6i.d.ts} +8 -0
  23. package/dist/{payload-CdDKeRpH.d.ts → payload-DLK7QaBB.d.ts} +17 -1
  24. package/dist/providers.d.ts +91 -6
  25. package/dist/providers.js +311 -4
  26. package/dist/providers.js.map +1 -1
  27. package/dist/{registry-BKQhhIO3.d.ts → registry-DM-4YvIA.d.ts} +1 -1
  28. package/dist/runtime.d.ts +3 -3
  29. package/dist/runtime.js +23 -3
  30. package/dist/runtime.js.map +1 -1
  31. package/dist/{schema-SpFM6YQY.d.ts → schema-CD61uW99.d.ts} +32 -3
  32. package/dist/state.js +20 -6
  33. package/dist/state.js.map +1 -1
  34. package/dist/telemetry.d.ts +4 -4
  35. package/dist/telemetry.js +865 -472
  36. package/dist/telemetry.js.map +1 -1
  37. package/dist/testing.d.ts +3 -3
  38. package/dist/testing.js +61 -21
  39. package/dist/testing.js.map +1 -1
  40. package/package.json +2 -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.0";
21
+ var VERSION = "0.13.2";
22
22
 
23
23
  // src/telemetry/export-identity.ts
24
24
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -1131,7 +1131,8 @@ var buildLifecycleSpan = (plan, resource, scope) => {
1131
1131
  const resolved = resolvePairing(group, anchor, correlation);
1132
1132
  const traceId = plan.traceId;
1133
1133
  const spanId = plan.spanId;
1134
- const parentSpanId = resolved.parent === void 0 ? void 0 : deriveSpanId(providerId, sessionId, resolved.parent);
1134
+ const parentRef = resolved.parent ?? resumedSessionParent(group.ref, correlation);
1135
+ const parentSpanId = parentRef === void 0 ? void 0 : deriveSpanId(providerId, sessionId, parentRef);
1135
1136
  let name = group.ref.family;
1136
1137
  let kind = SpanKind.INTERNAL;
1137
1138
  let status = { code: SpanStatusCode.UNSET };
@@ -1355,7 +1356,7 @@ var planGroup = (group, correlation, correlationAvailable) => {
1355
1356
  // persist something that should have been persisted.
1356
1357
  correlation === void 0 && correlationAvailable === void 0);
1357
1358
  const effective = durablyRecorded ? correlation : effectiveCorrelation(group, correlation);
1358
- const discriminator = durablyRecorded ? void 0 : effective?.spanIdDiscriminator;
1359
+ const discriminator = durablyRecorded ? runDiscriminatorOf(correlation) : effective?.spanIdDiscriminator ?? runDiscriminatorOf(effective);
1359
1360
  return {
1360
1361
  group,
1361
1362
  anchor,
@@ -1375,6 +1376,8 @@ var planGroup = (group, correlation, correlationAvailable) => {
1375
1376
  )
1376
1377
  };
1377
1378
  };
1379
+ var runDiscriminatorOf = (correlation) => correlation?.runSpanIdDiscriminator === void 0 ? void 0 : `run:${correlation.runSpanIdDiscriminator}`;
1380
+ var resumedSessionParent = (ref, correlation) => ref.family === "session" && correlation?.runSpanIdDiscriminator !== void 0 ? ref : void 0;
1378
1381
  var canonicalEventTraceIdentities = (events, options = {}) => {
1379
1382
  const layout = layoutBatch(events);
1380
1383
  const correlations = indexCorrelations(options.correlations);
@@ -1399,7 +1402,7 @@ var canonicalEventTraceIdentities = (events, options = {}) => {
1399
1402
  });
1400
1403
  continue;
1401
1404
  }
1402
- const parent = plan.correlation?.parent ?? parentScopeRefOf(event2);
1405
+ const parent = plan.correlation?.parent ?? parentScopeRefOf(event2) ?? resumedSessionParent(plan.group.ref, plan.correlation);
1403
1406
  identities.set(event2.eventId, {
1404
1407
  traceId: plan.traceId,
1405
1408
  spanId: plan.spanId,
@@ -1428,7 +1431,7 @@ var canonicalEventsToReadableSpans = (events, options) => {
1428
1431
 
1429
1432
  // src/telemetry/spool-queue.ts
1430
1433
  import { randomBytes } from "crypto";
1431
- import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "fs/promises";
1434
+ import { mkdir, open, readFile, readdir, rename, stat, unlink, writeFile } from "fs/promises";
1432
1435
  import * as path from "path";
1433
1436
 
1434
1437
  // src/state/keys.ts
@@ -1504,7 +1507,52 @@ var readSpoolQueueStats = async (queueDir) => {
1504
1507
  };
1505
1508
  };
1506
1509
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
1510
+ var SPOOL_CLAIM_STALE_MILLIS = 5 * 60 * 1e3;
1511
+ var CLAIM_SUFFIX = ".claim";
1512
+ var RELEASING_SUFFIX = ".releasing";
1513
+ var isClaimOwnerAlive = (pid) => {
1514
+ if (!Number.isSafeInteger(pid) || pid <= 0) {
1515
+ return true;
1516
+ }
1517
+ if (pid === process.pid) {
1518
+ return true;
1519
+ }
1520
+ try {
1521
+ process.kill(pid, 0);
1522
+ return true;
1523
+ } catch (thrown) {
1524
+ return thrown?.code !== "ESRCH";
1525
+ }
1526
+ };
1507
1527
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
1528
+ var readClaim = async (claimPath) => {
1529
+ try {
1530
+ const parsed = JSON.parse(await readFile(claimPath, "utf8"));
1531
+ return typeof parsed.token === "string" && typeof parsed.pid === "number" && typeof parsed.claimedAt === "number" ? { token: parsed.token, pid: parsed.pid, claimedAt: parsed.claimedAt } : void 0;
1532
+ } catch {
1533
+ return void 0;
1534
+ }
1535
+ };
1536
+ var releaseClaim = async (claimPath, token) => {
1537
+ const tombstone = `${claimPath}.${token ?? "untokened"}-${randomBytes(4).toString("hex")}${RELEASING_SUFFIX}`;
1538
+ for (let attempt = 1; ; attempt += 1) {
1539
+ try {
1540
+ await rename(claimPath, tombstone);
1541
+ break;
1542
+ } catch (thrown) {
1543
+ if (isErrnoException(thrown, "ENOENT") || attempt >= 3) {
1544
+ return;
1545
+ }
1546
+ await new Promise((resolve) => setTimeout(resolve, 10 * attempt));
1547
+ }
1548
+ }
1549
+ const captured = await readClaim(tombstone);
1550
+ if (captured !== void 0 && captured.token !== token) {
1551
+ await rename(tombstone, claimPath).catch(() => void 0);
1552
+ return;
1553
+ }
1554
+ await unlink(tombstone).catch(() => void 0);
1555
+ };
1508
1556
  var createSpoolQueue = (options) => {
1509
1557
  const [providerSegment, installationSegment] = namespaceSegments(options);
1510
1558
  const queueDir = path.join(options.rootDir, providerSegment, installationSegment, options.queueName);
@@ -1653,9 +1701,63 @@ var createSpoolQueue = (options) => {
1653
1701
  await rename(tmp, target);
1654
1702
  return { spooled: true };
1655
1703
  };
1704
+ const claimStaleMillis = options.claimStaleMillis ?? SPOOL_CLAIM_STALE_MILLIS;
1705
+ const staleClaim = async (claimPath) => {
1706
+ const claim = await readClaim(claimPath);
1707
+ const now = Date.now();
1708
+ if (claim !== void 0) {
1709
+ return !isClaimOwnerAlive(claim.pid) || now - claim.claimedAt > claimStaleMillis ? { stale: true, token: claim.token } : { stale: false };
1710
+ }
1711
+ try {
1712
+ return now - (await stat(claimPath)).mtimeMs > claimStaleMillis ? { stale: true, token: void 0 } : { stale: false };
1713
+ } catch {
1714
+ return { stale: false };
1715
+ }
1716
+ };
1717
+ const releaseStaleClaims = async () => {
1718
+ let entries;
1719
+ try {
1720
+ entries = await readdir(queueDir);
1721
+ } catch {
1722
+ return;
1723
+ }
1724
+ const now = Date.now();
1725
+ for (const entry of entries) {
1726
+ const entryPath = path.join(queueDir, entry);
1727
+ if (entry.endsWith(CLAIM_SUFFIX)) {
1728
+ const staleness = await staleClaim(entryPath);
1729
+ if (staleness.stale) {
1730
+ await releaseClaim(entryPath, staleness.token);
1731
+ }
1732
+ } else if (entry.endsWith(RELEASING_SUFFIX)) {
1733
+ try {
1734
+ if (now - (await stat(entryPath)).mtimeMs > claimStaleMillis) {
1735
+ await unlink(entryPath);
1736
+ }
1737
+ } catch {
1738
+ }
1739
+ }
1740
+ }
1741
+ };
1742
+ const claimBatch = async (claimPath) => {
1743
+ const token = randomBytes(16).toString("hex");
1744
+ try {
1745
+ const handle = await open(claimPath, "wx");
1746
+ try {
1747
+ const contents = { token, pid: process.pid, claimedAt: Date.now() };
1748
+ await handle.writeFile(JSON.stringify(contents), "utf8");
1749
+ } finally {
1750
+ await handle.close();
1751
+ }
1752
+ return token;
1753
+ } catch {
1754
+ return void 0;
1755
+ }
1756
+ };
1656
1757
  const drain = async (send, drainOptions) => {
1657
1758
  await ensureDirs();
1658
1759
  const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;
1760
+ await releaseStaleClaims();
1659
1761
  let files = await listSorted();
1660
1762
  if (options.maxAgeMillis !== void 0) {
1661
1763
  const now = options.clock.now();
@@ -1673,12 +1775,7 @@ var createSpoolQueue = (options) => {
1673
1775
  let failed = 0;
1674
1776
  let quarantined = 0;
1675
1777
  let index = 0;
1676
- for (; index < files.length && index < cap; index += 1) {
1677
- const fileName = files[index];
1678
- if (fileName === void 0) {
1679
- break;
1680
- }
1681
- const filePath = path.join(queueDir, fileName);
1778
+ const sendClaimed = async (fileName, filePath, claimPath, token) => {
1682
1779
  const quarantine = async (rejection) => {
1683
1780
  quarantined += 1;
1684
1781
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -1692,12 +1789,22 @@ var createSpoolQueue = (options) => {
1692
1789
  await unlink(filePath).catch(() => void 0);
1693
1790
  }
1694
1791
  };
1792
+ let text;
1793
+ try {
1794
+ text = await readFile(filePath, "utf8");
1795
+ } catch (thrown) {
1796
+ if (thrown?.code === "ENOENT") {
1797
+ return "next";
1798
+ }
1799
+ await quarantine("unreadable");
1800
+ return "next";
1801
+ }
1695
1802
  let parsed;
1696
1803
  try {
1697
- parsed = JSON.parse(await readFile(filePath, "utf8"));
1804
+ parsed = JSON.parse(text);
1698
1805
  } catch {
1699
1806
  await quarantine("unparseable-json");
1700
- continue;
1807
+ return "next";
1701
1808
  }
1702
1809
  const validation = options.validate(parsed, {
1703
1810
  providerId: options.providerId,
@@ -1705,7 +1812,10 @@ var createSpoolQueue = (options) => {
1705
1812
  });
1706
1813
  if ("rejection" in validation) {
1707
1814
  await quarantine(validation.rejection);
1708
- continue;
1815
+ return "next";
1816
+ }
1817
+ if ((await readClaim(claimPath))?.token !== token) {
1818
+ return "next";
1709
1819
  }
1710
1820
  let delivered;
1711
1821
  try {
@@ -1717,13 +1827,34 @@ var createSpoolQueue = (options) => {
1717
1827
  if (await unlink(filePath).then(() => true, () => false)) {
1718
1828
  await recordDrops("rejected", 1);
1719
1829
  }
1720
- continue;
1830
+ return "next";
1721
1831
  }
1722
1832
  if (delivered) {
1723
1833
  await unlink(filePath).catch(() => void 0);
1724
1834
  drained += 1;
1725
- } else {
1726
- failed += 1;
1835
+ return "next";
1836
+ }
1837
+ failed += 1;
1838
+ return "stop";
1839
+ };
1840
+ for (; index < files.length && index < cap; index += 1) {
1841
+ const fileName = files[index];
1842
+ if (fileName === void 0) {
1843
+ break;
1844
+ }
1845
+ const filePath = path.join(queueDir, fileName);
1846
+ const claimPath = `${filePath}${CLAIM_SUFFIX}`;
1847
+ const token = await claimBatch(claimPath);
1848
+ if (token === void 0) {
1849
+ continue;
1850
+ }
1851
+ let outcome;
1852
+ try {
1853
+ outcome = await sendClaimed(fileName, filePath, claimPath, token);
1854
+ } finally {
1855
+ await releaseClaim(claimPath, token);
1856
+ }
1857
+ if (outcome === "stop") {
1727
1858
  break;
1728
1859
  }
1729
1860
  }
@@ -1837,7 +1968,7 @@ var createFileDurableSpool = (options) => createSpoolQueue({
1837
1968
  });
1838
1969
 
1839
1970
  // src/telemetry/otlp-sink.ts
1840
- import { ExportResultCode } from "@opentelemetry/core";
1971
+ import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
1841
1972
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
1842
1973
 
1843
1974
  // src/errors/index.ts
@@ -1947,11 +2078,17 @@ var isPermanentExportFailure = (result) => {
1947
2078
  return typeof code === "number" && Number.isInteger(code) && code >= 400 && code < 600 && !RETRYABLE_HTTP_STATUSES.has(code);
1948
2079
  };
1949
2080
 
1950
- // src/telemetry/exporter-resource.ts
1951
- import { resourceFromAttributes } from "@opentelemetry/resources";
2081
+ // src/telemetry/endpoint-health.ts
2082
+ import { createHash as createHash3, randomBytes as randomBytes2 } from "crypto";
2083
+ import { mkdir as mkdir2, readFile as readFile2, rename as rename2, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
2084
+ import * as http from "http";
2085
+ import * as https from "https";
2086
+ import path2 from "path";
2087
+ import { ExportResultCode } from "@opentelemetry/core";
1952
2088
 
1953
- // src/config/resource-attributes.ts
1954
- import { z as z12 } from "zod";
2089
+ // src/config/schema.ts
2090
+ import { isAbsolute } from "path";
2091
+ import { z as z14 } from "zod";
1955
2092
 
1956
2093
  // src/privacy/policy.ts
1957
2094
  import { z as z11 } from "zod";
@@ -2030,7 +2167,182 @@ var DEFAULT_PRIVACY_POLICY = Object.freeze({
2030
2167
  limits: DEFAULT_PRIVACY_LIMITS
2031
2168
  });
2032
2169
 
2170
+ // src/config/destinations.ts
2171
+ import { z as z12 } from "zod";
2172
+
2173
+ // src/config/header-value.ts
2174
+ var isUnsafeHeaderValue = (value) => [...value].some((char) => {
2175
+ const code = char.codePointAt(0) ?? 0;
2176
+ return code < 32 && code !== 9 || code === 127 || code > 255;
2177
+ });
2178
+
2179
+ // src/config/otlp-headers.ts
2180
+ var MAX_OTLP_HEADERS = 32;
2181
+ var OTLP_HEADER_VARIABLES = Object.freeze({
2182
+ generic: "OTEL_EXPORTER_OTLP_HEADERS",
2183
+ traces: "OTEL_EXPORTER_OTLP_TRACES_HEADERS",
2184
+ logs: "OTEL_EXPORTER_OTLP_LOGS_HEADERS"
2185
+ });
2186
+
2187
+ // src/config/destinations.ts
2188
+ var DEFAULT_DESTINATION_NAME = "default";
2189
+ var DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;
2190
+ var MAX_EXPORT_DESTINATIONS = 16;
2191
+ var MAX_DESTINATION_HEADERS = MAX_OTLP_HEADERS;
2192
+ var HEADER_ENV_REFERENCE_PREFIX = "env:";
2193
+ var HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
2194
+ var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
2195
+ var MAX_HEADER_VALUE_LENGTH = 8192;
2196
+ var exportSignalSchema = z12.enum(["traces", "logs", "metrics"]);
2197
+ var headerValueSchema = z12.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
2198
+ (value) => !isUnsafeHeaderValue(value),
2199
+ "header values may not contain line breaks, control characters, or characters beyond Latin-1"
2200
+ ).refine(
2201
+ (value) => !value.startsWith(HEADER_ENV_REFERENCE_PREFIX) || ENV_VARIABLE_NAME_PATTERN.test(value.slice(HEADER_ENV_REFERENCE_PREFIX.length)),
2202
+ "an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN"
2203
+ );
2204
+ var endpointSchema = z12.string().url().max(2048);
2205
+ var exportDestinationSchema = z12.strictObject({
2206
+ /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */
2207
+ name: z12.string().regex(DESTINATION_NAME_PATTERN, "destination names are lowercase letters, digits, _ and -"),
2208
+ /** Default true. A disabled destination is neither sent to nor drained. */
2209
+ enabled: z12.boolean().optional(),
2210
+ /**
2211
+ * Traces URL, with the same meaning as `exporter.endpoint`: the logs URL is
2212
+ * derived from it (`/v1/traces` becomes `/v1/logs`) unless `logsEndpoint` is set.
2213
+ */
2214
+ endpoint: endpointSchema.optional(),
2215
+ /** Per-signal override of `endpoint` for traces. */
2216
+ tracesEndpoint: endpointSchema.optional(),
2217
+ /** Per-signal override of the derived logs URL. */
2218
+ logsEndpoint: endpointSchema.optional(),
2219
+ /** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */
2220
+ metricsEndpoint: endpointSchema.optional(),
2221
+ /** Defaults to `exporter.protocol`. */
2222
+ protocol: z12.enum(["http/protobuf", "http/json", "none"]).optional(),
2223
+ /**
2224
+ * Header name to value. A value of the form `env:NAME` is read from that
2225
+ * environment variable at send time, so a credential never has to be written
2226
+ * into the file. Values never appear in a snapshot, a diagnostic, or `doctor`.
2227
+ */
2228
+ headers: z12.record(z12.string().regex(HEADER_NAME_PATTERN, "not a valid header name"), headerValueSchema).refine(
2229
+ (headers) => Object.keys(headers).length <= MAX_DESTINATION_HEADERS,
2230
+ `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
2231
+ ).optional(),
2232
+ /**
2233
+ * Which signals this destination receives. Default: traces and logs. The logs
2234
+ * signal is still governed by `exporter.logs.enabled`, which stays the one
2235
+ * opt-in for content-bearing records leaving the host. `metrics` is never on by
2236
+ * default: a destination receives hook-derived metrics only when it lists them.
2237
+ */
2238
+ signals: z12.array(exportSignalSchema).min(1).max(3).readonly().optional()
2239
+ }).refine(
2240
+ (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
2241
+ "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
2242
+ );
2243
+ var DEFAULT_DESTINATION_SIGNALS = Object.freeze(["traces", "logs"]);
2244
+ var exportDestinationsSchema = z12.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
2245
+ const seen = /* @__PURE__ */ new Set();
2246
+ destinations.forEach((destination, index) => {
2247
+ if (destination.name === DEFAULT_DESTINATION_NAME) {
2248
+ context.addIssue({
2249
+ code: "custom",
2250
+ path: [index, "name"],
2251
+ message: 'the name "default" is reserved for exporter.endpoint and the OTEL_EXPORTER_OTLP_* variables'
2252
+ });
2253
+ }
2254
+ if (seen.has(destination.name)) {
2255
+ context.addIssue({
2256
+ code: "custom",
2257
+ path: [index, "name"],
2258
+ message: `duplicate destination name "${destination.name}"`
2259
+ });
2260
+ }
2261
+ seen.add(destination.name);
2262
+ });
2263
+ });
2264
+ var spoolPolicySchema = z12.strictObject({
2265
+ /** Total bytes of queued batches. Default 16 MiB. */
2266
+ maxBytes: z12.number().int().min(1024).max(1073741824),
2267
+ /** A batch older than this is dropped instead of sent. Default 72 hours. */
2268
+ maxAgeMillis: z12.number().int().min(1e3).max(30 * 24 * 60 * 60 * 1e3),
2269
+ /** Number of queued batches. Default 500. */
2270
+ maxBatches: z12.number().int().min(1).max(65536)
2271
+ });
2272
+ var DEFAULT_SPOOL_POLICY = Object.freeze({
2273
+ maxBytes: 16 * 1024 * 1024,
2274
+ maxAgeMillis: 72 * 60 * 60 * 1e3,
2275
+ maxBatches: 500
2276
+ });
2277
+ var effectiveSpoolPolicy = (exporter) => ({
2278
+ maxBytes: exporter.spool?.maxBytes ?? DEFAULT_SPOOL_POLICY.maxBytes,
2279
+ maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,
2280
+ maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches
2281
+ });
2282
+ var legacyDestination = (exporter) => ({
2283
+ name: DEFAULT_DESTINATION_NAME,
2284
+ source: "exporter",
2285
+ protocol: exporter.protocol,
2286
+ ...exporter.endpoint === void 0 ? {} : { endpoint: exporter.endpoint },
2287
+ ...exporter.logs.endpoint === void 0 ? {} : { logsEndpoint: exporter.logs.endpoint },
2288
+ ...exporter.metrics?.endpoint === void 0 ? {} : { metricsEndpoint: exporter.metrics.endpoint },
2289
+ signals: { traces: true, logs: exporter.logs.enabled, metrics: exporter.metrics?.enabled === true },
2290
+ headers: {}
2291
+ });
2292
+ var hasConfiguredDestinations = (exporter) => exporter.destinations !== void 0 && exporter.destinations.length > 0;
2293
+ var resolveExportDestinations = (exporter) => {
2294
+ if (!hasConfiguredDestinations(exporter)) {
2295
+ return [legacyDestination(exporter)];
2296
+ }
2297
+ const resolved = [];
2298
+ if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0 || exporter.metrics?.endpoint !== void 0) {
2299
+ resolved.push(legacyDestination(exporter));
2300
+ }
2301
+ for (const destination of exporter.destinations ?? []) {
2302
+ if (destination.enabled === false) {
2303
+ continue;
2304
+ }
2305
+ const signals = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;
2306
+ resolved.push({
2307
+ name: destination.name,
2308
+ source: "destinations",
2309
+ protocol: destination.protocol ?? exporter.protocol,
2310
+ ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
2311
+ ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
2312
+ ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
2313
+ ...destination.metricsEndpoint === void 0 ? {} : { metricsEndpoint: destination.metricsEndpoint },
2314
+ signals: {
2315
+ traces: signals.includes("traces"),
2316
+ logs: exporter.logs.enabled && signals.includes("logs"),
2317
+ metrics: signals.includes("metrics")
2318
+ },
2319
+ headers: { ...destination.headers ?? {} }
2320
+ });
2321
+ }
2322
+ return resolved;
2323
+ };
2324
+ var parseHeaderValueReference = (value) => value.startsWith(HEADER_ENV_REFERENCE_PREFIX) ? { kind: "env", variable: value.slice(HEADER_ENV_REFERENCE_PREFIX.length) } : { kind: "literal" };
2325
+ var resolveDestinationHeaders = (headers, environment) => {
2326
+ const values = {};
2327
+ const missing = [];
2328
+ for (const [name, value] of Object.entries(headers)) {
2329
+ const reference = parseHeaderValueReference(value);
2330
+ if (reference.kind === "literal") {
2331
+ values[name] = value;
2332
+ continue;
2333
+ }
2334
+ const resolved = environment?.[reference.variable];
2335
+ if (resolved === void 0 || resolved === "") {
2336
+ missing.push(reference.variable);
2337
+ continue;
2338
+ }
2339
+ values[name] = resolved;
2340
+ }
2341
+ return { values, missingVariables: [...new Set(missing)].sort() };
2342
+ };
2343
+
2033
2344
  // src/config/resource-attributes.ts
2345
+ import { z as z13 } from "zod";
2034
2346
  var MAX_RESOURCE_ATTRIBUTES = 64;
2035
2347
  var MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH = 255;
2036
2348
  var MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH = 2048;
@@ -2075,12 +2387,12 @@ var checkResourceAttributeKey = (key) => {
2075
2387
  }
2076
2388
  return void 0;
2077
2389
  };
2078
- var resourceAttributeValueSchema = z12.union([
2079
- z12.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),
2080
- z12.number().finite(),
2081
- z12.boolean()
2390
+ var resourceAttributeValueSchema = z13.union([
2391
+ z13.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),
2392
+ z13.number().finite(),
2393
+ z13.boolean()
2082
2394
  ]);
2083
- var resourceAttributesSchema = z12.record(z12.string(), resourceAttributeValueSchema).superRefine((value, ctx) => {
2395
+ var resourceAttributesSchema = z13.record(z13.string(), resourceAttributeValueSchema).superRefine((value, ctx) => {
2084
2396
  const keys = Object.keys(value);
2085
2397
  if (keys.length > MAX_RESOURCE_ATTRIBUTES) {
2086
2398
  ctx.addIssue({
@@ -2109,12 +2421,410 @@ var sanitizeResourceAttributes = (attributes) => {
2109
2421
  if (Object.keys(safe).length >= MAX_RESOURCE_ATTRIBUTES) {
2110
2422
  break;
2111
2423
  }
2112
- safe[key] = value;
2424
+ safe[key] = value;
2425
+ }
2426
+ return safe;
2427
+ };
2428
+
2429
+ // src/config/schema.ts
2430
+ var logsPolicySchema = z14.strictObject({
2431
+ enabled: z14.boolean(),
2432
+ /**
2433
+ * Full URL for the logs signal.
2434
+ *
2435
+ * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes
2436
+ * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.
2437
+ */
2438
+ endpoint: z14.string().url().max(2048).optional(),
2439
+ includeContent: z14.boolean(),
2440
+ maxBatchSize: z14.number().int().min(1).max(4096)
2441
+ });
2442
+ var DEFAULT_LOGS_POLICY = Object.freeze({
2443
+ enabled: false,
2444
+ includeContent: false,
2445
+ maxBatchSize: 128
2446
+ });
2447
+ var metricsPolicySchema = z14.strictObject({
2448
+ enabled: z14.boolean(),
2449
+ /** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */
2450
+ endpoint: z14.string().url().max(2048).optional(),
2451
+ temporality: z14.enum(["cumulative", "delta"]),
2452
+ includeSessionId: z14.boolean()
2453
+ });
2454
+ var DEFAULT_METRICS_POLICY = Object.freeze({
2455
+ enabled: false,
2456
+ temporality: "cumulative",
2457
+ includeSessionId: true
2458
+ });
2459
+ var exporterPolicySchema = z14.strictObject({
2460
+ enabled: z14.boolean(),
2461
+ protocol: z14.enum(["http/protobuf", "http/json", "none"]),
2462
+ endpoint: z14.string().url().max(2048).optional(),
2463
+ /**
2464
+ * Header names only. Values are supplied separately at construction time and
2465
+ * are never part of a resolved-config snapshot, which is logged and exported.
2466
+ */
2467
+ headerNames: z14.array(nonEmptyStringSchema).max(32).readonly(),
2468
+ timeoutMillis: z14.number().int().min(1).max(6e5),
2469
+ maxBatchSize: z14.number().int().min(1).max(4096),
2470
+ maxQueueSize: z14.number().int().min(1).max(65536),
2471
+ maxRetryAttempts: z14.number().int().min(0).max(10),
2472
+ serviceName: nonEmptyStringSchema,
2473
+ serviceNamespace: nonEmptyStringSchema.optional(),
2474
+ /**
2475
+ * Custom attributes merged into the exported OTLP Resource.
2476
+ *
2477
+ * Bounded and validated, and refusing `service.name`/`service.namespace`,
2478
+ * which are the two fields above. Distinct from an invocation's
2479
+ * `consumerAttributes`: this describes the emitting deployment, carries no
2480
+ * identity, and is the same for every span this process exports.
2481
+ */
2482
+ resourceAttributes: resourceAttributesSchema,
2483
+ /**
2484
+ * The logs signal. Nested under the exporter because it shares the endpoint,
2485
+ * headers, timeout, protocol, service identity, and resource attributes above —
2486
+ * a second top-level section would invite two of each to drift apart.
2487
+ */
2488
+ logs: logsPolicySchema,
2489
+ /**
2490
+ * Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before
2491
+ * metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.
2492
+ */
2493
+ metrics: metricsPolicySchema.optional(),
2494
+ /**
2495
+ * Additional OTLP destinations, each sent every batch in parallel.
2496
+ *
2497
+ * Absent (the default), the exporter has exactly one destination — the
2498
+ * single-endpoint settings above, named `default` — and behaves exactly as it
2499
+ * did before this list existed. See `destinations.ts`.
2500
+ *
2501
+ * Merged as one leaf: a higher layer that sets the list replaces it whole,
2502
+ * because "the union of two partial lists" has no answer an operator could
2503
+ * predict.
2504
+ */
2505
+ destinations: exportDestinationsSchema.optional(),
2506
+ /**
2507
+ * Per-destination retry spool bounds, each optional and merged per leaf; any
2508
+ * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.
2509
+ */
2510
+ spool: spoolPolicySchema.partial().optional(),
2511
+ /**
2512
+ * The most time one hook invocation spends trying to reach one endpoint, in
2513
+ * milliseconds: caps `timeoutMillis` for every OTLP request (connection setup
2514
+ * included) and the exporter's own retries inside it. A batch that does not
2515
+ * get through in time is spooled. Default {@link DEFAULT_EXPORT_BUDGET_MILLIS}:
2516
+ * the host agent waits for its hooks, so a down collector must not stall it.
2517
+ */
2518
+ exportBudgetMillis: z14.number().int().min(50).max(6e5).optional(),
2519
+ /**
2520
+ * After an endpoint was unreachable (refused, timed out, or answered a
2521
+ * retryable status), every hook spools for it without trying for this long,
2522
+ * in milliseconds; then one hook probes it again. 0 disables the window.
2523
+ * Default {@link DEFAULT_ENDPOINT_DOWN_MILLIS}.
2524
+ */
2525
+ endpointDownMillis: z14.number().int().min(0).max(36e5).optional()
2526
+ });
2527
+ var DEFAULT_EXPORT_BUDGET_MILLIS = 1500;
2528
+ var DEFAULT_ENDPOINT_DOWN_MILLIS = 3e4;
2529
+ var effectiveExportTimeoutMillis = (exporter) => Math.min(exporter.timeoutMillis, exporter.exportBudgetMillis ?? DEFAULT_EXPORT_BUDGET_MILLIS);
2530
+ var detectionPolicySchema = z14.strictObject({
2531
+ /** Detections below this confidence resolve to the unknown provider. */
2532
+ minimumConfidence: detectionConfidenceSchema,
2533
+ /** When false, an ambiguous detection is an error rather than unknown. */
2534
+ allowAmbiguousFallback: z14.boolean(),
2535
+ /** Optional allow-list of provider ids; empty means "any registered". */
2536
+ allowedProviderIds: z14.array(nonEmptyStringSchema).max(32).readonly()
2537
+ });
2538
+ var diagnosticsPolicySchema = z14.strictObject({
2539
+ logLevel: z14.enum(["silent", "error", "warn", "info", "debug"]),
2540
+ /** Emit `error.raised` events for contained failures. */
2541
+ emitErrorEvents: z14.boolean()
2542
+ });
2543
+ var providersPolicySchema = z14.strictObject({
2544
+ claudeCode: z14.strictObject({
2545
+ readTranscriptUsage: z14.boolean()
2546
+ }).optional(),
2547
+ codex: z14.strictObject({
2548
+ readRolloutUsage: z14.boolean()
2549
+ }).optional()
2550
+ });
2551
+ var sessionContextPolicySchema = z14.strictObject({
2552
+ /** Absolute path of the context directory. */
2553
+ dir: z14.string().min(1).max(4096).refine((value) => isAbsolute(value), { message: "must be an absolute path" })
2554
+ });
2555
+ var otelHookConfigSchema = z14.strictObject({
2556
+ exporter: exporterPolicySchema,
2557
+ privacy: privacyPolicySchema,
2558
+ detection: detectionPolicySchema,
2559
+ diagnostics: diagnosticsPolicySchema,
2560
+ /** Optional so a hand-built configuration from before it existed stays valid. */
2561
+ providers: providersPolicySchema.optional(),
2562
+ /** Optional: absent means no session context is read. */
2563
+ sessionContext: sessionContextPolicySchema.optional()
2564
+ });
2565
+ var otelHookConfigPatchSchema = z14.strictObject({
2566
+ // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
2567
+ // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
2568
+ // without also restating the endpoint and the batch size.
2569
+ exporter: exporterPolicySchema.omit({ logs: true, metrics: true, spool: true }).partial().extend({
2570
+ logs: logsPolicySchema.partial().optional(),
2571
+ metrics: metricsPolicySchema.partial().optional(),
2572
+ spool: spoolPolicySchema.partial().optional()
2573
+ }).optional(),
2574
+ privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
2575
+ detection: detectionPolicySchema.partial().optional(),
2576
+ diagnostics: diagnosticsPolicySchema.partial().optional(),
2577
+ providers: z14.strictObject({
2578
+ claudeCode: z14.strictObject({ readTranscriptUsage: z14.boolean() }).partial().optional(),
2579
+ codex: z14.strictObject({ readRolloutUsage: z14.boolean() }).partial().optional()
2580
+ }).partial().optional(),
2581
+ sessionContext: sessionContextPolicySchema.partial().optional()
2582
+ });
2583
+ var DEFAULT_EXPORTER_POLICY = Object.freeze({
2584
+ enabled: true,
2585
+ protocol: "http/protobuf",
2586
+ headerNames: Object.freeze([]),
2587
+ timeoutMillis: 1e4,
2588
+ maxBatchSize: 128,
2589
+ maxQueueSize: 2048,
2590
+ maxRetryAttempts: 2,
2591
+ serviceName: "coding-agent",
2592
+ resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
2593
+ logs: DEFAULT_LOGS_POLICY,
2594
+ metrics: DEFAULT_METRICS_POLICY
2595
+ });
2596
+ var DEFAULT_DETECTION_POLICY = Object.freeze({
2597
+ minimumConfidence: "strong",
2598
+ allowAmbiguousFallback: true,
2599
+ allowedProviderIds: Object.freeze([])
2600
+ });
2601
+ var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
2602
+ logLevel: "warn",
2603
+ emitErrorEvents: true
2604
+ });
2605
+ var DEFAULT_PROVIDERS_POLICY = Object.freeze({
2606
+ claudeCode: Object.freeze({ readTranscriptUsage: false }),
2607
+ codex: Object.freeze({ readRolloutUsage: false })
2608
+ });
2609
+ var DEFAULT_CONFIG = Object.freeze({
2610
+ exporter: DEFAULT_EXPORTER_POLICY,
2611
+ privacy: DEFAULT_PRIVACY_POLICY,
2612
+ detection: DEFAULT_DETECTION_POLICY,
2613
+ diagnostics: DEFAULT_DIAGNOSTICS_POLICY,
2614
+ providers: DEFAULT_PROVIDERS_POLICY
2615
+ });
2616
+ var effectiveMetricsPolicy = (exporter) => ({
2617
+ ...DEFAULT_METRICS_POLICY,
2618
+ ...exporter.metrics ?? {}
2619
+ });
2620
+
2621
+ // src/telemetry/endpoint-health.ts
2622
+ var ENDPOINT_DOWN_ERROR_CODE = "OTEL_HOOK_ENDPOINT_DOWN";
2623
+ var UNREACHABLE_NETWORK_CODES = /* @__PURE__ */ new Set([
2624
+ "ECONNREFUSED",
2625
+ "ECONNRESET",
2626
+ "ETIMEDOUT",
2627
+ "EPIPE",
2628
+ "EHOSTUNREACH",
2629
+ "ENETUNREACH",
2630
+ "EHOSTDOWN",
2631
+ "ENETDOWN",
2632
+ "EAI_AGAIN",
2633
+ "ENOTFOUND",
2634
+ ENDPOINT_DOWN_ERROR_CODE
2635
+ ]);
2636
+ var isUnreachableExportFailure = (result) => {
2637
+ if (result.code === ExportResultCode.SUCCESS) {
2638
+ return false;
2639
+ }
2640
+ const error = result.error;
2641
+ const code = error?.code;
2642
+ if (typeof code === "string") {
2643
+ return UNREACHABLE_NETWORK_CODES.has(code);
2644
+ }
2645
+ if (code !== void 0) {
2646
+ return false;
2647
+ }
2648
+ return typeof error?.message === "string" && /timed out/i.test(error.message);
2649
+ };
2650
+ var withConnectTimeout = (agent, connectTimeoutMillis) => {
2651
+ const target = agent;
2652
+ const original = target.createConnection.bind(agent);
2653
+ target.createConnection = (options, callback) => {
2654
+ const socket = original(options, callback);
2655
+ if (socket !== void 0 && socket.connecting) {
2656
+ const timer = setTimeout(() => {
2657
+ const error = Object.assign(new Error("connect timed out"), { code: "ETIMEDOUT" });
2658
+ socket.destroy(error);
2659
+ }, connectTimeoutMillis);
2660
+ timer.unref();
2661
+ const clear = () => {
2662
+ clearTimeout(timer);
2663
+ };
2664
+ socket.once("connect", clear);
2665
+ socket.once("close", clear);
2666
+ }
2667
+ return socket;
2668
+ };
2669
+ return agent;
2670
+ };
2671
+ var boundedExporterOptions = (exporter) => {
2672
+ const timeoutMillis = effectiveExportTimeoutMillis(exporter);
2673
+ let agents = {};
2674
+ return {
2675
+ timeoutMillis,
2676
+ httpAgentOptions: (protocol) => {
2677
+ if (protocol === "https:") {
2678
+ agents = { ...agents, https: agents.https ?? withConnectTimeout(new https.Agent({ keepAlive: true }), timeoutMillis) };
2679
+ return agents.https;
2680
+ }
2681
+ agents = { ...agents, http: agents.http ?? withConnectTimeout(new http.Agent({ keepAlive: true }), timeoutMillis) };
2682
+ return agents.http;
2683
+ }
2684
+ };
2685
+ };
2686
+ var parseMark = (raw) => {
2687
+ try {
2688
+ const parsed = JSON.parse(raw);
2689
+ return typeof parsed.downUntil === "number" && Number.isFinite(parsed.downUntil) ? {
2690
+ downUntil: parsed.downUntil,
2691
+ failures: typeof parsed.failures === "number" && Number.isInteger(parsed.failures) ? parsed.failures : 1
2692
+ } : void 0;
2693
+ } catch {
2694
+ return void 0;
2695
+ }
2696
+ };
2697
+ var originOf = (url) => {
2698
+ if (url === void 0) {
2699
+ return void 0;
2700
+ }
2701
+ try {
2702
+ return new URL(url).origin;
2703
+ } catch {
2704
+ return void 0;
2705
+ }
2706
+ };
2707
+ var createEndpointHealth = (options) => {
2708
+ const downMillis = options.downMillis ?? DEFAULT_ENDPOINT_DOWN_MILLIS;
2709
+ const gates = /* @__PURE__ */ new Map();
2710
+ const createGate = (origin) => {
2711
+ const digest = createHash3("sha256").update(origin, "utf8").digest("hex").slice(0, 32);
2712
+ const dir = options.rootDir === void 0 ? void 0 : path2.join(options.rootDir, "endpoint-health");
2713
+ const file = dir === void 0 ? void 0 : path2.join(dir, `${digest}.json`);
2714
+ let downUntil = 0;
2715
+ let failures = 0;
2716
+ let marked = false;
2717
+ let loaded;
2718
+ let warned = false;
2719
+ const write = async (mark) => {
2720
+ if (file === void 0 || dir === void 0) {
2721
+ return;
2722
+ }
2723
+ try {
2724
+ await mkdir2(dir, { recursive: true });
2725
+ const tmp = path2.join(dir, `.tmp-${randomBytes2(6).toString("hex")}.json`);
2726
+ await writeFile2(tmp, `${JSON.stringify(mark)}
2727
+ `);
2728
+ await rename2(tmp, file);
2729
+ marked = true;
2730
+ } catch {
2731
+ }
2732
+ };
2733
+ const load = () => {
2734
+ loaded ??= (async () => {
2735
+ if (file === void 0) {
2736
+ return;
2737
+ }
2738
+ let raw;
2739
+ try {
2740
+ raw = await readFile2(file, "utf8");
2741
+ } catch {
2742
+ return;
2743
+ }
2744
+ marked = true;
2745
+ const mark = parseMark(raw);
2746
+ if (mark === void 0) {
2747
+ return;
2748
+ }
2749
+ failures = mark.failures;
2750
+ const now = options.clock.now();
2751
+ if (mark.downUntil > now) {
2752
+ downUntil = mark.downUntil;
2753
+ return;
2754
+ }
2755
+ await write({ downUntil: now + options.probeMillis, failures });
2756
+ })();
2757
+ return loaded;
2758
+ };
2759
+ return {
2760
+ available: async () => {
2761
+ if (downMillis === 0) {
2762
+ return true;
2763
+ }
2764
+ await load();
2765
+ return options.clock.now() >= downUntil;
2766
+ },
2767
+ record: async (result) => {
2768
+ if (downMillis === 0) {
2769
+ return;
2770
+ }
2771
+ if (!isUnreachableExportFailure(result)) {
2772
+ if (!marked && downUntil === 0) {
2773
+ return;
2774
+ }
2775
+ downUntil = 0;
2776
+ failures = 0;
2777
+ marked = false;
2778
+ if (file !== void 0) {
2779
+ await unlink2(file).catch(() => void 0);
2780
+ }
2781
+ return;
2782
+ }
2783
+ failures += 1;
2784
+ downUntil = options.clock.now() + downMillis;
2785
+ if (!warned) {
2786
+ warned = true;
2787
+ options.logger?.warn("export endpoint unreachable; hooks spool for it without trying until it is probed again", {
2788
+ "export.endpoint_down_millis": downMillis,
2789
+ "export.endpoint_failures": failures
2790
+ });
2791
+ }
2792
+ await write({ downUntil, failures });
2793
+ }
2794
+ };
2795
+ };
2796
+ return {
2797
+ gateFor: (url) => {
2798
+ const origin = originOf(url);
2799
+ if (origin === void 0) {
2800
+ return void 0;
2801
+ }
2802
+ let gate = gates.get(origin);
2803
+ if (gate === void 0) {
2804
+ gate = createGate(origin);
2805
+ gates.set(origin, gate);
2806
+ }
2807
+ return gate;
2808
+ }
2809
+ };
2810
+ };
2811
+ var guardExport = async (gate, send) => {
2812
+ if (gate === void 0) {
2813
+ return send();
2113
2814
  }
2114
- return safe;
2815
+ if (!await gate.available()) {
2816
+ return {
2817
+ code: ExportResultCode.FAILED,
2818
+ error: Object.assign(new Error("endpoint marked down; batch not sent"), { code: ENDPOINT_DOWN_ERROR_CODE })
2819
+ };
2820
+ }
2821
+ const result = await send();
2822
+ await gate.record(result).catch(() => void 0);
2823
+ return result;
2115
2824
  };
2116
2825
 
2117
2826
  // src/telemetry/exporter-resource.ts
2827
+ import { resourceFromAttributes } from "@opentelemetry/resources";
2118
2828
  var resourceFromExporterPolicy = (policy) => resourceFromAttributes({
2119
2829
  ...sanitizeResourceAttributes(policy.resourceAttributes),
2120
2830
  "service.name": policy.serviceName,
@@ -2252,12 +2962,16 @@ var createOtlpTraceSink = (options) => {
2252
2962
  const exporter = new OTLPTraceExporter({
2253
2963
  url: options.exporter.endpoint,
2254
2964
  headers: { ...options.headers },
2255
- timeoutMillis: options.exporter.timeoutMillis
2965
+ ...boundedExporterOptions(options.exporter)
2256
2966
  });
2967
+ const gate = options.endpointHealth?.gateFor(options.exporter.endpoint);
2257
2968
  let shutdownCompleted = false;
2258
- const exportSpans = (spans) => new Promise((resolve) => {
2259
- exporter.export([...spans], (result) => resolve(result));
2260
- });
2969
+ const exportSpans = (spans) => guardExport(
2970
+ gate,
2971
+ () => new Promise((resolve) => {
2972
+ exporter.export([...spans], (result) => resolve(result));
2973
+ })
2974
+ );
2261
2975
  const toSpoolBatch = (spans, batchResource) => ({
2262
2976
  providerId: options.providerId,
2263
2977
  installationId: options.installationId,
@@ -2270,7 +2984,7 @@ var createOtlpTraceSink = (options) => {
2270
2984
  const batchResource = replayResource(batch.resourceAttributes, options.exporter);
2271
2985
  const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));
2272
2986
  const result = await exportSpans(spans);
2273
- if (result.code === ExportResultCode.SUCCESS) {
2987
+ if (result.code === ExportResultCode2.SUCCESS) {
2274
2988
  return true;
2275
2989
  }
2276
2990
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -2309,9 +3023,9 @@ var createOtlpTraceSink = (options) => {
2309
3023
  try {
2310
3024
  result = await exportSpans(batch);
2311
3025
  } catch (thrown) {
2312
- result = { code: ExportResultCode.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
3026
+ result = { code: ExportResultCode2.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
2313
3027
  }
2314
- if (result.code === ExportResultCode.SUCCESS) {
3028
+ if (result.code === ExportResultCode2.SUCCESS) {
2315
3029
  accepted += batch.length;
2316
3030
  health.recordSuccess(batch.length, options.clock.now());
2317
3031
  continue;
@@ -2348,6 +3062,9 @@ var createOtlpTraceSink = (options) => {
2348
3062
  if (options.spool === void 0) {
2349
3063
  return { drained: 0, remaining: 0, failed: 0 };
2350
3064
  }
3065
+ if (gate !== void 0 && !await gate.available()) {
3066
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
3067
+ }
2351
3068
  const result = await options.spool.drain(sendSerializedBatch, { ...maxBatches === void 0 ? {} : { maxBatches } });
2352
3069
  if (result.drained > 0) {
2353
3070
  health.recordSuccess(result.drained, options.clock.now());
@@ -2905,7 +3622,7 @@ var createFileDurableLogSpool = (options) => createSpoolQueue({
2905
3622
 
2906
3623
  // src/telemetry/otlp-log-sink.ts
2907
3624
  import { TraceFlags as TraceFlags3 } from "@opentelemetry/api";
2908
- import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
3625
+ import { ExportResultCode as ExportResultCode3 } from "@opentelemetry/core";
2909
3626
  import { millisToHrTime as millisToHrTime3 } from "@opentelemetry/core";
2910
3627
  import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
2911
3628
 
@@ -3084,12 +3801,16 @@ var createOtlpLogSink = (options) => {
3084
3801
  const exporter = new OTLPLogExporter({
3085
3802
  url: deliverability.endpoint,
3086
3803
  headers: { ...options.headers },
3087
- timeoutMillis: options.exporter.timeoutMillis
3804
+ ...boundedExporterOptions(options.exporter)
3088
3805
  });
3806
+ const gate = options.endpointHealth?.gateFor(deliverability.endpoint);
3089
3807
  let shutdownCompleted = false;
3090
- const exportRecords = (records) => new Promise((resolve) => {
3091
- exporter.export([...records], (result) => resolve(result));
3092
- });
3808
+ const exportRecords = (records) => guardExport(
3809
+ gate,
3810
+ () => new Promise((resolve) => {
3811
+ exporter.export([...records], (result) => resolve(result));
3812
+ })
3813
+ );
3093
3814
  const toSpoolBatch = (records, batchResource) => ({
3094
3815
  providerId: options.providerId,
3095
3816
  installationId: options.installationId,
@@ -3107,7 +3828,7 @@ var createOtlpLogSink = (options) => {
3107
3828
  (record) => deserializeRecord(record, batchResource, batch.instrumentationScope)
3108
3829
  );
3109
3830
  const result = await exportRecords(records);
3110
- if (result.code === ExportResultCode2.SUCCESS) {
3831
+ if (result.code === ExportResultCode3.SUCCESS) {
3111
3832
  return true;
3112
3833
  }
3113
3834
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -3153,11 +3874,11 @@ var createOtlpLogSink = (options) => {
3153
3874
  result = await exportRecords(batch);
3154
3875
  } catch (thrown) {
3155
3876
  result = {
3156
- code: ExportResultCode2.FAILED,
3877
+ code: ExportResultCode3.FAILED,
3157
3878
  error: thrown instanceof Error ? thrown : new Error("export threw")
3158
3879
  };
3159
3880
  }
3160
- if (result.code === ExportResultCode2.SUCCESS) {
3881
+ if (result.code === ExportResultCode3.SUCCESS) {
3161
3882
  accepted += batch.length;
3162
3883
  health.recordSuccess(batch.length, options.clock.now());
3163
3884
  continue;
@@ -3193,432 +3914,90 @@ var createOtlpLogSink = (options) => {
3193
3914
  );
3194
3915
  }
3195
3916
  return { accepted, rejected, errors };
3196
- };
3197
- const drainSpool = async (maxBatches) => {
3198
- if (options.spool === void 0) {
3199
- return { drained: 0, remaining: 0, failed: 0 };
3200
- }
3201
- const result = await options.spool.drain(sendSerializedBatch, {
3202
- ...maxBatches === void 0 ? {} : { maxBatches }
3203
- });
3204
- if (result.drained > 0) {
3205
- health.recordSuccess(result.drained, options.clock.now());
3206
- }
3207
- return result;
3208
- };
3209
- const flush = async () => {
3210
- try {
3211
- await exporter.forceFlush();
3212
- } catch {
3213
- }
3214
- await drainSpool().catch(() => void 0);
3215
- };
3216
- const shutdown = async () => {
3217
- if (shutdownCompleted) {
3218
- return;
3219
- }
3220
- shutdownCompleted = true;
3221
- await flush();
3222
- try {
3223
- await exporter.shutdown();
3224
- } catch {
3225
- }
3226
- };
3227
- return {
3228
- emit,
3229
- flush,
3230
- shutdown,
3231
- health: () => health.snapshot(),
3232
- drainSpool
3233
- };
3234
- };
3235
-
3236
- // src/telemetry/signal-fanout.ts
3237
- var createSignalFanout = (options) => {
3238
- const emit = async (events) => {
3239
- const traces = await options.traces.emit(events);
3240
- const logs = await options.logs.emit(events);
3241
- const errors = [...traces.errors, ...logs.errors];
3242
- return {
3243
- accepted: traces.accepted + logs.accepted,
3244
- rejected: traces.rejected + logs.rejected,
3245
- errors
3246
- };
3247
- };
3248
- const flush = async () => {
3249
- await options.traces.flush().catch(() => void 0);
3250
- await options.logs.flush().catch(() => void 0);
3251
- };
3252
- const shutdown = async () => {
3253
- await options.traces.shutdown().catch(() => void 0);
3254
- await options.logs.shutdown().catch(() => void 0);
3255
- };
3256
- return {
3257
- emit,
3258
- flush,
3259
- shutdown,
3260
- health: () => [
3261
- options.traces.health(),
3262
- options.logs.health()
3263
- ]
3264
- };
3265
- };
3266
- var shareCorrelationPerBatch = (correlate) => {
3267
- let pending;
3268
- return (events) => {
3269
- if (pending?.events === events) {
3270
- return pending.result;
3271
- }
3272
- const result = correlate(events);
3273
- pending = { events, result };
3274
- return result;
3275
- };
3276
- };
3277
-
3278
- // src/config/destinations.ts
3279
- import { z as z13 } from "zod";
3280
-
3281
- // src/config/header-value.ts
3282
- var isUnsafeHeaderValue = (value) => [...value].some((char) => {
3283
- const code = char.codePointAt(0) ?? 0;
3284
- return code < 32 && code !== 9 || code === 127 || code > 255;
3285
- });
3286
-
3287
- // src/config/otlp-headers.ts
3288
- var MAX_OTLP_HEADERS = 32;
3289
- var OTLP_HEADER_VARIABLES = Object.freeze({
3290
- generic: "OTEL_EXPORTER_OTLP_HEADERS",
3291
- traces: "OTEL_EXPORTER_OTLP_TRACES_HEADERS",
3292
- logs: "OTEL_EXPORTER_OTLP_LOGS_HEADERS"
3293
- });
3294
-
3295
- // src/config/destinations.ts
3296
- var DEFAULT_DESTINATION_NAME = "default";
3297
- var DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;
3298
- var MAX_EXPORT_DESTINATIONS = 16;
3299
- var MAX_DESTINATION_HEADERS = MAX_OTLP_HEADERS;
3300
- var HEADER_ENV_REFERENCE_PREFIX = "env:";
3301
- var HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
3302
- var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
3303
- var MAX_HEADER_VALUE_LENGTH = 8192;
3304
- var exportSignalSchema = z13.enum(["traces", "logs", "metrics"]);
3305
- var headerValueSchema = z13.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
3306
- (value) => !isUnsafeHeaderValue(value),
3307
- "header values may not contain line breaks, control characters, or characters beyond Latin-1"
3308
- ).refine(
3309
- (value) => !value.startsWith(HEADER_ENV_REFERENCE_PREFIX) || ENV_VARIABLE_NAME_PATTERN.test(value.slice(HEADER_ENV_REFERENCE_PREFIX.length)),
3310
- "an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN"
3311
- );
3312
- var endpointSchema = z13.string().url().max(2048);
3313
- var exportDestinationSchema = z13.strictObject({
3314
- /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */
3315
- name: z13.string().regex(DESTINATION_NAME_PATTERN, "destination names are lowercase letters, digits, _ and -"),
3316
- /** Default true. A disabled destination is neither sent to nor drained. */
3317
- enabled: z13.boolean().optional(),
3318
- /**
3319
- * Traces URL, with the same meaning as `exporter.endpoint`: the logs URL is
3320
- * derived from it (`/v1/traces` becomes `/v1/logs`) unless `logsEndpoint` is set.
3321
- */
3322
- endpoint: endpointSchema.optional(),
3323
- /** Per-signal override of `endpoint` for traces. */
3324
- tracesEndpoint: endpointSchema.optional(),
3325
- /** Per-signal override of the derived logs URL. */
3326
- logsEndpoint: endpointSchema.optional(),
3327
- /** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */
3328
- metricsEndpoint: endpointSchema.optional(),
3329
- /** Defaults to `exporter.protocol`. */
3330
- protocol: z13.enum(["http/protobuf", "http/json", "none"]).optional(),
3331
- /**
3332
- * Header name to value. A value of the form `env:NAME` is read from that
3333
- * environment variable at send time, so a credential never has to be written
3334
- * into the file. Values never appear in a snapshot, a diagnostic, or `doctor`.
3335
- */
3336
- headers: z13.record(z13.string().regex(HEADER_NAME_PATTERN, "not a valid header name"), headerValueSchema).refine(
3337
- (headers) => Object.keys(headers).length <= MAX_DESTINATION_HEADERS,
3338
- `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
3339
- ).optional(),
3340
- /**
3341
- * Which signals this destination receives. Default: traces and logs. The logs
3342
- * signal is still governed by `exporter.logs.enabled`, which stays the one
3343
- * opt-in for content-bearing records leaving the host. `metrics` is never on by
3344
- * default: a destination receives hook-derived metrics only when it lists them.
3345
- */
3346
- signals: z13.array(exportSignalSchema).min(1).max(3).readonly().optional()
3347
- }).refine(
3348
- (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
3349
- "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
3350
- );
3351
- var DEFAULT_DESTINATION_SIGNALS = Object.freeze(["traces", "logs"]);
3352
- var exportDestinationsSchema = z13.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
3353
- const seen = /* @__PURE__ */ new Set();
3354
- destinations.forEach((destination, index) => {
3355
- if (destination.name === DEFAULT_DESTINATION_NAME) {
3356
- context.addIssue({
3357
- code: "custom",
3358
- path: [index, "name"],
3359
- message: 'the name "default" is reserved for exporter.endpoint and the OTEL_EXPORTER_OTLP_* variables'
3360
- });
3361
- }
3362
- if (seen.has(destination.name)) {
3363
- context.addIssue({
3364
- code: "custom",
3365
- path: [index, "name"],
3366
- message: `duplicate destination name "${destination.name}"`
3367
- });
3368
- }
3369
- seen.add(destination.name);
3370
- });
3371
- });
3372
- var spoolPolicySchema = z13.strictObject({
3373
- /** Total bytes of queued batches. Default 16 MiB. */
3374
- maxBytes: z13.number().int().min(1024).max(1073741824),
3375
- /** A batch older than this is dropped instead of sent. Default 72 hours. */
3376
- maxAgeMillis: z13.number().int().min(1e3).max(30 * 24 * 60 * 60 * 1e3),
3377
- /** Number of queued batches. Default 500. */
3378
- maxBatches: z13.number().int().min(1).max(65536)
3379
- });
3380
- var DEFAULT_SPOOL_POLICY = Object.freeze({
3381
- maxBytes: 16 * 1024 * 1024,
3382
- maxAgeMillis: 72 * 60 * 60 * 1e3,
3383
- maxBatches: 500
3384
- });
3385
- var effectiveSpoolPolicy = (exporter) => ({
3386
- maxBytes: exporter.spool?.maxBytes ?? DEFAULT_SPOOL_POLICY.maxBytes,
3387
- maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,
3388
- maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches
3389
- });
3390
- var legacyDestination = (exporter) => ({
3391
- name: DEFAULT_DESTINATION_NAME,
3392
- source: "exporter",
3393
- protocol: exporter.protocol,
3394
- ...exporter.endpoint === void 0 ? {} : { endpoint: exporter.endpoint },
3395
- ...exporter.logs.endpoint === void 0 ? {} : { logsEndpoint: exporter.logs.endpoint },
3396
- ...exporter.metrics?.endpoint === void 0 ? {} : { metricsEndpoint: exporter.metrics.endpoint },
3397
- signals: { traces: true, logs: exporter.logs.enabled, metrics: exporter.metrics?.enabled === true },
3398
- headers: {}
3399
- });
3400
- var hasConfiguredDestinations = (exporter) => exporter.destinations !== void 0 && exporter.destinations.length > 0;
3401
- var resolveExportDestinations = (exporter) => {
3402
- if (!hasConfiguredDestinations(exporter)) {
3403
- return [legacyDestination(exporter)];
3404
- }
3405
- const resolved = [];
3406
- if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0 || exporter.metrics?.endpoint !== void 0) {
3407
- resolved.push(legacyDestination(exporter));
3408
- }
3409
- for (const destination of exporter.destinations ?? []) {
3410
- if (destination.enabled === false) {
3411
- continue;
3412
- }
3413
- const signals = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;
3414
- resolved.push({
3415
- name: destination.name,
3416
- source: "destinations",
3417
- protocol: destination.protocol ?? exporter.protocol,
3418
- ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
3419
- ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
3420
- ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
3421
- ...destination.metricsEndpoint === void 0 ? {} : { metricsEndpoint: destination.metricsEndpoint },
3422
- signals: {
3423
- traces: signals.includes("traces"),
3424
- logs: exporter.logs.enabled && signals.includes("logs"),
3425
- metrics: signals.includes("metrics")
3426
- },
3427
- headers: { ...destination.headers ?? {} }
3428
- });
3429
- }
3430
- return resolved;
3431
- };
3432
- var parseHeaderValueReference = (value) => value.startsWith(HEADER_ENV_REFERENCE_PREFIX) ? { kind: "env", variable: value.slice(HEADER_ENV_REFERENCE_PREFIX.length) } : { kind: "literal" };
3433
- var resolveDestinationHeaders = (headers, environment) => {
3434
- const values = {};
3435
- const missing = [];
3436
- for (const [name, value] of Object.entries(headers)) {
3437
- const reference = parseHeaderValueReference(value);
3438
- if (reference.kind === "literal") {
3439
- values[name] = value;
3440
- continue;
3917
+ };
3918
+ const drainSpool = async (maxBatches) => {
3919
+ if (options.spool === void 0) {
3920
+ return { drained: 0, remaining: 0, failed: 0 };
3441
3921
  }
3442
- const resolved = environment?.[reference.variable];
3443
- if (resolved === void 0 || resolved === "") {
3444
- missing.push(reference.variable);
3445
- continue;
3922
+ if (gate !== void 0 && !await gate.available()) {
3923
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
3446
3924
  }
3447
- values[name] = resolved;
3448
- }
3449
- return { values, missingVariables: [...new Set(missing)].sort() };
3925
+ const result = await options.spool.drain(sendSerializedBatch, {
3926
+ ...maxBatches === void 0 ? {} : { maxBatches }
3927
+ });
3928
+ if (result.drained > 0) {
3929
+ health.recordSuccess(result.drained, options.clock.now());
3930
+ }
3931
+ return result;
3932
+ };
3933
+ const flush = async () => {
3934
+ try {
3935
+ await exporter.forceFlush();
3936
+ } catch {
3937
+ }
3938
+ await drainSpool().catch(() => void 0);
3939
+ };
3940
+ const shutdown = async () => {
3941
+ if (shutdownCompleted) {
3942
+ return;
3943
+ }
3944
+ shutdownCompleted = true;
3945
+ await flush();
3946
+ try {
3947
+ await exporter.shutdown();
3948
+ } catch {
3949
+ }
3950
+ };
3951
+ return {
3952
+ emit,
3953
+ flush,
3954
+ shutdown,
3955
+ health: () => health.snapshot(),
3956
+ drainSpool
3957
+ };
3450
3958
  };
3451
3959
 
3452
- // src/config/schema.ts
3453
- import { isAbsolute } from "path";
3454
- import { z as z14 } from "zod";
3455
- var logsPolicySchema = z14.strictObject({
3456
- enabled: z14.boolean(),
3457
- /**
3458
- * Full URL for the logs signal.
3459
- *
3460
- * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes
3461
- * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.
3462
- */
3463
- endpoint: z14.string().url().max(2048).optional(),
3464
- includeContent: z14.boolean(),
3465
- maxBatchSize: z14.number().int().min(1).max(4096)
3466
- });
3467
- var DEFAULT_LOGS_POLICY = Object.freeze({
3468
- enabled: false,
3469
- includeContent: false,
3470
- maxBatchSize: 128
3471
- });
3472
- var metricsPolicySchema = z14.strictObject({
3473
- enabled: z14.boolean(),
3474
- /** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */
3475
- endpoint: z14.string().url().max(2048).optional(),
3476
- temporality: z14.enum(["cumulative", "delta"]),
3477
- includeSessionId: z14.boolean()
3478
- });
3479
- var DEFAULT_METRICS_POLICY = Object.freeze({
3480
- enabled: false,
3481
- temporality: "cumulative",
3482
- includeSessionId: true
3483
- });
3484
- var exporterPolicySchema = z14.strictObject({
3485
- enabled: z14.boolean(),
3486
- protocol: z14.enum(["http/protobuf", "http/json", "none"]),
3487
- endpoint: z14.string().url().max(2048).optional(),
3488
- /**
3489
- * Header names only. Values are supplied separately at construction time and
3490
- * are never part of a resolved-config snapshot, which is logged and exported.
3491
- */
3492
- headerNames: z14.array(nonEmptyStringSchema).max(32).readonly(),
3493
- timeoutMillis: z14.number().int().min(1).max(6e5),
3494
- maxBatchSize: z14.number().int().min(1).max(4096),
3495
- maxQueueSize: z14.number().int().min(1).max(65536),
3496
- maxRetryAttempts: z14.number().int().min(0).max(10),
3497
- serviceName: nonEmptyStringSchema,
3498
- serviceNamespace: nonEmptyStringSchema.optional(),
3499
- /**
3500
- * Custom attributes merged into the exported OTLP Resource.
3501
- *
3502
- * Bounded and validated, and refusing `service.name`/`service.namespace`,
3503
- * which are the two fields above. Distinct from an invocation's
3504
- * `consumerAttributes`: this describes the emitting deployment, carries no
3505
- * identity, and is the same for every span this process exports.
3506
- */
3507
- resourceAttributes: resourceAttributesSchema,
3508
- /**
3509
- * The logs signal. Nested under the exporter because it shares the endpoint,
3510
- * headers, timeout, protocol, service identity, and resource attributes above —
3511
- * a second top-level section would invite two of each to drift apart.
3512
- */
3513
- logs: logsPolicySchema,
3514
- /**
3515
- * Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before
3516
- * metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.
3517
- */
3518
- metrics: metricsPolicySchema.optional(),
3519
- /**
3520
- * Additional OTLP destinations, each sent every batch in parallel.
3521
- *
3522
- * Absent (the default), the exporter has exactly one destination — the
3523
- * single-endpoint settings above, named `default` — and behaves exactly as it
3524
- * did before this list existed. See `destinations.ts`.
3525
- *
3526
- * Merged as one leaf: a higher layer that sets the list replaces it whole,
3527
- * because "the union of two partial lists" has no answer an operator could
3528
- * predict.
3529
- */
3530
- destinations: exportDestinationsSchema.optional(),
3531
- /**
3532
- * Per-destination retry spool bounds, each optional and merged per leaf; any
3533
- * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.
3534
- */
3535
- spool: spoolPolicySchema.partial().optional()
3536
- });
3537
- var detectionPolicySchema = z14.strictObject({
3538
- /** Detections below this confidence resolve to the unknown provider. */
3539
- minimumConfidence: detectionConfidenceSchema,
3540
- /** When false, an ambiguous detection is an error rather than unknown. */
3541
- allowAmbiguousFallback: z14.boolean(),
3542
- /** Optional allow-list of provider ids; empty means "any registered". */
3543
- allowedProviderIds: z14.array(nonEmptyStringSchema).max(32).readonly()
3544
- });
3545
- var diagnosticsPolicySchema = z14.strictObject({
3546
- logLevel: z14.enum(["silent", "error", "warn", "info", "debug"]),
3547
- /** Emit `error.raised` events for contained failures. */
3548
- emitErrorEvents: z14.boolean()
3549
- });
3550
- var providersPolicySchema = z14.strictObject({
3551
- claudeCode: z14.strictObject({
3552
- readTranscriptUsage: z14.boolean()
3553
- }).optional()
3554
- });
3555
- var sessionContextPolicySchema = z14.strictObject({
3556
- /** Absolute path of the context directory. */
3557
- dir: z14.string().min(1).max(4096).refine((value) => isAbsolute(value), { message: "must be an absolute path" })
3558
- });
3559
- var otelHookConfigSchema = z14.strictObject({
3560
- exporter: exporterPolicySchema,
3561
- privacy: privacyPolicySchema,
3562
- detection: detectionPolicySchema,
3563
- diagnostics: diagnosticsPolicySchema,
3564
- /** Optional so a hand-built configuration from before it existed stays valid. */
3565
- providers: providersPolicySchema.optional(),
3566
- /** Optional: absent means no session context is read. */
3567
- sessionContext: sessionContextPolicySchema.optional()
3568
- });
3569
- var otelHookConfigPatchSchema = z14.strictObject({
3570
- // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
3571
- // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
3572
- // without also restating the endpoint and the batch size.
3573
- exporter: exporterPolicySchema.omit({ logs: true, metrics: true, spool: true }).partial().extend({
3574
- logs: logsPolicySchema.partial().optional(),
3575
- metrics: metricsPolicySchema.partial().optional(),
3576
- spool: spoolPolicySchema.partial().optional()
3577
- }).optional(),
3578
- privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
3579
- detection: detectionPolicySchema.partial().optional(),
3580
- diagnostics: diagnosticsPolicySchema.partial().optional(),
3581
- providers: z14.strictObject({
3582
- claudeCode: z14.strictObject({ readTranscriptUsage: z14.boolean() }).partial().optional()
3583
- }).partial().optional(),
3584
- sessionContext: sessionContextPolicySchema.partial().optional()
3585
- });
3586
- var DEFAULT_EXPORTER_POLICY = Object.freeze({
3587
- enabled: true,
3588
- protocol: "http/protobuf",
3589
- headerNames: Object.freeze([]),
3590
- timeoutMillis: 1e4,
3591
- maxBatchSize: 128,
3592
- maxQueueSize: 2048,
3593
- maxRetryAttempts: 2,
3594
- serviceName: "coding-agent",
3595
- resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
3596
- logs: DEFAULT_LOGS_POLICY,
3597
- metrics: DEFAULT_METRICS_POLICY
3598
- });
3599
- var DEFAULT_DETECTION_POLICY = Object.freeze({
3600
- minimumConfidence: "strong",
3601
- allowAmbiguousFallback: true,
3602
- allowedProviderIds: Object.freeze([])
3603
- });
3604
- var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
3605
- logLevel: "warn",
3606
- emitErrorEvents: true
3607
- });
3608
- var DEFAULT_PROVIDERS_POLICY = Object.freeze({
3609
- claudeCode: Object.freeze({ readTranscriptUsage: false })
3610
- });
3611
- var DEFAULT_CONFIG = Object.freeze({
3612
- exporter: DEFAULT_EXPORTER_POLICY,
3613
- privacy: DEFAULT_PRIVACY_POLICY,
3614
- detection: DEFAULT_DETECTION_POLICY,
3615
- diagnostics: DEFAULT_DIAGNOSTICS_POLICY,
3616
- providers: DEFAULT_PROVIDERS_POLICY
3617
- });
3618
- var effectiveMetricsPolicy = (exporter) => ({
3619
- ...DEFAULT_METRICS_POLICY,
3620
- ...exporter.metrics ?? {}
3621
- });
3960
+ // src/telemetry/signal-fanout.ts
3961
+ var createSignalFanout = (options) => {
3962
+ const emit = async (events) => {
3963
+ const traces = await options.traces.emit(events);
3964
+ const logs = await options.logs.emit(events);
3965
+ const errors = [...traces.errors, ...logs.errors];
3966
+ return {
3967
+ accepted: traces.accepted + logs.accepted,
3968
+ rejected: traces.rejected + logs.rejected,
3969
+ errors
3970
+ };
3971
+ };
3972
+ const flush = async () => {
3973
+ await options.traces.flush().catch(() => void 0);
3974
+ await options.logs.flush().catch(() => void 0);
3975
+ };
3976
+ const shutdown = async () => {
3977
+ await options.traces.shutdown().catch(() => void 0);
3978
+ await options.logs.shutdown().catch(() => void 0);
3979
+ };
3980
+ return {
3981
+ emit,
3982
+ flush,
3983
+ shutdown,
3984
+ health: () => [
3985
+ options.traces.health(),
3986
+ options.logs.health()
3987
+ ]
3988
+ };
3989
+ };
3990
+ var shareCorrelationPerBatch = (correlate) => {
3991
+ let pending;
3992
+ return (events) => {
3993
+ if (pending?.events === events) {
3994
+ return pending.result;
3995
+ }
3996
+ const result = correlate(events);
3997
+ pending = { events, result };
3998
+ return result;
3999
+ };
4000
+ };
3622
4001
 
3623
4002
  // src/telemetry/metric-model.ts
3624
4003
  var TOKEN_USAGE_BUCKETS = Object.freeze([
@@ -3977,7 +4356,7 @@ var createFileDurableMetricSpool = (options) => createSpoolQueue({
3977
4356
 
3978
4357
  // src/telemetry/otlp-metric-sink.ts
3979
4358
  import { ValueType } from "@opentelemetry/api";
3980
- import { ExportResultCode as ExportResultCode3, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
4359
+ import { ExportResultCode as ExportResultCode4, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
3981
4360
  import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
3982
4361
  import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
3983
4362
  import {
@@ -4121,10 +4500,12 @@ var createOtlpMetricSink = (options) => {
4121
4500
  const exporter = new OTLPMetricExporter({
4122
4501
  url: deliverability.endpoint,
4123
4502
  headers: { ...options.headers },
4124
- timeoutMillis: options.exporter.timeoutMillis
4503
+ ...boundedExporterOptions(options.exporter)
4125
4504
  });
4505
+ const gate = options.endpointHealth?.gateFor(deliverability.endpoint);
4126
4506
  let shutdownCompleted = false;
4127
- const exportResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve) => {
4507
+ const exportResourceMetrics = (points, batchResource, batchScope) => guardExport(gate, () => sendResourceMetrics(points, batchResource, batchScope));
4508
+ const sendResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve) => {
4128
4509
  const payload = {
4129
4510
  resource: batchResource,
4130
4511
  scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }]
@@ -4133,7 +4514,7 @@ var createOtlpMetricSink = (options) => {
4133
4514
  exporter.export(payload, (result) => resolve(result));
4134
4515
  } catch (thrown) {
4135
4516
  resolve({
4136
- code: ExportResultCode3.FAILED,
4517
+ code: ExportResultCode4.FAILED,
4137
4518
  error: thrown instanceof Error ? thrown : new Error("export threw")
4138
4519
  });
4139
4520
  }
@@ -4154,7 +4535,7 @@ var createOtlpMetricSink = (options) => {
4154
4535
  withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes)
4155
4536
  );
4156
4537
  const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);
4157
- if (result.code === ExportResultCode3.SUCCESS) {
4538
+ if (result.code === ExportResultCode4.SUCCESS) {
4158
4539
  return true;
4159
4540
  }
4160
4541
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -4165,7 +4546,7 @@ var createOtlpMetricSink = (options) => {
4165
4546
  }
4166
4547
  const batchResource = context === void 0 ? resource : resourceWithContext(resource, context);
4167
4548
  const result = await exportResourceMetrics(points, batchResource, scope);
4168
- if (result.code === ExportResultCode3.SUCCESS) {
4549
+ if (result.code === ExportResultCode4.SUCCESS) {
4169
4550
  health.recordSuccess(points.length, options.clock.now());
4170
4551
  return { accepted: points.length, rejected: 0, errors: [] };
4171
4552
  }
@@ -4205,6 +4586,9 @@ var createOtlpMetricSink = (options) => {
4205
4586
  if (options.spool === void 0) {
4206
4587
  return { drained: 0, remaining: 0, failed: 0 };
4207
4588
  }
4589
+ if (gate !== void 0 && !await gate.available()) {
4590
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
4591
+ }
4208
4592
  const result = await options.spool.drain(sendSerializedBatch, {
4209
4593
  ...maxBatches === void 0 ? {} : { maxBatches }
4210
4594
  });
@@ -4300,6 +4684,13 @@ var createExportDestinationSinks = (options) => {
4300
4684
  const spoolPolicy = effectiveSpoolPolicy(options.exporter);
4301
4685
  const destinations = [];
4302
4686
  const skipped = [];
4687
+ const endpointHealth = options.endpointHealth ?? createEndpointHealth({
4688
+ ...options.spoolRootDir === void 0 ? {} : { rootDir: options.spoolRootDir },
4689
+ clock: options.clock,
4690
+ ...options.logger === void 0 ? {} : { logger: options.logger },
4691
+ ...options.exporter.endpointDownMillis === void 0 ? {} : { downMillis: options.exporter.endpointDownMillis },
4692
+ probeMillis: effectiveExportTimeoutMillis(options.exporter) + 1e3
4693
+ });
4303
4694
  for (const destination of resolveExportDestinations(options.exporter)) {
4304
4695
  let headers;
4305
4696
  let logHeaders;
@@ -4359,6 +4750,7 @@ var createExportDestinationSinks = (options) => {
4359
4750
  const sinkShared = {
4360
4751
  exporter: policy,
4361
4752
  ...shared,
4753
+ endpointHealth,
4362
4754
  ...options.correlate === void 0 ? {} : { correlate: options.correlate },
4363
4755
  ...label === void 0 ? {} : { destination: label }
4364
4756
  };
@@ -4376,6 +4768,7 @@ var createExportDestinationSinks = (options) => {
4376
4768
  const metrics = destination.signals.metrics ? createOtlpMetricSink({
4377
4769
  exporter: policy,
4378
4770
  ...shared,
4771
+ endpointHealth,
4379
4772
  ...label === void 0 ? {} : { destination: label },
4380
4773
  ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
4381
4774
  ...metricSpool === void 0 ? {} : { spool: metricSpool }