@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/cli.js CHANGED
@@ -360,6 +360,7 @@ var BOOLEAN_FLAGS = /* @__PURE__ */ new Set([
360
360
  "--no-metrics",
361
361
  "--no-metrics-session-id",
362
362
  "--claude-transcript-usage",
363
+ "--codex-rollout-usage",
363
364
  "--include-experimental",
364
365
  "--no-experimental",
365
366
  "--dry-run",
@@ -567,6 +568,7 @@ var parsePolicy = (tokens, errors) => {
567
568
  ...metricsTemporality === void 0 ? {} : { metricsTemporality },
568
569
  ...tokens.booleans.has("--no-metrics-session-id") ? { metricsIncludeSessionId: false } : {},
569
570
  ...tokens.booleans.has("--claude-transcript-usage") ? { claudeTranscriptUsage: true } : {},
571
+ ...tokens.booleans.has("--codex-rollout-usage") ? { codexRolloutUsage: true } : {},
570
572
  ...sessionContextDir2 === void 0 || !isAbsolute(sessionContextDir2) ? {} : { sessionContextDir: sessionContextDir2 }
571
573
  };
572
574
  };
@@ -628,6 +630,7 @@ var RUN_FLAGS = /* @__PURE__ */ new Set([
628
630
  "--metrics-temporality",
629
631
  "--no-metrics-session-id",
630
632
  "--claude-transcript-usage",
633
+ "--codex-rollout-usage",
631
634
  "--session-context-dir",
632
635
  "--max-input-bytes",
633
636
  "--no-export",
@@ -664,6 +667,7 @@ var DOCTOR_FLAGS = /* @__PURE__ */ new Set([
664
667
  "--metrics-temporality",
665
668
  "--no-metrics-session-id",
666
669
  "--claude-transcript-usage",
670
+ "--codex-rollout-usage",
667
671
  "--session-context-dir",
668
672
  "--include-experimental",
669
673
  "--no-experimental"
@@ -921,6 +925,10 @@ Exporter and runtime policy (never identity):
921
925
  payload names (bounded) for the turn's model and
922
926
  summed token usage. Off by default; also
923
927
  OTEL_HOOK_CLAUDE_TRANSCRIPT_USAGE=1
928
+ --codex-rollout-usage Codex only: at Stop, read the session's rollout
929
+ (transcript_path; bounded, from a per-session
930
+ cursor) for the running token total. Off by
931
+ default; also OTEL_HOOK_CODEX_ROLLOUT_USAGE=1
924
932
  --session-context-dir <dir>
925
933
  absolute directory of session context files
926
934
  (<dir>/<agent-tool>/<session-id>.json); the
@@ -1428,7 +1436,9 @@ var ENVIRONMENT_VARIABLES = Object.freeze({
1428
1436
  minimumConfidence: "OTEL_HOOK_MIN_DETECTION_CONFIDENCE",
1429
1437
  logLevel: "OTEL_HOOK_LOG_LEVEL",
1430
1438
  /** `providers.claudeCode.readTranscriptUsage`; see `providersPolicySchema`. */
1431
- claudeTranscriptUsage: "OTEL_HOOK_CLAUDE_TRANSCRIPT_USAGE"
1439
+ claudeTranscriptUsage: "OTEL_HOOK_CLAUDE_TRANSCRIPT_USAGE",
1440
+ /** `providers.codex.readRolloutUsage`; see `providersPolicySchema`. */
1441
+ codexRolloutUsage: "OTEL_HOOK_CODEX_ROLLOUT_USAGE"
1432
1442
  });
1433
1443
  var BOOLEAN_TRUE = /* @__PURE__ */ new Set(["1", "true", "yes", "on"]);
1434
1444
  var BOOLEAN_FALSE = /* @__PURE__ */ new Set(["0", "false", "no", "off"]);
@@ -1623,7 +1633,11 @@ var parseEnvironmentConfig = (env) => {
1623
1633
  const detection = confidenceParsed?.success === true ? { minimumConfidence: confidenceParsed.data } : {};
1624
1634
  const diagnostics = logLevel === void 0 ? {} : { logLevel };
1625
1635
  const claudeTranscriptUsage = readBoolean(ENVIRONMENT_VARIABLES.claudeTranscriptUsage);
1626
- const providers = claudeTranscriptUsage === void 0 ? {} : { claudeCode: { readTranscriptUsage: claudeTranscriptUsage } };
1636
+ const codexRolloutUsage = readBoolean(ENVIRONMENT_VARIABLES.codexRolloutUsage);
1637
+ const providers = {
1638
+ ...claudeTranscriptUsage === void 0 ? {} : { claudeCode: { readTranscriptUsage: claudeTranscriptUsage } },
1639
+ ...codexRolloutUsage === void 0 ? {} : { codex: { readRolloutUsage: codexRolloutUsage } }
1640
+ };
1627
1641
  const patch = {
1628
1642
  ...Object.keys(exporter).length === 0 ? {} : { exporter },
1629
1643
  ...Object.keys(privacy).length === 0 ? {} : { privacy },
@@ -1639,6 +1653,62 @@ import { z as z8 } from "zod";
1639
1653
 
1640
1654
  // src/config/destinations.ts
1641
1655
  import { z as z6 } from "zod";
1656
+
1657
+ // src/config/repository-key.ts
1658
+ var ATTR_VCS_REPOSITORY_URL_FULL = "vcs.repository.url.full";
1659
+ var MAX_REPOSITORY_REFERENCE_LENGTH = 2048;
1660
+ var SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;
1661
+ var SCP_LIKE_PATTERN = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/\/)(.+)$/;
1662
+ var trimTrailingSlashes = (value) => {
1663
+ let end = value.length;
1664
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
1665
+ return value.slice(0, end);
1666
+ };
1667
+ var keyOf = (host, pathname) => {
1668
+ const withoutSlashes = trimTrailingSlashes(pathname);
1669
+ const cleanedPath = trimTrailingSlashes(
1670
+ withoutSlashes.toLowerCase().endsWith(".git") ? withoutSlashes.slice(0, -4) : withoutSlashes
1671
+ );
1672
+ if (host.length === 0 || cleanedPath.length === 0 || cleanedPath === "/") {
1673
+ return void 0;
1674
+ }
1675
+ const withSlash = cleanedPath.startsWith("/") ? cleanedPath : `/${cleanedPath}`;
1676
+ return `${host}${withSlash}`.toLowerCase();
1677
+ };
1678
+ var normalizeRepositoryKey = (reference) => {
1679
+ const trimmed = reference.trim();
1680
+ if (trimmed.length === 0 || trimmed.length > MAX_REPOSITORY_REFERENCE_LENGTH) {
1681
+ return void 0;
1682
+ }
1683
+ if (SCHEME_PATTERN.test(trimmed)) {
1684
+ let url;
1685
+ try {
1686
+ url = new URL(trimmed);
1687
+ } catch {
1688
+ return void 0;
1689
+ }
1690
+ if (url.protocol === "file:") {
1691
+ return void 0;
1692
+ }
1693
+ return keyOf(url.hostname, url.pathname);
1694
+ }
1695
+ if (trimmed.startsWith("/") || trimmed.startsWith(".") || trimmed.includes("\\")) {
1696
+ return void 0;
1697
+ }
1698
+ const scp = SCP_LIKE_PATTERN.exec(trimmed);
1699
+ if (scp !== null && !trimmed.split(":")[0]?.includes("/")) {
1700
+ const [, host, pathPart] = scp;
1701
+ return host === void 0 || pathPart === void 0 ? void 0 : keyOf(host, pathPart);
1702
+ }
1703
+ try {
1704
+ const url = new URL(`https://${trimmed}`);
1705
+ return keyOf(url.hostname, url.pathname);
1706
+ } catch {
1707
+ return void 0;
1708
+ }
1709
+ };
1710
+
1711
+ // src/config/destinations.ts
1642
1712
  var DEFAULT_DESTINATION_NAME = "default";
1643
1713
  var DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;
1644
1714
  var MAX_EXPORT_DESTINATIONS = 16;
@@ -1656,6 +1726,30 @@ var headerValueSchema = z6.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
1656
1726
  "an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN"
1657
1727
  );
1658
1728
  var endpointSchema = z6.string().url().max(2048);
1729
+ var MAX_DESTINATION_SCOPES = 64;
1730
+ var MAX_SCOPE_REPOSITORIES = 256;
1731
+ var ALL_REPOSITORIES = "*";
1732
+ var repositoryReferenceSchema = z6.string().min(1).max(MAX_REPOSITORY_REFERENCE_LENGTH).refine(
1733
+ (value) => normalizeRepositoryKey(value) !== void 0,
1734
+ "not a repository URL: use https://host/owner/repo, git@host:owner/repo.git, or host/owner/repo"
1735
+ );
1736
+ var destinationScopeSchema = z6.strictObject({
1737
+ /**
1738
+ * Repository URLs (any spelling of the remote; compared by host and path,
1739
+ * case-insensitively, without `.git`), or `"*"` for every record that names
1740
+ * a repository. A record that names none never matches a scope.
1741
+ */
1742
+ repositories: z6.union([
1743
+ z6.literal(ALL_REPOSITORIES),
1744
+ z6.array(repositoryReferenceSchema).min(1).max(MAX_SCOPE_REPOSITORIES).readonly()
1745
+ ]),
1746
+ /** Signals sent for these repositories. Default: every signal the destination takes. */
1747
+ signals: z6.array(exportSignalSchema).min(1).max(3).readonly().optional(),
1748
+ /** Content disclosure for these repositories, never above `privacy.contentMode`. Default: unchanged. */
1749
+ contentMode: contentModeSchema.optional(),
1750
+ /** False leaves `session.id` off metric data points for these repositories. Default true. */
1751
+ includeSessionId: z6.boolean().optional()
1752
+ });
1659
1753
  var exportDestinationSchema = z6.strictObject({
1660
1754
  /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */
1661
1755
  name: z6.string().regex(DESTINATION_NAME_PATTERN, "destination names are lowercase letters, digits, _ and -"),
@@ -1689,7 +1783,15 @@ var exportDestinationSchema = z6.strictObject({
1689
1783
  * opt-in for content-bearing records leaving the host. `metrics` is never on by
1690
1784
  * default: a destination receives hook-derived metrics only when it lists them.
1691
1785
  */
1692
- signals: z6.array(exportSignalSchema).min(1).max(3).readonly().optional()
1786
+ signals: z6.array(exportSignalSchema).min(1).max(3).readonly().optional(),
1787
+ /**
1788
+ * Per-repository filter. Absent: every record goes to this destination, as
1789
+ * before scopes existed. Present: a record goes only when its repository
1790
+ * (`vcs.repository.url.full`) matches a scope — the first matching scope
1791
+ * decides its signals, content mode, and session id — and a record that
1792
+ * names no repository is not sent here at all.
1793
+ */
1794
+ scopes: z6.array(destinationScopeSchema).min(1).max(MAX_DESTINATION_SCOPES).readonly().optional()
1693
1795
  }).refine(
1694
1796
  (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
1695
1797
  "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
@@ -1733,6 +1835,32 @@ var effectiveSpoolPolicy = (exporter) => ({
1733
1835
  maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,
1734
1836
  maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches
1735
1837
  });
1838
+ var resolveDestinationScopes = (scopes, destinationSignals) => scopes.map((scope) => {
1839
+ const listed = scope.signals ?? exportSignalSchema.options;
1840
+ return {
1841
+ repositories: scope.repositories === ALL_REPOSITORIES ? ALL_REPOSITORIES : new Set(
1842
+ scope.repositories.flatMap((reference) => {
1843
+ const key = normalizeRepositoryKey(reference);
1844
+ return key === void 0 ? [] : [key];
1845
+ })
1846
+ ),
1847
+ signals: {
1848
+ traces: destinationSignals.traces && listed.includes("traces"),
1849
+ logs: destinationSignals.logs && listed.includes("logs"),
1850
+ metrics: destinationSignals.metrics && listed.includes("metrics")
1851
+ },
1852
+ ...scope.contentMode === void 0 ? {} : { contentMode: scope.contentMode },
1853
+ includeSessionId: scope.includeSessionId ?? true
1854
+ };
1855
+ });
1856
+ var matchDestinationScope = (scopes, repositoryKey) => {
1857
+ if (repositoryKey === void 0) {
1858
+ return void 0;
1859
+ }
1860
+ return scopes.find(
1861
+ (scope) => scope.repositories === ALL_REPOSITORIES || scope.repositories.has(repositoryKey)
1862
+ );
1863
+ };
1736
1864
  var legacyDestination = (exporter) => ({
1737
1865
  name: DEFAULT_DESTINATION_NAME,
1738
1866
  source: "exporter",
@@ -1757,6 +1885,11 @@ var resolveExportDestinations = (exporter) => {
1757
1885
  continue;
1758
1886
  }
1759
1887
  const signals = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;
1888
+ const flags = {
1889
+ traces: signals.includes("traces"),
1890
+ logs: exporter.logs.enabled && signals.includes("logs"),
1891
+ metrics: signals.includes("metrics")
1892
+ };
1760
1893
  resolved.push({
1761
1894
  name: destination.name,
1762
1895
  source: "destinations",
@@ -1765,12 +1898,9 @@ var resolveExportDestinations = (exporter) => {
1765
1898
  ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
1766
1899
  ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
1767
1900
  ...destination.metricsEndpoint === void 0 ? {} : { metricsEndpoint: destination.metricsEndpoint },
1768
- signals: {
1769
- traces: signals.includes("traces"),
1770
- logs: exporter.logs.enabled && signals.includes("logs"),
1771
- metrics: signals.includes("metrics")
1772
- },
1773
- headers: { ...destination.headers ?? {} }
1901
+ signals: flags,
1902
+ headers: { ...destination.headers ?? {} },
1903
+ ...destination.scopes === void 0 ? {} : { scopes: resolveDestinationScopes(destination.scopes, flags) }
1774
1904
  });
1775
1905
  }
1776
1906
  return resolved;
@@ -1794,6 +1924,12 @@ var resolveDestinationHeaders = (headers, environment) => {
1794
1924
  }
1795
1925
  return { values, missingVariables: [...new Set(missing)].sort() };
1796
1926
  };
1927
+ var describeScope = (scope) => ({
1928
+ repositories: scope.repositories === ALL_REPOSITORIES ? ALL_REPOSITORIES : [...scope.repositories].sort(),
1929
+ signals: exportSignalSchema.options.filter((signal) => scope.signals[signal]),
1930
+ ...scope.contentMode === void 0 ? {} : { contentMode: scope.contentMode },
1931
+ includeSessionId: scope.includeSessionId
1932
+ });
1797
1933
  var endpointOrigin = (endpoint) => {
1798
1934
  if (endpoint === void 0) {
1799
1935
  return void 0;
@@ -1823,7 +1959,8 @@ var describeExportDestinations = (exporter) => {
1823
1959
  ...logsOrigin === void 0 || !destination.signals.logs ? {} : { logsEndpointOrigin: logsOrigin },
1824
1960
  ...metricsOrigin === void 0 || !destination.signals.metrics ? {} : { metricsEndpointOrigin: metricsOrigin },
1825
1961
  headerNames: destination.source === "exporter" ? [...exporter.headerNames].sort() : Object.keys(destination.headers).sort(),
1826
- headerVariables: [...new Set(variables)].sort()
1962
+ headerVariables: [...new Set(variables)].sort(),
1963
+ ...destination.scopes === void 0 ? {} : { scopes: destination.scopes.map(describeScope) }
1827
1964
  };
1828
1965
  };
1829
1966
  const enabled = resolveExportDestinations(exporter).map(
@@ -1837,7 +1974,14 @@ var describeExportDestinations = (exporter) => {
1837
1974
  protocol: destination.protocol ?? exporter.protocol,
1838
1975
  ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
1839
1976
  signals: { traces: false, logs: false, metrics: false },
1840
- headers: { ...destination.headers ?? {} }
1977
+ headers: { ...destination.headers ?? {} },
1978
+ ...destination.scopes === void 0 ? {} : {
1979
+ scopes: resolveDestinationScopes(destination.scopes, {
1980
+ traces: true,
1981
+ logs: true,
1982
+ metrics: true
1983
+ })
1984
+ }
1841
1985
  },
1842
1986
  false
1843
1987
  )
@@ -1928,8 +2072,26 @@ var exporterPolicySchema = z7.strictObject({
1928
2072
  * Per-destination retry spool bounds, each optional and merged per leaf; any
1929
2073
  * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.
1930
2074
  */
1931
- spool: spoolPolicySchema.partial().optional()
2075
+ spool: spoolPolicySchema.partial().optional(),
2076
+ /**
2077
+ * The most time one hook invocation spends trying to reach one endpoint, in
2078
+ * milliseconds: caps `timeoutMillis` for every OTLP request (connection setup
2079
+ * included) and the exporter's own retries inside it. A batch that does not
2080
+ * get through in time is spooled. Default {@link DEFAULT_EXPORT_BUDGET_MILLIS}:
2081
+ * the host agent waits for its hooks, so a down collector must not stall it.
2082
+ */
2083
+ exportBudgetMillis: z7.number().int().min(50).max(6e5).optional(),
2084
+ /**
2085
+ * After an endpoint was unreachable (refused, timed out, or answered a
2086
+ * retryable status), every hook spools for it without trying for this long,
2087
+ * in milliseconds; then one hook probes it again. 0 disables the window.
2088
+ * Default {@link DEFAULT_ENDPOINT_DOWN_MILLIS}.
2089
+ */
2090
+ endpointDownMillis: z7.number().int().min(0).max(36e5).optional()
1932
2091
  });
2092
+ var DEFAULT_EXPORT_BUDGET_MILLIS = 1500;
2093
+ var DEFAULT_ENDPOINT_DOWN_MILLIS = 3e4;
2094
+ var effectiveExportTimeoutMillis = (exporter) => Math.min(exporter.timeoutMillis, exporter.exportBudgetMillis ?? DEFAULT_EXPORT_BUDGET_MILLIS);
1933
2095
  var detectionPolicySchema = z7.strictObject({
1934
2096
  /** Detections below this confidence resolve to the unknown provider. */
1935
2097
  minimumConfidence: detectionConfidenceSchema,
@@ -1946,6 +2108,9 @@ var diagnosticsPolicySchema = z7.strictObject({
1946
2108
  var providersPolicySchema = z7.strictObject({
1947
2109
  claudeCode: z7.strictObject({
1948
2110
  readTranscriptUsage: z7.boolean()
2111
+ }).optional(),
2112
+ codex: z7.strictObject({
2113
+ readRolloutUsage: z7.boolean()
1949
2114
  }).optional()
1950
2115
  });
1951
2116
  var sessionContextPolicySchema = z7.strictObject({
@@ -1975,7 +2140,8 @@ var otelHookConfigPatchSchema = z7.strictObject({
1975
2140
  detection: detectionPolicySchema.partial().optional(),
1976
2141
  diagnostics: diagnosticsPolicySchema.partial().optional(),
1977
2142
  providers: z7.strictObject({
1978
- claudeCode: z7.strictObject({ readTranscriptUsage: z7.boolean() }).partial().optional()
2143
+ claudeCode: z7.strictObject({ readTranscriptUsage: z7.boolean() }).partial().optional(),
2144
+ codex: z7.strictObject({ readRolloutUsage: z7.boolean() }).partial().optional()
1979
2145
  }).partial().optional(),
1980
2146
  sessionContext: sessionContextPolicySchema.partial().optional()
1981
2147
  });
@@ -2002,7 +2168,8 @@ var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
2002
2168
  emitErrorEvents: true
2003
2169
  });
2004
2170
  var DEFAULT_PROVIDERS_POLICY = Object.freeze({
2005
- claudeCode: Object.freeze({ readTranscriptUsage: false })
2171
+ claudeCode: Object.freeze({ readTranscriptUsage: false }),
2172
+ codex: Object.freeze({ readRolloutUsage: false })
2006
2173
  });
2007
2174
  var DEFAULT_CONFIG = Object.freeze({
2008
2175
  exporter: DEFAULT_EXPORTER_POLICY,
@@ -2012,6 +2179,7 @@ var DEFAULT_CONFIG = Object.freeze({
2012
2179
  providers: DEFAULT_PROVIDERS_POLICY
2013
2180
  });
2014
2181
  var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
2182
+ var readsCodexRolloutUsage = (config) => config.providers?.codex?.readRolloutUsage === true;
2015
2183
  var sessionContextDir = (config) => config.sessionContext?.dir;
2016
2184
  var effectiveMetricsPolicy = (exporter) => ({
2017
2185
  ...DEFAULT_METRICS_POLICY,
@@ -2022,12 +2190,12 @@ var effectiveMetricsPolicy = (exporter) => ({
2022
2190
  var CONFIG_SOURCE_PRECEDENCE = ["defaults", "file", "environment", "inline-override"];
2023
2191
  var configSourceSchema = z8.enum(CONFIG_SOURCE_PRECEDENCE);
2024
2192
  var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2025
- var mergeLeaf = (target, patch, source, provenance, path15) => {
2193
+ var mergeLeaf = (target, patch, source, provenance, path17) => {
2026
2194
  for (const [key, value] of Object.entries(patch)) {
2027
2195
  if (value === void 0) {
2028
2196
  continue;
2029
2197
  }
2030
- const childPath = path15 === "" ? key : `${path15}.${key}`;
2198
+ const childPath = path17 === "" ? key : `${path17}.${key}`;
2031
2199
  const existing = target[key];
2032
2200
  if (isPlainObject(value) && (isPlainObject(existing) || existing === void 0)) {
2033
2201
  const child = { ...existing ?? {} };
@@ -2041,14 +2209,14 @@ var mergeLeaf = (target, patch, source, provenance, path15) => {
2041
2209
  };
2042
2210
  var initialProvenance = (config) => {
2043
2211
  const provenance = {};
2044
- const walk = (value, path15) => {
2212
+ const walk = (value, path17) => {
2045
2213
  if (isPlainObject(value)) {
2046
2214
  for (const [key, child] of Object.entries(value)) {
2047
- walk(child, path15 === "" ? key : `${path15}.${key}`);
2215
+ walk(child, path17 === "" ? key : `${path17}.${key}`);
2048
2216
  }
2049
2217
  return;
2050
2218
  }
2051
- provenance[path15] = "defaults";
2219
+ provenance[path17] = "defaults";
2052
2220
  };
2053
2221
  walk(config, "");
2054
2222
  return provenance;
@@ -2121,6 +2289,18 @@ var resolveConfig = (layers = []) => {
2121
2289
  );
2122
2290
  }
2123
2291
  }
2292
+ const rank = { omit: 0, mask: 1, redact: 2, raw: 3 };
2293
+ const effectiveMode = parsed.data.privacy.contentMode === "raw" && !parsed.data.privacy.allowRawContent ? "omit" : parsed.data.privacy.contentMode;
2294
+ const widening = enabled.filter(
2295
+ (destination) => (destination.scopes ?? []).some(
2296
+ (scope) => scope.contentMode !== void 0 && rank[scope.contentMode] > rank[effectiveMode]
2297
+ )
2298
+ ).map((destination) => destination.name);
2299
+ if (widening.length > 0) {
2300
+ notes.push(
2301
+ `destination(s) ${widening.join(", ")} have a scope contentMode above privacy.contentMode=${effectiveMode}; a scope can only lower disclosure, so ${effectiveMode} applies`
2302
+ );
2303
+ }
2124
2304
  }
2125
2305
  if (!withDestinations && parsed.data.exporter.logs.enabled && parsed.data.exporter.logs.endpoint === void 0 && parsed.data.exporter.endpoint === void 0) {
2126
2306
  notes.push(
@@ -2168,11 +2348,14 @@ var describeDestinationAttributes = (config) => {
2168
2348
  }
2169
2349
  attributes[`${prefix}.header_names`] = [...destination.headerNames];
2170
2350
  attributes[`${prefix}.header_variables`] = [...destination.headerVariables];
2351
+ if (destination.scopes !== void 0) {
2352
+ attributes[`${prefix}.scope_count`] = destination.scopes.length;
2353
+ }
2171
2354
  }
2172
2355
  return attributes;
2173
2356
  };
2174
2357
  var describeResolvedConfig = (config) => {
2175
- const originOf = (endpoint) => {
2358
+ const originOf2 = (endpoint) => {
2176
2359
  if (endpoint === void 0) {
2177
2360
  return void 0;
2178
2361
  }
@@ -2182,10 +2365,10 @@ var describeResolvedConfig = (config) => {
2182
2365
  return "<unparsable>";
2183
2366
  }
2184
2367
  };
2185
- const endpointOrigin2 = originOf(config.exporter.endpoint);
2186
- const logsEndpointOrigin = originOf(config.exporter.logs.endpoint);
2368
+ const endpointOrigin2 = originOf2(config.exporter.endpoint);
2369
+ const logsEndpointOrigin = originOf2(config.exporter.logs.endpoint);
2187
2370
  const metrics = effectiveMetricsPolicy(config.exporter);
2188
- const metricsEndpointOrigin = originOf(metrics.endpoint);
2371
+ const metricsEndpointOrigin = originOf2(metrics.endpoint);
2189
2372
  return {
2190
2373
  "exporter.enabled": config.exporter.enabled,
2191
2374
  "exporter.protocol": config.exporter.protocol,
@@ -3128,7 +3311,12 @@ var policyFlagsToPatch = (policy) => {
3128
3311
  ...Object.keys(exporter).length === 0 ? {} : { exporter },
3129
3312
  ...Object.keys(privacy).length === 0 ? {} : { privacy },
3130
3313
  ...Object.keys(diagnostics).length === 0 ? {} : { diagnostics },
3131
- ...policy.claudeTranscriptUsage === true ? { providers: { claudeCode: { readTranscriptUsage: true } } } : {},
3314
+ ...policy.claudeTranscriptUsage === true || policy.codexRolloutUsage === true ? {
3315
+ providers: {
3316
+ ...policy.claudeTranscriptUsage === true ? { claudeCode: { readTranscriptUsage: true } } : {},
3317
+ ...policy.codexRolloutUsage === true ? { codex: { readRolloutUsage: true } } : {}
3318
+ }
3319
+ } : {},
3132
3320
  ...policy.sessionContextDir === void 0 ? {} : { sessionContext: { dir: policy.sessionContextDir } }
3133
3321
  };
3134
3322
  };
@@ -3219,7 +3407,7 @@ var readIdentityFile = readJsonFile;
3219
3407
 
3220
3408
  // src/cli/doctor.ts
3221
3409
  import { readdir as readdir3, stat as stat3 } from "fs/promises";
3222
- import * as path4 from "path";
3410
+ import * as path5 from "path";
3223
3411
 
3224
3412
  // src/diagnostics/health.ts
3225
3413
  var createHealthTracker = (subsystem, options = {}) => {
@@ -3266,6 +3454,23 @@ var summarizeHealth = (snapshots) => ({
3266
3454
 
3267
3455
  // src/privacy/service.ts
3268
3456
  import { createHash } from "crypto";
3457
+ var DISCLOSURE_RANK = Object.freeze({
3458
+ omitted: 0,
3459
+ masked: 1,
3460
+ redacted: 2,
3461
+ raw: 3
3462
+ });
3463
+ var WHITESPACE = /\s/u;
3464
+ var withoutTrailingToken = (text) => {
3465
+ let end = text.length;
3466
+ while (end > 0) {
3467
+ const low = text.charCodeAt(end - 1);
3468
+ const width = end >= 2 && low >= 56320 && low <= 57343 ? 2 : 1;
3469
+ if (WHITESPACE.test(text.slice(end - width, end))) break;
3470
+ end -= width;
3471
+ }
3472
+ return text.slice(0, end);
3473
+ };
3269
3474
  var compilePatterns = (sources, flags) => {
3270
3475
  const compiled = [];
3271
3476
  for (const source of sources) {
@@ -3483,11 +3688,11 @@ var createPrivacyService = (policyInput) => {
3483
3688
  };
3484
3689
  const flattenToAttributes = (value, prefix) => {
3485
3690
  const attributes = {};
3486
- const walk = (current, path15) => {
3691
+ const walk = (current, path17) => {
3487
3692
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
3488
3693
  const primitive = toAttributePrimitive(current);
3489
3694
  if (primitive !== void 0) {
3490
- attributes[path15] = primitive;
3695
+ attributes[path17] = primitive;
3491
3696
  }
3492
3697
  return;
3493
3698
  }
@@ -3506,16 +3711,16 @@ var createPrivacyService = (policyInput) => {
3506
3711
  primitives.push(entryPrimitive);
3507
3712
  }
3508
3713
  if (uniform) {
3509
- attributes[path15] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
3714
+ attributes[path17] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
3510
3715
  return;
3511
3716
  }
3512
3717
  for (const [index, entry] of current.entries()) {
3513
- walk(entry, `${path15}.${index}`);
3718
+ walk(entry, `${path17}.${index}`);
3514
3719
  }
3515
3720
  return;
3516
3721
  }
3517
3722
  for (const [key, entry] of Object.entries(current)) {
3518
- walk(entry, path15 === "" ? key : `${path15}.${key}`);
3723
+ walk(entry, path17 === "" ? key : `${path17}.${key}`);
3519
3724
  }
3520
3725
  };
3521
3726
  walk(value, prefix);
@@ -3603,7 +3808,31 @@ var createPrivacyService = (policyInput) => {
3603
3808
  flattenToAttributes,
3604
3809
  sanitizeAttributes,
3605
3810
  sanitizeExtensions,
3606
- boundString
3811
+ boundString,
3812
+ restrictContent: (fact, mode) => {
3813
+ const target = CONTENT_MODE_DISCLOSURE[mode];
3814
+ if (fact.text === void 0 || DISCLOSURE_RANK[fact.disclosure] <= DISCLOSURE_RANK[target]) {
3815
+ return fact;
3816
+ }
3817
+ const { text, ...rest } = fact;
3818
+ switch (target) {
3819
+ case "omitted":
3820
+ return { ...rest, disclosure: "omitted", truncated: false };
3821
+ case "masked":
3822
+ return { ...rest, disclosure: "masked", text: maskText(text) };
3823
+ case "redacted": {
3824
+ const redacted = redactSecretSpans(fact.truncated ? withoutTrailingToken(text) : text);
3825
+ return {
3826
+ ...rest,
3827
+ disclosure: "redacted",
3828
+ text: redacted.text,
3829
+ secretsRedacted: fact.secretsRedacted + redacted.count
3830
+ };
3831
+ }
3832
+ case "raw":
3833
+ return fact;
3834
+ }
3835
+ }
3607
3836
  };
3608
3837
  };
3609
3838
 
@@ -5197,6 +5426,7 @@ var permissionModeSchema = z20.enum([
5197
5426
  var codexUsageSchema = z20.object({
5198
5427
  input_tokens: z20.number().int().min(0).optional(),
5199
5428
  cached_input_tokens: z20.number().int().min(0).optional(),
5429
+ cache_write_input_tokens: z20.number().int().min(0).optional(),
5200
5430
  output_tokens: z20.number().int().min(0).optional(),
5201
5431
  reasoning_output_tokens: z20.number().int().min(0).optional(),
5202
5432
  total_tokens: z20.number().int().min(0).optional()
@@ -5452,6 +5682,10 @@ var codexUsageToReport = (usage, temporality) => ({
5452
5682
  temporality,
5453
5683
  ...usage.input_tokens === void 0 ? {} : { inputTokens: usage.input_tokens },
5454
5684
  ...usage.cached_input_tokens === void 0 ? {} : { cachedInputTokens: usage.cached_input_tokens },
5685
+ ...usage.cache_write_input_tokens === void 0 ? {} : {
5686
+ cacheCreationInputTokens: usage.cache_write_input_tokens,
5687
+ cacheCreationAccounting: "included-in-input"
5688
+ },
5455
5689
  ...usage.output_tokens === void 0 ? {} : { outputTokens: usage.output_tokens },
5456
5690
  ...usage.reasoning_output_tokens === void 0 ? {} : { reasoningOutputTokens: usage.reasoning_output_tokens },
5457
5691
  ...usage.total_tokens === void 0 ? {} : { providerTotalTokens: usage.total_tokens }
@@ -5480,8 +5714,9 @@ var CODEX_CAPABILITIES = Object.freeze({
5480
5714
  // turn; see docs/usage-semantics.md.
5481
5715
  cumulativeUsageSeries: "session-lifetime",
5482
5716
  reportsCachedInput: true,
5483
- reportsCacheCreation: false,
5484
- cacheCreationAccounting: "not-reported",
5717
+ // Codex 0.163+ reports `cache_write_input_tokens`, a subset of `input_tokens`.
5718
+ reportsCacheCreation: true,
5719
+ cacheCreationAccounting: "included-in-input",
5485
5720
  reportsReasoningOutput: true,
5486
5721
  reportsProviderTotal: true,
5487
5722
  reportsCost: false,
@@ -8066,7 +8301,7 @@ var createFilesystemStateStore = (options) => {
8066
8301
 
8067
8302
  // src/telemetry/spool-queue.ts
8068
8303
  import { randomBytes as randomBytes2 } from "crypto";
8069
- import { mkdir as mkdir2, readFile as readFile3, readdir as readdir2, rename as rename2, stat as stat2, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
8304
+ import { mkdir as mkdir2, open as open2, readFile as readFile3, readdir as readdir2, rename as rename2, stat as stat2, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
8070
8305
  import * as path3 from "path";
8071
8306
  var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
8072
8307
  total: 0,
@@ -8126,7 +8361,8 @@ var readSpoolQueueStats = async (queueDir) => {
8126
8361
  };
8127
8362
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
8128
8363
  var SPOOL_CLAIM_STALE_MILLIS = 5 * 60 * 1e3;
8129
- var CLAIM_MARKER = ".claimed-";
8364
+ var CLAIM_SUFFIX = ".claim";
8365
+ var RELEASING_SUFFIX = ".releasing";
8130
8366
  var isClaimOwnerAlive = (pid) => {
8131
8367
  if (!Number.isSafeInteger(pid) || pid <= 0) {
8132
8368
  return true;
@@ -8142,6 +8378,34 @@ var isClaimOwnerAlive = (pid) => {
8142
8378
  }
8143
8379
  };
8144
8380
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
8381
+ var readClaim = async (claimPath) => {
8382
+ try {
8383
+ const parsed = JSON.parse(await readFile3(claimPath, "utf8"));
8384
+ return typeof parsed.token === "string" && typeof parsed.pid === "number" && typeof parsed.claimedAt === "number" ? { token: parsed.token, pid: parsed.pid, claimedAt: parsed.claimedAt } : void 0;
8385
+ } catch {
8386
+ return void 0;
8387
+ }
8388
+ };
8389
+ var releaseClaim = async (claimPath, token) => {
8390
+ const tombstone = `${claimPath}.${token ?? "untokened"}-${randomBytes2(4).toString("hex")}${RELEASING_SUFFIX}`;
8391
+ for (let attempt = 1; ; attempt += 1) {
8392
+ try {
8393
+ await rename2(claimPath, tombstone);
8394
+ break;
8395
+ } catch (thrown) {
8396
+ if (isErrnoException2(thrown, "ENOENT") || attempt >= 3) {
8397
+ return;
8398
+ }
8399
+ await new Promise((resolve8) => setTimeout(resolve8, 10 * attempt));
8400
+ }
8401
+ }
8402
+ const captured = await readClaim(tombstone);
8403
+ if (captured !== void 0 && captured.token !== token) {
8404
+ await rename2(tombstone, claimPath).catch(() => void 0);
8405
+ return;
8406
+ }
8407
+ await unlink2(tombstone).catch(() => void 0);
8408
+ };
8145
8409
  var createSpoolQueue = (options) => {
8146
8410
  const [providerSegment, installationSegment] = namespaceSegments(options);
8147
8411
  const queueDir = path3.join(options.rootDir, providerSegment, installationSegment, options.queueName);
@@ -8290,6 +8554,19 @@ var createSpoolQueue = (options) => {
8290
8554
  await rename2(tmp, target);
8291
8555
  return { spooled: true };
8292
8556
  };
8557
+ const claimStaleMillis = options.claimStaleMillis ?? SPOOL_CLAIM_STALE_MILLIS;
8558
+ const staleClaim = async (claimPath) => {
8559
+ const claim = await readClaim(claimPath);
8560
+ const now = Date.now();
8561
+ if (claim !== void 0) {
8562
+ return !isClaimOwnerAlive(claim.pid) || now - claim.claimedAt > claimStaleMillis ? { stale: true, token: claim.token } : { stale: false };
8563
+ }
8564
+ try {
8565
+ return now - (await stat2(claimPath)).mtimeMs > claimStaleMillis ? { stale: true, token: void 0 } : { stale: false };
8566
+ } catch {
8567
+ return { stale: false };
8568
+ }
8569
+ };
8293
8570
  const releaseStaleClaims = async () => {
8294
8571
  let entries;
8295
8572
  try {
@@ -8299,18 +8576,35 @@ var createSpoolQueue = (options) => {
8299
8576
  }
8300
8577
  const now = Date.now();
8301
8578
  for (const entry of entries) {
8302
- const marker = entry.lastIndexOf(CLAIM_MARKER);
8303
- if (marker <= 0) {
8304
- continue;
8579
+ const entryPath = path3.join(queueDir, entry);
8580
+ if (entry.endsWith(CLAIM_SUFFIX)) {
8581
+ const staleness = await staleClaim(entryPath);
8582
+ if (staleness.stale) {
8583
+ await releaseClaim(entryPath, staleness.token);
8584
+ }
8585
+ } else if (entry.endsWith(RELEASING_SUFFIX)) {
8586
+ try {
8587
+ if (now - (await stat2(entryPath)).mtimeMs > claimStaleMillis) {
8588
+ await unlink2(entryPath);
8589
+ }
8590
+ } catch {
8591
+ }
8305
8592
  }
8306
- const claimPath = path3.join(queueDir, entry);
8307
- const owner = Number.parseInt(entry.slice(marker + CLAIM_MARKER.length), 10);
8593
+ }
8594
+ };
8595
+ const claimBatch = async (claimPath) => {
8596
+ const token = randomBytes2(16).toString("hex");
8597
+ try {
8598
+ const handle = await open2(claimPath, "wx");
8308
8599
  try {
8309
- if (!isClaimOwnerAlive(owner) || now - (await stat2(claimPath)).ctimeMs > (options.claimStaleMillis ?? SPOOL_CLAIM_STALE_MILLIS)) {
8310
- await rename2(claimPath, path3.join(queueDir, entry.slice(0, marker)));
8311
- }
8312
- } catch {
8600
+ const contents = { token, pid: process.pid, claimedAt: Date.now() };
8601
+ await handle.writeFile(JSON.stringify(contents), "utf8");
8602
+ } finally {
8603
+ await handle.close();
8313
8604
  }
8605
+ return token;
8606
+ } catch {
8607
+ return void 0;
8314
8608
  }
8315
8609
  };
8316
8610
  const drain = async (send, drainOptions) => {
@@ -8334,21 +8628,7 @@ var createSpoolQueue = (options) => {
8334
8628
  let failed = 0;
8335
8629
  let quarantined = 0;
8336
8630
  let index = 0;
8337
- for (; index < files.length && index < cap; index += 1) {
8338
- const fileName = files[index];
8339
- if (fileName === void 0) {
8340
- break;
8341
- }
8342
- const queuedPath = path3.join(queueDir, fileName);
8343
- const filePath = path3.join(
8344
- queueDir,
8345
- `${fileName}${CLAIM_MARKER}${String(process.pid)}-${randomBytes2(4).toString("hex")}`
8346
- );
8347
- try {
8348
- await rename2(queuedPath, filePath);
8349
- } catch {
8350
- continue;
8351
- }
8631
+ const sendClaimed = async (fileName, filePath, claimPath, token) => {
8352
8632
  const quarantine = async (rejection) => {
8353
8633
  quarantined += 1;
8354
8634
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -8367,17 +8647,17 @@ var createSpoolQueue = (options) => {
8367
8647
  text = await readFile3(filePath, "utf8");
8368
8648
  } catch (thrown) {
8369
8649
  if (thrown?.code === "ENOENT") {
8370
- continue;
8650
+ return "next";
8371
8651
  }
8372
8652
  await quarantine("unreadable");
8373
- continue;
8653
+ return "next";
8374
8654
  }
8375
8655
  let parsed;
8376
8656
  try {
8377
8657
  parsed = JSON.parse(text);
8378
8658
  } catch {
8379
8659
  await quarantine("unparseable-json");
8380
- continue;
8660
+ return "next";
8381
8661
  }
8382
8662
  const validation = options.validate(parsed, {
8383
8663
  providerId: options.providerId,
@@ -8385,7 +8665,10 @@ var createSpoolQueue = (options) => {
8385
8665
  });
8386
8666
  if ("rejection" in validation) {
8387
8667
  await quarantine(validation.rejection);
8388
- continue;
8668
+ return "next";
8669
+ }
8670
+ if ((await readClaim(claimPath))?.token !== token) {
8671
+ return "next";
8389
8672
  }
8390
8673
  let delivered;
8391
8674
  try {
@@ -8397,14 +8680,34 @@ var createSpoolQueue = (options) => {
8397
8680
  if (await unlink2(filePath).then(() => true, () => false)) {
8398
8681
  await recordDrops("rejected", 1);
8399
8682
  }
8400
- continue;
8683
+ return "next";
8401
8684
  }
8402
8685
  if (delivered) {
8403
8686
  await unlink2(filePath).catch(() => void 0);
8404
8687
  drained += 1;
8405
- } else {
8406
- await rename2(filePath, queuedPath).catch(() => void 0);
8407
- failed += 1;
8688
+ return "next";
8689
+ }
8690
+ failed += 1;
8691
+ return "stop";
8692
+ };
8693
+ for (; index < files.length && index < cap; index += 1) {
8694
+ const fileName = files[index];
8695
+ if (fileName === void 0) {
8696
+ break;
8697
+ }
8698
+ const filePath = path3.join(queueDir, fileName);
8699
+ const claimPath = `${filePath}${CLAIM_SUFFIX}`;
8700
+ const token = await claimBatch(claimPath);
8701
+ if (token === void 0) {
8702
+ continue;
8703
+ }
8704
+ let outcome;
8705
+ try {
8706
+ outcome = await sendClaimed(fileName, filePath, claimPath, token);
8707
+ } finally {
8708
+ await releaseClaim(claimPath, token);
8709
+ }
8710
+ if (outcome === "stop") {
8408
8711
  break;
8409
8712
  }
8410
8713
  }
@@ -8621,7 +8924,7 @@ var createFileDurableSpool = (options) => createSpoolQueue({
8621
8924
 
8622
8925
  // src/telemetry/otlp-log-sink.ts
8623
8926
  import { TraceFlags as TraceFlags3 } from "@opentelemetry/api";
8624
- import { ExportResultCode } from "@opentelemetry/core";
8927
+ import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
8625
8928
  import { millisToHrTime as millisToHrTime3 } from "@opentelemetry/core";
8626
8929
  import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
8627
8930
 
@@ -8632,6 +8935,217 @@ var isPermanentExportFailure = (result) => {
8632
8935
  return typeof code === "number" && Number.isInteger(code) && code >= 400 && code < 600 && !RETRYABLE_HTTP_STATUSES.has(code);
8633
8936
  };
8634
8937
 
8938
+ // src/telemetry/endpoint-health.ts
8939
+ import { createHash as createHash3, randomBytes as randomBytes3 } from "crypto";
8940
+ import { mkdir as mkdir3, readFile as readFile4, rename as rename3, unlink as unlink3, writeFile as writeFile3 } from "fs/promises";
8941
+ import * as http from "http";
8942
+ import * as https from "https";
8943
+ import path4 from "path";
8944
+ import { ExportResultCode } from "@opentelemetry/core";
8945
+ var ENDPOINT_DOWN_ERROR_CODE = "OTEL_HOOK_ENDPOINT_DOWN";
8946
+ var UNREACHABLE_NETWORK_CODES = /* @__PURE__ */ new Set([
8947
+ "ECONNREFUSED",
8948
+ "ECONNRESET",
8949
+ "ETIMEDOUT",
8950
+ "EPIPE",
8951
+ "EHOSTUNREACH",
8952
+ "ENETUNREACH",
8953
+ "EHOSTDOWN",
8954
+ "ENETDOWN",
8955
+ "EAI_AGAIN",
8956
+ "ENOTFOUND",
8957
+ ENDPOINT_DOWN_ERROR_CODE
8958
+ ]);
8959
+ var isUnreachableExportFailure = (result) => {
8960
+ if (result.code === ExportResultCode.SUCCESS) {
8961
+ return false;
8962
+ }
8963
+ const error = result.error;
8964
+ const code = error?.code;
8965
+ if (typeof code === "string") {
8966
+ return UNREACHABLE_NETWORK_CODES.has(code);
8967
+ }
8968
+ if (code !== void 0) {
8969
+ return false;
8970
+ }
8971
+ return typeof error?.message === "string" && /timed out/i.test(error.message);
8972
+ };
8973
+ var withConnectTimeout = (agent, connectTimeoutMillis) => {
8974
+ const target = agent;
8975
+ const original = target.createConnection.bind(agent);
8976
+ target.createConnection = (options, callback) => {
8977
+ const socket = original(options, callback);
8978
+ if (socket !== void 0 && socket.connecting) {
8979
+ const timer = setTimeout(() => {
8980
+ const error = Object.assign(new Error("connect timed out"), { code: "ETIMEDOUT" });
8981
+ socket.destroy(error);
8982
+ }, connectTimeoutMillis);
8983
+ timer.unref();
8984
+ const clear = () => {
8985
+ clearTimeout(timer);
8986
+ };
8987
+ socket.once("connect", clear);
8988
+ socket.once("close", clear);
8989
+ }
8990
+ return socket;
8991
+ };
8992
+ return agent;
8993
+ };
8994
+ var boundedExporterOptions = (exporter) => {
8995
+ const timeoutMillis = effectiveExportTimeoutMillis(exporter);
8996
+ let agents = {};
8997
+ return {
8998
+ timeoutMillis,
8999
+ httpAgentOptions: (protocol) => {
9000
+ if (protocol === "https:") {
9001
+ agents = { ...agents, https: agents.https ?? withConnectTimeout(new https.Agent({ keepAlive: true }), timeoutMillis) };
9002
+ return agents.https;
9003
+ }
9004
+ agents = { ...agents, http: agents.http ?? withConnectTimeout(new http.Agent({ keepAlive: true }), timeoutMillis) };
9005
+ return agents.http;
9006
+ }
9007
+ };
9008
+ };
9009
+ var parseMark = (raw) => {
9010
+ try {
9011
+ const parsed = JSON.parse(raw);
9012
+ return typeof parsed.downUntil === "number" && Number.isFinite(parsed.downUntil) ? {
9013
+ downUntil: parsed.downUntil,
9014
+ failures: typeof parsed.failures === "number" && Number.isInteger(parsed.failures) ? parsed.failures : 1
9015
+ } : void 0;
9016
+ } catch {
9017
+ return void 0;
9018
+ }
9019
+ };
9020
+ var originOf = (url) => {
9021
+ if (url === void 0) {
9022
+ return void 0;
9023
+ }
9024
+ try {
9025
+ return new URL(url).origin;
9026
+ } catch {
9027
+ return void 0;
9028
+ }
9029
+ };
9030
+ var createEndpointHealth = (options) => {
9031
+ const downMillis = options.downMillis ?? DEFAULT_ENDPOINT_DOWN_MILLIS;
9032
+ const gates = /* @__PURE__ */ new Map();
9033
+ const createGate = (origin) => {
9034
+ const digest3 = createHash3("sha256").update(origin, "utf8").digest("hex").slice(0, 32);
9035
+ const dir = options.rootDir === void 0 ? void 0 : path4.join(options.rootDir, "endpoint-health");
9036
+ const file = dir === void 0 ? void 0 : path4.join(dir, `${digest3}.json`);
9037
+ let downUntil = 0;
9038
+ let failures = 0;
9039
+ let marked = false;
9040
+ let loaded;
9041
+ let warned = false;
9042
+ const write = async (mark) => {
9043
+ if (file === void 0 || dir === void 0) {
9044
+ return;
9045
+ }
9046
+ try {
9047
+ await mkdir3(dir, { recursive: true });
9048
+ const tmp = path4.join(dir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
9049
+ await writeFile3(tmp, `${JSON.stringify(mark)}
9050
+ `);
9051
+ await rename3(tmp, file);
9052
+ marked = true;
9053
+ } catch {
9054
+ }
9055
+ };
9056
+ const load = () => {
9057
+ loaded ??= (async () => {
9058
+ if (file === void 0) {
9059
+ return;
9060
+ }
9061
+ let raw;
9062
+ try {
9063
+ raw = await readFile4(file, "utf8");
9064
+ } catch {
9065
+ return;
9066
+ }
9067
+ marked = true;
9068
+ const mark = parseMark(raw);
9069
+ if (mark === void 0) {
9070
+ return;
9071
+ }
9072
+ failures = mark.failures;
9073
+ const now = options.clock.now();
9074
+ if (mark.downUntil > now) {
9075
+ downUntil = mark.downUntil;
9076
+ return;
9077
+ }
9078
+ await write({ downUntil: now + options.probeMillis, failures });
9079
+ })();
9080
+ return loaded;
9081
+ };
9082
+ return {
9083
+ available: async () => {
9084
+ if (downMillis === 0) {
9085
+ return true;
9086
+ }
9087
+ await load();
9088
+ return options.clock.now() >= downUntil;
9089
+ },
9090
+ record: async (result) => {
9091
+ if (downMillis === 0) {
9092
+ return;
9093
+ }
9094
+ if (!isUnreachableExportFailure(result)) {
9095
+ if (!marked && downUntil === 0) {
9096
+ return;
9097
+ }
9098
+ downUntil = 0;
9099
+ failures = 0;
9100
+ marked = false;
9101
+ if (file !== void 0) {
9102
+ await unlink3(file).catch(() => void 0);
9103
+ }
9104
+ return;
9105
+ }
9106
+ failures += 1;
9107
+ downUntil = options.clock.now() + downMillis;
9108
+ if (!warned) {
9109
+ warned = true;
9110
+ options.logger?.warn("export endpoint unreachable; hooks spool for it without trying until it is probed again", {
9111
+ "export.endpoint_down_millis": downMillis,
9112
+ "export.endpoint_failures": failures
9113
+ });
9114
+ }
9115
+ await write({ downUntil, failures });
9116
+ }
9117
+ };
9118
+ };
9119
+ return {
9120
+ gateFor: (url) => {
9121
+ const origin = originOf(url);
9122
+ if (origin === void 0) {
9123
+ return void 0;
9124
+ }
9125
+ let gate = gates.get(origin);
9126
+ if (gate === void 0) {
9127
+ gate = createGate(origin);
9128
+ gates.set(origin, gate);
9129
+ }
9130
+ return gate;
9131
+ }
9132
+ };
9133
+ };
9134
+ var guardExport = async (gate, send) => {
9135
+ if (gate === void 0) {
9136
+ return send();
9137
+ }
9138
+ if (!await gate.available()) {
9139
+ return {
9140
+ code: ExportResultCode.FAILED,
9141
+ error: Object.assign(new Error("endpoint marked down; batch not sent"), { code: ENDPOINT_DOWN_ERROR_CODE })
9142
+ };
9143
+ }
9144
+ const result = await send();
9145
+ await gate.record(result).catch(() => void 0);
9146
+ return result;
9147
+ };
9148
+
8635
9149
  // src/telemetry/exporter-resource.ts
8636
9150
  import { resourceFromAttributes } from "@opentelemetry/resources";
8637
9151
  var resourceFromExporterPolicy = (policy) => resourceFromAttributes({
@@ -8802,7 +9316,7 @@ var exportIdentityAttributes = (event3, resource, ids) => {
8802
9316
  };
8803
9317
 
8804
9318
  // src/telemetry/semconv.ts
8805
- import { createHash as createHash3 } from "crypto";
9319
+ import { createHash as createHash4 } from "crypto";
8806
9320
  import { SpanKind, SpanStatusCode, TraceFlags } from "@opentelemetry/api";
8807
9321
  import { millisToHrTime } from "@opentelemetry/core";
8808
9322
  import {
@@ -8821,7 +9335,7 @@ import {
8821
9335
  } from "@opentelemetry/semantic-conventions/incubating";
8822
9336
 
8823
9337
  // src/version.ts
8824
- var VERSION = "0.13.1";
9338
+ var VERSION = "0.14.0";
8825
9339
 
8826
9340
  // src/telemetry/semconv.ts
8827
9341
  var SCOPE_NAME = "@osfactory/otel-hook";
@@ -8842,7 +9356,7 @@ var ATTR_OTELHOOK_AGENT_NAME = "otelhook.agent.name";
8842
9356
  var ATTR_OTELHOOK_AGENT_VERSION = "otelhook.agent.version";
8843
9357
  var ATTR_OTELHOOK_GENERATION_ID = "otelhook.generation.id";
8844
9358
  var FIELD_SEPARATOR = "\0";
8845
- var digestHex = (parts, length) => createHash3("sha256").update(parts.join(FIELD_SEPARATOR)).digest("hex").slice(0, length);
9359
+ var digestHex = (parts, length) => createHash4("sha256").update(parts.join(FIELD_SEPARATOR)).digest("hex").slice(0, length);
8846
9360
  var MAX_RECOVERED_START_ATTRIBUTES = 16;
8847
9361
  var familyOf = (type) => {
8848
9362
  switch (type) {
@@ -9304,6 +9818,17 @@ var planGroup = (group, correlation, correlationAvailable) => {
9304
9818
  };
9305
9819
  var runDiscriminatorOf = (correlation) => correlation?.runSpanIdDiscriminator === void 0 ? void 0 : `run:${correlation.runSpanIdDiscriminator}`;
9306
9820
  var resumedSessionParent = (ref, correlation) => ref.family === "session" && correlation?.runSpanIdDiscriminator !== void 0 ? ref : void 0;
9821
+ var spanEndEdgesOf = (events) => {
9822
+ const layout = layoutBatch(events);
9823
+ const ends = /* @__PURE__ */ new Map();
9824
+ for (const [eventId, groupKey] of layout.groupOf) {
9825
+ const end = layout.groups.get(groupKey)?.end;
9826
+ if (end !== void 0) {
9827
+ ends.set(eventId, end);
9828
+ }
9829
+ }
9830
+ return ends;
9831
+ };
9307
9832
  var canonicalEventTraceIdentities = (events, options = {}) => {
9308
9833
  const layout = layoutBatch(events);
9309
9834
  const correlations = indexCorrelations(options.correlations);
@@ -9848,12 +10373,16 @@ var createOtlpLogSink = (options) => {
9848
10373
  const exporter = new OTLPLogExporter({
9849
10374
  url: deliverability.endpoint,
9850
10375
  headers: { ...options.headers },
9851
- timeoutMillis: options.exporter.timeoutMillis
10376
+ ...boundedExporterOptions(options.exporter)
9852
10377
  });
10378
+ const gate = options.endpointHealth?.gateFor(deliverability.endpoint);
9853
10379
  let shutdownCompleted = false;
9854
- const exportRecords = (records) => new Promise((resolve8) => {
9855
- exporter.export([...records], (result) => resolve8(result));
9856
- });
10380
+ const exportRecords = (records) => guardExport(
10381
+ gate,
10382
+ () => new Promise((resolve8) => {
10383
+ exporter.export([...records], (result) => resolve8(result));
10384
+ })
10385
+ );
9857
10386
  const toSpoolBatch = (records, batchResource) => ({
9858
10387
  providerId: options.providerId,
9859
10388
  installationId: options.installationId,
@@ -9871,7 +10400,7 @@ var createOtlpLogSink = (options) => {
9871
10400
  (record) => deserializeRecord(record, batchResource, batch.instrumentationScope)
9872
10401
  );
9873
10402
  const result = await exportRecords(records);
9874
- if (result.code === ExportResultCode.SUCCESS) {
10403
+ if (result.code === ExportResultCode2.SUCCESS) {
9875
10404
  return true;
9876
10405
  }
9877
10406
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -9917,11 +10446,11 @@ var createOtlpLogSink = (options) => {
9917
10446
  result = await exportRecords(batch);
9918
10447
  } catch (thrown) {
9919
10448
  result = {
9920
- code: ExportResultCode.FAILED,
10449
+ code: ExportResultCode2.FAILED,
9921
10450
  error: thrown instanceof Error ? thrown : new Error("export threw")
9922
10451
  };
9923
10452
  }
9924
- if (result.code === ExportResultCode.SUCCESS) {
10453
+ if (result.code === ExportResultCode2.SUCCESS) {
9925
10454
  accepted += batch.length;
9926
10455
  health.recordSuccess(batch.length, options.clock.now());
9927
10456
  continue;
@@ -9962,6 +10491,9 @@ var createOtlpLogSink = (options) => {
9962
10491
  if (options.spool === void 0) {
9963
10492
  return { drained: 0, remaining: 0, failed: 0 };
9964
10493
  }
10494
+ if (gate !== void 0 && !await gate.available()) {
10495
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
10496
+ }
9965
10497
  const result = await options.spool.drain(sendSerializedBatch, {
9966
10498
  ...maxBatches === void 0 ? {} : { maxBatches }
9967
10499
  });
@@ -9998,7 +10530,7 @@ var createOtlpLogSink = (options) => {
9998
10530
  };
9999
10531
 
10000
10532
  // src/telemetry/otlp-sink.ts
10001
- import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
10533
+ import { ExportResultCode as ExportResultCode3 } from "@opentelemetry/core";
10002
10534
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
10003
10535
  var chunk2 = (items, size) => {
10004
10536
  if (size <= 0 || items.length <= size) {
@@ -10076,12 +10608,16 @@ var createOtlpTraceSink = (options) => {
10076
10608
  const exporter = new OTLPTraceExporter({
10077
10609
  url: options.exporter.endpoint,
10078
10610
  headers: { ...options.headers },
10079
- timeoutMillis: options.exporter.timeoutMillis
10611
+ ...boundedExporterOptions(options.exporter)
10080
10612
  });
10613
+ const gate = options.endpointHealth?.gateFor(options.exporter.endpoint);
10081
10614
  let shutdownCompleted = false;
10082
- const exportSpans = (spans) => new Promise((resolve8) => {
10083
- exporter.export([...spans], (result) => resolve8(result));
10084
- });
10615
+ const exportSpans = (spans) => guardExport(
10616
+ gate,
10617
+ () => new Promise((resolve8) => {
10618
+ exporter.export([...spans], (result) => resolve8(result));
10619
+ })
10620
+ );
10085
10621
  const toSpoolBatch = (spans, batchResource) => ({
10086
10622
  providerId: options.providerId,
10087
10623
  installationId: options.installationId,
@@ -10094,7 +10630,7 @@ var createOtlpTraceSink = (options) => {
10094
10630
  const batchResource = replayResource(batch.resourceAttributes, options.exporter);
10095
10631
  const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));
10096
10632
  const result = await exportSpans(spans);
10097
- if (result.code === ExportResultCode2.SUCCESS) {
10633
+ if (result.code === ExportResultCode3.SUCCESS) {
10098
10634
  return true;
10099
10635
  }
10100
10636
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -10133,9 +10669,9 @@ var createOtlpTraceSink = (options) => {
10133
10669
  try {
10134
10670
  result = await exportSpans(batch);
10135
10671
  } catch (thrown) {
10136
- result = { code: ExportResultCode2.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
10672
+ result = { code: ExportResultCode3.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
10137
10673
  }
10138
- if (result.code === ExportResultCode2.SUCCESS) {
10674
+ if (result.code === ExportResultCode3.SUCCESS) {
10139
10675
  accepted += batch.length;
10140
10676
  health.recordSuccess(batch.length, options.clock.now());
10141
10677
  continue;
@@ -10172,6 +10708,9 @@ var createOtlpTraceSink = (options) => {
10172
10708
  if (options.spool === void 0) {
10173
10709
  return { drained: 0, remaining: 0, failed: 0 };
10174
10710
  }
10711
+ if (gate !== void 0 && !await gate.available()) {
10712
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
10713
+ }
10175
10714
  const result = await options.spool.drain(sendSerializedBatch, { ...maxBatches === void 0 ? {} : { maxBatches } });
10176
10715
  if (result.drained > 0) {
10177
10716
  health.recordSuccess(result.drained, options.clock.now());
@@ -10562,7 +11101,7 @@ var createFileDurableMetricSpool = (options) => createSpoolQueue({
10562
11101
 
10563
11102
  // src/telemetry/otlp-metric-sink.ts
10564
11103
  import { ValueType } from "@opentelemetry/api";
10565
- import { ExportResultCode as ExportResultCode3, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
11104
+ import { ExportResultCode as ExportResultCode4, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
10566
11105
  import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
10567
11106
  import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
10568
11107
  import {
@@ -10706,10 +11245,12 @@ var createOtlpMetricSink = (options) => {
10706
11245
  const exporter = new OTLPMetricExporter({
10707
11246
  url: deliverability.endpoint,
10708
11247
  headers: { ...options.headers },
10709
- timeoutMillis: options.exporter.timeoutMillis
11248
+ ...boundedExporterOptions(options.exporter)
10710
11249
  });
11250
+ const gate = options.endpointHealth?.gateFor(deliverability.endpoint);
10711
11251
  let shutdownCompleted = false;
10712
- const exportResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve8) => {
11252
+ const exportResourceMetrics = (points, batchResource, batchScope) => guardExport(gate, () => sendResourceMetrics(points, batchResource, batchScope));
11253
+ const sendResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve8) => {
10713
11254
  const payload = {
10714
11255
  resource: batchResource,
10715
11256
  scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }]
@@ -10718,7 +11259,7 @@ var createOtlpMetricSink = (options) => {
10718
11259
  exporter.export(payload, (result) => resolve8(result));
10719
11260
  } catch (thrown) {
10720
11261
  resolve8({
10721
- code: ExportResultCode3.FAILED,
11262
+ code: ExportResultCode4.FAILED,
10722
11263
  error: thrown instanceof Error ? thrown : new Error("export threw")
10723
11264
  });
10724
11265
  }
@@ -10739,7 +11280,7 @@ var createOtlpMetricSink = (options) => {
10739
11280
  withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes)
10740
11281
  );
10741
11282
  const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);
10742
- if (result.code === ExportResultCode3.SUCCESS) {
11283
+ if (result.code === ExportResultCode4.SUCCESS) {
10743
11284
  return true;
10744
11285
  }
10745
11286
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -10750,7 +11291,7 @@ var createOtlpMetricSink = (options) => {
10750
11291
  }
10751
11292
  const batchResource = context === void 0 ? resource : resourceWithContext(resource, context);
10752
11293
  const result = await exportResourceMetrics(points, batchResource, scope);
10753
- if (result.code === ExportResultCode3.SUCCESS) {
11294
+ if (result.code === ExportResultCode4.SUCCESS) {
10754
11295
  health.recordSuccess(points.length, options.clock.now());
10755
11296
  return { accepted: points.length, rejected: 0, errors: [] };
10756
11297
  }
@@ -10790,6 +11331,9 @@ var createOtlpMetricSink = (options) => {
10790
11331
  if (options.spool === void 0) {
10791
11332
  return { drained: 0, remaining: 0, failed: 0 };
10792
11333
  }
11334
+ if (gate !== void 0 && !await gate.available()) {
11335
+ return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
11336
+ }
10793
11337
  const result = await options.spool.drain(sendSerializedBatch, {
10794
11338
  ...maxBatches === void 0 ? {} : { maxBatches }
10795
11339
  });
@@ -10826,6 +11370,101 @@ var createOtlpMetricSink = (options) => {
10826
11370
  };
10827
11371
  };
10828
11372
 
11373
+ // src/telemetry/destination-scope.ts
11374
+ var DISCLOSURE_RANK2 = Object.freeze({
11375
+ omitted: 0,
11376
+ masked: 1,
11377
+ redacted: 2,
11378
+ raw: 3
11379
+ });
11380
+ var omitRestrictedContent = (fact, mode) => {
11381
+ if (fact.text === void 0 || DISCLOSURE_RANK2[fact.disclosure] <= DISCLOSURE_RANK2[CONTENT_MODE_DISCLOSURE[mode]]) {
11382
+ return fact;
11383
+ }
11384
+ const { text, ...rest } = fact;
11385
+ void text;
11386
+ return { ...rest, disclosure: "omitted", truncated: false };
11387
+ };
11388
+ var keyOfValue = (value) => typeof value === "string" ? normalizeRepositoryKey(value) : void 0;
11389
+ var resourceRepositoryKey = (attributes) => keyOfValue(attributes[ATTR_VCS_REPOSITORY_URL_FULL]);
11390
+ var eventRepositoryKey = (event3, fallbackKey) => {
11391
+ const stamped = event3.contextAttributes?.[ATTR_VCS_REPOSITORY_URL_FULL];
11392
+ return stamped === void 0 ? fallbackKey : keyOfValue(stamped);
11393
+ };
11394
+ var pointRepositoryKey = (point, fallbackKey) => {
11395
+ const stamped = point.attributes[ATTR_VCS_REPOSITORY_URL_FULL];
11396
+ return stamped === void 0 ? fallbackKey : keyOfValue(stamped);
11397
+ };
11398
+ var restrictFacts = (facts, mode, restrict) => facts?.map((fact) => restrict(fact, mode));
11399
+ var restrictEventContent = (event3, mode, restrict) => {
11400
+ switch (event3.type) {
11401
+ case "prompt.submitted":
11402
+ return event3.content === void 0 ? event3 : { ...event3, content: restrict(event3.content, mode) };
11403
+ case "generation.start": {
11404
+ const inputContent = restrictFacts(event3.inputContent, mode, restrict);
11405
+ return inputContent === void 0 ? event3 : { ...event3, inputContent };
11406
+ }
11407
+ case "generation.end": {
11408
+ const outputContent = restrictFacts(event3.outputContent, mode, restrict);
11409
+ return outputContent === void 0 ? event3 : { ...event3, outputContent };
11410
+ }
11411
+ case "tool.start":
11412
+ return event3.input === void 0 ? event3 : { ...event3, input: restrict(event3.input, mode) };
11413
+ case "tool.end":
11414
+ return event3.output === void 0 ? event3 : { ...event3, output: restrict(event3.output, mode) };
11415
+ case "error.raised":
11416
+ return event3.message === void 0 ? event3 : { ...event3, message: restrict(event3.message, mode) };
11417
+ default:
11418
+ return event3;
11419
+ }
11420
+ };
11421
+ var routeEventsToScopes = (events, scopes, options) => {
11422
+ const ends = spanEndEdgesOf(events);
11423
+ const traces = [];
11424
+ const logs = [];
11425
+ let unchanged = true;
11426
+ for (const event3 of events) {
11427
+ const anchor = ends.get(event3.eventId) ?? event3;
11428
+ const scope = matchDestinationScope(scopes, eventRepositoryKey(anchor, options.resourceRepositoryKey));
11429
+ if (scope === void 0 || !scope.signals.traces || !scope.signals.logs) {
11430
+ unchanged = false;
11431
+ }
11432
+ if (scope === void 0) {
11433
+ continue;
11434
+ }
11435
+ const restricted = scope.contentMode === void 0 ? event3 : restrictEventContent(event3, scope.contentMode, options.restrict);
11436
+ if (restricted !== event3) {
11437
+ unchanged = false;
11438
+ }
11439
+ if (scope.signals.traces) {
11440
+ traces.push(restricted);
11441
+ }
11442
+ if (scope.signals.logs) {
11443
+ logs.push(restricted);
11444
+ }
11445
+ }
11446
+ return unchanged ? { traces: events, logs: events } : { traces, logs };
11447
+ };
11448
+ var routePointsToScopes = (scopes, pointsFor, options) => {
11449
+ const effective = (scope) => options.includeSessionId && scope.includeSessionId;
11450
+ const kept = [];
11451
+ for (const variant of [true, false]) {
11452
+ if (!scopes.some((scope) => scope.signals.metrics && effective(scope) === variant)) {
11453
+ continue;
11454
+ }
11455
+ for (const point of pointsFor(variant) ?? []) {
11456
+ const scope = matchDestinationScope(scopes, pointRepositoryKey(point, options.fallbackKey));
11457
+ if (scope?.signals.metrics === true && effective(scope) === variant) {
11458
+ kept.push(point);
11459
+ }
11460
+ }
11461
+ }
11462
+ return kept;
11463
+ };
11464
+ var sessionIdVariantsFor = (scopes, includeSessionId) => new Set(
11465
+ scopes.filter((scope) => scope.signals.metrics).map((scope) => includeSessionId && scope.includeSessionId)
11466
+ );
11467
+
10829
11468
  // src/telemetry/signal-fanout.ts
10830
11469
  var createSignalFanout = (options) => {
10831
11470
  const emit = async (events) => {
@@ -10858,14 +11497,20 @@ var createSignalFanout = (options) => {
10858
11497
  };
10859
11498
  var shareCorrelationPerBatch = (correlate) => {
10860
11499
  let pending;
10861
- return (events) => {
10862
- if (pending?.events === events) {
11500
+ const resolve8 = (events) => {
11501
+ if (pending !== void 0 && (pending.events === events || pending.aliases.has(events))) {
10863
11502
  return pending.result;
10864
11503
  }
10865
11504
  const result = correlate(events);
10866
- pending = { events, result };
11505
+ pending = { events, aliases: /* @__PURE__ */ new Set(), result };
10867
11506
  return result;
10868
11507
  };
11508
+ const alias = (subset, batch) => {
11509
+ if (pending?.events === batch && subset !== batch) {
11510
+ pending.aliases.add(subset);
11511
+ }
11512
+ };
11513
+ return Object.assign(resolve8, { alias });
10869
11514
  };
10870
11515
 
10871
11516
  // src/telemetry/export-destinations.ts
@@ -10927,6 +11572,15 @@ var createExportDestinationSinks = (options) => {
10927
11572
  const spoolPolicy = effectiveSpoolPolicy(options.exporter);
10928
11573
  const destinations = [];
10929
11574
  const skipped = [];
11575
+ const endpointHealth = options.endpointHealth ?? createEndpointHealth({
11576
+ ...options.spoolRootDir === void 0 ? {} : { rootDir: options.spoolRootDir },
11577
+ clock: options.clock,
11578
+ ...options.logger === void 0 ? {} : { logger: options.logger },
11579
+ ...options.exporter.endpointDownMillis === void 0 ? {} : { downMillis: options.exporter.endpointDownMillis },
11580
+ probeMillis: effectiveExportTimeoutMillis(options.exporter) + 1e3
11581
+ });
11582
+ const scopedResourceKey = resourceRepositoryKey(resourceFromExporterPolicy(options.exporter).attributes);
11583
+ const restrict = options.restrictContent ?? omitRestrictedContent;
10930
11584
  for (const destination of resolveExportDestinations(options.exporter)) {
10931
11585
  let headers;
10932
11586
  let logHeaders;
@@ -10986,6 +11640,7 @@ var createExportDestinationSinks = (options) => {
10986
11640
  const sinkShared = {
10987
11641
  exporter: policy,
10988
11642
  ...shared,
11643
+ endpointHealth,
10989
11644
  ...options.correlate === void 0 ? {} : { correlate: options.correlate },
10990
11645
  ...label === void 0 ? {} : { destination: label }
10991
11646
  };
@@ -11003,6 +11658,7 @@ var createExportDestinationSinks = (options) => {
11003
11658
  const metrics = destination.signals.metrics ? createOtlpMetricSink({
11004
11659
  exporter: policy,
11005
11660
  ...shared,
11661
+ endpointHealth,
11006
11662
  ...label === void 0 ? {} : { destination: label },
11007
11663
  ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
11008
11664
  ...metricSpool === void 0 ? {} : { spool: metricSpool }
@@ -11014,17 +11670,51 @@ var createExportDestinationSinks = (options) => {
11014
11670
  metrics,
11015
11671
  ...spool === void 0 ? {} : { spool },
11016
11672
  ...logSpool === void 0 ? {} : { logSpool },
11017
- ...metricSpool === void 0 ? {} : { metricSpool }
11673
+ ...metricSpool === void 0 ? {} : { metricSpool },
11674
+ ...destination.scopes === void 0 ? {} : {
11675
+ scopes: destination.scopes,
11676
+ route: (events) => routeEventsToScopes(events, destination.scopes ?? [], {
11677
+ ...scopedResourceKey === void 0 ? {} : { resourceRepositoryKey: scopedResourceKey },
11678
+ restrict
11679
+ })
11680
+ }
11018
11681
  });
11019
11682
  }
11020
11683
  return { destinations, skipped };
11021
11684
  };
11022
- var createDestinationFanout = (destinations) => {
11685
+ var createScopedFanout = (destination, correlate) => {
11686
+ const route = destination.route;
11687
+ const unscoped = createSignalFanout({ traces: destination.traces, logs: destination.logs });
11688
+ if (route === void 0) {
11689
+ return unscoped;
11690
+ }
11691
+ const none2 = { accepted: 0, rejected: 0, errors: [] };
11692
+ return {
11693
+ ...unscoped,
11694
+ emit: async (events) => {
11695
+ const batch = route(events);
11696
+ if (correlate !== void 0 && (batch.traces.length > 0 || batch.logs.length > 0)) {
11697
+ await correlate(events);
11698
+ correlate.alias(batch.traces, events);
11699
+ correlate.alias(batch.logs, events);
11700
+ }
11701
+ const traces = batch.traces.length === 0 ? none2 : await destination.traces.emit(batch.traces);
11702
+ const logs = batch.logs.length === 0 ? none2 : await destination.logs.emit(batch.logs);
11703
+ return {
11704
+ accepted: traces.accepted + logs.accepted,
11705
+ rejected: traces.rejected + logs.rejected,
11706
+ errors: [...traces.errors, ...logs.errors]
11707
+ };
11708
+ }
11709
+ };
11710
+ };
11711
+ var createDestinationFanout = (destinations, options = {}) => {
11023
11712
  const fanouts = destinations.map((destination) => ({
11024
11713
  name: destination.name,
11025
- sink: createSignalFanout({ traces: destination.traces, logs: destination.logs })
11714
+ sink: createScopedFanout(destination, options.correlate)
11026
11715
  }));
11027
- const only = fanouts.length === 1 ? fanouts[0] : void 0;
11716
+ const scoped = destinations.some((destination) => destination.route !== void 0);
11717
+ const only = fanouts.length === 1 && !scoped ? fanouts[0] : void 0;
11028
11718
  if (only !== void 0) {
11029
11719
  return only.sink;
11030
11720
  }
@@ -11185,7 +11875,7 @@ var collectDoctorReport = async (command, io) => {
11185
11875
  checks.push({
11186
11876
  name: "session-context",
11187
11877
  ok: true,
11188
- detail: contextDir === void 0 ? "off (sessionContext.dir is not set)" : `reading ${path4.join(contextDir, "<agent-tool>", "<session-id>.json")}${contextDirExists ? "" : " (directory does not exist yet; nothing is stamped until it does)"}`
11878
+ detail: contextDir === void 0 ? "off (sessionContext.dir is not set)" : `reading ${path5.join(contextDir, "<agent-tool>", "<session-id>.json")}${contextDirExists ? "" : " (directory does not exist yet; nothing is stamped until it does)"}`
11189
11879
  });
11190
11880
  const providers = describeProviderCatalog({
11191
11881
  includeExperimental: command.policy.includeExperimental ?? true
@@ -11254,8 +11944,25 @@ var describeDestinationLine = (destination) => {
11254
11944
  );
11255
11945
  }
11256
11946
  }
11257
- return `${destination.ok ? "ok " : "FAIL"} destination ${destination.name}: ${parts.join("; ")}`;
11947
+ if (destination.scopes === void 0) {
11948
+ if (destination.enabled) {
11949
+ parts.push("all repositories");
11950
+ }
11951
+ } else {
11952
+ parts.push(`scoped (${String(destination.scopes.length)} scope(s); records without a repository are not sent)`);
11953
+ }
11954
+ const lines = [`${destination.ok ? "ok " : "FAIL"} destination ${destination.name}: ${parts.join("; ")}`];
11955
+ for (const [index, scope] of (destination.scopes ?? []).entries()) {
11956
+ lines.push(` scope ${String(index + 1)}: ${describeScopeLine(scope)}`);
11957
+ }
11958
+ return lines.join("\n");
11258
11959
  };
11960
+ var describeScopeLine = (scope) => [
11961
+ scope.repositories === "*" ? "every repository" : scope.repositories.join(", "),
11962
+ scope.signals.length === 0 ? "no signals" : scope.signals.join("+"),
11963
+ `content ${scope.contentMode ?? "as configured"}`,
11964
+ scope.includeSessionId ? "session.id on metrics" : "no session.id on metrics"
11965
+ ].join("; ");
11259
11966
  var sumSpoolStats = (all) => {
11260
11967
  const oldest = all.map((stats) => stats.oldestEnqueuedAt).filter((value) => value !== void 0);
11261
11968
  const lastDropped = all.map((stats) => stats.dropped.lastDroppedAt).filter((value) => value !== void 0);
@@ -11283,7 +11990,7 @@ var inspectQueue = async (spool, queueName) => {
11283
11990
  const installation = sanitizeSegment(spool.installationId);
11284
11991
  const stats = await Promise.all(
11285
11992
  namespaces.map(
11286
- (namespace) => readSpoolQueueStats(path4.join(spool.rootDir, namespace, installation, queueName))
11993
+ (namespace) => readSpoolQueueStats(path5.join(spool.rootDir, namespace, installation, queueName))
11287
11994
  )
11288
11995
  );
11289
11996
  return stats.length === 0 ? { batches: 0, bytes: 0, dropped: EMPTY_SPOOL_DROP_COUNTS } : sumSpoolStats(stats);
@@ -12228,7 +12935,7 @@ var SUPPORTED_REGISTRATION_PROVIDER_IDS = Object.freeze(
12228
12935
  );
12229
12936
 
12230
12937
  // src/install/scopes.ts
12231
- import * as path5 from "path";
12938
+ import * as path6 from "path";
12232
12939
  var REGISTRATION_SCOPES = Object.freeze([
12233
12940
  "global",
12234
12941
  "project"
@@ -12296,15 +13003,15 @@ var PROVIDERS_WITH_VERIFIED_LOCATION = Object.freeze([
12296
13003
  var findInstallLocation = (providerId, scope) => PROVIDER_INSTALL_LOCATIONS.find(
12297
13004
  (entry) => entry.providerId === providerId && entry.scope === scope
12298
13005
  );
12299
- var resolveInstallPath = (location, roots) => path5.resolve(
13006
+ var resolveInstallPath = (location, roots) => path6.resolve(
12300
13007
  location.scope === "global" ? roots.homeDir : roots.projectDir,
12301
13008
  ...location.segments
12302
13009
  );
12303
13010
 
12304
13011
  // src/install/document.ts
12305
- import { randomBytes as randomBytes3 } from "crypto";
12306
- import { chmod, mkdir as mkdir3, open as open2, readFile as readFile4, rename as rename3, stat as stat4, unlink as unlink3 } from "fs/promises";
12307
- import * as path6 from "path";
13012
+ import { randomBytes as randomBytes4 } from "crypto";
13013
+ import { chmod, mkdir as mkdir4, open as open3, readFile as readFile5, rename as rename4, stat as stat4, unlink as unlink4 } from "fs/promises";
13014
+ import * as path7 from "path";
12308
13015
  var DEFAULT_DOCUMENT_FORMAT = Object.freeze({
12309
13016
  indent: " ",
12310
13017
  eol: "\n",
@@ -12328,7 +13035,7 @@ var renderJsonDocument = (value, format) => {
12328
13035
  var readJsonDocument = async (filePath) => {
12329
13036
  let raw;
12330
13037
  try {
12331
- raw = await readFile4(filePath, "utf8");
13038
+ raw = await readFile5(filePath, "utf8");
12332
13039
  } catch (thrown) {
12333
13040
  if (isErrnoException3(thrown, "ENOENT")) {
12334
13041
  return { status: "absent", format: DEFAULT_DOCUMENT_FORMAT };
@@ -12360,7 +13067,7 @@ var delay = (millis) => new Promise((resolve8) => {
12360
13067
  var renameWithRetry = async (from, to) => {
12361
13068
  for (let attempt = 0; ; attempt += 1) {
12362
13069
  try {
12363
- await rename3(from, to);
13070
+ await rename4(from, to);
12364
13071
  return;
12365
13072
  } catch (thrown) {
12366
13073
  const retryable = isErrnoException3(thrown, "EPERM", "EACCES", "EBUSY");
@@ -12375,11 +13082,11 @@ var renameWithRetry = async (from, to) => {
12375
13082
  var NEW_DOCUMENT_MODE = 384;
12376
13083
  var TEMPORARY_DOCUMENT_MODE = 384;
12377
13084
  var writeDocumentAtomically = async (filePath, contents) => {
12378
- const directory = path6.dirname(filePath);
12379
- await mkdir3(directory, { recursive: true });
12380
- const temporary = path6.join(
13085
+ const directory = path7.dirname(filePath);
13086
+ await mkdir4(directory, { recursive: true });
13087
+ const temporary = path7.join(
12381
13088
  directory,
12382
- `.${path6.basename(filePath)}.${randomBytes3(6).toString("hex")}.tmp`
13089
+ `.${path7.basename(filePath)}.${randomBytes4(6).toString("hex")}.tmp`
12383
13090
  );
12384
13091
  let existingMode;
12385
13092
  try {
@@ -12391,7 +13098,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
12391
13098
  }
12392
13099
  const targetMode = existingMode ?? NEW_DOCUMENT_MODE;
12393
13100
  try {
12394
- const handle = await open2(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
13101
+ const handle = await open3(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
12395
13102
  try {
12396
13103
  await handle.writeFile(contents, "utf8");
12397
13104
  await handle.sync();
@@ -12401,19 +13108,19 @@ var writeDocumentAtomically = async (filePath, contents) => {
12401
13108
  }
12402
13109
  await renameWithRetry(temporary, filePath);
12403
13110
  } catch (thrown) {
12404
- await unlink3(temporary).catch(() => void 0);
13111
+ await unlink4(temporary).catch(() => void 0);
12405
13112
  throw thrown;
12406
13113
  }
12407
13114
  };
12408
13115
 
12409
13116
  // src/install/file-lock.ts
12410
- import { randomBytes as randomBytes4 } from "crypto";
12411
- import { mkdir as mkdir4, open as open3, readFile as readFile5, rename as rename4, stat as stat5, unlink as unlink4 } from "fs/promises";
12412
- import * as path7 from "path";
13117
+ import { randomBytes as randomBytes5 } from "crypto";
13118
+ import { mkdir as mkdir5, open as open4, readFile as readFile6, rename as rename5, stat as stat5, unlink as unlink5 } from "fs/promises";
13119
+ import * as path8 from "path";
12413
13120
  var FileLockTimeoutError = class extends Error {
12414
13121
  constructor(lockPath, timeoutMillis) {
12415
13122
  super(
12416
- `timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path7.basename(lockPath)}`
13123
+ `timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path8.basename(lockPath)}`
12417
13124
  );
12418
13125
  this.name = "FileLockTimeoutError";
12419
13126
  }
@@ -12424,7 +13131,7 @@ var isErrnoException4 = (thrown, code) => thrown instanceof Error && thrown.code
12424
13131
  var readLockContents = async (lockPath) => {
12425
13132
  let raw;
12426
13133
  try {
12427
- raw = await readFile5(lockPath, "utf8");
13134
+ raw = await readFile6(lockPath, "utf8");
12428
13135
  } catch {
12429
13136
  return void 0;
12430
13137
  }
@@ -12438,18 +13145,18 @@ var readLockContents = async (lockPath) => {
12438
13145
  var releaseIfOwned = async (lockPath, token) => {
12439
13146
  const tombstone = `${lockPath}.${token}.releasing`;
12440
13147
  try {
12441
- await rename4(lockPath, tombstone);
13148
+ await rename5(lockPath, tombstone);
12442
13149
  } catch {
12443
13150
  return false;
12444
13151
  }
12445
13152
  const captured = await readLockContents(tombstone);
12446
13153
  if (captured !== void 0 && captured.token !== token) {
12447
- await rename4(tombstone, lockPath).catch(async () => {
13154
+ await rename5(tombstone, lockPath).catch(async () => {
12448
13155
  await Promise.resolve();
12449
13156
  });
12450
13157
  return false;
12451
13158
  }
12452
- await unlink4(tombstone).catch(() => void 0);
13159
+ await unlink5(tombstone).catch(() => void 0);
12453
13160
  return true;
12454
13161
  };
12455
13162
  var delay2 = (millis) => new Promise((resolve8) => {
@@ -12458,7 +13165,7 @@ var delay2 = (millis) => new Promise((resolve8) => {
12458
13165
  var isStale = async (lockPath, clock, staleMillis) => {
12459
13166
  let raw;
12460
13167
  try {
12461
- raw = await readFile5(lockPath, "utf8");
13168
+ raw = await readFile6(lockPath, "utf8");
12462
13169
  } catch (thrown) {
12463
13170
  return { stale: !isErrnoException4(thrown, "ENOENT") };
12464
13171
  }
@@ -12485,12 +13192,12 @@ var withFileLock = async (filePath, options, fn) => {
12485
13192
  const pollIntervalMillis = options.pollIntervalMillis ?? 25;
12486
13193
  const lockPath = lockPathFor(filePath);
12487
13194
  const startedAt = options.clock.monotonicMillis();
12488
- await mkdir4(path7.dirname(filePath), { recursive: true });
13195
+ await mkdir5(path8.dirname(filePath), { recursive: true });
12489
13196
  for (; ; ) {
12490
- const token = randomBytes4(16).toString("hex");
13197
+ const token = randomBytes5(16).toString("hex");
12491
13198
  let acquired = false;
12492
13199
  try {
12493
- const handle = await open3(lockPath, "wx", 384);
13200
+ const handle = await open4(lockPath, "wx", 384);
12494
13201
  try {
12495
13202
  const contents = {
12496
13203
  token,
@@ -12532,8 +13239,8 @@ var withFileLock = async (filePath, options, fn) => {
12532
13239
  };
12533
13240
 
12534
13241
  // src/install/lifecycle.ts
12535
- import { readFile as readFile6 } from "fs/promises";
12536
- import * as path8 from "path";
13242
+ import { readFile as readFile7 } from "fs/promises";
13243
+ import * as path9 from "path";
12537
13244
  var defaultHookCommand = (providerId) => `otel-hook run --provider ${providerId}`;
12538
13245
  var unsupportedOutcome = (providerId, scope, reason) => ({
12539
13246
  providerId,
@@ -12550,7 +13257,7 @@ var unsupportedOutcome = (providerId, scope, reason) => ({
12550
13257
  var resolveTarget = (providerId, scope, request) => {
12551
13258
  if (request.configFile !== void 0) {
12552
13259
  return {
12553
- configPath: path8.resolve(request.configFile),
13260
+ configPath: path9.resolve(request.configFile),
12554
13261
  evidence: "path supplied by the caller with --settings-file"
12555
13262
  };
12556
13263
  }
@@ -12567,14 +13274,14 @@ var resolveTarget = (providerId, scope, request) => {
12567
13274
  };
12568
13275
  };
12569
13276
  var codexFeatureNote = async (configPath) => {
12570
- const tomlPath = path8.join(path8.dirname(configPath), "config.toml");
13277
+ const tomlPath = path9.join(path9.dirname(configPath), "config.toml");
12571
13278
  let raw;
12572
13279
  try {
12573
- raw = await readFile6(tomlPath, "utf8");
13280
+ raw = await readFile7(tomlPath, "utf8");
12574
13281
  } catch {
12575
13282
  return void 0;
12576
13283
  }
12577
- return readCodexHooksFeatureFlag(raw) === "disabled" ? `${path8.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed` : void 0;
13284
+ return readCodexHooksFeatureFlag(raw) === "disabled" ? `${path9.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed` : void 0;
12578
13285
  };
12579
13286
  var readState = async (configPath) => {
12580
13287
  const read = await readJsonDocument(configPath);
@@ -12586,12 +13293,12 @@ var readState = async (configPath) => {
12586
13293
  case "unparseable":
12587
13294
  return {
12588
13295
  status: "blocked",
12589
- problem: `${path8.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`
13296
+ problem: `${path9.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`
12590
13297
  };
12591
13298
  case "unreadable":
12592
13299
  return {
12593
13300
  status: "failed",
12594
- problem: `${path8.basename(configPath)} could not be read (${read.detail})`
13301
+ problem: `${path9.basename(configPath)} could not be read (${read.detail})`
12595
13302
  };
12596
13303
  }
12597
13304
  };
@@ -12703,7 +13410,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
12703
13410
  missingEvents: [],
12704
13411
  notes,
12705
13412
  problems: planned.conflicts.map(
12706
- (conflict) => `${path8.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`
13413
+ (conflict) => `${path9.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`
12707
13414
  )
12708
13415
  };
12709
13416
  }
@@ -12714,7 +13421,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
12714
13421
  changed: false,
12715
13422
  registeredEvents: [],
12716
13423
  missingEvents: [],
12717
- notes: [...notes, `${path8.basename(configPath)} does not exist; nothing to remove`],
13424
+ notes: [...notes, `${path9.basename(configPath)} does not exist; nothing to remove`],
12718
13425
  problems: []
12719
13426
  };
12720
13427
  }
@@ -12757,7 +13464,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
12757
13464
  missingEvents: [],
12758
13465
  notes,
12759
13466
  problems: [
12760
- `could not write ${path8.basename(configPath)} (${thrown instanceof Error ? thrown.name : typeof thrown})`
13467
+ `could not write ${path9.basename(configPath)} (${thrown instanceof Error ? thrown.name : typeof thrown})`
12761
13468
  ]
12762
13469
  };
12763
13470
  }
@@ -12784,7 +13491,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
12784
13491
  missingEvents: [],
12785
13492
  notes,
12786
13493
  problems: [
12787
- thrown instanceof Error ? `${path8.basename(configPath)}: ${thrown.message}` : `${path8.basename(configPath)}: the configuration file could not be locked`
13494
+ thrown instanceof Error ? `${path9.basename(configPath)}: ${thrown.message}` : `${path9.basename(configPath)}: the configuration file could not be locked`
12788
13495
  ]
12789
13496
  };
12790
13497
  }
@@ -12880,9 +13587,9 @@ var runProvidersCommand = (command, io) => {
12880
13587
 
12881
13588
  // src/cli/registration.ts
12882
13589
  import * as os2 from "os";
12883
- import * as path9 from "path";
12884
- var resolveProjectDir = (command, io) => path9.resolve(command.projectDir ?? io.env.PWD ?? process.cwd());
12885
- var resolveHomeDir = (command, io) => path9.resolve(command.homeDir ?? io.homeDir ?? os2.homedir());
13590
+ import * as path10 from "path";
13591
+ var resolveProjectDir = (command, io) => path10.resolve(command.projectDir ?? io.env.PWD ?? process.cwd());
13592
+ var resolveHomeDir = (command, io) => path10.resolve(command.homeDir ?? io.homeDir ?? os2.homedir());
12886
13593
  var collectRegistrationReport = async (command, io) => runRegistrationLifecycle({
12887
13594
  action: command.name,
12888
13595
  // A bare `diagnose` sweeps the providers this tool can locate by itself.
@@ -12963,10 +13670,10 @@ var runRegistrationCommand = async (command, io) => {
12963
13670
  };
12964
13671
 
12965
13672
  // src/cli/run.ts
12966
- import * as path14 from "path";
13673
+ import * as path16 from "path";
12967
13674
 
12968
13675
  // src/lifecycle/dedup.ts
12969
- import { randomBytes as randomBytes5 } from "crypto";
13676
+ import { randomBytes as randomBytes6 } from "crypto";
12970
13677
 
12971
13678
  // src/lifecycle/keys.ts
12972
13679
  var LIFECYCLE_PREFIX = "lifecycle";
@@ -13020,7 +13727,7 @@ var ownerOf = (record) => {
13020
13727
  const owner = record.value.attributes.owner;
13021
13728
  return typeof owner === "string" && owner.length > 0 ? owner : void 0;
13022
13729
  };
13023
- var newOwnerToken = () => randomBytes5(12).toString("hex");
13730
+ var newOwnerToken = () => randomBytes6(12).toString("hex");
13024
13731
  var claimedAtOf = (record) => {
13025
13732
  if (record?.value.kind !== "attributes") {
13026
13733
  return void 0;
@@ -13163,12 +13870,12 @@ var createCallbackDeduplicator = (deps) => {
13163
13870
  };
13164
13871
 
13165
13872
  // src/lifecycle/metric-series.ts
13166
- import { createHash as createHash4 } from "crypto";
13873
+ import { createHash as createHash5 } from "crypto";
13167
13874
  var TURN_START_SEGMENT = "turn-start";
13168
13875
  var SHARED_SCOPE = "all";
13169
13876
  var SHARED_LOCK = "otelhook.metrics.shared";
13170
13877
  var sessionScope = (sessionId) => `s=${sessionId}`;
13171
- var digest = (identity) => createHash4("sha256").update(identity).digest("base64url").slice(0, 43);
13878
+ var digest = (identity) => createHash5("sha256").update(identity).digest("base64url").slice(0, 43);
13172
13879
  var toStoredHistogram = (histogram) => ({
13173
13880
  count: histogram.count,
13174
13881
  sum: histogram.sum,
@@ -13855,9 +14562,9 @@ var createUsageAccumulator = (deps) => {
13855
14562
  };
13856
14563
 
13857
14564
  // src/providers/claude/transcript.ts
13858
- import { createHash as createHash5 } from "crypto";
13859
- import { open as open4, stat as stat6 } from "fs/promises";
13860
- import path10 from "path";
14565
+ import { createHash as createHash6 } from "crypto";
14566
+ import { open as open5, stat as stat6 } from "fs/promises";
14567
+ import path11 from "path";
13861
14568
  var DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES = 1048576;
13862
14569
  var DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS = 250;
13863
14570
  var DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES = 8388608;
@@ -13878,7 +14585,7 @@ var clamp = (value, fallback, min, max) => {
13878
14585
  return Math.min(max, Math.max(min, Math.floor(value)));
13879
14586
  };
13880
14587
  var asRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
13881
- var isTranscriptPath = (transcriptPath) => typeof transcriptPath === "string" && transcriptPath.length > 0 && !transcriptPath.includes("\0") && path10.isAbsolute(transcriptPath) && path10.extname(transcriptPath) === ".jsonl";
14588
+ var isTranscriptPath = (transcriptPath) => typeof transcriptPath === "string" && transcriptPath.length > 0 && !transcriptPath.includes("\0") && path11.isAbsolute(transcriptPath) && path11.extname(transcriptPath) === ".jsonl";
13882
14589
  var isRecordOfAgent = (record, agentId) => record.isSidechain === true && (typeof record.agentId !== "string" || record.agentId === agentId);
13883
14590
  var assistantRecordOf = (line, agentId) => {
13884
14591
  if (!line.includes('"assistant"')) {
@@ -13958,7 +14665,7 @@ var withRegularFile = async (transcriptPath, body) => {
13958
14665
  }
13959
14666
  let handle;
13960
14667
  try {
13961
- handle = await open4(transcriptPath, "r");
14668
+ handle = await open5(transcriptPath, "r");
13962
14669
  } catch {
13963
14670
  return { status: "unavailable", reason: "unreadable" };
13964
14671
  }
@@ -14078,7 +14785,7 @@ var hasUsage = (record) => record.usage !== void 0 || record.token_usage !== voi
14078
14785
  var eventNameOf = (record) => record.hook_event_name ?? record.hookEventName;
14079
14786
  var transcriptPathOf = (record) => record.transcript_path ?? record.transcriptPath;
14080
14787
  var CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
14081
- var sourceDigest = (transcriptPath) => createHash5("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
14788
+ var sourceDigest = (transcriptPath) => createHash6("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
14082
14789
  var SUBAGENT_STOP = "SubagentStop";
14083
14790
  var agentIdOf = (record) => {
14084
14791
  const agentId = record.agent_id ?? record.agentId;
@@ -14091,7 +14798,7 @@ var subagentCursorScope = (payload) => {
14091
14798
  return void 0;
14092
14799
  }
14093
14800
  const agentId = agentIdOf(record);
14094
- return agentId === void 0 ? void 0 : `agent-${createHash5("sha256").update(agentId, "utf8").digest("hex").slice(0, 32)}`;
14801
+ return agentId === void 0 ? void 0 : `agent-${createHash6("sha256").update(agentId, "utf8").digest("hex").slice(0, 32)}`;
14095
14802
  };
14096
14803
  var createClaudeTranscriptUsageEnricher = (options = {}) => {
14097
14804
  const fileSize = async (transcriptPath) => {
@@ -14193,6 +14900,283 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
14193
14900
  });
14194
14901
  };
14195
14902
 
14903
+ // src/providers/codex/rollout-usage.ts
14904
+ import { createHash as createHash7 } from "crypto";
14905
+ import { open as open6, readdir as readdir4, stat as stat7 } from "fs/promises";
14906
+ import path12 from "path";
14907
+ var CODEX_ROLLOUT_USAGE_ENRICHER_ID = "codex-rollout-usage";
14908
+ var DEFAULT_CODEX_ROLLOUT_RANGE_BYTES = 8388608;
14909
+ var DEFAULT_CODEX_ROLLOUT_TAIL_BYTES = 1048576;
14910
+ var DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS = 500;
14911
+ var DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS = 150;
14912
+ var ROLLOUT_LOOKUP_DAYS = 7;
14913
+ var MIN_BYTES = 65536;
14914
+ var MAX_RANGE_BYTES2 = 67108864;
14915
+ var MAX_TAIL_BYTES2 = 16777216;
14916
+ var MIN_TIMEOUT_MILLIS2 = 10;
14917
+ var MAX_TIMEOUT_MILLIS2 = 5e3;
14918
+ var MAX_SETTLE_MILLIS = 1e3;
14919
+ var MAX_MODEL_ID_LENGTH2 = 256;
14920
+ var MAX_LOOKUP_DIR_ENTRIES = 2e4;
14921
+ var SESSION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{7,127}$/;
14922
+ var clamp2 = (value, fallback, min, max) => {
14923
+ if (value === void 0 || !Number.isFinite(value)) {
14924
+ return fallback;
14925
+ }
14926
+ return Math.min(max, Math.max(min, Math.floor(value)));
14927
+ };
14928
+ var asRecord8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
14929
+ var isRolloutPath = (value) => typeof value === "string" && value.length > 0 && value.length <= 4096 && !value.includes("\0") && path12.isAbsolute(value) && path12.extname(value) === ".jsonl";
14930
+ var sourceDigest2 = (rolloutPath) => createHash7("sha256").update(rolloutPath, "utf8").digest("hex").slice(0, 32);
14931
+ var parseUsage = (value) => {
14932
+ const parsed = codexUsageSchema.safeParse(value);
14933
+ if (!parsed.success) {
14934
+ return void 0;
14935
+ }
14936
+ const usage = parsed.data;
14937
+ return usage.input_tokens === void 0 || usage.output_tokens === void 0 ? void 0 : usage;
14938
+ };
14939
+ var modelOf = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_MODEL_ID_LENGTH2 ? value : void 0;
14940
+ var factsOf2 = (line) => {
14941
+ const usageLine = line.includes('"token_count"') || line.includes('"token_usage_record"');
14942
+ const contextLine = line.includes('"turn_context"');
14943
+ if (!usageLine && !contextLine) {
14944
+ return void 0;
14945
+ }
14946
+ let parsed;
14947
+ try {
14948
+ parsed = JSON.parse(line);
14949
+ } catch {
14950
+ return void 0;
14951
+ }
14952
+ const record = asRecord8(parsed);
14953
+ const payload = asRecord8(record?.payload);
14954
+ if (record === void 0 || payload === void 0) {
14955
+ return void 0;
14956
+ }
14957
+ if (record.type === "turn_context") {
14958
+ const model = modelOf(payload.model);
14959
+ return model === void 0 ? void 0 : { model };
14960
+ }
14961
+ if (record.type === "event_msg" && payload.type === "token_count") {
14962
+ const info = asRecord8(payload.info) ?? payload;
14963
+ const usage = parseUsage(info.total_token_usage);
14964
+ return usage === void 0 ? void 0 : { usage };
14965
+ }
14966
+ if (record.type === "token_usage_record") {
14967
+ const usage = parseUsage(payload.thread_token_usage);
14968
+ return usage === void 0 ? void 0 : { usage };
14969
+ }
14970
+ return void 0;
14971
+ };
14972
+ var lastSnapshotIn = (lines) => {
14973
+ let usage;
14974
+ let model;
14975
+ for (const line of lines) {
14976
+ const facts = factsOf2(line.trim());
14977
+ if (facts === void 0) {
14978
+ continue;
14979
+ }
14980
+ if (facts.model !== void 0) {
14981
+ model = facts.model;
14982
+ }
14983
+ if (facts.usage !== void 0) {
14984
+ usage = facts.usage;
14985
+ }
14986
+ }
14987
+ return usage === void 0 ? void 0 : { usage, ...model === void 0 ? {} : { model } };
14988
+ };
14989
+ var readBytes2 = async (handle, start, length) => {
14990
+ const buffer = Buffer.alloc(length);
14991
+ let filled = 0;
14992
+ while (filled < length) {
14993
+ const { bytesRead } = await handle.read(buffer, filled, length - filled, start + filled);
14994
+ if (bytesRead === 0) {
14995
+ break;
14996
+ }
14997
+ filled += bytesRead;
14998
+ }
14999
+ return buffer.subarray(0, filled);
15000
+ };
15001
+ var readRollout = async (rolloutPath, fromOffset, maxRangeBytes, tailBytes) => {
15002
+ let handle;
15003
+ try {
15004
+ const info = await stat7(rolloutPath);
15005
+ if (!info.isFile()) {
15006
+ return { status: "unavailable", reason: "not-a-file" };
15007
+ }
15008
+ handle = await open6(rolloutPath, "r");
15009
+ } catch {
15010
+ return { status: "unavailable", reason: "unreadable" };
15011
+ }
15012
+ try {
15013
+ const { size } = await handle.stat();
15014
+ let start;
15015
+ if (fromOffset === void 0) {
15016
+ start = Math.max(0, size - tailBytes);
15017
+ } else if (size < fromOffset) {
15018
+ return { status: "unavailable", reason: "truncated" };
15019
+ } else if (size - fromOffset > maxRangeBytes) {
15020
+ return { status: "unavailable", reason: "over-cap" };
15021
+ } else {
15022
+ start = fromOffset;
15023
+ }
15024
+ const bytes = await readBytes2(handle, start, size - start);
15025
+ const lastNewline = bytes.lastIndexOf(10);
15026
+ const endOffset = lastNewline < 0 ? start : start + lastNewline + 1;
15027
+ const lines = bytes.subarray(0, endOffset - start).toString("utf8").split("\n");
15028
+ if (fromOffset === void 0 && start > 0) {
15029
+ lines.shift();
15030
+ }
15031
+ const snapshot = lastSnapshotIn(lines);
15032
+ return { status: "found", ...snapshot === void 0 ? {} : { snapshot }, endOffset };
15033
+ } catch {
15034
+ return { status: "unavailable", reason: "unreadable" };
15035
+ } finally {
15036
+ await handle.close().catch(() => void 0);
15037
+ }
15038
+ };
15039
+ var pad = (value) => String(value).padStart(2, "0");
15040
+ var findRolloutBySessionId = async (sessionsRoot, sessionId, now) => {
15041
+ if (!SESSION_ID_PATTERN.test(sessionId) || !path12.isAbsolute(sessionsRoot)) {
15042
+ return void 0;
15043
+ }
15044
+ const suffix = `-${sessionId}.jsonl`;
15045
+ for (let back = 0; back < ROLLOUT_LOOKUP_DAYS; back += 1) {
15046
+ const day = new Date(now.getFullYear(), now.getMonth(), now.getDate() - back);
15047
+ const dir = path12.join(sessionsRoot, String(day.getFullYear()), pad(day.getMonth() + 1), pad(day.getDate()));
15048
+ let names;
15049
+ try {
15050
+ names = await readdir4(dir);
15051
+ } catch {
15052
+ continue;
15053
+ }
15054
+ if (names.length > MAX_LOOKUP_DIR_ENTRIES) {
15055
+ continue;
15056
+ }
15057
+ const match = names.find((name) => name.startsWith("rollout-") && name.endsWith(suffix));
15058
+ if (match !== void 0) {
15059
+ return path12.join(dir, match);
15060
+ }
15061
+ }
15062
+ return void 0;
15063
+ };
15064
+ var TIMED_OUT2 = /* @__PURE__ */ Symbol("timed-out");
15065
+ var withTimeout2 = async (work, timeoutMillis) => {
15066
+ let timer;
15067
+ const timeout = new Promise((resolve8) => {
15068
+ timer = setTimeout(() => {
15069
+ resolve8(TIMED_OUT2);
15070
+ }, timeoutMillis);
15071
+ timer.unref();
15072
+ });
15073
+ try {
15074
+ return await Promise.race([work, timeout]);
15075
+ } finally {
15076
+ clearTimeout(timer);
15077
+ }
15078
+ };
15079
+ var sleep2 = (millis) => new Promise((resolve8) => {
15080
+ setTimeout(resolve8, millis).unref();
15081
+ });
15082
+ var hasUsage2 = (record) => record.usage !== void 0;
15083
+ var createCodexRolloutUsageEnricher = (options = {}) => {
15084
+ const maxRangeBytes = clamp2(options.maxRangeBytes, DEFAULT_CODEX_ROLLOUT_RANGE_BYTES, MIN_BYTES, MAX_RANGE_BYTES2);
15085
+ const maxTailBytes = clamp2(options.maxTailBytes, DEFAULT_CODEX_ROLLOUT_TAIL_BYTES, MIN_BYTES, MAX_TAIL_BYTES2);
15086
+ const timeoutMillis = clamp2(
15087
+ options.timeoutMillis,
15088
+ DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS,
15089
+ MIN_TIMEOUT_MILLIS2,
15090
+ MAX_TIMEOUT_MILLIS2
15091
+ );
15092
+ const settleMillis = clamp2(options.settleMillis, DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS, 0, MAX_SETTLE_MILLIS);
15093
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
15094
+ const fileSize = async (rolloutPath) => {
15095
+ try {
15096
+ const info = await stat7(rolloutPath);
15097
+ return info.isFile() ? info.size : void 0;
15098
+ } catch (thrown) {
15099
+ return thrown?.code === "ENOENT" ? "absent" : void 0;
15100
+ }
15101
+ };
15102
+ const resolveRollout = async (record) => {
15103
+ const named = record.transcript_path;
15104
+ if (named !== void 0 && named !== null) {
15105
+ return isRolloutPath(named) ? named : void 0;
15106
+ }
15107
+ const sessionId = record.session_id;
15108
+ if (options.sessionsRoot === void 0 || typeof sessionId !== "string") {
15109
+ return void 0;
15110
+ }
15111
+ return findRolloutBySessionId(options.sessionsRoot, sessionId, now());
15112
+ };
15113
+ const enrichWithin = async (input) => {
15114
+ const unchanged = { payload: input.payload };
15115
+ const record = asRecord8(input.payload);
15116
+ const eventName = record?.hook_event_name;
15117
+ if (record === void 0 || eventName !== "SessionStart" && eventName !== "Stop") {
15118
+ return unchanged;
15119
+ }
15120
+ const rolloutPath = await resolveRollout(record);
15121
+ if (rolloutPath === void 0) {
15122
+ return { ...unchanged, notes: ["no rollout named or found for this session"] };
15123
+ }
15124
+ const source = sourceDigest2(rolloutPath);
15125
+ const cursor = input.cursor?.source === source ? input.cursor : void 0;
15126
+ if (eventName === "SessionStart") {
15127
+ if (cursor !== void 0) {
15128
+ return unchanged;
15129
+ }
15130
+ const size = await fileSize(rolloutPath);
15131
+ if (size === void 0) {
15132
+ return { ...unchanged, notes: ["rollout is not a readable regular file; no cursor recorded"] };
15133
+ }
15134
+ return { payload: input.payload, cursor: { source, offset: size === "absent" ? 0 : size } };
15135
+ }
15136
+ if (hasUsage2(record)) {
15137
+ const size = await fileSize(rolloutPath);
15138
+ return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
15139
+ }
15140
+ const attach = (snapshot) => ({
15141
+ ...record,
15142
+ ...record.model === void 0 && snapshot.model !== void 0 ? { model: snapshot.model } : {},
15143
+ usage: snapshot.usage
15144
+ });
15145
+ let read = await readRollout(rolloutPath, cursor?.offset, maxRangeBytes, maxTailBytes);
15146
+ if (read.status === "found" && read.snapshot === void 0 && cursor !== void 0 && settleMillis > 0) {
15147
+ await sleep2(settleMillis);
15148
+ read = await readRollout(rolloutPath, cursor.offset, maxRangeBytes, maxTailBytes);
15149
+ }
15150
+ if (read.status === "unavailable") {
15151
+ if (read.reason !== "truncated" && read.reason !== "over-cap") {
15152
+ return { ...unchanged, notes: [`rollout not read (${read.reason}); cursor kept`] };
15153
+ }
15154
+ read = await readRollout(rolloutPath, void 0, maxRangeBytes, maxTailBytes);
15155
+ if (read.status === "unavailable") {
15156
+ return { ...unchanged, notes: [`rollout tail not read (${read.reason})`] };
15157
+ }
15158
+ }
15159
+ const next = { source, offset: read.endOffset };
15160
+ if (read.snapshot === void 0) {
15161
+ return { payload: input.payload, cursor: next, notes: ["no token_count since the last stop"] };
15162
+ }
15163
+ return {
15164
+ payload: attach(read.snapshot),
15165
+ cursor: next,
15166
+ notes: [cursor === void 0 ? "no cursor; attached the last running total in the tail" : "attached the running total"]
15167
+ };
15168
+ };
15169
+ const enrich = async (input) => {
15170
+ try {
15171
+ const result = await withTimeout2(enrichWithin(input), timeoutMillis);
15172
+ return result === TIMED_OUT2 ? { payload: input.payload, notes: ["rollout read timed out; cursor kept"] } : result;
15173
+ } catch {
15174
+ return { payload: input.payload, notes: ["rollout read failed; cursor kept"] };
15175
+ }
15176
+ };
15177
+ return Object.freeze({ id: CODEX_ROLLOUT_USAGE_ENRICHER_ID, providerId: CODEX_PROVIDER_ID, enrich });
15178
+ };
15179
+
14196
15180
  // src/runtime/hook.ts
14197
15181
  import { z as z24 } from "zod";
14198
15182
 
@@ -14226,9 +15210,9 @@ var resolveDeliveryIdentity = (input) => {
14226
15210
  };
14227
15211
 
14228
15212
  // src/runtime/ids.ts
14229
- import { createHash as createHash6, randomUUID } from "crypto";
15213
+ import { createHash as createHash8, randomUUID } from "crypto";
14230
15214
  var digest2 = (namespace, parts) => {
14231
- const hash = createHash6("sha256");
15215
+ const hash = createHash8("sha256");
14232
15216
  hash.update(namespace);
14233
15217
  for (const part of parts) {
14234
15218
  hash.update("\0");
@@ -14267,16 +15251,16 @@ var createDeterministicIdGenerator = (options = {}) => {
14267
15251
  };
14268
15252
 
14269
15253
  // src/runtime/target-resolution.ts
14270
- import * as path11 from "path";
15254
+ import * as path13 from "path";
14271
15255
  var DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS = 50;
14272
15256
  var absolutePathsOf = (hint) => {
14273
- const base = hint.baseDirectory !== void 0 && path11.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
15257
+ const base = hint.baseDirectory !== void 0 && path13.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
14274
15258
  const resolved = [];
14275
15259
  for (const candidate of hint.paths) {
14276
- if (path11.isAbsolute(candidate)) {
14277
- resolved.push(path11.resolve(candidate));
15260
+ if (path13.isAbsolute(candidate)) {
15261
+ resolved.push(path13.resolve(candidate));
14278
15262
  } else if (base !== void 0) {
14279
- resolved.push(path11.resolve(base, candidate));
15263
+ resolved.push(path13.resolve(base, candidate));
14280
15264
  } else {
14281
15265
  return void 0;
14282
15266
  }
@@ -14355,8 +15339,8 @@ var resolveEventTargets = async (input) => {
14355
15339
  };
14356
15340
 
14357
15341
  // src/runtime/session-context.ts
14358
- import { open as open5 } from "fs/promises";
14359
- import * as path12 from "path";
15342
+ import { open as open7 } from "fs/promises";
15343
+ import * as path14 from "path";
14360
15344
  import { z as z23 } from "zod";
14361
15345
  var SESSION_CONTEXT_FILE_VERSION = 1;
14362
15346
  var DEFAULT_SESSION_CONTEXT_MAX_BYTES = 256 * 1024;
@@ -14374,10 +15358,10 @@ var SESSION_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
14374
15358
  var isSessionContextFileName = (sessionId) => SESSION_FILE_NAME_PATTERN.test(sessionId) && !sessionId.includes("..");
14375
15359
  var sessionContextFilePath = (dir, providerId, sessionId) => {
14376
15360
  const tool = sessionContextAgentTool(providerId);
14377
- if (tool === void 0 || !isSessionContextFileName(sessionId) || !path12.isAbsolute(dir)) {
15361
+ if (tool === void 0 || !isSessionContextFileName(sessionId) || !path14.isAbsolute(dir)) {
14378
15362
  return void 0;
14379
15363
  }
14380
- return path12.join(dir, tool, `${sessionId}.json`);
15364
+ return path14.join(dir, tool, `${sessionId}.json`);
14381
15365
  };
14382
15366
  var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([
14383
15367
  "session.id",
@@ -14473,7 +15457,7 @@ var stampSessionContext = (events, segments) => events.map((event3) => {
14473
15457
  var readBounded = async (file, maxBytes) => {
14474
15458
  let handle;
14475
15459
  try {
14476
- handle = await open5(file, "r");
15460
+ handle = await open7(file, "r");
14477
15461
  } catch {
14478
15462
  return void 0;
14479
15463
  }
@@ -15426,8 +16410,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
15426
16410
  };
15427
16411
 
15428
16412
  // src/runtime/git-worktree.ts
15429
- import { lstat, open as open6, stat as stat7 } from "fs/promises";
15430
- import * as path13 from "path";
16413
+ import { lstat, open as open8, stat as stat8 } from "fs/promises";
16414
+ import * as path15 from "path";
15431
16415
  var MAX_WORKTREE_WALK_DEPTH = 128;
15432
16416
  var MAX_GIT_FILE_BYTES = 4096;
15433
16417
  var MAX_CACHE_ENTRIES = 1024;
@@ -15438,7 +16422,7 @@ var INVALID = Object.freeze({ kind: "invalid" });
15438
16422
  var readBounded2 = async (filePath) => {
15439
16423
  let handle;
15440
16424
  try {
15441
- handle = await open6(filePath, "r");
16425
+ handle = await open8(filePath, "r");
15442
16426
  const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
15443
16427
  const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
15444
16428
  return buffer.subarray(0, bytesRead).toString("utf8");
@@ -15459,7 +16443,7 @@ var parseHeadBranch = (head) => {
15459
16443
  return branch;
15460
16444
  };
15461
16445
  var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
15462
- var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path13.resolve(base, target);
16446
+ var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path15.resolve(base, target);
15463
16447
  var parseGitDirFile = (content, worktreeRoot) => {
15464
16448
  const line = firstLine(content);
15465
16449
  return resolveGitPath(
@@ -15479,26 +16463,26 @@ var isMissing = async (filePath) => {
15479
16463
  };
15480
16464
  var isDirectory = async (directory) => {
15481
16465
  try {
15482
- return (await stat7(directory)).isDirectory();
16466
+ return (await stat8(directory)).isDirectory();
15483
16467
  } catch {
15484
16468
  return false;
15485
16469
  }
15486
16470
  };
15487
16471
  var repositoryOf = async (worktreeRoot, gitDir) => {
15488
- const commonDirFile = path13.join(gitDir, "commondir");
16472
+ const commonDirFile = path15.join(gitDir, "commondir");
15489
16473
  const content = await readBounded2(commonDirFile);
15490
16474
  if (content === void 0) {
15491
16475
  return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
15492
16476
  }
15493
16477
  const commonDir = parseCommonDirFile(content, gitDir);
15494
- const mainRoot = commonDir !== void 0 && path13.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path13.dirname(commonDir) : void 0;
16478
+ const mainRoot = commonDir !== void 0 && path15.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path15.dirname(commonDir) : void 0;
15495
16479
  return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
15496
16480
  };
15497
16481
  var probeDirectory = async (directory) => {
15498
- const dotGit = path13.join(directory, ".git");
16482
+ const dotGit = path15.join(directory, ".git");
15499
16483
  let info;
15500
16484
  try {
15501
- info = await stat7(dotGit);
16485
+ info = await stat8(dotGit);
15502
16486
  } catch {
15503
16487
  return ABSENT;
15504
16488
  }
@@ -15512,7 +16496,7 @@ var probeDirectory = async (directory) => {
15512
16496
  if (gitDir === void 0) {
15513
16497
  return INVALID;
15514
16498
  }
15515
- const head = await readBounded2(path13.join(gitDir, "HEAD"));
16499
+ const head = await readBounded2(path15.join(gitDir, "HEAD"));
15516
16500
  if (head === void 0) {
15517
16501
  return INVALID;
15518
16502
  }
@@ -15542,10 +16526,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
15542
16526
  };
15543
16527
  const locate = async (absolutePath) => {
15544
16528
  try {
15545
- if (!path13.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
16529
+ if (!path15.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
15546
16530
  return void 0;
15547
16531
  }
15548
- let directory = path13.resolve(absolutePath);
16532
+ let directory = path15.resolve(absolutePath);
15549
16533
  for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
15550
16534
  const probe = await cachedProbe(directory);
15551
16535
  if (probe.kind === "worktree") {
@@ -15554,7 +16538,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
15554
16538
  if (probe.kind === "invalid") {
15555
16539
  return void 0;
15556
16540
  }
15557
- const parent = path13.dirname(directory);
16541
+ const parent = path15.dirname(directory);
15558
16542
  if (parent === directory) {
15559
16543
  return void 0;
15560
16544
  }
@@ -15653,7 +16637,8 @@ var createHookRuntime = (options) => {
15653
16637
  // has always been governed by.
15654
16638
  allowRawContent: privacy.policy.allowRawContent
15655
16639
  },
15656
- correlate
16640
+ correlate,
16641
+ restrictContent: (fact, mode) => privacy.restrictContent(fact, mode)
15657
16642
  });
15658
16643
  const primary = exportDestinations.destinations[0];
15659
16644
  const traceSink = primary?.traces ?? createOtlpTraceSink({
@@ -15670,7 +16655,7 @@ var createHookRuntime = (options) => {
15670
16655
  });
15671
16656
  const spool = primary?.spool;
15672
16657
  const logSpool = primary?.logSpool;
15673
- const sink = createDestinationFanout(exportDestinations.destinations);
16658
+ const sink = createDestinationFanout(exportDestinations.destinations, { correlate });
15674
16659
  const hookDeps = {
15675
16660
  stateStore,
15676
16661
  config: options.config,
@@ -15680,7 +16665,14 @@ var createHookRuntime = (options) => {
15680
16665
  privacy,
15681
16666
  logger,
15682
16667
  installationId: options.installationId,
15683
- payloadEnrichers: options.payloadEnrichers ?? (readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : []),
16668
+ payloadEnrichers: options.payloadEnrichers ?? [
16669
+ ...readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : [],
16670
+ ...readsCodexRolloutUsage(options.config) ? [
16671
+ createCodexRolloutUsageEnricher(
16672
+ options.codexSessionsRoot === void 0 ? {} : { sessionsRoot: options.codexSessionsRoot }
16673
+ )
16674
+ ] : []
16675
+ ],
15684
16676
  ...(() => {
15685
16677
  if (options.sessionContextReader === null) {
15686
16678
  return {};
@@ -15704,6 +16696,8 @@ var createHookRuntime = (options) => {
15704
16696
  (destination) => destination.metrics.enabled
15705
16697
  );
15706
16698
  const metricResource = resourceFromExporterPolicy(options.config.exporter);
16699
+ const scopedMetricDestinations = metricDestinations.filter((destination) => destination.scopes !== void 0);
16700
+ const unscopedMetricDestinations = metricDestinations.filter((destination) => destination.scopes === void 0);
15707
16701
  const deliveryRetentionMillis = options.deliveryRetentionMillis ?? lifecycleMaxAge;
15708
16702
  if (deliveryRetentionMillis < staleClaimMillis) {
15709
16703
  logger.warn("delivery retention is shorter than the stale-claim window", {
@@ -15769,28 +16763,63 @@ var createHookRuntime = (options) => {
15769
16763
  turnStarts.set(event3.sessionId, await metricSeries.readTurnStart(event3.sessionId));
15770
16764
  }
15771
16765
  }
15772
- const observations = deriveMetricObservations({
15773
- events: ingest.events,
15774
- usage: ingest.usageObservations,
15775
- resource: metricResource,
15776
- includeSessionId: metricsPolicy.includeSessionId,
15777
- ...generationStarts === void 0 ? {} : { generationStarts },
15778
- turnStart: (sessionId) => turnStarts.get(sessionId)
15779
- });
15780
- if (observations.length === 0) {
16766
+ const scopedRepositoryFallback = scopedMetricDestinations.length === 0 ? void 0 : resourceRepositoryKey(metricResource.attributes);
16767
+ const resourceRepository = metricResource.attributes[ATTR_VCS_REPOSITORY_URL_FULL];
16768
+ const metricEvents = scopedRepositoryFallback === void 0 || typeof resourceRepository !== "string" ? ingest.events : ingest.events.map(
16769
+ (event3) => event3.contextAttributes?.[ATTR_VCS_REPOSITORY_URL_FULL] === void 0 ? {
16770
+ ...event3,
16771
+ contextAttributes: {
16772
+ ...event3.contextAttributes,
16773
+ [ATTR_VCS_REPOSITORY_URL_FULL]: resourceRepository
16774
+ }
16775
+ } : event3
16776
+ );
16777
+ const pointsByVariant = /* @__PURE__ */ new Map();
16778
+ const variants = new Set(
16779
+ unscopedMetricDestinations.length > 0 ? [metricsPolicy.includeSessionId] : []
16780
+ );
16781
+ for (const destination of scopedMetricDestinations) {
16782
+ for (const variant of sessionIdVariantsFor(destination.scopes ?? [], metricsPolicy.includeSessionId)) {
16783
+ variants.add(variant);
16784
+ }
16785
+ }
16786
+ for (const includeSessionId of variants) {
16787
+ const observations = deriveMetricObservations({
16788
+ events: metricEvents,
16789
+ usage: ingest.usageObservations,
16790
+ resource: metricResource,
16791
+ includeSessionId,
16792
+ ...generationStarts === void 0 ? {} : { generationStarts },
16793
+ turnStart: (sessionId) => turnStarts.get(sessionId)
16794
+ });
16795
+ if (observations.length === 0) {
16796
+ continue;
16797
+ }
16798
+ pointsByVariant.set(
16799
+ includeSessionId,
16800
+ metricsPolicy.temporality === "delta" ? aggregateDeltaPoints(observations, clock.now()) : await metricSeries.recordCumulative(observations, {
16801
+ perSession: includeSessionId,
16802
+ ...deliveryToken === void 0 ? {} : { deliveryToken }
16803
+ })
16804
+ );
16805
+ }
16806
+ if (pointsByVariant.size === 0) {
15781
16807
  return void 0;
15782
16808
  }
15783
- const points = metricsPolicy.temporality === "delta" ? aggregateDeltaPoints(observations, clock.now()) : await metricSeries.recordCumulative(observations, {
15784
- perSession: metricsPolicy.includeSessionId,
15785
- ...deliveryToken === void 0 ? {} : { deliveryToken }
15786
- });
15787
16809
  const context = agreedContextAttributes(ingest.events);
15788
16810
  const results = await Promise.all(
15789
16811
  metricDestinations.map(async (destination) => {
15790
- const result = await destination.metrics.exportPoints(points, context).catch(
16812
+ const points2 = destination.scopes === void 0 ? pointsByVariant.get(metricsPolicy.includeSessionId) ?? [] : routePointsToScopes(destination.scopes, (variant) => pointsByVariant.get(variant), {
16813
+ fallbackKey: scopedRepositoryFallback,
16814
+ includeSessionId: metricsPolicy.includeSessionId
16815
+ });
16816
+ if (points2.length === 0) {
16817
+ return { name: destination.name, accepted: 0, rejected: 0 };
16818
+ }
16819
+ const result = await destination.metrics.exportPoints(points2, context).catch(
15791
16820
  (thrown) => ({
15792
16821
  accepted: 0,
15793
- rejected: points.length,
16822
+ rejected: points2.length,
15794
16823
  errors: [
15795
16824
  errorInfoFromThrown(thrown, { code: "telemetry-export-failure", phase: "export" })
15796
16825
  ]
@@ -15800,7 +16829,8 @@ var createHookRuntime = (options) => {
15800
16829
  return { name: destination.name, accepted: result.accepted, rejected: result.rejected };
15801
16830
  })
15802
16831
  );
15803
- return { points: points.length, destinations: results };
16832
+ const points = Math.max(0, ...[...pointsByVariant.values()].map((variant) => variant.length));
16833
+ return { points, destinations: results };
15804
16834
  } catch (thrown) {
15805
16835
  diagnostics.push(stateDiagnostic(thrown));
15806
16836
  logger.warn("hook-derived metrics could not be recorded for this callback", {});
@@ -16222,6 +17252,14 @@ var readBoundedJson = async (stream, maxBytes) => {
16222
17252
  };
16223
17253
 
16224
17254
  // src/cli/run.ts
17255
+ var codexSessionsRoot = (env) => {
17256
+ const codexHome = env.CODEX_HOME;
17257
+ if (codexHome !== void 0 && codexHome.length > 0) {
17258
+ return path16.isAbsolute(codexHome) ? path16.join(codexHome, "sessions") : void 0;
17259
+ }
17260
+ const home = env.HOME;
17261
+ return home !== void 0 && path16.isAbsolute(home) ? path16.join(home, ".codex", "sessions") : void 0;
17262
+ };
16225
17263
  var MAX_LOGGED_DIAGNOSTICS = 16;
16226
17264
  var logDiagnostics = (logger, diagnostics) => {
16227
17265
  for (const info of diagnostics.slice(0, MAX_LOGGED_DIAGNOSTICS)) {
@@ -16356,13 +17394,13 @@ var runHookCommand = async (command, io) => {
16356
17394
  }
16357
17395
  const identityClaims = [];
16358
17396
  if (command.identity.identityFile !== void 0) {
16359
- const read = await readIdentityFile(path14.resolve(command.identity.identityFile));
17397
+ const read = await readIdentityFile(path16.resolve(command.identity.identityFile));
16360
17398
  if ("error" in read) {
16361
17399
  logDiagnostics(logger, [read.error]);
16362
17400
  } else {
16363
17401
  const fromFile = claimFromIdentityFile(
16364
17402
  read.value,
16365
- path14.basename(command.identity.identityFile)
17403
+ path16.basename(command.identity.identityFile)
16366
17404
  );
16367
17405
  logDiagnostics(logger, fromFile.errors);
16368
17406
  identityClaims.push(...fromFile.claims);
@@ -16372,6 +17410,7 @@ var runHookCommand = async (command, io) => {
16372
17410
  logDiagnostics(logger, fromFlags.errors);
16373
17411
  identityClaims.push(...fromFlags.claims);
16374
17412
  const headers = resolveCliExporterHeaders(command.policy, io);
17413
+ const codexSessions = codexSessionsRoot(io.env);
16375
17414
  const runtime = createHookRuntime({
16376
17415
  // Detection policy narrowed to the selected adapter; everything else is the
16377
17416
  // resolved configuration exactly as it stands.
@@ -16391,6 +17430,7 @@ var runHookCommand = async (command, io) => {
16391
17430
  privacy,
16392
17431
  ...command.policy.flushTimeoutMillis === void 0 ? {} : { flushTimeoutMillis: command.policy.flushTimeoutMillis },
16393
17432
  ...command.policy.spoolDisabled === true ? { enableSpool: false } : {},
17433
+ ...codexSessions === void 0 ? {} : { codexSessionsRoot: codexSessions },
16394
17434
  ...command.requireCallbackId === true ? { requireCallbackId: true } : {},
16395
17435
  ...command.noDeriveCallbackId === true ? { deriveDeliveryIdentity: false } : {}
16396
17436
  });