@osfactory/otel-hook 0.13.1 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +94 -3
  2. package/dist/{adapter-DyCb7y1N.d.ts → adapter-D5R8lhfl.d.ts} +1 -1
  3. package/dist/cli.js +1240 -200
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +32 -4
  6. package/dist/config.js +200 -14
  7. package/dist/config.js.map +1 -1
  8. package/dist/{destinations-DvqsPulb.d.ts → destinations-2KrcRslo.d.ts} +92 -2
  9. package/dist/{export-destinations-DUeQKr_C.d.ts → export-destinations-DvoH4QOe.d.ts} +135 -11
  10. package/dist/{hook-D5imE0Qc.d.ts → hook-DVK8Don-.d.ts} +4 -4
  11. package/dist/index.d.ts +11 -11
  12. package/dist/index.js +1262 -228
  13. package/dist/index.js.map +1 -1
  14. package/dist/install.d.ts +3 -3
  15. package/dist/install.js +1 -0
  16. package/dist/install.js.map +1 -1
  17. package/dist/integration.d.ts +16 -9
  18. package/dist/integration.js +1298 -205
  19. package/dist/integration.js.map +1 -1
  20. package/dist/lifecycle.js +1 -1
  21. package/dist/lifecycle.js.map +1 -1
  22. package/dist/{payload-CdDKeRpH.d.ts → payload-D4r71EL-.d.ts} +18 -2
  23. package/dist/privacy.d.ts +2 -2
  24. package/dist/privacy.js +42 -1
  25. package/dist/privacy.js.map +1 -1
  26. package/dist/providers.d.ts +94 -9
  27. package/dist/providers.js +300 -2
  28. package/dist/providers.js.map +1 -1
  29. package/dist/{registry-BKQhhIO3.d.ts → registry-DOJh9mzB.d.ts} +2 -2
  30. package/dist/runtime.d.ts +5 -5
  31. package/dist/runtime.js +151 -5
  32. package/dist/runtime.js.map +1 -1
  33. package/dist/{schema-SpFM6YQY.d.ts → schema-oRsbo7WO.d.ts} +77 -3
  34. package/dist/{service-CbI9CObT.d.ts → service-DySC7KQM.d.ts} +6 -1
  35. package/dist/telemetry.d.ts +5 -4
  36. package/dist/telemetry.js +1076 -476
  37. package/dist/telemetry.js.map +1 -1
  38. package/dist/testing.d.ts +5 -5
  39. package/dist/testing.js +178 -21
  40. package/dist/testing.js.map +1 -1
  41. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1143,6 +1143,23 @@ var resolvePrivacyPolicy = (policy) => {
1143
1143
 
1144
1144
  // src/privacy/service.ts
1145
1145
  import { createHash } from "crypto";
1146
+ var DISCLOSURE_RANK = Object.freeze({
1147
+ omitted: 0,
1148
+ masked: 1,
1149
+ redacted: 2,
1150
+ raw: 3
1151
+ });
1152
+ var WHITESPACE = /\s/u;
1153
+ var withoutTrailingToken = (text) => {
1154
+ let end = text.length;
1155
+ while (end > 0) {
1156
+ const low = text.charCodeAt(end - 1);
1157
+ const width = end >= 2 && low >= 56320 && low <= 57343 ? 2 : 1;
1158
+ if (WHITESPACE.test(text.slice(end - width, end))) break;
1159
+ end -= width;
1160
+ }
1161
+ return text.slice(0, end);
1162
+ };
1146
1163
  var compilePatterns = (sources, flags) => {
1147
1164
  const compiled = [];
1148
1165
  for (const source of sources) {
@@ -1360,11 +1377,11 @@ var createPrivacyService = (policyInput) => {
1360
1377
  };
1361
1378
  const flattenToAttributes = (value, prefix) => {
1362
1379
  const attributes = {};
1363
- const walk = (current, path11) => {
1380
+ const walk = (current, path13) => {
1364
1381
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
1365
1382
  const primitive = toAttributePrimitive(current);
1366
1383
  if (primitive !== void 0) {
1367
- attributes[path11] = primitive;
1384
+ attributes[path13] = primitive;
1368
1385
  }
1369
1386
  return;
1370
1387
  }
@@ -1383,16 +1400,16 @@ var createPrivacyService = (policyInput) => {
1383
1400
  primitives.push(entryPrimitive);
1384
1401
  }
1385
1402
  if (uniform) {
1386
- attributes[path11] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
1403
+ attributes[path13] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
1387
1404
  return;
1388
1405
  }
1389
1406
  for (const [index, entry] of current.entries()) {
1390
- walk(entry, `${path11}.${index}`);
1407
+ walk(entry, `${path13}.${index}`);
1391
1408
  }
1392
1409
  return;
1393
1410
  }
1394
1411
  for (const [key, entry] of Object.entries(current)) {
1395
- walk(entry, path11 === "" ? key : `${path11}.${key}`);
1412
+ walk(entry, path13 === "" ? key : `${path13}.${key}`);
1396
1413
  }
1397
1414
  };
1398
1415
  walk(value, prefix);
@@ -1480,7 +1497,31 @@ var createPrivacyService = (policyInput) => {
1480
1497
  flattenToAttributes,
1481
1498
  sanitizeAttributes,
1482
1499
  sanitizeExtensions,
1483
- boundString
1500
+ boundString,
1501
+ restrictContent: (fact, mode) => {
1502
+ const target = CONTENT_MODE_DISCLOSURE[mode];
1503
+ if (fact.text === void 0 || DISCLOSURE_RANK[fact.disclosure] <= DISCLOSURE_RANK[target]) {
1504
+ return fact;
1505
+ }
1506
+ const { text, ...rest } = fact;
1507
+ switch (target) {
1508
+ case "omitted":
1509
+ return { ...rest, disclosure: "omitted", truncated: false };
1510
+ case "masked":
1511
+ return { ...rest, disclosure: "masked", text: maskText(text) };
1512
+ case "redacted": {
1513
+ const redacted = redactSecretSpans(fact.truncated ? withoutTrailingToken(text) : text);
1514
+ return {
1515
+ ...rest,
1516
+ disclosure: "redacted",
1517
+ text: redacted.text,
1518
+ secretsRedacted: fact.secretsRedacted + redacted.count
1519
+ };
1520
+ }
1521
+ case "raw":
1522
+ return fact;
1523
+ }
1524
+ }
1484
1525
  };
1485
1526
  };
1486
1527
 
@@ -1820,6 +1861,60 @@ var unionOtlpHeaderNames = (...lists) => {
1820
1861
  };
1821
1862
  var describeOtlpHeaderNames = (...sources) => unionOtlpHeaderNames(...sources.map((source) => Object.keys(source)));
1822
1863
 
1864
+ // src/config/repository-key.ts
1865
+ var ATTR_VCS_REPOSITORY_URL_FULL = "vcs.repository.url.full";
1866
+ var MAX_REPOSITORY_REFERENCE_LENGTH = 2048;
1867
+ var SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;
1868
+ var SCP_LIKE_PATTERN = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/\/)(.+)$/;
1869
+ var trimTrailingSlashes = (value) => {
1870
+ let end = value.length;
1871
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
1872
+ return value.slice(0, end);
1873
+ };
1874
+ var keyOf = (host, pathname) => {
1875
+ const withoutSlashes = trimTrailingSlashes(pathname);
1876
+ const cleanedPath = trimTrailingSlashes(
1877
+ withoutSlashes.toLowerCase().endsWith(".git") ? withoutSlashes.slice(0, -4) : withoutSlashes
1878
+ );
1879
+ if (host.length === 0 || cleanedPath.length === 0 || cleanedPath === "/") {
1880
+ return void 0;
1881
+ }
1882
+ const withSlash = cleanedPath.startsWith("/") ? cleanedPath : `/${cleanedPath}`;
1883
+ return `${host}${withSlash}`.toLowerCase();
1884
+ };
1885
+ var normalizeRepositoryKey = (reference) => {
1886
+ const trimmed = reference.trim();
1887
+ if (trimmed.length === 0 || trimmed.length > MAX_REPOSITORY_REFERENCE_LENGTH) {
1888
+ return void 0;
1889
+ }
1890
+ if (SCHEME_PATTERN.test(trimmed)) {
1891
+ let url;
1892
+ try {
1893
+ url = new URL(trimmed);
1894
+ } catch {
1895
+ return void 0;
1896
+ }
1897
+ if (url.protocol === "file:") {
1898
+ return void 0;
1899
+ }
1900
+ return keyOf(url.hostname, url.pathname);
1901
+ }
1902
+ if (trimmed.startsWith("/") || trimmed.startsWith(".") || trimmed.includes("\\")) {
1903
+ return void 0;
1904
+ }
1905
+ const scp = SCP_LIKE_PATTERN.exec(trimmed);
1906
+ if (scp !== null && !trimmed.split(":")[0]?.includes("/")) {
1907
+ const [, host, pathPart] = scp;
1908
+ return host === void 0 || pathPart === void 0 ? void 0 : keyOf(host, pathPart);
1909
+ }
1910
+ try {
1911
+ const url = new URL(`https://${trimmed}`);
1912
+ return keyOf(url.hostname, url.pathname);
1913
+ } catch {
1914
+ return void 0;
1915
+ }
1916
+ };
1917
+
1823
1918
  // src/config/destinations.ts
1824
1919
  var DEFAULT_DESTINATION_NAME = "default";
1825
1920
  var DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;
@@ -1838,6 +1933,30 @@ var headerValueSchema = z13.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
1838
1933
  "an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN"
1839
1934
  );
1840
1935
  var endpointSchema = z13.string().url().max(2048);
1936
+ var MAX_DESTINATION_SCOPES = 64;
1937
+ var MAX_SCOPE_REPOSITORIES = 256;
1938
+ var ALL_REPOSITORIES = "*";
1939
+ var repositoryReferenceSchema = z13.string().min(1).max(MAX_REPOSITORY_REFERENCE_LENGTH).refine(
1940
+ (value) => normalizeRepositoryKey(value) !== void 0,
1941
+ "not a repository URL: use https://host/owner/repo, git@host:owner/repo.git, or host/owner/repo"
1942
+ );
1943
+ var destinationScopeSchema = z13.strictObject({
1944
+ /**
1945
+ * Repository URLs (any spelling of the remote; compared by host and path,
1946
+ * case-insensitively, without `.git`), or `"*"` for every record that names
1947
+ * a repository. A record that names none never matches a scope.
1948
+ */
1949
+ repositories: z13.union([
1950
+ z13.literal(ALL_REPOSITORIES),
1951
+ z13.array(repositoryReferenceSchema).min(1).max(MAX_SCOPE_REPOSITORIES).readonly()
1952
+ ]),
1953
+ /** Signals sent for these repositories. Default: every signal the destination takes. */
1954
+ signals: z13.array(exportSignalSchema).min(1).max(3).readonly().optional(),
1955
+ /** Content disclosure for these repositories, never above `privacy.contentMode`. Default: unchanged. */
1956
+ contentMode: contentModeSchema.optional(),
1957
+ /** False leaves `session.id` off metric data points for these repositories. Default true. */
1958
+ includeSessionId: z13.boolean().optional()
1959
+ });
1841
1960
  var exportDestinationSchema = z13.strictObject({
1842
1961
  /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */
1843
1962
  name: z13.string().regex(DESTINATION_NAME_PATTERN, "destination names are lowercase letters, digits, _ and -"),
@@ -1871,7 +1990,15 @@ var exportDestinationSchema = z13.strictObject({
1871
1990
  * opt-in for content-bearing records leaving the host. `metrics` is never on by
1872
1991
  * default: a destination receives hook-derived metrics only when it lists them.
1873
1992
  */
1874
- signals: z13.array(exportSignalSchema).min(1).max(3).readonly().optional()
1993
+ signals: z13.array(exportSignalSchema).min(1).max(3).readonly().optional(),
1994
+ /**
1995
+ * Per-repository filter. Absent: every record goes to this destination, as
1996
+ * before scopes existed. Present: a record goes only when its repository
1997
+ * (`vcs.repository.url.full`) matches a scope — the first matching scope
1998
+ * decides its signals, content mode, and session id — and a record that
1999
+ * names no repository is not sent here at all.
2000
+ */
2001
+ scopes: z13.array(destinationScopeSchema).min(1).max(MAX_DESTINATION_SCOPES).readonly().optional()
1875
2002
  }).refine(
1876
2003
  (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
1877
2004
  "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
@@ -1915,6 +2042,32 @@ var effectiveSpoolPolicy = (exporter) => ({
1915
2042
  maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,
1916
2043
  maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches
1917
2044
  });
2045
+ var resolveDestinationScopes = (scopes, destinationSignals) => scopes.map((scope) => {
2046
+ const listed = scope.signals ?? exportSignalSchema.options;
2047
+ return {
2048
+ repositories: scope.repositories === ALL_REPOSITORIES ? ALL_REPOSITORIES : new Set(
2049
+ scope.repositories.flatMap((reference) => {
2050
+ const key = normalizeRepositoryKey(reference);
2051
+ return key === void 0 ? [] : [key];
2052
+ })
2053
+ ),
2054
+ signals: {
2055
+ traces: destinationSignals.traces && listed.includes("traces"),
2056
+ logs: destinationSignals.logs && listed.includes("logs"),
2057
+ metrics: destinationSignals.metrics && listed.includes("metrics")
2058
+ },
2059
+ ...scope.contentMode === void 0 ? {} : { contentMode: scope.contentMode },
2060
+ includeSessionId: scope.includeSessionId ?? true
2061
+ };
2062
+ });
2063
+ var matchDestinationScope = (scopes, repositoryKey) => {
2064
+ if (repositoryKey === void 0) {
2065
+ return void 0;
2066
+ }
2067
+ return scopes.find(
2068
+ (scope) => scope.repositories === ALL_REPOSITORIES || scope.repositories.has(repositoryKey)
2069
+ );
2070
+ };
1918
2071
  var legacyDestination = (exporter) => ({
1919
2072
  name: DEFAULT_DESTINATION_NAME,
1920
2073
  source: "exporter",
@@ -1939,6 +2092,11 @@ var resolveExportDestinations = (exporter) => {
1939
2092
  continue;
1940
2093
  }
1941
2094
  const signals = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;
2095
+ const flags = {
2096
+ traces: signals.includes("traces"),
2097
+ logs: exporter.logs.enabled && signals.includes("logs"),
2098
+ metrics: signals.includes("metrics")
2099
+ };
1942
2100
  resolved.push({
1943
2101
  name: destination.name,
1944
2102
  source: "destinations",
@@ -1947,12 +2105,9 @@ var resolveExportDestinations = (exporter) => {
1947
2105
  ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
1948
2106
  ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
1949
2107
  ...destination.metricsEndpoint === void 0 ? {} : { metricsEndpoint: destination.metricsEndpoint },
1950
- signals: {
1951
- traces: signals.includes("traces"),
1952
- logs: exporter.logs.enabled && signals.includes("logs"),
1953
- metrics: signals.includes("metrics")
1954
- },
1955
- headers: { ...destination.headers ?? {} }
2108
+ signals: flags,
2109
+ headers: { ...destination.headers ?? {} },
2110
+ ...destination.scopes === void 0 ? {} : { scopes: resolveDestinationScopes(destination.scopes, flags) }
1956
2111
  });
1957
2112
  }
1958
2113
  return resolved;
@@ -1976,6 +2131,12 @@ var resolveDestinationHeaders = (headers, environment) => {
1976
2131
  }
1977
2132
  return { values, missingVariables: [...new Set(missing)].sort() };
1978
2133
  };
2134
+ var describeScope = (scope) => ({
2135
+ repositories: scope.repositories === ALL_REPOSITORIES ? ALL_REPOSITORIES : [...scope.repositories].sort(),
2136
+ signals: exportSignalSchema.options.filter((signal) => scope.signals[signal]),
2137
+ ...scope.contentMode === void 0 ? {} : { contentMode: scope.contentMode },
2138
+ includeSessionId: scope.includeSessionId
2139
+ });
1979
2140
  var endpointOrigin = (endpoint) => {
1980
2141
  if (endpoint === void 0) {
1981
2142
  return void 0;
@@ -2005,7 +2166,8 @@ var describeExportDestinations = (exporter) => {
2005
2166
  ...logsOrigin === void 0 || !destination.signals.logs ? {} : { logsEndpointOrigin: logsOrigin },
2006
2167
  ...metricsOrigin === void 0 || !destination.signals.metrics ? {} : { metricsEndpointOrigin: metricsOrigin },
2007
2168
  headerNames: destination.source === "exporter" ? [...exporter.headerNames].sort() : Object.keys(destination.headers).sort(),
2008
- headerVariables: [...new Set(variables)].sort()
2169
+ headerVariables: [...new Set(variables)].sort(),
2170
+ ...destination.scopes === void 0 ? {} : { scopes: destination.scopes.map(describeScope) }
2009
2171
  };
2010
2172
  };
2011
2173
  const enabled = resolveExportDestinations(exporter).map(
@@ -2019,7 +2181,14 @@ var describeExportDestinations = (exporter) => {
2019
2181
  protocol: destination.protocol ?? exporter.protocol,
2020
2182
  ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
2021
2183
  signals: { traces: false, logs: false, metrics: false },
2022
- headers: { ...destination.headers ?? {} }
2184
+ headers: { ...destination.headers ?? {} },
2185
+ ...destination.scopes === void 0 ? {} : {
2186
+ scopes: resolveDestinationScopes(destination.scopes, {
2187
+ traces: true,
2188
+ logs: true,
2189
+ metrics: true
2190
+ })
2191
+ }
2023
2192
  },
2024
2193
  false
2025
2194
  )
@@ -2108,8 +2277,26 @@ var exporterPolicySchema = z14.strictObject({
2108
2277
  * Per-destination retry spool bounds, each optional and merged per leaf; any
2109
2278
  * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.
2110
2279
  */
2111
- spool: spoolPolicySchema.partial().optional()
2280
+ spool: spoolPolicySchema.partial().optional(),
2281
+ /**
2282
+ * The most time one hook invocation spends trying to reach one endpoint, in
2283
+ * milliseconds: caps `timeoutMillis` for every OTLP request (connection setup
2284
+ * included) and the exporter's own retries inside it. A batch that does not
2285
+ * get through in time is spooled. Default {@link DEFAULT_EXPORT_BUDGET_MILLIS}:
2286
+ * the host agent waits for its hooks, so a down collector must not stall it.
2287
+ */
2288
+ exportBudgetMillis: z14.number().int().min(50).max(6e5).optional(),
2289
+ /**
2290
+ * After an endpoint was unreachable (refused, timed out, or answered a
2291
+ * retryable status), every hook spools for it without trying for this long,
2292
+ * in milliseconds; then one hook probes it again. 0 disables the window.
2293
+ * Default {@link DEFAULT_ENDPOINT_DOWN_MILLIS}.
2294
+ */
2295
+ endpointDownMillis: z14.number().int().min(0).max(36e5).optional()
2112
2296
  });
2297
+ var DEFAULT_EXPORT_BUDGET_MILLIS = 1500;
2298
+ var DEFAULT_ENDPOINT_DOWN_MILLIS = 3e4;
2299
+ var effectiveExportTimeoutMillis = (exporter) => Math.min(exporter.timeoutMillis, exporter.exportBudgetMillis ?? DEFAULT_EXPORT_BUDGET_MILLIS);
2113
2300
  var detectionPolicySchema = z14.strictObject({
2114
2301
  /** Detections below this confidence resolve to the unknown provider. */
2115
2302
  minimumConfidence: detectionConfidenceSchema,
@@ -2126,6 +2313,9 @@ var diagnosticsPolicySchema = z14.strictObject({
2126
2313
  var providersPolicySchema = z14.strictObject({
2127
2314
  claudeCode: z14.strictObject({
2128
2315
  readTranscriptUsage: z14.boolean()
2316
+ }).optional(),
2317
+ codex: z14.strictObject({
2318
+ readRolloutUsage: z14.boolean()
2129
2319
  }).optional()
2130
2320
  });
2131
2321
  var sessionContextPolicySchema = z14.strictObject({
@@ -2155,7 +2345,8 @@ var otelHookConfigPatchSchema = z14.strictObject({
2155
2345
  detection: detectionPolicySchema.partial().optional(),
2156
2346
  diagnostics: diagnosticsPolicySchema.partial().optional(),
2157
2347
  providers: z14.strictObject({
2158
- claudeCode: z14.strictObject({ readTranscriptUsage: z14.boolean() }).partial().optional()
2348
+ claudeCode: z14.strictObject({ readTranscriptUsage: z14.boolean() }).partial().optional(),
2349
+ codex: z14.strictObject({ readRolloutUsage: z14.boolean() }).partial().optional()
2159
2350
  }).partial().optional(),
2160
2351
  sessionContext: sessionContextPolicySchema.partial().optional()
2161
2352
  });
@@ -2182,7 +2373,8 @@ var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
2182
2373
  emitErrorEvents: true
2183
2374
  });
2184
2375
  var DEFAULT_PROVIDERS_POLICY = Object.freeze({
2185
- claudeCode: Object.freeze({ readTranscriptUsage: false })
2376
+ claudeCode: Object.freeze({ readTranscriptUsage: false }),
2377
+ codex: Object.freeze({ readRolloutUsage: false })
2186
2378
  });
2187
2379
  var DEFAULT_CONFIG = Object.freeze({
2188
2380
  exporter: DEFAULT_EXPORTER_POLICY,
@@ -2192,6 +2384,7 @@ var DEFAULT_CONFIG = Object.freeze({
2192
2384
  providers: DEFAULT_PROVIDERS_POLICY
2193
2385
  });
2194
2386
  var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
2387
+ var readsCodexRolloutUsage = (config) => config.providers?.codex?.readRolloutUsage === true;
2195
2388
  var sessionContextDir = (config) => config.sessionContext?.dir;
2196
2389
  var effectiveMetricsPolicy = (exporter) => ({
2197
2390
  ...DEFAULT_METRICS_POLICY,
@@ -2203,12 +2396,12 @@ import { z as z15 } from "zod";
2203
2396
  var CONFIG_SOURCE_PRECEDENCE = ["defaults", "file", "environment", "inline-override"];
2204
2397
  var configSourceSchema = z15.enum(CONFIG_SOURCE_PRECEDENCE);
2205
2398
  var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2206
- var mergeLeaf = (target, patch, source, provenance, path11) => {
2399
+ var mergeLeaf = (target, patch, source, provenance, path13) => {
2207
2400
  for (const [key, value] of Object.entries(patch)) {
2208
2401
  if (value === void 0) {
2209
2402
  continue;
2210
2403
  }
2211
- const childPath = path11 === "" ? key : `${path11}.${key}`;
2404
+ const childPath = path13 === "" ? key : `${path13}.${key}`;
2212
2405
  const existing = target[key];
2213
2406
  if (isPlainObject(value) && (isPlainObject(existing) || existing === void 0)) {
2214
2407
  const child = { ...existing ?? {} };
@@ -2222,14 +2415,14 @@ var mergeLeaf = (target, patch, source, provenance, path11) => {
2222
2415
  };
2223
2416
  var initialProvenance = (config) => {
2224
2417
  const provenance = {};
2225
- const walk = (value, path11) => {
2418
+ const walk = (value, path13) => {
2226
2419
  if (isPlainObject(value)) {
2227
2420
  for (const [key, child] of Object.entries(value)) {
2228
- walk(child, path11 === "" ? key : `${path11}.${key}`);
2421
+ walk(child, path13 === "" ? key : `${path13}.${key}`);
2229
2422
  }
2230
2423
  return;
2231
2424
  }
2232
- provenance[path11] = "defaults";
2425
+ provenance[path13] = "defaults";
2233
2426
  };
2234
2427
  walk(config, "");
2235
2428
  return provenance;
@@ -2302,6 +2495,18 @@ var resolveConfig = (layers = []) => {
2302
2495
  );
2303
2496
  }
2304
2497
  }
2498
+ const rank = { omit: 0, mask: 1, redact: 2, raw: 3 };
2499
+ const effectiveMode = parsed.data.privacy.contentMode === "raw" && !parsed.data.privacy.allowRawContent ? "omit" : parsed.data.privacy.contentMode;
2500
+ const widening = enabled.filter(
2501
+ (destination) => (destination.scopes ?? []).some(
2502
+ (scope) => scope.contentMode !== void 0 && rank[scope.contentMode] > rank[effectiveMode]
2503
+ )
2504
+ ).map((destination) => destination.name);
2505
+ if (widening.length > 0) {
2506
+ notes.push(
2507
+ `destination(s) ${widening.join(", ")} have a scope contentMode above privacy.contentMode=${effectiveMode}; a scope can only lower disclosure, so ${effectiveMode} applies`
2508
+ );
2509
+ }
2305
2510
  }
2306
2511
  if (!withDestinations && parsed.data.exporter.logs.enabled && parsed.data.exporter.logs.endpoint === void 0 && parsed.data.exporter.endpoint === void 0) {
2307
2512
  notes.push(
@@ -2349,11 +2554,14 @@ var describeDestinationAttributes = (config) => {
2349
2554
  }
2350
2555
  attributes[`${prefix}.header_names`] = [...destination.headerNames];
2351
2556
  attributes[`${prefix}.header_variables`] = [...destination.headerVariables];
2557
+ if (destination.scopes !== void 0) {
2558
+ attributes[`${prefix}.scope_count`] = destination.scopes.length;
2559
+ }
2352
2560
  }
2353
2561
  return attributes;
2354
2562
  };
2355
2563
  var describeResolvedConfig = (config) => {
2356
- const originOf = (endpoint) => {
2564
+ const originOf2 = (endpoint) => {
2357
2565
  if (endpoint === void 0) {
2358
2566
  return void 0;
2359
2567
  }
@@ -2363,10 +2571,10 @@ var describeResolvedConfig = (config) => {
2363
2571
  return "<unparsable>";
2364
2572
  }
2365
2573
  };
2366
- const endpointOrigin2 = originOf(config.exporter.endpoint);
2367
- const logsEndpointOrigin = originOf(config.exporter.logs.endpoint);
2574
+ const endpointOrigin2 = originOf2(config.exporter.endpoint);
2575
+ const logsEndpointOrigin = originOf2(config.exporter.logs.endpoint);
2368
2576
  const metrics = effectiveMetricsPolicy(config.exporter);
2369
- const metricsEndpointOrigin = originOf(metrics.endpoint);
2577
+ const metricsEndpointOrigin = originOf2(metrics.endpoint);
2370
2578
  return {
2371
2579
  "exporter.enabled": config.exporter.enabled,
2372
2580
  "exporter.protocol": config.exporter.protocol,
@@ -2486,7 +2694,9 @@ var ENVIRONMENT_VARIABLES = Object.freeze({
2486
2694
  minimumConfidence: "OTEL_HOOK_MIN_DETECTION_CONFIDENCE",
2487
2695
  logLevel: "OTEL_HOOK_LOG_LEVEL",
2488
2696
  /** `providers.claudeCode.readTranscriptUsage`; see `providersPolicySchema`. */
2489
- claudeTranscriptUsage: "OTEL_HOOK_CLAUDE_TRANSCRIPT_USAGE"
2697
+ claudeTranscriptUsage: "OTEL_HOOK_CLAUDE_TRANSCRIPT_USAGE",
2698
+ /** `providers.codex.readRolloutUsage`; see `providersPolicySchema`. */
2699
+ codexRolloutUsage: "OTEL_HOOK_CODEX_ROLLOUT_USAGE"
2490
2700
  });
2491
2701
  var BOOLEAN_TRUE = /* @__PURE__ */ new Set(["1", "true", "yes", "on"]);
2492
2702
  var BOOLEAN_FALSE = /* @__PURE__ */ new Set(["0", "false", "no", "off"]);
@@ -2681,7 +2891,11 @@ var parseEnvironmentConfig = (env) => {
2681
2891
  const detection = confidenceParsed?.success === true ? { minimumConfidence: confidenceParsed.data } : {};
2682
2892
  const diagnostics = logLevel === void 0 ? {} : { logLevel };
2683
2893
  const claudeTranscriptUsage = readBoolean(ENVIRONMENT_VARIABLES.claudeTranscriptUsage);
2684
- const providers = claudeTranscriptUsage === void 0 ? {} : { claudeCode: { readTranscriptUsage: claudeTranscriptUsage } };
2894
+ const codexRolloutUsage = readBoolean(ENVIRONMENT_VARIABLES.codexRolloutUsage);
2895
+ const providers = {
2896
+ ...claudeTranscriptUsage === void 0 ? {} : { claudeCode: { readTranscriptUsage: claudeTranscriptUsage } },
2897
+ ...codexRolloutUsage === void 0 ? {} : { codex: { readRolloutUsage: codexRolloutUsage } }
2898
+ };
2685
2899
  const patch = {
2686
2900
  ...Object.keys(exporter).length === 0 ? {} : { exporter },
2687
2901
  ...Object.keys(privacy).length === 0 ? {} : { privacy },
@@ -5434,6 +5648,7 @@ var permissionModeSchema = z19.enum([
5434
5648
  var codexUsageSchema = z19.object({
5435
5649
  input_tokens: z19.number().int().min(0).optional(),
5436
5650
  cached_input_tokens: z19.number().int().min(0).optional(),
5651
+ cache_write_input_tokens: z19.number().int().min(0).optional(),
5437
5652
  output_tokens: z19.number().int().min(0).optional(),
5438
5653
  reasoning_output_tokens: z19.number().int().min(0).optional(),
5439
5654
  total_tokens: z19.number().int().min(0).optional()
@@ -5689,6 +5904,10 @@ var codexUsageToReport = (usage, temporality) => ({
5689
5904
  temporality,
5690
5905
  ...usage.input_tokens === void 0 ? {} : { inputTokens: usage.input_tokens },
5691
5906
  ...usage.cached_input_tokens === void 0 ? {} : { cachedInputTokens: usage.cached_input_tokens },
5907
+ ...usage.cache_write_input_tokens === void 0 ? {} : {
5908
+ cacheCreationInputTokens: usage.cache_write_input_tokens,
5909
+ cacheCreationAccounting: "included-in-input"
5910
+ },
5692
5911
  ...usage.output_tokens === void 0 ? {} : { outputTokens: usage.output_tokens },
5693
5912
  ...usage.reasoning_output_tokens === void 0 ? {} : { reasoningOutputTokens: usage.reasoning_output_tokens },
5694
5913
  ...usage.total_tokens === void 0 ? {} : { providerTotalTokens: usage.total_tokens }
@@ -5717,8 +5936,9 @@ var CODEX_CAPABILITIES = Object.freeze({
5717
5936
  // turn; see docs/usage-semantics.md.
5718
5937
  cumulativeUsageSeries: "session-lifetime",
5719
5938
  reportsCachedInput: true,
5720
- reportsCacheCreation: false,
5721
- cacheCreationAccounting: "not-reported",
5939
+ // Codex 0.163+ reports `cache_write_input_tokens`, a subset of `input_tokens`.
5940
+ reportsCacheCreation: true,
5941
+ cacheCreationAccounting: "included-in-input",
5722
5942
  reportsReasoningOutput: true,
5723
5943
  reportsProviderTotal: true,
5724
5944
  reportsCost: false,
@@ -6077,6 +6297,291 @@ var createCodexAdapter = () => ({
6077
6297
  hookResponse
6078
6298
  });
6079
6299
 
6300
+ // src/providers/codex/rollout-usage.ts
6301
+ import { createHash as createHash3 } from "crypto";
6302
+ import { open as open2, readdir, stat as stat2 } from "fs/promises";
6303
+ import path2 from "path";
6304
+ var CODEX_ROLLOUT_USAGE_ENRICHER_ID = "codex-rollout-usage";
6305
+ var DEFAULT_CODEX_ROLLOUT_RANGE_BYTES = 8388608;
6306
+ var DEFAULT_CODEX_ROLLOUT_TAIL_BYTES = 1048576;
6307
+ var DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS = 500;
6308
+ var DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS = 150;
6309
+ var ROLLOUT_LOOKUP_DAYS = 7;
6310
+ var MIN_BYTES = 65536;
6311
+ var MAX_RANGE_BYTES2 = 67108864;
6312
+ var MAX_TAIL_BYTES2 = 16777216;
6313
+ var MIN_TIMEOUT_MILLIS2 = 10;
6314
+ var MAX_TIMEOUT_MILLIS2 = 5e3;
6315
+ var MAX_SETTLE_MILLIS = 1e3;
6316
+ var MAX_MODEL_ID_LENGTH2 = 256;
6317
+ var MAX_LOOKUP_DIR_ENTRIES = 2e4;
6318
+ var SESSION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{7,127}$/;
6319
+ var clamp2 = (value, fallback, min, max) => {
6320
+ if (value === void 0 || !Number.isFinite(value)) {
6321
+ return fallback;
6322
+ }
6323
+ return Math.min(max, Math.max(min, Math.floor(value)));
6324
+ };
6325
+ var asRecord8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
6326
+ var isRolloutPath = (value) => typeof value === "string" && value.length > 0 && value.length <= 4096 && !value.includes("\0") && path2.isAbsolute(value) && path2.extname(value) === ".jsonl";
6327
+ var sourceDigest2 = (rolloutPath) => createHash3("sha256").update(rolloutPath, "utf8").digest("hex").slice(0, 32);
6328
+ var parseUsage = (value) => {
6329
+ const parsed = codexUsageSchema.safeParse(value);
6330
+ if (!parsed.success) {
6331
+ return void 0;
6332
+ }
6333
+ const usage = parsed.data;
6334
+ return usage.input_tokens === void 0 || usage.output_tokens === void 0 ? void 0 : usage;
6335
+ };
6336
+ var modelOf = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_MODEL_ID_LENGTH2 ? value : void 0;
6337
+ var factsOf = (line) => {
6338
+ const usageLine = line.includes('"token_count"') || line.includes('"token_usage_record"');
6339
+ const contextLine = line.includes('"turn_context"');
6340
+ if (!usageLine && !contextLine) {
6341
+ return void 0;
6342
+ }
6343
+ let parsed;
6344
+ try {
6345
+ parsed = JSON.parse(line);
6346
+ } catch {
6347
+ return void 0;
6348
+ }
6349
+ const record = asRecord8(parsed);
6350
+ const payload = asRecord8(record?.payload);
6351
+ if (record === void 0 || payload === void 0) {
6352
+ return void 0;
6353
+ }
6354
+ if (record.type === "turn_context") {
6355
+ const model = modelOf(payload.model);
6356
+ return model === void 0 ? void 0 : { model };
6357
+ }
6358
+ if (record.type === "event_msg" && payload.type === "token_count") {
6359
+ const info = asRecord8(payload.info) ?? payload;
6360
+ const usage = parseUsage(info.total_token_usage);
6361
+ return usage === void 0 ? void 0 : { usage };
6362
+ }
6363
+ if (record.type === "token_usage_record") {
6364
+ const usage = parseUsage(payload.thread_token_usage);
6365
+ return usage === void 0 ? void 0 : { usage };
6366
+ }
6367
+ return void 0;
6368
+ };
6369
+ var lastSnapshotIn = (lines) => {
6370
+ let usage;
6371
+ let model;
6372
+ for (const line of lines) {
6373
+ const facts = factsOf(line.trim());
6374
+ if (facts === void 0) {
6375
+ continue;
6376
+ }
6377
+ if (facts.model !== void 0) {
6378
+ model = facts.model;
6379
+ }
6380
+ if (facts.usage !== void 0) {
6381
+ usage = facts.usage;
6382
+ }
6383
+ }
6384
+ return usage === void 0 ? void 0 : { usage, ...model === void 0 ? {} : { model } };
6385
+ };
6386
+ var readBytes2 = async (handle, start, length) => {
6387
+ const buffer = Buffer.alloc(length);
6388
+ let filled = 0;
6389
+ while (filled < length) {
6390
+ const { bytesRead } = await handle.read(buffer, filled, length - filled, start + filled);
6391
+ if (bytesRead === 0) {
6392
+ break;
6393
+ }
6394
+ filled += bytesRead;
6395
+ }
6396
+ return buffer.subarray(0, filled);
6397
+ };
6398
+ var readRollout = async (rolloutPath, fromOffset, maxRangeBytes, tailBytes) => {
6399
+ let handle;
6400
+ try {
6401
+ const info = await stat2(rolloutPath);
6402
+ if (!info.isFile()) {
6403
+ return { status: "unavailable", reason: "not-a-file" };
6404
+ }
6405
+ handle = await open2(rolloutPath, "r");
6406
+ } catch {
6407
+ return { status: "unavailable", reason: "unreadable" };
6408
+ }
6409
+ try {
6410
+ const { size } = await handle.stat();
6411
+ let start;
6412
+ if (fromOffset === void 0) {
6413
+ start = Math.max(0, size - tailBytes);
6414
+ } else if (size < fromOffset) {
6415
+ return { status: "unavailable", reason: "truncated" };
6416
+ } else if (size - fromOffset > maxRangeBytes) {
6417
+ return { status: "unavailable", reason: "over-cap" };
6418
+ } else {
6419
+ start = fromOffset;
6420
+ }
6421
+ const bytes = await readBytes2(handle, start, size - start);
6422
+ const lastNewline = bytes.lastIndexOf(10);
6423
+ const endOffset = lastNewline < 0 ? start : start + lastNewline + 1;
6424
+ const lines = bytes.subarray(0, endOffset - start).toString("utf8").split("\n");
6425
+ if (fromOffset === void 0 && start > 0) {
6426
+ lines.shift();
6427
+ }
6428
+ const snapshot = lastSnapshotIn(lines);
6429
+ return { status: "found", ...snapshot === void 0 ? {} : { snapshot }, endOffset };
6430
+ } catch {
6431
+ return { status: "unavailable", reason: "unreadable" };
6432
+ } finally {
6433
+ await handle.close().catch(() => void 0);
6434
+ }
6435
+ };
6436
+ var pad = (value) => String(value).padStart(2, "0");
6437
+ var findRolloutBySessionId = async (sessionsRoot, sessionId, now) => {
6438
+ if (!SESSION_ID_PATTERN.test(sessionId) || !path2.isAbsolute(sessionsRoot)) {
6439
+ return void 0;
6440
+ }
6441
+ const suffix = `-${sessionId}.jsonl`;
6442
+ for (let back = 0; back < ROLLOUT_LOOKUP_DAYS; back += 1) {
6443
+ const day = new Date(now.getFullYear(), now.getMonth(), now.getDate() - back);
6444
+ const dir = path2.join(sessionsRoot, String(day.getFullYear()), pad(day.getMonth() + 1), pad(day.getDate()));
6445
+ let names;
6446
+ try {
6447
+ names = await readdir(dir);
6448
+ } catch {
6449
+ continue;
6450
+ }
6451
+ if (names.length > MAX_LOOKUP_DIR_ENTRIES) {
6452
+ continue;
6453
+ }
6454
+ const match = names.find((name) => name.startsWith("rollout-") && name.endsWith(suffix));
6455
+ if (match !== void 0) {
6456
+ return path2.join(dir, match);
6457
+ }
6458
+ }
6459
+ return void 0;
6460
+ };
6461
+ var TIMED_OUT2 = /* @__PURE__ */ Symbol("timed-out");
6462
+ var withTimeout2 = async (work, timeoutMillis) => {
6463
+ let timer;
6464
+ const timeout = new Promise((resolve5) => {
6465
+ timer = setTimeout(() => {
6466
+ resolve5(TIMED_OUT2);
6467
+ }, timeoutMillis);
6468
+ timer.unref();
6469
+ });
6470
+ try {
6471
+ return await Promise.race([work, timeout]);
6472
+ } finally {
6473
+ clearTimeout(timer);
6474
+ }
6475
+ };
6476
+ var sleep = (millis) => new Promise((resolve5) => {
6477
+ setTimeout(resolve5, millis).unref();
6478
+ });
6479
+ var hasUsage2 = (record) => record.usage !== void 0;
6480
+ var createCodexRolloutUsageEnricher = (options = {}) => {
6481
+ const maxRangeBytes = clamp2(options.maxRangeBytes, DEFAULT_CODEX_ROLLOUT_RANGE_BYTES, MIN_BYTES, MAX_RANGE_BYTES2);
6482
+ const maxTailBytes = clamp2(options.maxTailBytes, DEFAULT_CODEX_ROLLOUT_TAIL_BYTES, MIN_BYTES, MAX_TAIL_BYTES2);
6483
+ const timeoutMillis = clamp2(
6484
+ options.timeoutMillis,
6485
+ DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS,
6486
+ MIN_TIMEOUT_MILLIS2,
6487
+ MAX_TIMEOUT_MILLIS2
6488
+ );
6489
+ const settleMillis = clamp2(options.settleMillis, DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS, 0, MAX_SETTLE_MILLIS);
6490
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
6491
+ const fileSize = async (rolloutPath) => {
6492
+ try {
6493
+ const info = await stat2(rolloutPath);
6494
+ return info.isFile() ? info.size : void 0;
6495
+ } catch (thrown) {
6496
+ return thrown?.code === "ENOENT" ? "absent" : void 0;
6497
+ }
6498
+ };
6499
+ const resolveRollout = async (record) => {
6500
+ const named = record.transcript_path;
6501
+ if (named !== void 0 && named !== null) {
6502
+ return isRolloutPath(named) ? named : void 0;
6503
+ }
6504
+ const sessionId = record.session_id;
6505
+ if (options.sessionsRoot === void 0 || typeof sessionId !== "string") {
6506
+ return void 0;
6507
+ }
6508
+ return findRolloutBySessionId(options.sessionsRoot, sessionId, now());
6509
+ };
6510
+ const enrichWithin = async (input) => {
6511
+ const unchanged = { payload: input.payload };
6512
+ const record = asRecord8(input.payload);
6513
+ const eventName = record?.hook_event_name;
6514
+ if (record === void 0 || eventName !== "SessionStart" && eventName !== "Stop") {
6515
+ return unchanged;
6516
+ }
6517
+ const rolloutPath = await resolveRollout(record);
6518
+ if (rolloutPath === void 0) {
6519
+ return { ...unchanged, notes: ["no rollout named or found for this session"] };
6520
+ }
6521
+ const source = sourceDigest2(rolloutPath);
6522
+ const cursor = input.cursor?.source === source ? input.cursor : void 0;
6523
+ if (eventName === "SessionStart") {
6524
+ if (cursor !== void 0) {
6525
+ return unchanged;
6526
+ }
6527
+ const size = await fileSize(rolloutPath);
6528
+ if (size === void 0) {
6529
+ return { ...unchanged, notes: ["rollout is not a readable regular file; no cursor recorded"] };
6530
+ }
6531
+ return { payload: input.payload, cursor: { source, offset: size === "absent" ? 0 : size } };
6532
+ }
6533
+ if (hasUsage2(record)) {
6534
+ const size = await fileSize(rolloutPath);
6535
+ return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
6536
+ }
6537
+ const attach = (snapshot) => ({
6538
+ ...record,
6539
+ ...record.model === void 0 && snapshot.model !== void 0 ? { model: snapshot.model } : {},
6540
+ usage: snapshot.usage
6541
+ });
6542
+ let read = await readRollout(rolloutPath, cursor?.offset, maxRangeBytes, maxTailBytes);
6543
+ if (read.status === "found" && read.snapshot === void 0 && cursor !== void 0 && settleMillis > 0) {
6544
+ await sleep(settleMillis);
6545
+ read = await readRollout(rolloutPath, cursor.offset, maxRangeBytes, maxTailBytes);
6546
+ }
6547
+ if (read.status === "unavailable") {
6548
+ if (read.reason !== "truncated" && read.reason !== "over-cap") {
6549
+ return { ...unchanged, notes: [`rollout not read (${read.reason}); cursor kept`] };
6550
+ }
6551
+ read = await readRollout(rolloutPath, void 0, maxRangeBytes, maxTailBytes);
6552
+ if (read.status === "unavailable") {
6553
+ return { ...unchanged, notes: [`rollout tail not read (${read.reason})`] };
6554
+ }
6555
+ }
6556
+ const next = { source, offset: read.endOffset };
6557
+ if (read.snapshot === void 0) {
6558
+ return { payload: input.payload, cursor: next, notes: ["no token_count since the last stop"] };
6559
+ }
6560
+ return {
6561
+ payload: attach(read.snapshot),
6562
+ cursor: next,
6563
+ notes: [cursor === void 0 ? "no cursor; attached the last running total in the tail" : "attached the running total"]
6564
+ };
6565
+ };
6566
+ const enrich = async (input) => {
6567
+ try {
6568
+ const result = await withTimeout2(enrichWithin(input), timeoutMillis);
6569
+ return result === TIMED_OUT2 ? { payload: input.payload, notes: ["rollout read timed out; cursor kept"] } : result;
6570
+ } catch {
6571
+ return { payload: input.payload, notes: ["rollout read failed; cursor kept"] };
6572
+ }
6573
+ };
6574
+ return Object.freeze({ id: CODEX_ROLLOUT_USAGE_ENRICHER_ID, providerId: CODEX_PROVIDER_ID, enrich });
6575
+ };
6576
+ var readCodexRolloutUsage = async (rolloutPath, options = {}) => {
6577
+ if (!isRolloutPath(rolloutPath)) {
6578
+ return void 0;
6579
+ }
6580
+ const tail = clamp2(options.maxTailBytes, DEFAULT_CODEX_ROLLOUT_TAIL_BYTES, MIN_BYTES, MAX_TAIL_BYTES2);
6581
+ const read = await readRollout(rolloutPath, void 0, DEFAULT_CODEX_ROLLOUT_RANGE_BYTES, tail).catch(() => void 0);
6582
+ return read?.status === "found" ? read.snapshot : void 0;
6583
+ };
6584
+
6080
6585
  // src/providers/gemini/delivery.ts
6081
6586
  var GEMINI_UNIDENTIFIABLE_CALLBACKS = Object.freeze({
6082
6587
  SessionStart: "fires again within the same session_id on resume and clear (payload `source`), so session_id names a class of firings rather than one",
@@ -7208,9 +7713,9 @@ var createFixedClock = (options = {}) => {
7208
7713
  };
7209
7714
 
7210
7715
  // src/runtime/ids.ts
7211
- import { createHash as createHash3, randomUUID } from "crypto";
7716
+ import { createHash as createHash4, randomUUID } from "crypto";
7212
7717
  var digest = (namespace, parts) => {
7213
- const hash = createHash3("sha256");
7718
+ const hash = createHash4("sha256");
7214
7719
  hash.update(namespace);
7215
7720
  for (const part of parts) {
7216
7721
  hash.update("\0");
@@ -7446,16 +7951,16 @@ var resolveDeliveryIdentity = (input) => {
7446
7951
  import { z as z24 } from "zod";
7447
7952
 
7448
7953
  // src/runtime/target-resolution.ts
7449
- import * as path2 from "path";
7954
+ import * as path3 from "path";
7450
7955
  var DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS = 50;
7451
7956
  var absolutePathsOf = (hint) => {
7452
- const base = hint.baseDirectory !== void 0 && path2.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
7957
+ const base = hint.baseDirectory !== void 0 && path3.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
7453
7958
  const resolved = [];
7454
7959
  for (const candidate of hint.paths) {
7455
- if (path2.isAbsolute(candidate)) {
7456
- resolved.push(path2.resolve(candidate));
7960
+ if (path3.isAbsolute(candidate)) {
7961
+ resolved.push(path3.resolve(candidate));
7457
7962
  } else if (base !== void 0) {
7458
- resolved.push(path2.resolve(base, candidate));
7963
+ resolved.push(path3.resolve(base, candidate));
7459
7964
  } else {
7460
7965
  return void 0;
7461
7966
  }
@@ -7613,8 +8118,8 @@ var withOptionalSessionLock = async (store, sessionId, fn, options) => {
7613
8118
  };
7614
8119
 
7615
8120
  // src/runtime/session-context.ts
7616
- import { open as open2 } from "fs/promises";
7617
- import * as path3 from "path";
8121
+ import { open as open3 } from "fs/promises";
8122
+ import * as path4 from "path";
7618
8123
  import { z as z23 } from "zod";
7619
8124
  var SESSION_CONTEXT_FILE_VERSION = 1;
7620
8125
  var DEFAULT_SESSION_CONTEXT_MAX_BYTES = 256 * 1024;
@@ -7632,10 +8137,10 @@ var SESSION_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
7632
8137
  var isSessionContextFileName = (sessionId) => SESSION_FILE_NAME_PATTERN.test(sessionId) && !sessionId.includes("..");
7633
8138
  var sessionContextFilePath = (dir, providerId, sessionId) => {
7634
8139
  const tool = sessionContextAgentTool(providerId);
7635
- if (tool === void 0 || !isSessionContextFileName(sessionId) || !path3.isAbsolute(dir)) {
8140
+ if (tool === void 0 || !isSessionContextFileName(sessionId) || !path4.isAbsolute(dir)) {
7636
8141
  return void 0;
7637
8142
  }
7638
- return path3.join(dir, tool, `${sessionId}.json`);
8143
+ return path4.join(dir, tool, `${sessionId}.json`);
7639
8144
  };
7640
8145
  var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([
7641
8146
  "session.id",
@@ -7731,7 +8236,7 @@ var stampSessionContext = (events, segments) => events.map((event3) => {
7731
8236
  var readBounded = async (file, maxBytes) => {
7732
8237
  let handle;
7733
8238
  try {
7734
- handle = await open2(file, "r");
8239
+ handle = await open3(file, "r");
7735
8240
  } catch {
7736
8241
  return void 0;
7737
8242
  }
@@ -8684,8 +9189,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
8684
9189
  };
8685
9190
 
8686
9191
  // src/runtime/git-worktree.ts
8687
- import { lstat, open as open3, stat as stat2 } from "fs/promises";
8688
- import * as path4 from "path";
9192
+ import { lstat, open as open4, stat as stat3 } from "fs/promises";
9193
+ import * as path5 from "path";
8689
9194
  var MAX_WORKTREE_WALK_DEPTH = 128;
8690
9195
  var MAX_GIT_FILE_BYTES = 4096;
8691
9196
  var MAX_CACHE_ENTRIES = 1024;
@@ -8696,7 +9201,7 @@ var INVALID = Object.freeze({ kind: "invalid" });
8696
9201
  var readBounded2 = async (filePath) => {
8697
9202
  let handle;
8698
9203
  try {
8699
- handle = await open3(filePath, "r");
9204
+ handle = await open4(filePath, "r");
8700
9205
  const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
8701
9206
  const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
8702
9207
  return buffer.subarray(0, bytesRead).toString("utf8");
@@ -8717,7 +9222,7 @@ var parseHeadBranch = (head) => {
8717
9222
  return branch;
8718
9223
  };
8719
9224
  var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
8720
- var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path4.resolve(base, target);
9225
+ var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path5.resolve(base, target);
8721
9226
  var parseGitDirFile = (content, worktreeRoot) => {
8722
9227
  const line = firstLine(content);
8723
9228
  return resolveGitPath(
@@ -8737,26 +9242,26 @@ var isMissing = async (filePath) => {
8737
9242
  };
8738
9243
  var isDirectory = async (directory) => {
8739
9244
  try {
8740
- return (await stat2(directory)).isDirectory();
9245
+ return (await stat3(directory)).isDirectory();
8741
9246
  } catch {
8742
9247
  return false;
8743
9248
  }
8744
9249
  };
8745
9250
  var repositoryOf = async (worktreeRoot, gitDir) => {
8746
- const commonDirFile = path4.join(gitDir, "commondir");
9251
+ const commonDirFile = path5.join(gitDir, "commondir");
8747
9252
  const content = await readBounded2(commonDirFile);
8748
9253
  if (content === void 0) {
8749
9254
  return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
8750
9255
  }
8751
9256
  const commonDir = parseCommonDirFile(content, gitDir);
8752
- const mainRoot = commonDir !== void 0 && path4.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path4.dirname(commonDir) : void 0;
9257
+ const mainRoot = commonDir !== void 0 && path5.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path5.dirname(commonDir) : void 0;
8753
9258
  return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
8754
9259
  };
8755
9260
  var probeDirectory = async (directory) => {
8756
- const dotGit = path4.join(directory, ".git");
9261
+ const dotGit = path5.join(directory, ".git");
8757
9262
  let info;
8758
9263
  try {
8759
- info = await stat2(dotGit);
9264
+ info = await stat3(dotGit);
8760
9265
  } catch {
8761
9266
  return ABSENT;
8762
9267
  }
@@ -8770,7 +9275,7 @@ var probeDirectory = async (directory) => {
8770
9275
  if (gitDir === void 0) {
8771
9276
  return INVALID;
8772
9277
  }
8773
- const head = await readBounded2(path4.join(gitDir, "HEAD"));
9278
+ const head = await readBounded2(path5.join(gitDir, "HEAD"));
8774
9279
  if (head === void 0) {
8775
9280
  return INVALID;
8776
9281
  }
@@ -8800,10 +9305,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
8800
9305
  };
8801
9306
  const locate = async (absolutePath) => {
8802
9307
  try {
8803
- if (!path4.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
9308
+ if (!path5.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
8804
9309
  return void 0;
8805
9310
  }
8806
- let directory = path4.resolve(absolutePath);
9311
+ let directory = path5.resolve(absolutePath);
8807
9312
  for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
8808
9313
  const probe = await cachedProbe(directory);
8809
9314
  if (probe.kind === "worktree") {
@@ -8812,7 +9317,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
8812
9317
  if (probe.kind === "invalid") {
8813
9318
  return void 0;
8814
9319
  }
8815
- const parent = path4.dirname(directory);
9320
+ const parent = path5.dirname(directory);
8816
9321
  if (parent === directory) {
8817
9322
  return void 0;
8818
9323
  }
@@ -9024,7 +9529,7 @@ var createCallbackDeduplicator = (deps) => {
9024
9529
  };
9025
9530
 
9026
9531
  // src/telemetry/semconv.ts
9027
- import { createHash as createHash4 } from "crypto";
9532
+ import { createHash as createHash5 } from "crypto";
9028
9533
  import { SpanKind, SpanStatusCode, TraceFlags } from "@opentelemetry/api";
9029
9534
  import { millisToHrTime } from "@opentelemetry/core";
9030
9535
  import {
@@ -9043,7 +9548,7 @@ import {
9043
9548
  } from "@opentelemetry/semantic-conventions/incubating";
9044
9549
 
9045
9550
  // src/version.ts
9046
- var VERSION = "0.13.1";
9551
+ var VERSION = "0.14.0";
9047
9552
 
9048
9553
  // src/telemetry/export-identity.ts
9049
9554
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -9154,7 +9659,7 @@ var ATTR_OTELHOOK_AGENT_NAME = "otelhook.agent.name";
9154
9659
  var ATTR_OTELHOOK_AGENT_VERSION = "otelhook.agent.version";
9155
9660
  var ATTR_OTELHOOK_GENERATION_ID = "otelhook.generation.id";
9156
9661
  var FIELD_SEPARATOR = "\0";
9157
- var digestHex = (parts, length) => createHash4("sha256").update(parts.join(FIELD_SEPARATOR)).digest("hex").slice(0, length);
9662
+ var digestHex = (parts, length) => createHash5("sha256").update(parts.join(FIELD_SEPARATOR)).digest("hex").slice(0, length);
9158
9663
  var MAX_RECOVERED_START_ATTRIBUTES = 16;
9159
9664
  var familyOf = (type) => {
9160
9665
  switch (type) {
@@ -9616,6 +10121,17 @@ var planGroup = (group, correlation, correlationAvailable) => {
9616
10121
  };
9617
10122
  var runDiscriminatorOf = (correlation) => correlation?.runSpanIdDiscriminator === void 0 ? void 0 : `run:${correlation.runSpanIdDiscriminator}`;
9618
10123
  var resumedSessionParent = (ref, correlation) => ref.family === "session" && correlation?.runSpanIdDiscriminator !== void 0 ? ref : void 0;
10124
+ var spanEndEdgesOf = (events) => {
10125
+ const layout = layoutBatch(events);
10126
+ const ends = /* @__PURE__ */ new Map();
10127
+ for (const [eventId, groupKey] of layout.groupOf) {
10128
+ const end = layout.groups.get(groupKey)?.end;
10129
+ if (end !== void 0) {
10130
+ ends.set(eventId, end);
10131
+ }
10132
+ }
10133
+ return ends;
10134
+ };
9619
10135
  var canonicalEventTraceIdentities = (events, options = {}) => {
9620
10136
  const layout = layoutBatch(events);
9621
10137
  const correlations = indexCorrelations(options.correlations);
@@ -9767,7 +10283,7 @@ var decodeRecord = (attributes) => {
9767
10283
  }
9768
10284
  };
9769
10285
  };
9770
- var factsOf = (record) => ({
10286
+ var factsOf2 = (record) => ({
9771
10287
  ...record.startedAt === void 0 ? {} : { startedAt: record.startedAt },
9772
10288
  ...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
9773
10289
  ...record.parent === void 0 ? {} : { parent: record.parent },
@@ -9825,7 +10341,7 @@ var createSpanCorrelator = (deps) => {
9825
10341
  return { status: "conflict", reason: "provider-mismatch" };
9826
10342
  }
9827
10343
  if (existing.startEventId === input.eventId) {
9828
- return { status: "duplicate", facts: factsOf(existing) };
10344
+ return { status: "duplicate", facts: factsOf2(existing) };
9829
10345
  }
9830
10346
  if (existing.startEventId === void 0 && existing.endEventId !== void 0) {
9831
10347
  const completed = {
@@ -9836,7 +10352,7 @@ var createSpanCorrelator = (deps) => {
9836
10352
  ...input.attributes === void 0 ? {} : { attributes: input.attributes }
9837
10353
  };
9838
10354
  await stateStore.write(key, encodeRecord(completed));
9839
- return existing.exported === true ? { status: "published", facts: factsOf(completed) } : { status: "recorded", facts: factsOf(completed) };
10355
+ return existing.exported === true ? { status: "published", facts: factsOf2(completed) } : { status: "recorded", facts: factsOf2(completed) };
9840
10356
  }
9841
10357
  }
9842
10358
  const previouslyExported = decoded.kind === "present" && decoded.record.exported === true;
@@ -9849,7 +10365,7 @@ var createSpanCorrelator = (deps) => {
9849
10365
  ...input.attributes === void 0 ? {} : { attributes: input.attributes }
9850
10366
  };
9851
10367
  await stateStore.write(key, encodeRecord(fresh));
9852
- return { status: "recorded", facts: factsOf(fresh) };
10368
+ return { status: "recorded", facts: factsOf2(fresh) };
9853
10369
  });
9854
10370
  const recordEnd = (input) => withOptionalSessionLock(stateStore, input.sessionId, async () => {
9855
10371
  const key = keyFor(input);
@@ -9868,7 +10384,7 @@ var createSpanCorrelator = (deps) => {
9868
10384
  exported: true
9869
10385
  };
9870
10386
  await stateStore.write(key, encodeRecord(endOnly));
9871
- return { status: "orphaned", reason: "no-start-recorded", facts: factsOf(endOnly) };
10387
+ return { status: "orphaned", reason: "no-start-recorded", facts: factsOf2(endOnly) };
9872
10388
  }
9873
10389
  const existing = decoded.record;
9874
10390
  if (existing.providerId !== input.providerId) {
@@ -9879,7 +10395,7 @@ var createSpanCorrelator = (deps) => {
9879
10395
  };
9880
10396
  }
9881
10397
  if (existing.endEventId === input.eventId) {
9882
- return { status: "duplicate", facts: factsOf(existing) };
10398
+ return { status: "duplicate", facts: factsOf2(existing) };
9883
10399
  }
9884
10400
  if (existing.endEventId !== void 0) {
9885
10401
  return {
@@ -9896,7 +10412,7 @@ var createSpanCorrelator = (deps) => {
9896
10412
  exported: true
9897
10413
  };
9898
10414
  await stateStore.write(key, encodeRecord(replaced));
9899
- return { status: "orphaned", reason: "no-start-recorded", facts: factsOf(replaced) };
10415
+ return { status: "orphaned", reason: "no-start-recorded", facts: factsOf2(replaced) };
9900
10416
  }
9901
10417
  if (input.occurredAt - existing.startedAt > maxStartAgeMillis) {
9902
10418
  await stateStore.delete(key);
@@ -9913,7 +10429,7 @@ var createSpanCorrelator = (deps) => {
9913
10429
  status: "matched",
9914
10430
  startedAt: existing.startedAt,
9915
10431
  durationMillis: Math.max(0, input.occurredAt - existing.startedAt),
9916
- facts: factsOf(closed)
10432
+ facts: factsOf2(closed)
9917
10433
  };
9918
10434
  });
9919
10435
  const correlateGroup = async (group) => {
@@ -10182,7 +10698,7 @@ var createUsageAccumulator = (deps) => {
10182
10698
  };
10183
10699
 
10184
10700
  // src/lifecycle/metric-series.ts
10185
- import { createHash as createHash5 } from "crypto";
10701
+ import { createHash as createHash6 } from "crypto";
10186
10702
 
10187
10703
  // src/telemetry/metric-model.ts
10188
10704
  var TOKEN_USAGE_BUCKETS = Object.freeze([
@@ -10465,7 +10981,7 @@ var TURN_START_SEGMENT = "turn-start";
10465
10981
  var SHARED_SCOPE = "all";
10466
10982
  var SHARED_LOCK = "otelhook.metrics.shared";
10467
10983
  var sessionScope = (sessionId) => `s=${sessionId}`;
10468
- var digest2 = (identity) => createHash5("sha256").update(identity).digest("base64url").slice(0, 43);
10984
+ var digest2 = (identity) => createHash6("sha256").update(identity).digest("base64url").slice(0, 43);
10469
10985
  var toStoredHistogram = (histogram) => ({
10470
10986
  count: histogram.count,
10471
10987
  sum: histogram.sum,
@@ -10707,28 +11223,28 @@ var createBoundedMemoryStateStore = (options) => {
10707
11223
 
10708
11224
  // src/state/filesystem-store.ts
10709
11225
  import { randomBytes as randomBytes2 } from "crypto";
10710
- import { mkdir, open as open4, readFile, readdir, rename, stat as stat3, unlink, writeFile } from "fs/promises";
10711
- import * as path5 from "path";
11226
+ import { mkdir, open as open5, readFile, readdir as readdir2, rename, stat as stat4, unlink, writeFile } from "fs/promises";
11227
+ import * as path6 from "path";
10712
11228
 
10713
11229
  // src/state/keys.ts
10714
- import { createHash as createHash6 } from "crypto";
11230
+ import { createHash as createHash7 } from "crypto";
10715
11231
  var SAFE_SEGMENT_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
10716
11232
  var isSafeSegment = (segment) => SAFE_SEGMENT_PATTERN.test(segment);
10717
11233
  var sanitizeSegment = (segment) => {
10718
11234
  if (isSafeSegment(segment)) {
10719
11235
  return segment;
10720
11236
  }
10721
- return `h_${createHash6("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
11237
+ return `h_${createHash7("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
10722
11238
  };
10723
11239
  var namespaceSegments = (namespace) => [
10724
11240
  sanitizeSegment(namespace.providerId),
10725
11241
  sanitizeSegment(namespace.installationId)
10726
11242
  ];
10727
- var keyDigest = (key) => createHash6("sha256").update(key, "utf8").digest("hex");
11243
+ var keyDigest = (key) => createHash7("sha256").update(key, "utf8").digest("hex");
10728
11244
 
10729
11245
  // src/state/filesystem-store.ts
10730
11246
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
10731
- var sleep = (millis) => new Promise((resolve5) => {
11247
+ var sleep2 = (millis) => new Promise((resolve5) => {
10732
11248
  setTimeout(resolve5, millis);
10733
11249
  });
10734
11250
  var wrapFsError = (thrown, operation) => {
@@ -10739,10 +11255,10 @@ var wrapFsError = (thrown, operation) => {
10739
11255
  };
10740
11256
  var createFilesystemStateStore = (options) => {
10741
11257
  const [providerSegment, installationSegment] = namespaceSegments(options);
10742
- const baseDir = path5.join(options.rootDir, providerSegment, installationSegment);
10743
- const recordsDir = path5.join(baseDir, "records");
10744
- const quarantineDir = path5.join(baseDir, "quarantine");
10745
- const locksDir = path5.join(baseDir, "locks");
11258
+ const baseDir = path6.join(options.rootDir, providerSegment, installationSegment);
11259
+ const recordsDir = path6.join(baseDir, "records");
11260
+ const quarantineDir = path6.join(baseDir, "quarantine");
11261
+ const locksDir = path6.join(baseDir, "locks");
10746
11262
  const lockTimeoutMillis = options.lockTimeoutMillis ?? 5e3;
10747
11263
  const lockStaleMillis = options.lockStaleMillis ?? 3e4;
10748
11264
  const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;
@@ -10766,11 +11282,11 @@ var createFilesystemStateStore = (options) => {
10766
11282
  throw wrapFsError(thrown, "ensure-dirs");
10767
11283
  }
10768
11284
  };
10769
- const recordPath = (key) => path5.join(recordsDir, `${keyDigest(key)}.json`);
10770
- const tempPath = (key) => path5.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
10771
- const lockPath = (sessionId) => path5.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
11285
+ const recordPath = (key) => path6.join(recordsDir, `${keyDigest(key)}.json`);
11286
+ const tempPath = (key) => path6.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
11287
+ const lockPath = (sessionId) => path6.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
10772
11288
  const quarantine = async (filePath, key, reason) => {
10773
- const dest = path5.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
11289
+ const dest = path6.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
10774
11290
  try {
10775
11291
  await rename(filePath, dest);
10776
11292
  } catch {
@@ -10834,7 +11350,7 @@ var createFilesystemStateStore = (options) => {
10834
11350
  const startedAt = options.clock.monotonicMillis();
10835
11351
  for (; ; ) {
10836
11352
  try {
10837
- const handle = await open4(filePath, "wx");
11353
+ const handle = await open5(filePath, "wx");
10838
11354
  try {
10839
11355
  await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));
10840
11356
  } finally {
@@ -10863,7 +11379,7 @@ var createFilesystemStateStore = (options) => {
10863
11379
  } catch {
10864
11380
  }
10865
11381
  try {
10866
- const stats = await stat3(filePath);
11382
+ const stats = await stat4(filePath);
10867
11383
  return Date.now() - stats.mtimeMs > lockStaleMillis;
10868
11384
  } catch {
10869
11385
  return "gone";
@@ -10879,7 +11395,7 @@ var createFilesystemStateStore = (options) => {
10879
11395
  if (options.clock.monotonicMillis() - startedAt >= timeoutMillis) {
10880
11396
  throw new StateLockTimeoutError(sessionId, timeoutMillis);
10881
11397
  }
10882
- await sleep(lockPollIntervalMillis);
11398
+ await sleep2(lockPollIntervalMillis);
10883
11399
  }
10884
11400
  };
10885
11401
  return {
@@ -10903,7 +11419,7 @@ var createFilesystemStateStore = (options) => {
10903
11419
  await ensureDirs();
10904
11420
  let entries;
10905
11421
  try {
10906
- entries = await readdir(recordsDir);
11422
+ entries = await readdir2(recordsDir);
10907
11423
  } catch (thrown) {
10908
11424
  if (isErrnoException(thrown, "ENOENT")) {
10909
11425
  return [];
@@ -10917,7 +11433,7 @@ var createFilesystemStateStore = (options) => {
10917
11433
  }
10918
11434
  let raw;
10919
11435
  try {
10920
- raw = await readFile(path5.join(recordsDir, entry), "utf8");
11436
+ raw = await readFile(path6.join(recordsDir, entry), "utf8");
10921
11437
  } catch {
10922
11438
  continue;
10923
11439
  }
@@ -10955,7 +11471,7 @@ var createFilesystemStateStore = (options) => {
10955
11471
  let scanned = 0;
10956
11472
  let entries;
10957
11473
  try {
10958
- entries = await readdir(recordsDir);
11474
+ entries = await readdir2(recordsDir);
10959
11475
  } catch (thrown) {
10960
11476
  if (!isErrnoException(thrown, "ENOENT")) {
10961
11477
  throw wrapFsError(thrown, "prune");
@@ -10970,7 +11486,7 @@ var createFilesystemStateStore = (options) => {
10970
11486
  continue;
10971
11487
  }
10972
11488
  scanned += 1;
10973
- const filePath = path5.join(recordsDir, entry);
11489
+ const filePath = path6.join(recordsDir, entry);
10974
11490
  try {
10975
11491
  const raw = await readFile(filePath, "utf8");
10976
11492
  const envelope = JSON.parse(raw);
@@ -10985,12 +11501,12 @@ var createFilesystemStateStore = (options) => {
10985
11501
  }
10986
11502
  let lockEntries;
10987
11503
  try {
10988
- lockEntries = await readdir(locksDir);
11504
+ lockEntries = await readdir2(locksDir);
10989
11505
  } catch {
10990
11506
  lockEntries = [];
10991
11507
  }
10992
11508
  for (const entry of lockEntries) {
10993
- const filePath = path5.join(locksDir, entry);
11509
+ const filePath = path6.join(locksDir, entry);
10994
11510
  try {
10995
11511
  const raw = await readFile(filePath, "utf8");
10996
11512
  const parsed = JSON.parse(raw);
@@ -11008,8 +11524,8 @@ var createFilesystemStateStore = (options) => {
11008
11524
 
11009
11525
  // src/telemetry/spool-queue.ts
11010
11526
  import { randomBytes as randomBytes3 } from "crypto";
11011
- import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, rename as rename2, stat as stat4, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
11012
- import * as path6 from "path";
11527
+ import { mkdir as mkdir2, open as open6, readFile as readFile2, readdir as readdir3, rename as rename2, stat as stat5, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
11528
+ import * as path7 from "path";
11013
11529
  var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
11014
11530
  total: 0,
11015
11531
  age: 0,
@@ -11025,7 +11541,7 @@ var enqueuedAtOf = (fileName) => {
11025
11541
  var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
11026
11542
  var readSpoolDropCounts = async (queueDir) => {
11027
11543
  try {
11028
- const parsed = JSON.parse(await readFile2(path6.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
11544
+ const parsed = JSON.parse(await readFile2(path7.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
11029
11545
  if (typeof parsed !== "object" || parsed === null) {
11030
11546
  return EMPTY_SPOOL_DROP_COUNTS;
11031
11547
  }
@@ -11046,7 +11562,7 @@ var readSpoolDropCounts = async (queueDir) => {
11046
11562
  var readSpoolQueueStats = async (queueDir) => {
11047
11563
  let entries;
11048
11564
  try {
11049
- entries = await readdir2(queueDir);
11565
+ entries = await readdir3(queueDir);
11050
11566
  } catch {
11051
11567
  return { batches: 0, bytes: 0, dropped: await readSpoolDropCounts(queueDir) };
11052
11568
  }
@@ -11054,7 +11570,7 @@ var readSpoolQueueStats = async (queueDir) => {
11054
11570
  let bytes = 0;
11055
11571
  for (const file of files) {
11056
11572
  try {
11057
- bytes += (await stat4(path6.join(queueDir, file))).size;
11573
+ bytes += (await stat5(path7.join(queueDir, file))).size;
11058
11574
  } catch {
11059
11575
  }
11060
11576
  }
@@ -11068,7 +11584,8 @@ var readSpoolQueueStats = async (queueDir) => {
11068
11584
  };
11069
11585
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
11070
11586
  var SPOOL_CLAIM_STALE_MILLIS = 5 * 60 * 1e3;
11071
- var CLAIM_MARKER = ".claimed-";
11587
+ var CLAIM_SUFFIX = ".claim";
11588
+ var RELEASING_SUFFIX = ".releasing";
11072
11589
  var isClaimOwnerAlive = (pid) => {
11073
11590
  if (!Number.isSafeInteger(pid) || pid <= 0) {
11074
11591
  return true;
@@ -11084,10 +11601,38 @@ var isClaimOwnerAlive = (pid) => {
11084
11601
  }
11085
11602
  };
11086
11603
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
11604
+ var readClaim = async (claimPath) => {
11605
+ try {
11606
+ const parsed = JSON.parse(await readFile2(claimPath, "utf8"));
11607
+ return typeof parsed.token === "string" && typeof parsed.pid === "number" && typeof parsed.claimedAt === "number" ? { token: parsed.token, pid: parsed.pid, claimedAt: parsed.claimedAt } : void 0;
11608
+ } catch {
11609
+ return void 0;
11610
+ }
11611
+ };
11612
+ var releaseClaim = async (claimPath, token) => {
11613
+ const tombstone = `${claimPath}.${token ?? "untokened"}-${randomBytes3(4).toString("hex")}${RELEASING_SUFFIX}`;
11614
+ for (let attempt = 1; ; attempt += 1) {
11615
+ try {
11616
+ await rename2(claimPath, tombstone);
11617
+ break;
11618
+ } catch (thrown) {
11619
+ if (isErrnoException2(thrown, "ENOENT") || attempt >= 3) {
11620
+ return;
11621
+ }
11622
+ await new Promise((resolve5) => setTimeout(resolve5, 10 * attempt));
11623
+ }
11624
+ }
11625
+ const captured = await readClaim(tombstone);
11626
+ if (captured !== void 0 && captured.token !== token) {
11627
+ await rename2(tombstone, claimPath).catch(() => void 0);
11628
+ return;
11629
+ }
11630
+ await unlink2(tombstone).catch(() => void 0);
11631
+ };
11087
11632
  var createSpoolQueue = (options) => {
11088
11633
  const [providerSegment, installationSegment] = namespaceSegments(options);
11089
- const queueDir = path6.join(options.rootDir, providerSegment, installationSegment, options.queueName);
11090
- const corruptDir = path6.join(
11634
+ const queueDir = path7.join(options.rootDir, providerSegment, installationSegment, options.queueName);
11635
+ const corruptDir = path7.join(
11091
11636
  options.rootDir,
11092
11637
  providerSegment,
11093
11638
  installationSegment,
@@ -11113,7 +11658,7 @@ var createSpoolQueue = (options) => {
11113
11658
  const listSorted = async () => {
11114
11659
  let entries;
11115
11660
  try {
11116
- entries = await readdir2(queueDir);
11661
+ entries = await readdir3(queueDir);
11117
11662
  } catch (thrown) {
11118
11663
  if (isErrnoException2(thrown, "ENOENT")) {
11119
11664
  return [];
@@ -11134,9 +11679,9 @@ var createSpoolQueue = (options) => {
11134
11679
  [reason]: current[reason] + dropped,
11135
11680
  lastDroppedAt: options.clock.now()
11136
11681
  };
11137
- const tmp = path6.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
11682
+ const tmp = path7.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
11138
11683
  await writeFile2(tmp, JSON.stringify(next), "utf8");
11139
- await rename2(tmp, path6.join(queueDir, SPOOL_DROPS_FILE));
11684
+ await rename2(tmp, path7.join(queueDir, SPOOL_DROPS_FILE));
11140
11685
  } catch {
11141
11686
  }
11142
11687
  options.logger?.warn("durable spool dropped batches", {
@@ -11152,7 +11697,7 @@ var createSpoolQueue = (options) => {
11152
11697
  let bytes = 0;
11153
11698
  if (options.maxBytes !== void 0) {
11154
11699
  try {
11155
- bytes = (await stat4(path6.join(queueDir, name))).size;
11700
+ bytes = (await stat5(path7.join(queueDir, name))).size;
11156
11701
  } catch {
11157
11702
  continue;
11158
11703
  }
@@ -11166,7 +11711,7 @@ var createSpoolQueue = (options) => {
11166
11711
  let removed = 0;
11167
11712
  for (const file of files) {
11168
11713
  try {
11169
- await unlink2(path6.join(queueDir, file.name));
11714
+ await unlink2(path7.join(queueDir, file.name));
11170
11715
  removed += 1;
11171
11716
  } catch {
11172
11717
  }
@@ -11226,33 +11771,63 @@ var createSpoolQueue = (options) => {
11226
11771
  }
11227
11772
  }
11228
11773
  const fileName = `${String(now).padStart(16, "0")}-${randomBytes3(6).toString("hex")}.json`;
11229
- const target = path6.join(queueDir, fileName);
11230
- const tmp = path6.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
11774
+ const target = path7.join(queueDir, fileName);
11775
+ const tmp = path7.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
11231
11776
  await writeFile2(tmp, serialized, "utf8");
11232
11777
  await rename2(tmp, target);
11233
11778
  return { spooled: true };
11234
11779
  };
11780
+ const claimStaleMillis = options.claimStaleMillis ?? SPOOL_CLAIM_STALE_MILLIS;
11781
+ const staleClaim = async (claimPath) => {
11782
+ const claim = await readClaim(claimPath);
11783
+ const now = Date.now();
11784
+ if (claim !== void 0) {
11785
+ return !isClaimOwnerAlive(claim.pid) || now - claim.claimedAt > claimStaleMillis ? { stale: true, token: claim.token } : { stale: false };
11786
+ }
11787
+ try {
11788
+ return now - (await stat5(claimPath)).mtimeMs > claimStaleMillis ? { stale: true, token: void 0 } : { stale: false };
11789
+ } catch {
11790
+ return { stale: false };
11791
+ }
11792
+ };
11235
11793
  const releaseStaleClaims = async () => {
11236
11794
  let entries;
11237
11795
  try {
11238
- entries = await readdir2(queueDir);
11796
+ entries = await readdir3(queueDir);
11239
11797
  } catch {
11240
11798
  return;
11241
11799
  }
11242
11800
  const now = Date.now();
11243
11801
  for (const entry of entries) {
11244
- const marker = entry.lastIndexOf(CLAIM_MARKER);
11245
- if (marker <= 0) {
11246
- continue;
11802
+ const entryPath = path7.join(queueDir, entry);
11803
+ if (entry.endsWith(CLAIM_SUFFIX)) {
11804
+ const staleness = await staleClaim(entryPath);
11805
+ if (staleness.stale) {
11806
+ await releaseClaim(entryPath, staleness.token);
11807
+ }
11808
+ } else if (entry.endsWith(RELEASING_SUFFIX)) {
11809
+ try {
11810
+ if (now - (await stat5(entryPath)).mtimeMs > claimStaleMillis) {
11811
+ await unlink2(entryPath);
11812
+ }
11813
+ } catch {
11814
+ }
11247
11815
  }
11248
- const claimPath = path6.join(queueDir, entry);
11249
- const owner = Number.parseInt(entry.slice(marker + CLAIM_MARKER.length), 10);
11816
+ }
11817
+ };
11818
+ const claimBatch = async (claimPath) => {
11819
+ const token = randomBytes3(16).toString("hex");
11820
+ try {
11821
+ const handle = await open6(claimPath, "wx");
11250
11822
  try {
11251
- if (!isClaimOwnerAlive(owner) || now - (await stat4(claimPath)).ctimeMs > (options.claimStaleMillis ?? SPOOL_CLAIM_STALE_MILLIS)) {
11252
- await rename2(claimPath, path6.join(queueDir, entry.slice(0, marker)));
11253
- }
11254
- } catch {
11823
+ const contents = { token, pid: process.pid, claimedAt: Date.now() };
11824
+ await handle.writeFile(JSON.stringify(contents), "utf8");
11825
+ } finally {
11826
+ await handle.close();
11255
11827
  }
11828
+ return token;
11829
+ } catch {
11830
+ return void 0;
11256
11831
  }
11257
11832
  };
11258
11833
  const drain = async (send, drainOptions) => {
@@ -11276,21 +11851,7 @@ var createSpoolQueue = (options) => {
11276
11851
  let failed = 0;
11277
11852
  let quarantined = 0;
11278
11853
  let index = 0;
11279
- for (; index < files.length && index < cap; index += 1) {
11280
- const fileName = files[index];
11281
- if (fileName === void 0) {
11282
- break;
11283
- }
11284
- const queuedPath = path6.join(queueDir, fileName);
11285
- const filePath = path6.join(
11286
- queueDir,
11287
- `${fileName}${CLAIM_MARKER}${String(process.pid)}-${randomBytes3(4).toString("hex")}`
11288
- );
11289
- try {
11290
- await rename2(queuedPath, filePath);
11291
- } catch {
11292
- continue;
11293
- }
11854
+ const sendClaimed = async (fileName, filePath, claimPath, token) => {
11294
11855
  const quarantine = async (rejection) => {
11295
11856
  quarantined += 1;
11296
11857
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -11299,7 +11860,7 @@ var createSpoolQueue = (options) => {
11299
11860
  "spool.queue": options.queueName
11300
11861
  });
11301
11862
  try {
11302
- await rename2(filePath, path6.join(corruptDir, fileName));
11863
+ await rename2(filePath, path7.join(corruptDir, fileName));
11303
11864
  } catch {
11304
11865
  await unlink2(filePath).catch(() => void 0);
11305
11866
  }
@@ -11309,17 +11870,17 @@ var createSpoolQueue = (options) => {
11309
11870
  text = await readFile2(filePath, "utf8");
11310
11871
  } catch (thrown) {
11311
11872
  if (thrown?.code === "ENOENT") {
11312
- continue;
11873
+ return "next";
11313
11874
  }
11314
11875
  await quarantine("unreadable");
11315
- continue;
11876
+ return "next";
11316
11877
  }
11317
11878
  let parsed;
11318
11879
  try {
11319
11880
  parsed = JSON.parse(text);
11320
11881
  } catch {
11321
11882
  await quarantine("unparseable-json");
11322
- continue;
11883
+ return "next";
11323
11884
  }
11324
11885
  const validation = options.validate(parsed, {
11325
11886
  providerId: options.providerId,
@@ -11327,7 +11888,10 @@ var createSpoolQueue = (options) => {
11327
11888
  });
11328
11889
  if ("rejection" in validation) {
11329
11890
  await quarantine(validation.rejection);
11330
- continue;
11891
+ return "next";
11892
+ }
11893
+ if ((await readClaim(claimPath))?.token !== token) {
11894
+ return "next";
11331
11895
  }
11332
11896
  let delivered;
11333
11897
  try {
@@ -11339,14 +11903,34 @@ var createSpoolQueue = (options) => {
11339
11903
  if (await unlink2(filePath).then(() => true, () => false)) {
11340
11904
  await recordDrops("rejected", 1);
11341
11905
  }
11342
- continue;
11906
+ return "next";
11343
11907
  }
11344
11908
  if (delivered) {
11345
11909
  await unlink2(filePath).catch(() => void 0);
11346
11910
  drained += 1;
11347
- } else {
11348
- await rename2(filePath, queuedPath).catch(() => void 0);
11349
- failed += 1;
11911
+ return "next";
11912
+ }
11913
+ failed += 1;
11914
+ return "stop";
11915
+ };
11916
+ for (; index < files.length && index < cap; index += 1) {
11917
+ const fileName = files[index];
11918
+ if (fileName === void 0) {
11919
+ break;
11920
+ }
11921
+ const filePath = path7.join(queueDir, fileName);
11922
+ const claimPath = `${filePath}${CLAIM_SUFFIX}`;
11923
+ const token = await claimBatch(claimPath);
11924
+ if (token === void 0) {
11925
+ continue;
11926
+ }
11927
+ let outcome;
11928
+ try {
11929
+ outcome = await sendClaimed(fileName, filePath, claimPath, token);
11930
+ } finally {
11931
+ await releaseClaim(claimPath, token);
11932
+ }
11933
+ if (outcome === "stop") {
11350
11934
  break;
11351
11935
  }
11352
11936
  }
@@ -11460,7 +12044,7 @@ var createFileDurableSpool = (options) => createSpoolQueue({
11460
12044
  });
11461
12045
 
11462
12046
  // src/telemetry/otlp-sink.ts
11463
- import { ExportResultCode } from "@opentelemetry/core";
12047
+ import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
11464
12048
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
11465
12049
 
11466
12050
  // src/diagnostics/health.ts
@@ -11513,6 +12097,217 @@ var isPermanentExportFailure = (result) => {
11513
12097
  return typeof code === "number" && Number.isInteger(code) && code >= 400 && code < 600 && !RETRYABLE_HTTP_STATUSES.has(code);
11514
12098
  };
11515
12099
 
12100
+ // src/telemetry/endpoint-health.ts
12101
+ import { createHash as createHash8, randomBytes as randomBytes4 } from "crypto";
12102
+ import { mkdir as mkdir3, readFile as readFile3, rename as rename3, unlink as unlink3, writeFile as writeFile3 } from "fs/promises";
12103
+ import * as http from "http";
12104
+ import * as https from "https";
12105
+ import path8 from "path";
12106
+ import { ExportResultCode } from "@opentelemetry/core";
12107
+ var ENDPOINT_DOWN_ERROR_CODE = "OTEL_HOOK_ENDPOINT_DOWN";
12108
+ var UNREACHABLE_NETWORK_CODES = /* @__PURE__ */ new Set([
12109
+ "ECONNREFUSED",
12110
+ "ECONNRESET",
12111
+ "ETIMEDOUT",
12112
+ "EPIPE",
12113
+ "EHOSTUNREACH",
12114
+ "ENETUNREACH",
12115
+ "EHOSTDOWN",
12116
+ "ENETDOWN",
12117
+ "EAI_AGAIN",
12118
+ "ENOTFOUND",
12119
+ ENDPOINT_DOWN_ERROR_CODE
12120
+ ]);
12121
+ var isUnreachableExportFailure = (result) => {
12122
+ if (result.code === ExportResultCode.SUCCESS) {
12123
+ return false;
12124
+ }
12125
+ const error = result.error;
12126
+ const code = error?.code;
12127
+ if (typeof code === "string") {
12128
+ return UNREACHABLE_NETWORK_CODES.has(code);
12129
+ }
12130
+ if (code !== void 0) {
12131
+ return false;
12132
+ }
12133
+ return typeof error?.message === "string" && /timed out/i.test(error.message);
12134
+ };
12135
+ var withConnectTimeout = (agent, connectTimeoutMillis) => {
12136
+ const target = agent;
12137
+ const original = target.createConnection.bind(agent);
12138
+ target.createConnection = (options, callback) => {
12139
+ const socket = original(options, callback);
12140
+ if (socket !== void 0 && socket.connecting) {
12141
+ const timer = setTimeout(() => {
12142
+ const error = Object.assign(new Error("connect timed out"), { code: "ETIMEDOUT" });
12143
+ socket.destroy(error);
12144
+ }, connectTimeoutMillis);
12145
+ timer.unref();
12146
+ const clear = () => {
12147
+ clearTimeout(timer);
12148
+ };
12149
+ socket.once("connect", clear);
12150
+ socket.once("close", clear);
12151
+ }
12152
+ return socket;
12153
+ };
12154
+ return agent;
12155
+ };
12156
+ var boundedExporterOptions = (exporter) => {
12157
+ const timeoutMillis = effectiveExportTimeoutMillis(exporter);
12158
+ let agents = {};
12159
+ return {
12160
+ timeoutMillis,
12161
+ httpAgentOptions: (protocol) => {
12162
+ if (protocol === "https:") {
12163
+ agents = { ...agents, https: agents.https ?? withConnectTimeout(new https.Agent({ keepAlive: true }), timeoutMillis) };
12164
+ return agents.https;
12165
+ }
12166
+ agents = { ...agents, http: agents.http ?? withConnectTimeout(new http.Agent({ keepAlive: true }), timeoutMillis) };
12167
+ return agents.http;
12168
+ }
12169
+ };
12170
+ };
12171
+ var parseMark = (raw) => {
12172
+ try {
12173
+ const parsed = JSON.parse(raw);
12174
+ return typeof parsed.downUntil === "number" && Number.isFinite(parsed.downUntil) ? {
12175
+ downUntil: parsed.downUntil,
12176
+ failures: typeof parsed.failures === "number" && Number.isInteger(parsed.failures) ? parsed.failures : 1
12177
+ } : void 0;
12178
+ } catch {
12179
+ return void 0;
12180
+ }
12181
+ };
12182
+ var originOf = (url) => {
12183
+ if (url === void 0) {
12184
+ return void 0;
12185
+ }
12186
+ try {
12187
+ return new URL(url).origin;
12188
+ } catch {
12189
+ return void 0;
12190
+ }
12191
+ };
12192
+ var createEndpointHealth = (options) => {
12193
+ const downMillis = options.downMillis ?? DEFAULT_ENDPOINT_DOWN_MILLIS;
12194
+ const gates = /* @__PURE__ */ new Map();
12195
+ const createGate = (origin) => {
12196
+ const digest3 = createHash8("sha256").update(origin, "utf8").digest("hex").slice(0, 32);
12197
+ const dir = options.rootDir === void 0 ? void 0 : path8.join(options.rootDir, "endpoint-health");
12198
+ const file = dir === void 0 ? void 0 : path8.join(dir, `${digest3}.json`);
12199
+ let downUntil = 0;
12200
+ let failures = 0;
12201
+ let marked = false;
12202
+ let loaded;
12203
+ let warned = false;
12204
+ const write = async (mark) => {
12205
+ if (file === void 0 || dir === void 0) {
12206
+ return;
12207
+ }
12208
+ try {
12209
+ await mkdir3(dir, { recursive: true });
12210
+ const tmp = path8.join(dir, `.tmp-${randomBytes4(6).toString("hex")}.json`);
12211
+ await writeFile3(tmp, `${JSON.stringify(mark)}
12212
+ `);
12213
+ await rename3(tmp, file);
12214
+ marked = true;
12215
+ } catch {
12216
+ }
12217
+ };
12218
+ const load = () => {
12219
+ loaded ??= (async () => {
12220
+ if (file === void 0) {
12221
+ return;
12222
+ }
12223
+ let raw;
12224
+ try {
12225
+ raw = await readFile3(file, "utf8");
12226
+ } catch {
12227
+ return;
12228
+ }
12229
+ marked = true;
12230
+ const mark = parseMark(raw);
12231
+ if (mark === void 0) {
12232
+ return;
12233
+ }
12234
+ failures = mark.failures;
12235
+ const now = options.clock.now();
12236
+ if (mark.downUntil > now) {
12237
+ downUntil = mark.downUntil;
12238
+ return;
12239
+ }
12240
+ await write({ downUntil: now + options.probeMillis, failures });
12241
+ })();
12242
+ return loaded;
12243
+ };
12244
+ return {
12245
+ available: async () => {
12246
+ if (downMillis === 0) {
12247
+ return true;
12248
+ }
12249
+ await load();
12250
+ return options.clock.now() >= downUntil;
12251
+ },
12252
+ record: async (result) => {
12253
+ if (downMillis === 0) {
12254
+ return;
12255
+ }
12256
+ if (!isUnreachableExportFailure(result)) {
12257
+ if (!marked && downUntil === 0) {
12258
+ return;
12259
+ }
12260
+ downUntil = 0;
12261
+ failures = 0;
12262
+ marked = false;
12263
+ if (file !== void 0) {
12264
+ await unlink3(file).catch(() => void 0);
12265
+ }
12266
+ return;
12267
+ }
12268
+ failures += 1;
12269
+ downUntil = options.clock.now() + downMillis;
12270
+ if (!warned) {
12271
+ warned = true;
12272
+ options.logger?.warn("export endpoint unreachable; hooks spool for it without trying until it is probed again", {
12273
+ "export.endpoint_down_millis": downMillis,
12274
+ "export.endpoint_failures": failures
12275
+ });
12276
+ }
12277
+ await write({ downUntil, failures });
12278
+ }
12279
+ };
12280
+ };
12281
+ return {
12282
+ gateFor: (url) => {
12283
+ const origin = originOf(url);
12284
+ if (origin === void 0) {
12285
+ return void 0;
12286
+ }
12287
+ let gate = gates.get(origin);
12288
+ if (gate === void 0) {
12289
+ gate = createGate(origin);
12290
+ gates.set(origin, gate);
12291
+ }
12292
+ return gate;
12293
+ }
12294
+ };
12295
+ };
12296
+ var guardExport = async (gate, send) => {
12297
+ if (gate === void 0) {
12298
+ return send();
12299
+ }
12300
+ if (!await gate.available()) {
12301
+ return {
12302
+ code: ExportResultCode.FAILED,
12303
+ error: Object.assign(new Error("endpoint marked down; batch not sent"), { code: ENDPOINT_DOWN_ERROR_CODE })
12304
+ };
12305
+ }
12306
+ const result = await send();
12307
+ await gate.record(result).catch(() => void 0);
12308
+ return result;
12309
+ };
12310
+
11516
12311
  // src/telemetry/exporter-resource.ts
11517
12312
  import { resourceFromAttributes } from "@opentelemetry/resources";
11518
12313
  var resourceFromExporterPolicy = (policy) => resourceFromAttributes({
@@ -11652,12 +12447,16 @@ var createOtlpTraceSink = (options) => {
11652
12447
  const exporter = new OTLPTraceExporter({
11653
12448
  url: options.exporter.endpoint,
11654
12449
  headers: { ...options.headers },
11655
- timeoutMillis: options.exporter.timeoutMillis
12450
+ ...boundedExporterOptions(options.exporter)
11656
12451
  });
12452
+ const gate = options.endpointHealth?.gateFor(options.exporter.endpoint);
11657
12453
  let shutdownCompleted = false;
11658
- const exportSpans = (spans) => new Promise((resolve5) => {
11659
- exporter.export([...spans], (result) => resolve5(result));
11660
- });
12454
+ const exportSpans = (spans) => guardExport(
12455
+ gate,
12456
+ () => new Promise((resolve5) => {
12457
+ exporter.export([...spans], (result) => resolve5(result));
12458
+ })
12459
+ );
11661
12460
  const toSpoolBatch = (spans, batchResource) => ({
11662
12461
  providerId: options.providerId,
11663
12462
  installationId: options.installationId,
@@ -11670,7 +12469,7 @@ var createOtlpTraceSink = (options) => {
11670
12469
  const batchResource = replayResource(batch.resourceAttributes, options.exporter);
11671
12470
  const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));
11672
12471
  const result = await exportSpans(spans);
11673
- if (result.code === ExportResultCode.SUCCESS) {
12472
+ if (result.code === ExportResultCode2.SUCCESS) {
11674
12473
  return true;
11675
12474
  }
11676
12475
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -11709,9 +12508,9 @@ var createOtlpTraceSink = (options) => {
11709
12508
  try {
11710
12509
  result = await exportSpans(batch);
11711
12510
  } catch (thrown) {
11712
- result = { code: ExportResultCode.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
12511
+ result = { code: ExportResultCode2.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
11713
12512
  }
11714
- if (result.code === ExportResultCode.SUCCESS) {
12513
+ if (result.code === ExportResultCode2.SUCCESS) {
11715
12514
  accepted += batch.length;
11716
12515
  health.recordSuccess(batch.length, options.clock.now());
11717
12516
  continue;
@@ -11748,6 +12547,9 @@ var createOtlpTraceSink = (options) => {
11748
12547
  if (options.spool === void 0) {
11749
12548
  return { drained: 0, remaining: 0, failed: 0 };
11750
12549
  }
12550
+ if (gate !== void 0 && !await gate.available()) {
12551
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
12552
+ }
11751
12553
  const result = await options.spool.drain(sendSerializedBatch, { ...maxBatches === void 0 ? {} : { maxBatches } });
11752
12554
  if (result.drained > 0) {
11753
12555
  health.recordSuccess(result.drained, options.clock.now());
@@ -12305,7 +13107,7 @@ var createFileDurableLogSpool = (options) => createSpoolQueue({
12305
13107
 
12306
13108
  // src/telemetry/otlp-log-sink.ts
12307
13109
  import { TraceFlags as TraceFlags3 } from "@opentelemetry/api";
12308
- import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
13110
+ import { ExportResultCode as ExportResultCode3 } from "@opentelemetry/core";
12309
13111
  import { millisToHrTime as millisToHrTime3 } from "@opentelemetry/core";
12310
13112
  import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
12311
13113
  var resolveLogsEndpoint = (exporter) => {
@@ -12448,12 +13250,16 @@ var createOtlpLogSink = (options) => {
12448
13250
  const exporter = new OTLPLogExporter({
12449
13251
  url: deliverability.endpoint,
12450
13252
  headers: { ...options.headers },
12451
- timeoutMillis: options.exporter.timeoutMillis
13253
+ ...boundedExporterOptions(options.exporter)
12452
13254
  });
13255
+ const gate = options.endpointHealth?.gateFor(deliverability.endpoint);
12453
13256
  let shutdownCompleted = false;
12454
- const exportRecords = (records) => new Promise((resolve5) => {
12455
- exporter.export([...records], (result) => resolve5(result));
12456
- });
13257
+ const exportRecords = (records) => guardExport(
13258
+ gate,
13259
+ () => new Promise((resolve5) => {
13260
+ exporter.export([...records], (result) => resolve5(result));
13261
+ })
13262
+ );
12457
13263
  const toSpoolBatch = (records, batchResource) => ({
12458
13264
  providerId: options.providerId,
12459
13265
  installationId: options.installationId,
@@ -12471,7 +13277,7 @@ var createOtlpLogSink = (options) => {
12471
13277
  (record) => deserializeRecord(record, batchResource, batch.instrumentationScope)
12472
13278
  );
12473
13279
  const result = await exportRecords(records);
12474
- if (result.code === ExportResultCode2.SUCCESS) {
13280
+ if (result.code === ExportResultCode3.SUCCESS) {
12475
13281
  return true;
12476
13282
  }
12477
13283
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -12517,11 +13323,11 @@ var createOtlpLogSink = (options) => {
12517
13323
  result = await exportRecords(batch);
12518
13324
  } catch (thrown) {
12519
13325
  result = {
12520
- code: ExportResultCode2.FAILED,
13326
+ code: ExportResultCode3.FAILED,
12521
13327
  error: thrown instanceof Error ? thrown : new Error("export threw")
12522
13328
  };
12523
13329
  }
12524
- if (result.code === ExportResultCode2.SUCCESS) {
13330
+ if (result.code === ExportResultCode3.SUCCESS) {
12525
13331
  accepted += batch.length;
12526
13332
  health.recordSuccess(batch.length, options.clock.now());
12527
13333
  continue;
@@ -12562,6 +13368,9 @@ var createOtlpLogSink = (options) => {
12562
13368
  if (options.spool === void 0) {
12563
13369
  return { drained: 0, remaining: 0, failed: 0 };
12564
13370
  }
13371
+ if (gate !== void 0 && !await gate.available()) {
13372
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
13373
+ }
12565
13374
  const result = await options.spool.drain(sendSerializedBatch, {
12566
13375
  ...maxBatches === void 0 ? {} : { maxBatches }
12567
13376
  });
@@ -12629,14 +13438,20 @@ var createSignalFanout = (options) => {
12629
13438
  };
12630
13439
  var shareCorrelationPerBatch = (correlate) => {
12631
13440
  let pending;
12632
- return (events) => {
12633
- if (pending?.events === events) {
13441
+ const resolve5 = (events) => {
13442
+ if (pending !== void 0 && (pending.events === events || pending.aliases.has(events))) {
12634
13443
  return pending.result;
12635
13444
  }
12636
13445
  const result = correlate(events);
12637
- pending = { events, result };
13446
+ pending = { events, aliases: /* @__PURE__ */ new Set(), result };
12638
13447
  return result;
12639
13448
  };
13449
+ const alias = (subset, batch) => {
13450
+ if (pending?.events === batch && subset !== batch) {
13451
+ pending.aliases.add(subset);
13452
+ }
13453
+ };
13454
+ return Object.assign(resolve5, { alias });
12640
13455
  };
12641
13456
 
12642
13457
  // src/telemetry/durable-metric-spool.ts
@@ -12720,7 +13535,7 @@ var createFileDurableMetricSpool = (options) => createSpoolQueue({
12720
13535
 
12721
13536
  // src/telemetry/otlp-metric-sink.ts
12722
13537
  import { ValueType } from "@opentelemetry/api";
12723
- import { ExportResultCode as ExportResultCode3, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
13538
+ import { ExportResultCode as ExportResultCode4, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
12724
13539
  import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
12725
13540
  import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
12726
13541
  import {
@@ -12864,10 +13679,12 @@ var createOtlpMetricSink = (options) => {
12864
13679
  const exporter = new OTLPMetricExporter({
12865
13680
  url: deliverability.endpoint,
12866
13681
  headers: { ...options.headers },
12867
- timeoutMillis: options.exporter.timeoutMillis
13682
+ ...boundedExporterOptions(options.exporter)
12868
13683
  });
13684
+ const gate = options.endpointHealth?.gateFor(deliverability.endpoint);
12869
13685
  let shutdownCompleted = false;
12870
- const exportResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve5) => {
13686
+ const exportResourceMetrics = (points, batchResource, batchScope) => guardExport(gate, () => sendResourceMetrics(points, batchResource, batchScope));
13687
+ const sendResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve5) => {
12871
13688
  const payload = {
12872
13689
  resource: batchResource,
12873
13690
  scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }]
@@ -12876,7 +13693,7 @@ var createOtlpMetricSink = (options) => {
12876
13693
  exporter.export(payload, (result) => resolve5(result));
12877
13694
  } catch (thrown) {
12878
13695
  resolve5({
12879
- code: ExportResultCode3.FAILED,
13696
+ code: ExportResultCode4.FAILED,
12880
13697
  error: thrown instanceof Error ? thrown : new Error("export threw")
12881
13698
  });
12882
13699
  }
@@ -12897,7 +13714,7 @@ var createOtlpMetricSink = (options) => {
12897
13714
  withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes)
12898
13715
  );
12899
13716
  const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);
12900
- if (result.code === ExportResultCode3.SUCCESS) {
13717
+ if (result.code === ExportResultCode4.SUCCESS) {
12901
13718
  return true;
12902
13719
  }
12903
13720
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -12908,7 +13725,7 @@ var createOtlpMetricSink = (options) => {
12908
13725
  }
12909
13726
  const batchResource = context === void 0 ? resource : resourceWithContext(resource, context);
12910
13727
  const result = await exportResourceMetrics(points, batchResource, scope);
12911
- if (result.code === ExportResultCode3.SUCCESS) {
13728
+ if (result.code === ExportResultCode4.SUCCESS) {
12912
13729
  health.recordSuccess(points.length, options.clock.now());
12913
13730
  return { accepted: points.length, rejected: 0, errors: [] };
12914
13731
  }
@@ -12948,6 +13765,9 @@ var createOtlpMetricSink = (options) => {
12948
13765
  if (options.spool === void 0) {
12949
13766
  return { drained: 0, remaining: 0, failed: 0 };
12950
13767
  }
13768
+ if (gate !== void 0 && !await gate.available()) {
13769
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
13770
+ }
12951
13771
  const result = await options.spool.drain(sendSerializedBatch, {
12952
13772
  ...maxBatches === void 0 ? {} : { maxBatches }
12953
13773
  });
@@ -12984,6 +13804,101 @@ var createOtlpMetricSink = (options) => {
12984
13804
  };
12985
13805
  };
12986
13806
 
13807
+ // src/telemetry/destination-scope.ts
13808
+ var DISCLOSURE_RANK2 = Object.freeze({
13809
+ omitted: 0,
13810
+ masked: 1,
13811
+ redacted: 2,
13812
+ raw: 3
13813
+ });
13814
+ var omitRestrictedContent = (fact, mode) => {
13815
+ if (fact.text === void 0 || DISCLOSURE_RANK2[fact.disclosure] <= DISCLOSURE_RANK2[CONTENT_MODE_DISCLOSURE[mode]]) {
13816
+ return fact;
13817
+ }
13818
+ const { text, ...rest } = fact;
13819
+ void text;
13820
+ return { ...rest, disclosure: "omitted", truncated: false };
13821
+ };
13822
+ var keyOfValue = (value) => typeof value === "string" ? normalizeRepositoryKey(value) : void 0;
13823
+ var resourceRepositoryKey = (attributes) => keyOfValue(attributes[ATTR_VCS_REPOSITORY_URL_FULL]);
13824
+ var eventRepositoryKey = (event3, fallbackKey) => {
13825
+ const stamped = event3.contextAttributes?.[ATTR_VCS_REPOSITORY_URL_FULL];
13826
+ return stamped === void 0 ? fallbackKey : keyOfValue(stamped);
13827
+ };
13828
+ var pointRepositoryKey = (point, fallbackKey) => {
13829
+ const stamped = point.attributes[ATTR_VCS_REPOSITORY_URL_FULL];
13830
+ return stamped === void 0 ? fallbackKey : keyOfValue(stamped);
13831
+ };
13832
+ var restrictFacts = (facts, mode, restrict) => facts?.map((fact) => restrict(fact, mode));
13833
+ var restrictEventContent = (event3, mode, restrict) => {
13834
+ switch (event3.type) {
13835
+ case "prompt.submitted":
13836
+ return event3.content === void 0 ? event3 : { ...event3, content: restrict(event3.content, mode) };
13837
+ case "generation.start": {
13838
+ const inputContent = restrictFacts(event3.inputContent, mode, restrict);
13839
+ return inputContent === void 0 ? event3 : { ...event3, inputContent };
13840
+ }
13841
+ case "generation.end": {
13842
+ const outputContent = restrictFacts(event3.outputContent, mode, restrict);
13843
+ return outputContent === void 0 ? event3 : { ...event3, outputContent };
13844
+ }
13845
+ case "tool.start":
13846
+ return event3.input === void 0 ? event3 : { ...event3, input: restrict(event3.input, mode) };
13847
+ case "tool.end":
13848
+ return event3.output === void 0 ? event3 : { ...event3, output: restrict(event3.output, mode) };
13849
+ case "error.raised":
13850
+ return event3.message === void 0 ? event3 : { ...event3, message: restrict(event3.message, mode) };
13851
+ default:
13852
+ return event3;
13853
+ }
13854
+ };
13855
+ var routeEventsToScopes = (events, scopes, options) => {
13856
+ const ends = spanEndEdgesOf(events);
13857
+ const traces = [];
13858
+ const logs = [];
13859
+ let unchanged = true;
13860
+ for (const event3 of events) {
13861
+ const anchor = ends.get(event3.eventId) ?? event3;
13862
+ const scope = matchDestinationScope(scopes, eventRepositoryKey(anchor, options.resourceRepositoryKey));
13863
+ if (scope === void 0 || !scope.signals.traces || !scope.signals.logs) {
13864
+ unchanged = false;
13865
+ }
13866
+ if (scope === void 0) {
13867
+ continue;
13868
+ }
13869
+ const restricted = scope.contentMode === void 0 ? event3 : restrictEventContent(event3, scope.contentMode, options.restrict);
13870
+ if (restricted !== event3) {
13871
+ unchanged = false;
13872
+ }
13873
+ if (scope.signals.traces) {
13874
+ traces.push(restricted);
13875
+ }
13876
+ if (scope.signals.logs) {
13877
+ logs.push(restricted);
13878
+ }
13879
+ }
13880
+ return unchanged ? { traces: events, logs: events } : { traces, logs };
13881
+ };
13882
+ var routePointsToScopes = (scopes, pointsFor, options) => {
13883
+ const effective = (scope) => options.includeSessionId && scope.includeSessionId;
13884
+ const kept = [];
13885
+ for (const variant of [true, false]) {
13886
+ if (!scopes.some((scope) => scope.signals.metrics && effective(scope) === variant)) {
13887
+ continue;
13888
+ }
13889
+ for (const point of pointsFor(variant) ?? []) {
13890
+ const scope = matchDestinationScope(scopes, pointRepositoryKey(point, options.fallbackKey));
13891
+ if (scope?.signals.metrics === true && effective(scope) === variant) {
13892
+ kept.push(point);
13893
+ }
13894
+ }
13895
+ }
13896
+ return kept;
13897
+ };
13898
+ var sessionIdVariantsFor = (scopes, includeSessionId) => new Set(
13899
+ scopes.filter((scope) => scope.signals.metrics).map((scope) => includeSessionId && scope.includeSessionId)
13900
+ );
13901
+
12987
13902
  // src/telemetry/export-destinations.ts
12988
13903
  var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs", metrics: "spool-metrics" } : {
12989
13904
  traces: `destinations/${destination}/spool`,
@@ -13043,6 +13958,15 @@ var createExportDestinationSinks = (options) => {
13043
13958
  const spoolPolicy = effectiveSpoolPolicy(options.exporter);
13044
13959
  const destinations = [];
13045
13960
  const skipped = [];
13961
+ const endpointHealth = options.endpointHealth ?? createEndpointHealth({
13962
+ ...options.spoolRootDir === void 0 ? {} : { rootDir: options.spoolRootDir },
13963
+ clock: options.clock,
13964
+ ...options.logger === void 0 ? {} : { logger: options.logger },
13965
+ ...options.exporter.endpointDownMillis === void 0 ? {} : { downMillis: options.exporter.endpointDownMillis },
13966
+ probeMillis: effectiveExportTimeoutMillis(options.exporter) + 1e3
13967
+ });
13968
+ const scopedResourceKey = resourceRepositoryKey(resourceFromExporterPolicy(options.exporter).attributes);
13969
+ const restrict = options.restrictContent ?? omitRestrictedContent;
13046
13970
  for (const destination of resolveExportDestinations(options.exporter)) {
13047
13971
  let headers;
13048
13972
  let logHeaders;
@@ -13102,6 +14026,7 @@ var createExportDestinationSinks = (options) => {
13102
14026
  const sinkShared = {
13103
14027
  exporter: policy,
13104
14028
  ...shared,
14029
+ endpointHealth,
13105
14030
  ...options.correlate === void 0 ? {} : { correlate: options.correlate },
13106
14031
  ...label === void 0 ? {} : { destination: label }
13107
14032
  };
@@ -13119,6 +14044,7 @@ var createExportDestinationSinks = (options) => {
13119
14044
  const metrics = destination.signals.metrics ? createOtlpMetricSink({
13120
14045
  exporter: policy,
13121
14046
  ...shared,
14047
+ endpointHealth,
13122
14048
  ...label === void 0 ? {} : { destination: label },
13123
14049
  ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
13124
14050
  ...metricSpool === void 0 ? {} : { spool: metricSpool }
@@ -13130,17 +14056,51 @@ var createExportDestinationSinks = (options) => {
13130
14056
  metrics,
13131
14057
  ...spool === void 0 ? {} : { spool },
13132
14058
  ...logSpool === void 0 ? {} : { logSpool },
13133
- ...metricSpool === void 0 ? {} : { metricSpool }
14059
+ ...metricSpool === void 0 ? {} : { metricSpool },
14060
+ ...destination.scopes === void 0 ? {} : {
14061
+ scopes: destination.scopes,
14062
+ route: (events) => routeEventsToScopes(events, destination.scopes ?? [], {
14063
+ ...scopedResourceKey === void 0 ? {} : { resourceRepositoryKey: scopedResourceKey },
14064
+ restrict
14065
+ })
14066
+ }
13134
14067
  });
13135
14068
  }
13136
14069
  return { destinations, skipped };
13137
14070
  };
13138
- var createDestinationFanout = (destinations) => {
14071
+ var createScopedFanout = (destination, correlate) => {
14072
+ const route = destination.route;
14073
+ const unscoped = createSignalFanout({ traces: destination.traces, logs: destination.logs });
14074
+ if (route === void 0) {
14075
+ return unscoped;
14076
+ }
14077
+ const none2 = { accepted: 0, rejected: 0, errors: [] };
14078
+ return {
14079
+ ...unscoped,
14080
+ emit: async (events) => {
14081
+ const batch = route(events);
14082
+ if (correlate !== void 0 && (batch.traces.length > 0 || batch.logs.length > 0)) {
14083
+ await correlate(events);
14084
+ correlate.alias(batch.traces, events);
14085
+ correlate.alias(batch.logs, events);
14086
+ }
14087
+ const traces = batch.traces.length === 0 ? none2 : await destination.traces.emit(batch.traces);
14088
+ const logs = batch.logs.length === 0 ? none2 : await destination.logs.emit(batch.logs);
14089
+ return {
14090
+ accepted: traces.accepted + logs.accepted,
14091
+ rejected: traces.rejected + logs.rejected,
14092
+ errors: [...traces.errors, ...logs.errors]
14093
+ };
14094
+ }
14095
+ };
14096
+ };
14097
+ var createDestinationFanout = (destinations, options = {}) => {
13139
14098
  const fanouts = destinations.map((destination) => ({
13140
14099
  name: destination.name,
13141
- sink: createSignalFanout({ traces: destination.traces, logs: destination.logs })
14100
+ sink: createScopedFanout(destination, options.correlate)
13142
14101
  }));
13143
- const only = fanouts.length === 1 ? fanouts[0] : void 0;
14102
+ const scoped = destinations.some((destination) => destination.route !== void 0);
14103
+ const only = fanouts.length === 1 && !scoped ? fanouts[0] : void 0;
13144
14104
  if (only !== void 0) {
13145
14105
  return only.sink;
13146
14106
  }
@@ -13261,7 +14221,8 @@ var createHookRuntime = (options) => {
13261
14221
  // has always been governed by.
13262
14222
  allowRawContent: privacy.policy.allowRawContent
13263
14223
  },
13264
- correlate
14224
+ correlate,
14225
+ restrictContent: (fact, mode) => privacy.restrictContent(fact, mode)
13265
14226
  });
13266
14227
  const primary = exportDestinations.destinations[0];
13267
14228
  const traceSink = primary?.traces ?? createOtlpTraceSink({
@@ -13278,7 +14239,7 @@ var createHookRuntime = (options) => {
13278
14239
  });
13279
14240
  const spool = primary?.spool;
13280
14241
  const logSpool = primary?.logSpool;
13281
- const sink = createDestinationFanout(exportDestinations.destinations);
14242
+ const sink = createDestinationFanout(exportDestinations.destinations, { correlate });
13282
14243
  const hookDeps = {
13283
14244
  stateStore,
13284
14245
  config: options.config,
@@ -13288,7 +14249,14 @@ var createHookRuntime = (options) => {
13288
14249
  privacy,
13289
14250
  logger,
13290
14251
  installationId: options.installationId,
13291
- payloadEnrichers: options.payloadEnrichers ?? (readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : []),
14252
+ payloadEnrichers: options.payloadEnrichers ?? [
14253
+ ...readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : [],
14254
+ ...readsCodexRolloutUsage(options.config) ? [
14255
+ createCodexRolloutUsageEnricher(
14256
+ options.codexSessionsRoot === void 0 ? {} : { sessionsRoot: options.codexSessionsRoot }
14257
+ )
14258
+ ] : []
14259
+ ],
13292
14260
  ...(() => {
13293
14261
  if (options.sessionContextReader === null) {
13294
14262
  return {};
@@ -13312,6 +14280,8 @@ var createHookRuntime = (options) => {
13312
14280
  (destination) => destination.metrics.enabled
13313
14281
  );
13314
14282
  const metricResource = resourceFromExporterPolicy(options.config.exporter);
14283
+ const scopedMetricDestinations = metricDestinations.filter((destination) => destination.scopes !== void 0);
14284
+ const unscopedMetricDestinations = metricDestinations.filter((destination) => destination.scopes === void 0);
13315
14285
  const deliveryRetentionMillis = options.deliveryRetentionMillis ?? lifecycleMaxAge;
13316
14286
  if (deliveryRetentionMillis < staleClaimMillis) {
13317
14287
  logger.warn("delivery retention is shorter than the stale-claim window", {
@@ -13377,28 +14347,63 @@ var createHookRuntime = (options) => {
13377
14347
  turnStarts.set(event3.sessionId, await metricSeries.readTurnStart(event3.sessionId));
13378
14348
  }
13379
14349
  }
13380
- const observations = deriveMetricObservations({
13381
- events: ingest.events,
13382
- usage: ingest.usageObservations,
13383
- resource: metricResource,
13384
- includeSessionId: metricsPolicy.includeSessionId,
13385
- ...generationStarts === void 0 ? {} : { generationStarts },
13386
- turnStart: (sessionId) => turnStarts.get(sessionId)
13387
- });
13388
- if (observations.length === 0) {
14350
+ const scopedRepositoryFallback = scopedMetricDestinations.length === 0 ? void 0 : resourceRepositoryKey(metricResource.attributes);
14351
+ const resourceRepository = metricResource.attributes[ATTR_VCS_REPOSITORY_URL_FULL];
14352
+ const metricEvents = scopedRepositoryFallback === void 0 || typeof resourceRepository !== "string" ? ingest.events : ingest.events.map(
14353
+ (event3) => event3.contextAttributes?.[ATTR_VCS_REPOSITORY_URL_FULL] === void 0 ? {
14354
+ ...event3,
14355
+ contextAttributes: {
14356
+ ...event3.contextAttributes,
14357
+ [ATTR_VCS_REPOSITORY_URL_FULL]: resourceRepository
14358
+ }
14359
+ } : event3
14360
+ );
14361
+ const pointsByVariant = /* @__PURE__ */ new Map();
14362
+ const variants = new Set(
14363
+ unscopedMetricDestinations.length > 0 ? [metricsPolicy.includeSessionId] : []
14364
+ );
14365
+ for (const destination of scopedMetricDestinations) {
14366
+ for (const variant of sessionIdVariantsFor(destination.scopes ?? [], metricsPolicy.includeSessionId)) {
14367
+ variants.add(variant);
14368
+ }
14369
+ }
14370
+ for (const includeSessionId of variants) {
14371
+ const observations = deriveMetricObservations({
14372
+ events: metricEvents,
14373
+ usage: ingest.usageObservations,
14374
+ resource: metricResource,
14375
+ includeSessionId,
14376
+ ...generationStarts === void 0 ? {} : { generationStarts },
14377
+ turnStart: (sessionId) => turnStarts.get(sessionId)
14378
+ });
14379
+ if (observations.length === 0) {
14380
+ continue;
14381
+ }
14382
+ pointsByVariant.set(
14383
+ includeSessionId,
14384
+ metricsPolicy.temporality === "delta" ? aggregateDeltaPoints(observations, clock.now()) : await metricSeries.recordCumulative(observations, {
14385
+ perSession: includeSessionId,
14386
+ ...deliveryToken === void 0 ? {} : { deliveryToken }
14387
+ })
14388
+ );
14389
+ }
14390
+ if (pointsByVariant.size === 0) {
13389
14391
  return void 0;
13390
14392
  }
13391
- const points = metricsPolicy.temporality === "delta" ? aggregateDeltaPoints(observations, clock.now()) : await metricSeries.recordCumulative(observations, {
13392
- perSession: metricsPolicy.includeSessionId,
13393
- ...deliveryToken === void 0 ? {} : { deliveryToken }
13394
- });
13395
14393
  const context = agreedContextAttributes(ingest.events);
13396
14394
  const results = await Promise.all(
13397
14395
  metricDestinations.map(async (destination) => {
13398
- const result = await destination.metrics.exportPoints(points, context).catch(
14396
+ const points2 = destination.scopes === void 0 ? pointsByVariant.get(metricsPolicy.includeSessionId) ?? [] : routePointsToScopes(destination.scopes, (variant) => pointsByVariant.get(variant), {
14397
+ fallbackKey: scopedRepositoryFallback,
14398
+ includeSessionId: metricsPolicy.includeSessionId
14399
+ });
14400
+ if (points2.length === 0) {
14401
+ return { name: destination.name, accepted: 0, rejected: 0 };
14402
+ }
14403
+ const result = await destination.metrics.exportPoints(points2, context).catch(
13399
14404
  (thrown) => ({
13400
14405
  accepted: 0,
13401
- rejected: points.length,
14406
+ rejected: points2.length,
13402
14407
  errors: [
13403
14408
  errorInfoFromThrown(thrown, { code: "telemetry-export-failure", phase: "export" })
13404
14409
  ]
@@ -13408,7 +14413,8 @@ var createHookRuntime = (options) => {
13408
14413
  return { name: destination.name, accepted: result.accepted, rejected: result.rejected };
13409
14414
  })
13410
14415
  );
13411
- return { points: points.length, destinations: results };
14416
+ const points = Math.max(0, ...[...pointsByVariant.values()].map((variant) => variant.length));
14417
+ return { points, destinations: results };
13412
14418
  } catch (thrown) {
13413
14419
  diagnostics.push(stateDiagnostic(thrown));
13414
14420
  logger.warn("hook-derived metrics could not be recorded for this callback", {});
@@ -14535,7 +15541,7 @@ var SUPPORTED_REGISTRATION_PROVIDER_IDS = Object.freeze(
14535
15541
  );
14536
15542
 
14537
15543
  // src/install/scopes.ts
14538
- import * as path7 from "path";
15544
+ import * as path9 from "path";
14539
15545
  var REGISTRATION_SCOPES = Object.freeze([
14540
15546
  "global",
14541
15547
  "project"
@@ -14603,15 +15609,15 @@ var PROVIDERS_WITH_VERIFIED_LOCATION = Object.freeze([
14603
15609
  var findInstallLocation = (providerId, scope) => PROVIDER_INSTALL_LOCATIONS.find(
14604
15610
  (entry) => entry.providerId === providerId && entry.scope === scope
14605
15611
  );
14606
- var resolveInstallPath = (location, roots) => path7.resolve(
15612
+ var resolveInstallPath = (location, roots) => path9.resolve(
14607
15613
  location.scope === "global" ? roots.homeDir : roots.projectDir,
14608
15614
  ...location.segments
14609
15615
  );
14610
15616
 
14611
15617
  // src/install/document.ts
14612
- import { randomBytes as randomBytes4 } from "crypto";
14613
- import { chmod, mkdir as mkdir3, open as open5, readFile as readFile3, rename as rename3, stat as stat5, unlink as unlink3 } from "fs/promises";
14614
- import * as path8 from "path";
15618
+ import { randomBytes as randomBytes5 } from "crypto";
15619
+ import { chmod, mkdir as mkdir4, open as open7, readFile as readFile4, rename as rename4, stat as stat6, unlink as unlink4 } from "fs/promises";
15620
+ import * as path10 from "path";
14615
15621
  var DEFAULT_DOCUMENT_FORMAT = Object.freeze({
14616
15622
  indent: " ",
14617
15623
  eol: "\n",
@@ -14635,7 +15641,7 @@ var renderJsonDocument = (value, format) => {
14635
15641
  var readJsonDocument = async (filePath) => {
14636
15642
  let raw;
14637
15643
  try {
14638
- raw = await readFile3(filePath, "utf8");
15644
+ raw = await readFile4(filePath, "utf8");
14639
15645
  } catch (thrown) {
14640
15646
  if (isErrnoException3(thrown, "ENOENT")) {
14641
15647
  return { status: "absent", format: DEFAULT_DOCUMENT_FORMAT };
@@ -14667,7 +15673,7 @@ var delay2 = (millis) => new Promise((resolve5) => {
14667
15673
  var renameWithRetry = async (from, to) => {
14668
15674
  for (let attempt = 0; ; attempt += 1) {
14669
15675
  try {
14670
- await rename3(from, to);
15676
+ await rename4(from, to);
14671
15677
  return;
14672
15678
  } catch (thrown) {
14673
15679
  const retryable = isErrnoException3(thrown, "EPERM", "EACCES", "EBUSY");
@@ -14682,15 +15688,15 @@ var renameWithRetry = async (from, to) => {
14682
15688
  var NEW_DOCUMENT_MODE = 384;
14683
15689
  var TEMPORARY_DOCUMENT_MODE = 384;
14684
15690
  var writeDocumentAtomically = async (filePath, contents) => {
14685
- const directory = path8.dirname(filePath);
14686
- await mkdir3(directory, { recursive: true });
14687
- const temporary = path8.join(
15691
+ const directory = path10.dirname(filePath);
15692
+ await mkdir4(directory, { recursive: true });
15693
+ const temporary = path10.join(
14688
15694
  directory,
14689
- `.${path8.basename(filePath)}.${randomBytes4(6).toString("hex")}.tmp`
15695
+ `.${path10.basename(filePath)}.${randomBytes5(6).toString("hex")}.tmp`
14690
15696
  );
14691
15697
  let existingMode;
14692
15698
  try {
14693
- existingMode = (await stat5(filePath)).mode & 4095;
15699
+ existingMode = (await stat6(filePath)).mode & 4095;
14694
15700
  } catch (thrown) {
14695
15701
  if (!isErrnoException3(thrown, "ENOENT")) {
14696
15702
  throw thrown;
@@ -14698,7 +15704,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
14698
15704
  }
14699
15705
  const targetMode = existingMode ?? NEW_DOCUMENT_MODE;
14700
15706
  try {
14701
- const handle = await open5(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
15707
+ const handle = await open7(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
14702
15708
  try {
14703
15709
  await handle.writeFile(contents, "utf8");
14704
15710
  await handle.sync();
@@ -14708,19 +15714,19 @@ var writeDocumentAtomically = async (filePath, contents) => {
14708
15714
  }
14709
15715
  await renameWithRetry(temporary, filePath);
14710
15716
  } catch (thrown) {
14711
- await unlink3(temporary).catch(() => void 0);
15717
+ await unlink4(temporary).catch(() => void 0);
14712
15718
  throw thrown;
14713
15719
  }
14714
15720
  };
14715
15721
 
14716
15722
  // src/install/file-lock.ts
14717
- import { randomBytes as randomBytes5 } from "crypto";
14718
- import { mkdir as mkdir4, open as open6, readFile as readFile4, rename as rename4, stat as stat6, unlink as unlink4 } from "fs/promises";
14719
- import * as path9 from "path";
15723
+ import { randomBytes as randomBytes6 } from "crypto";
15724
+ import { mkdir as mkdir5, open as open8, readFile as readFile5, rename as rename5, stat as stat7, unlink as unlink5 } from "fs/promises";
15725
+ import * as path11 from "path";
14720
15726
  var FileLockTimeoutError = class extends Error {
14721
15727
  constructor(lockPath, timeoutMillis) {
14722
15728
  super(
14723
- `timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path9.basename(lockPath)}`
15729
+ `timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path11.basename(lockPath)}`
14724
15730
  );
14725
15731
  this.name = "FileLockTimeoutError";
14726
15732
  }
@@ -14731,7 +15737,7 @@ var isErrnoException4 = (thrown, code) => thrown instanceof Error && thrown.code
14731
15737
  var readLockContents = async (lockPath) => {
14732
15738
  let raw;
14733
15739
  try {
14734
- raw = await readFile4(lockPath, "utf8");
15740
+ raw = await readFile5(lockPath, "utf8");
14735
15741
  } catch {
14736
15742
  return void 0;
14737
15743
  }
@@ -14745,18 +15751,18 @@ var readLockContents = async (lockPath) => {
14745
15751
  var releaseIfOwned = async (lockPath, token) => {
14746
15752
  const tombstone = `${lockPath}.${token}.releasing`;
14747
15753
  try {
14748
- await rename4(lockPath, tombstone);
15754
+ await rename5(lockPath, tombstone);
14749
15755
  } catch {
14750
15756
  return false;
14751
15757
  }
14752
15758
  const captured = await readLockContents(tombstone);
14753
15759
  if (captured !== void 0 && captured.token !== token) {
14754
- await rename4(tombstone, lockPath).catch(async () => {
15760
+ await rename5(tombstone, lockPath).catch(async () => {
14755
15761
  await Promise.resolve();
14756
15762
  });
14757
15763
  return false;
14758
15764
  }
14759
- await unlink4(tombstone).catch(() => void 0);
15765
+ await unlink5(tombstone).catch(() => void 0);
14760
15766
  return true;
14761
15767
  };
14762
15768
  var delay3 = (millis) => new Promise((resolve5) => {
@@ -14765,7 +15771,7 @@ var delay3 = (millis) => new Promise((resolve5) => {
14765
15771
  var isStale = async (lockPath, clock, staleMillis) => {
14766
15772
  let raw;
14767
15773
  try {
14768
- raw = await readFile4(lockPath, "utf8");
15774
+ raw = await readFile5(lockPath, "utf8");
14769
15775
  } catch (thrown) {
14770
15776
  return { stale: !isErrnoException4(thrown, "ENOENT") };
14771
15777
  }
@@ -14780,7 +15786,7 @@ var isStale = async (lockPath, clock, staleMillis) => {
14780
15786
  } catch {
14781
15787
  }
14782
15788
  try {
14783
- const stats = await stat6(lockPath);
15789
+ const stats = await stat7(lockPath);
14784
15790
  return { stale: clock.now() - stats.mtimeMs > staleMillis };
14785
15791
  } catch (thrown) {
14786
15792
  return { stale: !isErrnoException4(thrown, "ENOENT") };
@@ -14792,12 +15798,12 @@ var withFileLock = async (filePath, options, fn) => {
14792
15798
  const pollIntervalMillis = options.pollIntervalMillis ?? 25;
14793
15799
  const lockPath = lockPathFor(filePath);
14794
15800
  const startedAt = options.clock.monotonicMillis();
14795
- await mkdir4(path9.dirname(filePath), { recursive: true });
15801
+ await mkdir5(path11.dirname(filePath), { recursive: true });
14796
15802
  for (; ; ) {
14797
- const token = randomBytes5(16).toString("hex");
15803
+ const token = randomBytes6(16).toString("hex");
14798
15804
  let acquired = false;
14799
15805
  try {
14800
- const handle = await open6(lockPath, "wx", 384);
15806
+ const handle = await open8(lockPath, "wx", 384);
14801
15807
  try {
14802
15808
  const contents = {
14803
15809
  token,
@@ -14839,8 +15845,8 @@ var withFileLock = async (filePath, options, fn) => {
14839
15845
  };
14840
15846
 
14841
15847
  // src/install/lifecycle.ts
14842
- import { readFile as readFile5 } from "fs/promises";
14843
- import * as path10 from "path";
15848
+ import { readFile as readFile6 } from "fs/promises";
15849
+ import * as path12 from "path";
14844
15850
  var defaultHookCommand = (providerId) => `otel-hook run --provider ${providerId}`;
14845
15851
  var unsupportedOutcome = (providerId, scope, reason) => ({
14846
15852
  providerId,
@@ -14857,7 +15863,7 @@ var unsupportedOutcome = (providerId, scope, reason) => ({
14857
15863
  var resolveTarget = (providerId, scope, request) => {
14858
15864
  if (request.configFile !== void 0) {
14859
15865
  return {
14860
- configPath: path10.resolve(request.configFile),
15866
+ configPath: path12.resolve(request.configFile),
14861
15867
  evidence: "path supplied by the caller with --settings-file"
14862
15868
  };
14863
15869
  }
@@ -14874,14 +15880,14 @@ var resolveTarget = (providerId, scope, request) => {
14874
15880
  };
14875
15881
  };
14876
15882
  var codexFeatureNote = async (configPath) => {
14877
- const tomlPath = path10.join(path10.dirname(configPath), "config.toml");
15883
+ const tomlPath = path12.join(path12.dirname(configPath), "config.toml");
14878
15884
  let raw;
14879
15885
  try {
14880
- raw = await readFile5(tomlPath, "utf8");
15886
+ raw = await readFile6(tomlPath, "utf8");
14881
15887
  } catch {
14882
15888
  return void 0;
14883
15889
  }
14884
- return readCodexHooksFeatureFlag(raw) === "disabled" ? `${path10.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed` : void 0;
15890
+ return readCodexHooksFeatureFlag(raw) === "disabled" ? `${path12.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed` : void 0;
14885
15891
  };
14886
15892
  var readState = async (configPath) => {
14887
15893
  const read = await readJsonDocument(configPath);
@@ -14893,12 +15899,12 @@ var readState = async (configPath) => {
14893
15899
  case "unparseable":
14894
15900
  return {
14895
15901
  status: "blocked",
14896
- problem: `${path10.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`
15902
+ problem: `${path12.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`
14897
15903
  };
14898
15904
  case "unreadable":
14899
15905
  return {
14900
15906
  status: "failed",
14901
- problem: `${path10.basename(configPath)} could not be read (${read.detail})`
15907
+ problem: `${path12.basename(configPath)} could not be read (${read.detail})`
14902
15908
  };
14903
15909
  }
14904
15910
  };
@@ -15010,7 +16016,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
15010
16016
  missingEvents: [],
15011
16017
  notes,
15012
16018
  problems: planned.conflicts.map(
15013
- (conflict) => `${path10.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`
16019
+ (conflict) => `${path12.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`
15014
16020
  )
15015
16021
  };
15016
16022
  }
@@ -15021,7 +16027,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
15021
16027
  changed: false,
15022
16028
  registeredEvents: [],
15023
16029
  missingEvents: [],
15024
- notes: [...notes, `${path10.basename(configPath)} does not exist; nothing to remove`],
16030
+ notes: [...notes, `${path12.basename(configPath)} does not exist; nothing to remove`],
15025
16031
  problems: []
15026
16032
  };
15027
16033
  }
@@ -15064,7 +16070,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
15064
16070
  missingEvents: [],
15065
16071
  notes,
15066
16072
  problems: [
15067
- `could not write ${path10.basename(configPath)} (${thrown instanceof Error ? thrown.name : typeof thrown})`
16073
+ `could not write ${path12.basename(configPath)} (${thrown instanceof Error ? thrown.name : typeof thrown})`
15068
16074
  ]
15069
16075
  };
15070
16076
  }
@@ -15091,7 +16097,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
15091
16097
  missingEvents: [],
15092
16098
  notes,
15093
16099
  problems: [
15094
- thrown instanceof Error ? `${path10.basename(configPath)}: ${thrown.message}` : `${path10.basename(configPath)}: the configuration file could not be locked`
16100
+ thrown instanceof Error ? `${path12.basename(configPath)}: ${thrown.message}` : `${path12.basename(configPath)}: the configuration file could not be locked`
15095
16101
  ]
15096
16102
  };
15097
16103
  }
@@ -15171,11 +16177,13 @@ var planProviderRegistration = (input) => {
15171
16177
  };
15172
16178
  };
15173
16179
  export {
16180
+ ALL_REPOSITORIES,
15174
16181
  ANTIGRAVITY_CAPABILITIES,
15175
16182
  ANTIGRAVITY_HOOK_EVENT_NAMES,
15176
16183
  ANTIGRAVITY_PROMOTION_GATES,
15177
16184
  ANTIGRAVITY_PROVIDER_ID,
15178
16185
  ANTIGRAVITY_PROVIDER_MATURITY,
16186
+ ATTR_VCS_REPOSITORY_URL_FULL,
15179
16187
  BUILT_IN_PROVIDERS,
15180
16188
  CANONICAL_EVENT_TYPES,
15181
16189
  CANONICAL_SCHEMA_VERSION,
@@ -15192,6 +16200,7 @@ export {
15192
16200
  CODEX_HOOK_EVENT_NAMES,
15193
16201
  CODEX_PROVIDER_ID,
15194
16202
  CODEX_REGISTRABLE_HOOK_EVENTS,
16203
+ CODEX_ROLLOUT_USAGE_ENRICHER_ID,
15195
16204
  CODEX_UNREGISTERED_HOOK_EVENTS,
15196
16205
  CONFIG_SOURCE_PRECEDENCE,
15197
16206
  CONTENT_HASH_PATTERN,
@@ -15210,13 +16219,19 @@ export {
15210
16219
  DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS,
15211
16220
  DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES,
15212
16221
  DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS,
16222
+ DEFAULT_CODEX_ROLLOUT_RANGE_BYTES,
16223
+ DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS,
16224
+ DEFAULT_CODEX_ROLLOUT_TAIL_BYTES,
16225
+ DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS,
15213
16226
  DEFAULT_CONFIG,
15214
16227
  DEFAULT_DESTINATION_NAME,
15215
16228
  DEFAULT_DESTINATION_SIGNALS,
15216
16229
  DEFAULT_DETECTION_POLICY,
15217
16230
  DEFAULT_DIAGNOSTICS_POLICY,
15218
16231
  DEFAULT_DOCUMENT_FORMAT,
16232
+ DEFAULT_ENDPOINT_DOWN_MILLIS,
15219
16233
  DEFAULT_EXPORTER_POLICY,
16234
+ DEFAULT_EXPORT_BUDGET_MILLIS,
15220
16235
  DEFAULT_GEMINI_CAPABILITIES,
15221
16236
  DEFAULT_INSTRUMENTATION_SCOPE,
15222
16237
  DEFAULT_LOGS_POLICY,
@@ -15260,6 +16275,7 @@ export {
15260
16275
  MAX_DELIVERY_COMPONENTS,
15261
16276
  MAX_DELIVERY_GAPS,
15262
16277
  MAX_DESTINATION_HEADERS,
16278
+ MAX_DESTINATION_SCOPES,
15263
16279
  MAX_EXPORT_DESTINATIONS,
15264
16280
  MAX_EXTENSION_ENTRIES,
15265
16281
  MAX_IDENTIFIER_LENGTH,
@@ -15268,9 +16284,11 @@ export {
15268
16284
  MAX_LOG_RECORDS_PER_EVENT,
15269
16285
  MAX_OTLP_HEADERS,
15270
16286
  MAX_RECOVERED_START_ATTRIBUTES,
16287
+ MAX_REPOSITORY_REFERENCE_LENGTH,
15271
16288
  MAX_RESOURCE_ATTRIBUTES,
15272
16289
  MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH,
15273
16290
  MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH,
16291
+ MAX_SCOPE_REPOSITORIES,
15274
16292
  MAX_SESSION_CONTEXT_SEGMENTS,
15275
16293
  MAX_TARGET_HINT_PATHS,
15276
16294
  MAX_TARGET_PATH_LENGTH,
@@ -15353,6 +16371,7 @@ export {
15353
16371
  createClaudeCodeAdapter,
15354
16372
  createClaudeTranscriptUsageEnricher,
15355
16373
  createCodexAdapter,
16374
+ createCodexRolloutUsageEnricher,
15356
16375
  createCursorAdapter,
15357
16376
  createDefaultProviderRegistry,
15358
16377
  createDestinationFanout,
@@ -15406,11 +16425,13 @@ export {
15406
16425
  describeResolvedConfig,
15407
16426
  describeResourceAttributeNames,
15408
16427
  describeThrown,
16428
+ destinationScopeSchema,
15409
16429
  detectDocumentFormat,
15410
16430
  detectionConfidenceSchema,
15411
16431
  detectionPolicySchema,
15412
16432
  diagnosticsPolicySchema,
15413
16433
  durationMillisSchema,
16434
+ effectiveExportTimeoutMillis,
15414
16435
  effectiveMetricsPolicy,
15415
16436
  effectiveSpoolPolicy,
15416
16437
  emptyExtensions,
@@ -15421,6 +16442,7 @@ export {
15421
16442
  errorRaisedEventSchema,
15422
16443
  errorSeveritySchema,
15423
16444
  eventIdSchema,
16445
+ eventRepositoryKey,
15424
16446
  eventUsage,
15425
16447
  exportDestinationSchema,
15426
16448
  exportDestinationsSchema,
@@ -15463,6 +16485,7 @@ export {
15463
16485
  logSignalsForLifecycleEvents,
15464
16486
  logsPolicySchema,
15465
16487
  managedHookPredicate,
16488
+ matchDestinationScope,
15466
16489
  mergeAntigravityHookRegistration,
15467
16490
  mergeClaudeHookRegistration,
15468
16491
  mergeCodexHookRegistration,
@@ -15474,8 +16497,10 @@ export {
15474
16497
  minimumStaleClaimMillis,
15475
16498
  modelDescriptorSchema,
15476
16499
  nonEmptyStringSchema,
16500
+ normalizeRepositoryKey,
15477
16501
  normalizeUsage,
15478
16502
  normalizeUsageOrThrow,
16503
+ omitRestrictedContent,
15479
16504
  otelHookConfigPatchSchema,
15480
16505
  otelHookConfigSchema,
15481
16506
  otelHookErrorCodeSchema,
@@ -15492,6 +16517,7 @@ export {
15492
16517
  parseResourceAttributesValue,
15493
16518
  parseSessionContextFile,
15494
16519
  planProviderRegistration,
16520
+ pointRepositoryKey,
15495
16521
  privacyLimitsSchema,
15496
16522
  privacyPolicySchema,
15497
16523
  promptSubmittedEventSchema,
@@ -15509,6 +16535,7 @@ export {
15509
16535
  readClaudeTranscriptTurn,
15510
16536
  readCodexHookRegistrations,
15511
16537
  readCodexHooksFeatureFlag,
16538
+ readCodexRolloutUsage,
15512
16539
  readCursorHookRegistrations,
15513
16540
  readDeliveryClaim,
15514
16541
  readDeliveryGap,
@@ -15516,6 +16543,7 @@ export {
15516
16543
  readJsonDocument,
15517
16544
  readNestedHookRegistrations,
15518
16545
  readsClaudeTranscriptUsage,
16546
+ readsCodexRolloutUsage,
15519
16547
  removeAntigravityHookRegistration,
15520
16548
  removeClaudeHookRegistration,
15521
16549
  removeCodexHookRegistration,
@@ -15526,6 +16554,7 @@ export {
15526
16554
  resolveConfig,
15527
16555
  resolveDeliveryIdentity,
15528
16556
  resolveDestinationHeaders,
16557
+ resolveDestinationScopes,
15529
16558
  resolveEventTargets,
15530
16559
  resolveExportDestinations,
15531
16560
  resolveInstallPath,
@@ -15537,6 +16566,10 @@ export {
15537
16566
  resolvedProviderIdSchema,
15538
16567
  resourceAttributeValueSchema,
15539
16568
  resourceAttributesSchema,
16569
+ resourceRepositoryKey,
16570
+ restrictEventContent,
16571
+ routeEventsToScopes,
16572
+ routePointsToScopes,
15540
16573
  runRegistrationLifecycle,
15541
16574
  sanitizeResourceAttributes,
15542
16575
  sanitizeSessionContextAttributes,
@@ -15549,6 +16582,7 @@ export {
15549
16582
  sessionCwdHint,
15550
16583
  sessionEndEventSchema,
15551
16584
  sessionIdSchema,
16585
+ sessionIdVariantsFor,
15552
16586
  sessionStartEventSchema,
15553
16587
  shareCorrelationPerBatch,
15554
16588
  sourceProvenanceSchema,