@osfactory/otel-hook 0.13.1 → 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.
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.13.2";
22
22
 
23
23
  // src/telemetry/export-identity.ts
24
24
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -1431,7 +1431,7 @@ var canonicalEventsToReadableSpans = (events, options) => {
1431
1431
 
1432
1432
  // src/telemetry/spool-queue.ts
1433
1433
  import { randomBytes } from "crypto";
1434
- import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "fs/promises";
1434
+ import { mkdir, open, readFile, readdir, rename, stat, unlink, writeFile } from "fs/promises";
1435
1435
  import * as path from "path";
1436
1436
 
1437
1437
  // src/state/keys.ts
@@ -1508,7 +1508,8 @@ var readSpoolQueueStats = async (queueDir) => {
1508
1508
  };
1509
1509
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
1510
1510
  var SPOOL_CLAIM_STALE_MILLIS = 5 * 60 * 1e3;
1511
- var CLAIM_MARKER = ".claimed-";
1511
+ var CLAIM_SUFFIX = ".claim";
1512
+ var RELEASING_SUFFIX = ".releasing";
1512
1513
  var isClaimOwnerAlive = (pid) => {
1513
1514
  if (!Number.isSafeInteger(pid) || pid <= 0) {
1514
1515
  return true;
@@ -1524,6 +1525,34 @@ var isClaimOwnerAlive = (pid) => {
1524
1525
  }
1525
1526
  };
1526
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
+ };
1527
1556
  var createSpoolQueue = (options) => {
1528
1557
  const [providerSegment, installationSegment] = namespaceSegments(options);
1529
1558
  const queueDir = path.join(options.rootDir, providerSegment, installationSegment, options.queueName);
@@ -1672,6 +1701,19 @@ var createSpoolQueue = (options) => {
1672
1701
  await rename(tmp, target);
1673
1702
  return { spooled: true };
1674
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
+ };
1675
1717
  const releaseStaleClaims = async () => {
1676
1718
  let entries;
1677
1719
  try {
@@ -1681,18 +1723,35 @@ var createSpoolQueue = (options) => {
1681
1723
  }
1682
1724
  const now = Date.now();
1683
1725
  for (const entry of entries) {
1684
- const marker = entry.lastIndexOf(CLAIM_MARKER);
1685
- if (marker <= 0) {
1686
- continue;
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
+ }
1687
1739
  }
1688
- const claimPath = path.join(queueDir, entry);
1689
- const owner = Number.parseInt(entry.slice(marker + CLAIM_MARKER.length), 10);
1740
+ }
1741
+ };
1742
+ const claimBatch = async (claimPath) => {
1743
+ const token = randomBytes(16).toString("hex");
1744
+ try {
1745
+ const handle = await open(claimPath, "wx");
1690
1746
  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 {
1747
+ const contents = { token, pid: process.pid, claimedAt: Date.now() };
1748
+ await handle.writeFile(JSON.stringify(contents), "utf8");
1749
+ } finally {
1750
+ await handle.close();
1695
1751
  }
1752
+ return token;
1753
+ } catch {
1754
+ return void 0;
1696
1755
  }
1697
1756
  };
1698
1757
  const drain = async (send, drainOptions) => {
@@ -1716,21 +1775,7 @@ var createSpoolQueue = (options) => {
1716
1775
  let failed = 0;
1717
1776
  let quarantined = 0;
1718
1777
  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
- }
1778
+ const sendClaimed = async (fileName, filePath, claimPath, token) => {
1734
1779
  const quarantine = async (rejection) => {
1735
1780
  quarantined += 1;
1736
1781
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -1749,17 +1794,17 @@ var createSpoolQueue = (options) => {
1749
1794
  text = await readFile(filePath, "utf8");
1750
1795
  } catch (thrown) {
1751
1796
  if (thrown?.code === "ENOENT") {
1752
- continue;
1797
+ return "next";
1753
1798
  }
1754
1799
  await quarantine("unreadable");
1755
- continue;
1800
+ return "next";
1756
1801
  }
1757
1802
  let parsed;
1758
1803
  try {
1759
1804
  parsed = JSON.parse(text);
1760
1805
  } catch {
1761
1806
  await quarantine("unparseable-json");
1762
- continue;
1807
+ return "next";
1763
1808
  }
1764
1809
  const validation = options.validate(parsed, {
1765
1810
  providerId: options.providerId,
@@ -1767,7 +1812,10 @@ var createSpoolQueue = (options) => {
1767
1812
  });
1768
1813
  if ("rejection" in validation) {
1769
1814
  await quarantine(validation.rejection);
1770
- continue;
1815
+ return "next";
1816
+ }
1817
+ if ((await readClaim(claimPath))?.token !== token) {
1818
+ return "next";
1771
1819
  }
1772
1820
  let delivered;
1773
1821
  try {
@@ -1779,14 +1827,34 @@ var createSpoolQueue = (options) => {
1779
1827
  if (await unlink(filePath).then(() => true, () => false)) {
1780
1828
  await recordDrops("rejected", 1);
1781
1829
  }
1782
- continue;
1830
+ return "next";
1783
1831
  }
1784
1832
  if (delivered) {
1785
1833
  await unlink(filePath).catch(() => void 0);
1786
1834
  drained += 1;
1787
- } else {
1788
- await rename(filePath, queuedPath).catch(() => void 0);
1789
- 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") {
1790
1858
  break;
1791
1859
  }
1792
1860
  }
@@ -1900,7 +1968,7 @@ var createFileDurableSpool = (options) => createSpoolQueue({
1900
1968
  });
1901
1969
 
1902
1970
  // src/telemetry/otlp-sink.ts
1903
- import { ExportResultCode } from "@opentelemetry/core";
1971
+ import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
1904
1972
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
1905
1973
 
1906
1974
  // src/errors/index.ts
@@ -2010,11 +2078,17 @@ var isPermanentExportFailure = (result) => {
2010
2078
  return typeof code === "number" && Number.isInteger(code) && code >= 400 && code < 600 && !RETRYABLE_HTTP_STATUSES.has(code);
2011
2079
  };
2012
2080
 
2013
- // src/telemetry/exporter-resource.ts
2014
- 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";
2015
2088
 
2016
- // src/config/resource-attributes.ts
2017
- import { z as z12 } from "zod";
2089
+ // src/config/schema.ts
2090
+ import { isAbsolute } from "path";
2091
+ import { z as z14 } from "zod";
2018
2092
 
2019
2093
  // src/privacy/policy.ts
2020
2094
  import { z as z11 } from "zod";
@@ -2093,7 +2167,182 @@ var DEFAULT_PRIVACY_POLICY = Object.freeze({
2093
2167
  limits: DEFAULT_PRIVACY_LIMITS
2094
2168
  });
2095
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
+
2096
2344
  // src/config/resource-attributes.ts
2345
+ import { z as z13 } from "zod";
2097
2346
  var MAX_RESOURCE_ATTRIBUTES = 64;
2098
2347
  var MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH = 255;
2099
2348
  var MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH = 2048;
@@ -2138,12 +2387,12 @@ var checkResourceAttributeKey = (key) => {
2138
2387
  }
2139
2388
  return void 0;
2140
2389
  };
2141
- var resourceAttributeValueSchema = z12.union([
2142
- z12.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),
2143
- z12.number().finite(),
2144
- z12.boolean()
2390
+ var resourceAttributeValueSchema = z13.union([
2391
+ z13.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),
2392
+ z13.number().finite(),
2393
+ z13.boolean()
2145
2394
  ]);
2146
- var resourceAttributesSchema = z12.record(z12.string(), resourceAttributeValueSchema).superRefine((value, ctx) => {
2395
+ var resourceAttributesSchema = z13.record(z13.string(), resourceAttributeValueSchema).superRefine((value, ctx) => {
2147
2396
  const keys = Object.keys(value);
2148
2397
  if (keys.length > MAX_RESOURCE_ATTRIBUTES) {
2149
2398
  ctx.addIssue({
@@ -2172,12 +2421,410 @@ var sanitizeResourceAttributes = (attributes) => {
2172
2421
  if (Object.keys(safe).length >= MAX_RESOURCE_ATTRIBUTES) {
2173
2422
  break;
2174
2423
  }
2175
- 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();
2176
2814
  }
2177
- 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;
2178
2824
  };
2179
2825
 
2180
2826
  // src/telemetry/exporter-resource.ts
2827
+ import { resourceFromAttributes } from "@opentelemetry/resources";
2181
2828
  var resourceFromExporterPolicy = (policy) => resourceFromAttributes({
2182
2829
  ...sanitizeResourceAttributes(policy.resourceAttributes),
2183
2830
  "service.name": policy.serviceName,
@@ -2315,12 +2962,16 @@ var createOtlpTraceSink = (options) => {
2315
2962
  const exporter = new OTLPTraceExporter({
2316
2963
  url: options.exporter.endpoint,
2317
2964
  headers: { ...options.headers },
2318
- timeoutMillis: options.exporter.timeoutMillis
2965
+ ...boundedExporterOptions(options.exporter)
2319
2966
  });
2967
+ const gate = options.endpointHealth?.gateFor(options.exporter.endpoint);
2320
2968
  let shutdownCompleted = false;
2321
- const exportSpans = (spans) => new Promise((resolve) => {
2322
- exporter.export([...spans], (result) => resolve(result));
2323
- });
2969
+ const exportSpans = (spans) => guardExport(
2970
+ gate,
2971
+ () => new Promise((resolve) => {
2972
+ exporter.export([...spans], (result) => resolve(result));
2973
+ })
2974
+ );
2324
2975
  const toSpoolBatch = (spans, batchResource) => ({
2325
2976
  providerId: options.providerId,
2326
2977
  installationId: options.installationId,
@@ -2333,7 +2984,7 @@ var createOtlpTraceSink = (options) => {
2333
2984
  const batchResource = replayResource(batch.resourceAttributes, options.exporter);
2334
2985
  const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));
2335
2986
  const result = await exportSpans(spans);
2336
- if (result.code === ExportResultCode.SUCCESS) {
2987
+ if (result.code === ExportResultCode2.SUCCESS) {
2337
2988
  return true;
2338
2989
  }
2339
2990
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -2372,9 +3023,9 @@ var createOtlpTraceSink = (options) => {
2372
3023
  try {
2373
3024
  result = await exportSpans(batch);
2374
3025
  } catch (thrown) {
2375
- 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") };
2376
3027
  }
2377
- if (result.code === ExportResultCode.SUCCESS) {
3028
+ if (result.code === ExportResultCode2.SUCCESS) {
2378
3029
  accepted += batch.length;
2379
3030
  health.recordSuccess(batch.length, options.clock.now());
2380
3031
  continue;
@@ -2411,6 +3062,9 @@ var createOtlpTraceSink = (options) => {
2411
3062
  if (options.spool === void 0) {
2412
3063
  return { drained: 0, remaining: 0, failed: 0 };
2413
3064
  }
3065
+ if (gate !== void 0 && !await gate.available()) {
3066
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
3067
+ }
2414
3068
  const result = await options.spool.drain(sendSerializedBatch, { ...maxBatches === void 0 ? {} : { maxBatches } });
2415
3069
  if (result.drained > 0) {
2416
3070
  health.recordSuccess(result.drained, options.clock.now());
@@ -2968,7 +3622,7 @@ var createFileDurableLogSpool = (options) => createSpoolQueue({
2968
3622
 
2969
3623
  // src/telemetry/otlp-log-sink.ts
2970
3624
  import { TraceFlags as TraceFlags3 } from "@opentelemetry/api";
2971
- import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
3625
+ import { ExportResultCode as ExportResultCode3 } from "@opentelemetry/core";
2972
3626
  import { millisToHrTime as millisToHrTime3 } from "@opentelemetry/core";
2973
3627
  import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
2974
3628
 
@@ -3147,12 +3801,16 @@ var createOtlpLogSink = (options) => {
3147
3801
  const exporter = new OTLPLogExporter({
3148
3802
  url: deliverability.endpoint,
3149
3803
  headers: { ...options.headers },
3150
- timeoutMillis: options.exporter.timeoutMillis
3804
+ ...boundedExporterOptions(options.exporter)
3151
3805
  });
3806
+ const gate = options.endpointHealth?.gateFor(deliverability.endpoint);
3152
3807
  let shutdownCompleted = false;
3153
- const exportRecords = (records) => new Promise((resolve) => {
3154
- exporter.export([...records], (result) => resolve(result));
3155
- });
3808
+ const exportRecords = (records) => guardExport(
3809
+ gate,
3810
+ () => new Promise((resolve) => {
3811
+ exporter.export([...records], (result) => resolve(result));
3812
+ })
3813
+ );
3156
3814
  const toSpoolBatch = (records, batchResource) => ({
3157
3815
  providerId: options.providerId,
3158
3816
  installationId: options.installationId,
@@ -3170,7 +3828,7 @@ var createOtlpLogSink = (options) => {
3170
3828
  (record) => deserializeRecord(record, batchResource, batch.instrumentationScope)
3171
3829
  );
3172
3830
  const result = await exportRecords(records);
3173
- if (result.code === ExportResultCode2.SUCCESS) {
3831
+ if (result.code === ExportResultCode3.SUCCESS) {
3174
3832
  return true;
3175
3833
  }
3176
3834
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -3216,11 +3874,11 @@ var createOtlpLogSink = (options) => {
3216
3874
  result = await exportRecords(batch);
3217
3875
  } catch (thrown) {
3218
3876
  result = {
3219
- code: ExportResultCode2.FAILED,
3877
+ code: ExportResultCode3.FAILED,
3220
3878
  error: thrown instanceof Error ? thrown : new Error("export threw")
3221
3879
  };
3222
3880
  }
3223
- if (result.code === ExportResultCode2.SUCCESS) {
3881
+ if (result.code === ExportResultCode3.SUCCESS) {
3224
3882
  accepted += batch.length;
3225
3883
  health.recordSuccess(batch.length, options.clock.now());
3226
3884
  continue;
@@ -3256,432 +3914,90 @@ var createOtlpLogSink = (options) => {
3256
3914
  );
3257
3915
  }
3258
3916
  return { accepted, rejected, errors };
3259
- };
3260
- const drainSpool = async (maxBatches) => {
3261
- if (options.spool === void 0) {
3262
- return { drained: 0, remaining: 0, failed: 0 };
3263
- }
3264
- const result = await options.spool.drain(sendSerializedBatch, {
3265
- ...maxBatches === void 0 ? {} : { maxBatches }
3266
- });
3267
- if (result.drained > 0) {
3268
- health.recordSuccess(result.drained, options.clock.now());
3269
- }
3270
- return result;
3271
- };
3272
- const flush = async () => {
3273
- try {
3274
- await exporter.forceFlush();
3275
- } catch {
3276
- }
3277
- await drainSpool().catch(() => void 0);
3278
- };
3279
- const shutdown = async () => {
3280
- if (shutdownCompleted) {
3281
- return;
3282
- }
3283
- shutdownCompleted = true;
3284
- await flush();
3285
- try {
3286
- await exporter.shutdown();
3287
- } catch {
3288
- }
3289
- };
3290
- return {
3291
- emit,
3292
- flush,
3293
- shutdown,
3294
- health: () => health.snapshot(),
3295
- drainSpool
3296
- };
3297
- };
3298
-
3299
- // src/telemetry/signal-fanout.ts
3300
- var createSignalFanout = (options) => {
3301
- const emit = async (events) => {
3302
- const traces = await options.traces.emit(events);
3303
- const logs = await options.logs.emit(events);
3304
- const errors = [...traces.errors, ...logs.errors];
3305
- return {
3306
- accepted: traces.accepted + logs.accepted,
3307
- rejected: traces.rejected + logs.rejected,
3308
- 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;
3494
- };
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;
3917
+ };
3918
+ const drainSpool = async (maxBatches) => {
3919
+ if (options.spool === void 0) {
3920
+ return { drained: 0, remaining: 0, failed: 0 };
3504
3921
  }
3505
- const resolved = environment?.[reference.variable];
3506
- if (resolved === void 0 || resolved === "") {
3507
- missing.push(reference.variable);
3508
- continue;
3922
+ if (gate !== void 0 && !await gate.available()) {
3923
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
3509
3924
  }
3510
- values[name] = resolved;
3511
- }
3512
- 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
+ };
3513
3958
  };
3514
3959
 
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
- });
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
+ };
3685
4001
 
3686
4002
  // src/telemetry/metric-model.ts
3687
4003
  var TOKEN_USAGE_BUCKETS = Object.freeze([
@@ -4040,7 +4356,7 @@ var createFileDurableMetricSpool = (options) => createSpoolQueue({
4040
4356
 
4041
4357
  // src/telemetry/otlp-metric-sink.ts
4042
4358
  import { ValueType } from "@opentelemetry/api";
4043
- import { ExportResultCode as ExportResultCode3, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
4359
+ import { ExportResultCode as ExportResultCode4, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
4044
4360
  import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
4045
4361
  import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
4046
4362
  import {
@@ -4184,10 +4500,12 @@ var createOtlpMetricSink = (options) => {
4184
4500
  const exporter = new OTLPMetricExporter({
4185
4501
  url: deliverability.endpoint,
4186
4502
  headers: { ...options.headers },
4187
- timeoutMillis: options.exporter.timeoutMillis
4503
+ ...boundedExporterOptions(options.exporter)
4188
4504
  });
4505
+ const gate = options.endpointHealth?.gateFor(deliverability.endpoint);
4189
4506
  let shutdownCompleted = false;
4190
- 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) => {
4191
4509
  const payload = {
4192
4510
  resource: batchResource,
4193
4511
  scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }]
@@ -4196,7 +4514,7 @@ var createOtlpMetricSink = (options) => {
4196
4514
  exporter.export(payload, (result) => resolve(result));
4197
4515
  } catch (thrown) {
4198
4516
  resolve({
4199
- code: ExportResultCode3.FAILED,
4517
+ code: ExportResultCode4.FAILED,
4200
4518
  error: thrown instanceof Error ? thrown : new Error("export threw")
4201
4519
  });
4202
4520
  }
@@ -4217,7 +4535,7 @@ var createOtlpMetricSink = (options) => {
4217
4535
  withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes)
4218
4536
  );
4219
4537
  const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);
4220
- if (result.code === ExportResultCode3.SUCCESS) {
4538
+ if (result.code === ExportResultCode4.SUCCESS) {
4221
4539
  return true;
4222
4540
  }
4223
4541
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -4228,7 +4546,7 @@ var createOtlpMetricSink = (options) => {
4228
4546
  }
4229
4547
  const batchResource = context === void 0 ? resource : resourceWithContext(resource, context);
4230
4548
  const result = await exportResourceMetrics(points, batchResource, scope);
4231
- if (result.code === ExportResultCode3.SUCCESS) {
4549
+ if (result.code === ExportResultCode4.SUCCESS) {
4232
4550
  health.recordSuccess(points.length, options.clock.now());
4233
4551
  return { accepted: points.length, rejected: 0, errors: [] };
4234
4552
  }
@@ -4268,6 +4586,9 @@ var createOtlpMetricSink = (options) => {
4268
4586
  if (options.spool === void 0) {
4269
4587
  return { drained: 0, remaining: 0, failed: 0 };
4270
4588
  }
4589
+ if (gate !== void 0 && !await gate.available()) {
4590
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
4591
+ }
4271
4592
  const result = await options.spool.drain(sendSerializedBatch, {
4272
4593
  ...maxBatches === void 0 ? {} : { maxBatches }
4273
4594
  });
@@ -4363,6 +4684,13 @@ var createExportDestinationSinks = (options) => {
4363
4684
  const spoolPolicy = effectiveSpoolPolicy(options.exporter);
4364
4685
  const destinations = [];
4365
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
+ });
4366
4694
  for (const destination of resolveExportDestinations(options.exporter)) {
4367
4695
  let headers;
4368
4696
  let logHeaders;
@@ -4422,6 +4750,7 @@ var createExportDestinationSinks = (options) => {
4422
4750
  const sinkShared = {
4423
4751
  exporter: policy,
4424
4752
  ...shared,
4753
+ endpointHealth,
4425
4754
  ...options.correlate === void 0 ? {} : { correlate: options.correlate },
4426
4755
  ...label === void 0 ? {} : { destination: label }
4427
4756
  };
@@ -4439,6 +4768,7 @@ var createExportDestinationSinks = (options) => {
4439
4768
  const metrics = destination.signals.metrics ? createOtlpMetricSink({
4440
4769
  exporter: policy,
4441
4770
  ...shared,
4771
+ endpointHealth,
4442
4772
  ...label === void 0 ? {} : { destination: label },
4443
4773
  ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
4444
4774
  ...metricSpool === void 0 ? {} : { spool: metricSpool }