@osfactory/otel-hook 0.7.0 → 0.9.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.
package/dist/index.js CHANGED
@@ -1676,37 +1676,361 @@ var sanitizeResourceAttributes = (attributes) => {
1676
1676
  var describeResourceAttributeNames = (attributes) => Object.keys(attributes).sort();
1677
1677
 
1678
1678
  // src/config/schema.ts
1679
+ import { z as z14 } from "zod";
1680
+
1681
+ // src/config/destinations.ts
1679
1682
  import { z as z13 } from "zod";
1680
- var logsPolicySchema = z13.strictObject({
1681
- enabled: z13.boolean(),
1683
+
1684
+ // src/config/header-value.ts
1685
+ var isUnsafeHeaderValue = (value) => [...value].some((char) => {
1686
+ const code = char.codePointAt(0) ?? 0;
1687
+ return code < 32 && code !== 9 || code === 127 || code > 255;
1688
+ });
1689
+
1690
+ // src/config/otlp-headers.ts
1691
+ var MAX_OTLP_HEADERS = 32;
1692
+ var OTLP_HEADER_VARIABLES = Object.freeze({
1693
+ generic: "OTEL_EXPORTER_OTLP_HEADERS",
1694
+ traces: "OTEL_EXPORTER_OTLP_TRACES_HEADERS",
1695
+ logs: "OTEL_EXPORTER_OTLP_LOGS_HEADERS"
1696
+ });
1697
+ var HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
1698
+ var decode = (raw) => {
1699
+ try {
1700
+ return decodeURIComponent(raw);
1701
+ } catch {
1702
+ return void 0;
1703
+ }
1704
+ };
1705
+ var parseOtlpHeadersValue = (raw) => {
1706
+ const headers = {};
1707
+ const warnings = [];
1708
+ let overflowed = false;
1709
+ for (const [index, rawEntry] of raw.split(",").entries()) {
1710
+ const position = String(index + 1);
1711
+ const entry = rawEntry.trim();
1712
+ if (entry === "") {
1713
+ continue;
1714
+ }
1715
+ const equals = entry.indexOf("=");
1716
+ if (equals <= 0) {
1717
+ warnings.push(`entry ${position} is not a key=value pair; ignored`);
1718
+ continue;
1719
+ }
1720
+ const key = decode(entry.slice(0, equals).trim());
1721
+ const value = decode(entry.slice(equals + 1).trim());
1722
+ if (key === void 0 || value === void 0) {
1723
+ warnings.push(`entry ${position} has malformed percent-encoding; ignored`);
1724
+ continue;
1725
+ }
1726
+ const name = key.trim();
1727
+ const trimmedValue = value.trim();
1728
+ if (!HEADER_NAME_PATTERN.test(name)) {
1729
+ warnings.push(`entry ${position} does not name a valid HTTP header; ignored`);
1730
+ continue;
1731
+ }
1732
+ if (trimmedValue === "") {
1733
+ warnings.push(`entry ${position} has an empty value; ignored`);
1734
+ continue;
1735
+ }
1736
+ if (isUnsafeHeaderValue(trimmedValue)) {
1737
+ warnings.push(`entry ${position} has a character not allowed in an HTTP header value; ignored`);
1738
+ continue;
1739
+ }
1740
+ const existing = findHeaderName(headers, name);
1741
+ if (existing === void 0 && Object.keys(headers).length >= MAX_OTLP_HEADERS) {
1742
+ overflowed = true;
1743
+ continue;
1744
+ }
1745
+ if (existing !== void 0) {
1746
+ delete headers[existing];
1747
+ }
1748
+ headers[name] = trimmedValue;
1749
+ }
1750
+ if (overflowed) {
1751
+ warnings.push(`more than ${String(MAX_OTLP_HEADERS)} headers were supplied; the excess was ignored`);
1752
+ }
1753
+ return { headers, warnings };
1754
+ };
1755
+ var findHeaderName = (headers, name) => {
1756
+ const lower = name.toLowerCase();
1757
+ return Object.keys(headers).find((candidate) => candidate.toLowerCase() === lower);
1758
+ };
1759
+ var mergeOtlpHeaders = (...sources) => {
1760
+ const merged = {};
1761
+ for (const source of sources) {
1762
+ for (const [name, value] of Object.entries(source)) {
1763
+ const existing = findHeaderName(merged, name);
1764
+ if (existing !== void 0) {
1765
+ delete merged[existing];
1766
+ }
1767
+ merged[name] = value;
1768
+ }
1769
+ }
1770
+ return merged;
1771
+ };
1772
+ var resolveOtlpHeaders = (env, explicit = {}) => {
1773
+ const warnings = [];
1774
+ const read = (variable) => {
1775
+ const raw = env[variable];
1776
+ if (raw === void 0 || raw.trim() === "") {
1777
+ return {};
1778
+ }
1779
+ const parsed = parseOtlpHeadersValue(raw);
1780
+ for (const detail of parsed.warnings) {
1781
+ warnings.push({ variable, detail });
1782
+ }
1783
+ return parsed.headers;
1784
+ };
1785
+ const generic = read(OTLP_HEADER_VARIABLES.generic);
1786
+ const traces = read(OTLP_HEADER_VARIABLES.traces);
1787
+ const logs = read(OTLP_HEADER_VARIABLES.logs);
1788
+ return {
1789
+ traces: mergeOtlpHeaders(generic, traces, explicit),
1790
+ logs: mergeOtlpHeaders(generic, logs, explicit),
1791
+ warnings
1792
+ };
1793
+ };
1794
+ var unionOtlpHeaderNames = (...lists) => {
1795
+ const names = [];
1796
+ const seen = /* @__PURE__ */ new Set();
1797
+ for (const name of lists.flat()) {
1798
+ if (!seen.has(name.toLowerCase())) {
1799
+ seen.add(name.toLowerCase());
1800
+ names.push(name);
1801
+ }
1802
+ }
1803
+ return names.sort().slice(0, MAX_OTLP_HEADERS);
1804
+ };
1805
+ var describeOtlpHeaderNames = (...sources) => unionOtlpHeaderNames(...sources.map((source) => Object.keys(source)));
1806
+
1807
+ // src/config/destinations.ts
1808
+ var DEFAULT_DESTINATION_NAME = "default";
1809
+ var DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;
1810
+ var MAX_EXPORT_DESTINATIONS = 16;
1811
+ var MAX_DESTINATION_HEADERS = MAX_OTLP_HEADERS;
1812
+ var HEADER_ENV_REFERENCE_PREFIX = "env:";
1813
+ var HEADER_NAME_PATTERN2 = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
1814
+ var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
1815
+ var MAX_HEADER_VALUE_LENGTH = 8192;
1816
+ var exportSignalSchema = z13.enum(["traces", "logs"]);
1817
+ var headerValueSchema = z13.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
1818
+ (value) => !isUnsafeHeaderValue(value),
1819
+ "header values may not contain line breaks, control characters, or characters beyond Latin-1"
1820
+ ).refine(
1821
+ (value) => !value.startsWith(HEADER_ENV_REFERENCE_PREFIX) || ENV_VARIABLE_NAME_PATTERN.test(value.slice(HEADER_ENV_REFERENCE_PREFIX.length)),
1822
+ "an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN"
1823
+ );
1824
+ var endpointSchema = z13.string().url().max(2048);
1825
+ var exportDestinationSchema = z13.strictObject({
1826
+ /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */
1827
+ name: z13.string().regex(DESTINATION_NAME_PATTERN, "destination names are lowercase letters, digits, _ and -"),
1828
+ /** Default true. A disabled destination is neither sent to nor drained. */
1829
+ enabled: z13.boolean().optional(),
1830
+ /**
1831
+ * Traces URL, with the same meaning as `exporter.endpoint`: the logs URL is
1832
+ * derived from it (`/v1/traces` becomes `/v1/logs`) unless `logsEndpoint` is set.
1833
+ */
1834
+ endpoint: endpointSchema.optional(),
1835
+ /** Per-signal override of `endpoint` for traces. */
1836
+ tracesEndpoint: endpointSchema.optional(),
1837
+ /** Per-signal override of the derived logs URL. */
1838
+ logsEndpoint: endpointSchema.optional(),
1839
+ /** Defaults to `exporter.protocol`. */
1840
+ protocol: z13.enum(["http/protobuf", "http/json", "none"]).optional(),
1841
+ /**
1842
+ * Header name to value. A value of the form `env:NAME` is read from that
1843
+ * environment variable at send time, so a credential never has to be written
1844
+ * into the file. Values never appear in a snapshot, a diagnostic, or `doctor`.
1845
+ */
1846
+ headers: z13.record(z13.string().regex(HEADER_NAME_PATTERN2, "not a valid header name"), headerValueSchema).refine(
1847
+ (headers) => Object.keys(headers).length <= MAX_DESTINATION_HEADERS,
1848
+ `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
1849
+ ).optional(),
1850
+ /**
1851
+ * Which signals this destination receives. Default: both. The logs signal is
1852
+ * still governed by `exporter.logs.enabled`, which stays the one opt-in for a
1853
+ * second stream leaving the host.
1854
+ */
1855
+ signals: z13.array(exportSignalSchema).min(1).max(2).readonly().optional()
1856
+ }).refine(
1857
+ (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0,
1858
+ "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint"
1859
+ );
1860
+ var exportDestinationsSchema = z13.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
1861
+ const seen = /* @__PURE__ */ new Set();
1862
+ destinations.forEach((destination, index) => {
1863
+ if (destination.name === DEFAULT_DESTINATION_NAME) {
1864
+ context.addIssue({
1865
+ code: "custom",
1866
+ path: [index, "name"],
1867
+ message: 'the name "default" is reserved for exporter.endpoint and the OTEL_EXPORTER_OTLP_* variables'
1868
+ });
1869
+ }
1870
+ if (seen.has(destination.name)) {
1871
+ context.addIssue({
1872
+ code: "custom",
1873
+ path: [index, "name"],
1874
+ message: `duplicate destination name "${destination.name}"`
1875
+ });
1876
+ }
1877
+ seen.add(destination.name);
1878
+ });
1879
+ });
1880
+ var spoolPolicySchema = z13.strictObject({
1881
+ /** Total bytes of queued batches. Default 16 MiB. */
1882
+ maxBytes: z13.number().int().min(1024).max(1073741824),
1883
+ /** A batch older than this is dropped instead of sent. Default 72 hours. */
1884
+ maxAgeMillis: z13.number().int().min(1e3).max(30 * 24 * 60 * 60 * 1e3),
1885
+ /** Number of queued batches. Default 500. */
1886
+ maxBatches: z13.number().int().min(1).max(65536)
1887
+ });
1888
+ var DEFAULT_SPOOL_POLICY = Object.freeze({
1889
+ maxBytes: 16 * 1024 * 1024,
1890
+ maxAgeMillis: 72 * 60 * 60 * 1e3,
1891
+ maxBatches: 500
1892
+ });
1893
+ var effectiveSpoolPolicy = (exporter) => ({
1894
+ maxBytes: exporter.spool?.maxBytes ?? DEFAULT_SPOOL_POLICY.maxBytes,
1895
+ maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,
1896
+ maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches
1897
+ });
1898
+ var legacyDestination = (exporter) => ({
1899
+ name: DEFAULT_DESTINATION_NAME,
1900
+ source: "exporter",
1901
+ protocol: exporter.protocol,
1902
+ ...exporter.endpoint === void 0 ? {} : { endpoint: exporter.endpoint },
1903
+ ...exporter.logs.endpoint === void 0 ? {} : { logsEndpoint: exporter.logs.endpoint },
1904
+ signals: { traces: true, logs: exporter.logs.enabled },
1905
+ headers: {}
1906
+ });
1907
+ var hasConfiguredDestinations = (exporter) => exporter.destinations !== void 0 && exporter.destinations.length > 0;
1908
+ var resolveExportDestinations = (exporter) => {
1909
+ if (!hasConfiguredDestinations(exporter)) {
1910
+ return [legacyDestination(exporter)];
1911
+ }
1912
+ const resolved = [];
1913
+ if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0) {
1914
+ resolved.push(legacyDestination(exporter));
1915
+ }
1916
+ for (const destination of exporter.destinations ?? []) {
1917
+ if (destination.enabled === false) {
1918
+ continue;
1919
+ }
1920
+ const signals = destination.signals ?? exportSignalSchema.options;
1921
+ resolved.push({
1922
+ name: destination.name,
1923
+ source: "destinations",
1924
+ protocol: destination.protocol ?? exporter.protocol,
1925
+ ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
1926
+ ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
1927
+ ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
1928
+ signals: {
1929
+ traces: signals.includes("traces"),
1930
+ logs: exporter.logs.enabled && signals.includes("logs")
1931
+ },
1932
+ headers: { ...destination.headers ?? {} }
1933
+ });
1934
+ }
1935
+ return resolved;
1936
+ };
1937
+ var parseHeaderValueReference = (value) => value.startsWith(HEADER_ENV_REFERENCE_PREFIX) ? { kind: "env", variable: value.slice(HEADER_ENV_REFERENCE_PREFIX.length) } : { kind: "literal" };
1938
+ var resolveDestinationHeaders = (headers, environment) => {
1939
+ const values = {};
1940
+ const missing = [];
1941
+ for (const [name, value] of Object.entries(headers)) {
1942
+ const reference = parseHeaderValueReference(value);
1943
+ if (reference.kind === "literal") {
1944
+ values[name] = value;
1945
+ continue;
1946
+ }
1947
+ const resolved = environment?.[reference.variable];
1948
+ if (resolved === void 0 || resolved === "") {
1949
+ missing.push(reference.variable);
1950
+ continue;
1951
+ }
1952
+ values[name] = resolved;
1953
+ }
1954
+ return { values, missingVariables: [...new Set(missing)].sort() };
1955
+ };
1956
+ var endpointOrigin = (endpoint) => {
1957
+ if (endpoint === void 0) {
1958
+ return void 0;
1959
+ }
1960
+ try {
1961
+ return new URL(endpoint).origin;
1962
+ } catch {
1963
+ return "<unparsable>";
1964
+ }
1965
+ };
1966
+ var describeExportDestinations = (exporter) => {
1967
+ const describe = (destination, enabled2) => {
1968
+ const tracesOrigin = endpointOrigin(destination.tracesEndpoint ?? destination.endpoint);
1969
+ const logsOrigin = endpointOrigin(
1970
+ destination.logsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint
1971
+ );
1972
+ const variables = Object.values(destination.headers).map(parseHeaderValueReference).flatMap((reference) => reference.kind === "env" ? [reference.variable] : []);
1973
+ return {
1974
+ name: destination.name,
1975
+ enabled: enabled2,
1976
+ protocol: destination.protocol,
1977
+ signals: exportSignalSchema.options.filter((signal) => destination.signals[signal]),
1978
+ ...tracesOrigin === void 0 || !destination.signals.traces ? {} : { tracesEndpointOrigin: tracesOrigin },
1979
+ ...logsOrigin === void 0 || !destination.signals.logs ? {} : { logsEndpointOrigin: logsOrigin },
1980
+ headerNames: destination.source === "exporter" ? [...exporter.headerNames].sort() : Object.keys(destination.headers).sort(),
1981
+ headerVariables: [...new Set(variables)].sort()
1982
+ };
1983
+ };
1984
+ const enabled = resolveExportDestinations(exporter).map(
1985
+ (destination) => describe(destination, true)
1986
+ );
1987
+ const disabled = (exporter.destinations ?? []).filter((destination) => destination.enabled === false).map(
1988
+ (destination) => describe(
1989
+ {
1990
+ name: destination.name,
1991
+ source: "destinations",
1992
+ protocol: destination.protocol ?? exporter.protocol,
1993
+ ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
1994
+ signals: { traces: false, logs: false },
1995
+ headers: { ...destination.headers ?? {} }
1996
+ },
1997
+ false
1998
+ )
1999
+ );
2000
+ return [...enabled, ...disabled];
2001
+ };
2002
+
2003
+ // src/config/schema.ts
2004
+ var logsPolicySchema = z14.strictObject({
2005
+ enabled: z14.boolean(),
1682
2006
  /**
1683
2007
  * Full URL for the logs signal.
1684
2008
  *
1685
2009
  * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes
1686
2010
  * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.
1687
2011
  */
1688
- endpoint: z13.string().url().max(2048).optional(),
1689
- includeContent: z13.boolean(),
1690
- maxBatchSize: z13.number().int().min(1).max(4096)
2012
+ endpoint: z14.string().url().max(2048).optional(),
2013
+ includeContent: z14.boolean(),
2014
+ maxBatchSize: z14.number().int().min(1).max(4096)
1691
2015
  });
1692
2016
  var DEFAULT_LOGS_POLICY = Object.freeze({
1693
2017
  enabled: false,
1694
2018
  includeContent: false,
1695
2019
  maxBatchSize: 128
1696
2020
  });
1697
- var exporterPolicySchema = z13.strictObject({
1698
- enabled: z13.boolean(),
1699
- protocol: z13.enum(["http/protobuf", "http/json", "none"]),
1700
- endpoint: z13.string().url().max(2048).optional(),
2021
+ var exporterPolicySchema = z14.strictObject({
2022
+ enabled: z14.boolean(),
2023
+ protocol: z14.enum(["http/protobuf", "http/json", "none"]),
2024
+ endpoint: z14.string().url().max(2048).optional(),
1701
2025
  /**
1702
2026
  * Header names only. Values are supplied separately at construction time and
1703
2027
  * are never part of a resolved-config snapshot, which is logged and exported.
1704
2028
  */
1705
- headerNames: z13.array(nonEmptyStringSchema).max(32).readonly(),
1706
- timeoutMillis: z13.number().int().min(1).max(6e5),
1707
- maxBatchSize: z13.number().int().min(1).max(4096),
1708
- maxQueueSize: z13.number().int().min(1).max(65536),
1709
- maxRetryAttempts: z13.number().int().min(0).max(10),
2029
+ headerNames: z14.array(nonEmptyStringSchema).max(32).readonly(),
2030
+ timeoutMillis: z14.number().int().min(1).max(6e5),
2031
+ maxBatchSize: z14.number().int().min(1).max(4096),
2032
+ maxQueueSize: z14.number().int().min(1).max(65536),
2033
+ maxRetryAttempts: z14.number().int().min(0).max(10),
1710
2034
  serviceName: nonEmptyStringSchema,
1711
2035
  serviceNamespace: nonEmptyStringSchema.optional(),
1712
2036
  /**
@@ -1723,32 +2047,52 @@ var exporterPolicySchema = z13.strictObject({
1723
2047
  * headers, timeout, protocol, service identity, and resource attributes above —
1724
2048
  * a second top-level section would invite two of each to drift apart.
1725
2049
  */
1726
- logs: logsPolicySchema
2050
+ logs: logsPolicySchema,
2051
+ /**
2052
+ * Additional OTLP destinations, each sent every batch in parallel.
2053
+ *
2054
+ * Absent (the default), the exporter has exactly one destination — the
2055
+ * single-endpoint settings above, named `default` — and behaves exactly as it
2056
+ * did before this list existed. See `destinations.ts`.
2057
+ *
2058
+ * Merged as one leaf: a higher layer that sets the list replaces it whole,
2059
+ * because "the union of two partial lists" has no answer an operator could
2060
+ * predict.
2061
+ */
2062
+ destinations: exportDestinationsSchema.optional(),
2063
+ /**
2064
+ * Per-destination retry spool bounds, each optional and merged per leaf; any
2065
+ * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.
2066
+ */
2067
+ spool: spoolPolicySchema.partial().optional()
1727
2068
  });
1728
- var detectionPolicySchema = z13.strictObject({
2069
+ var detectionPolicySchema = z14.strictObject({
1729
2070
  /** Detections below this confidence resolve to the unknown provider. */
1730
2071
  minimumConfidence: detectionConfidenceSchema,
1731
2072
  /** When false, an ambiguous detection is an error rather than unknown. */
1732
- allowAmbiguousFallback: z13.boolean(),
2073
+ allowAmbiguousFallback: z14.boolean(),
1733
2074
  /** Optional allow-list of provider ids; empty means "any registered". */
1734
- allowedProviderIds: z13.array(nonEmptyStringSchema).max(32).readonly()
2075
+ allowedProviderIds: z14.array(nonEmptyStringSchema).max(32).readonly()
1735
2076
  });
1736
- var diagnosticsPolicySchema = z13.strictObject({
1737
- logLevel: z13.enum(["silent", "error", "warn", "info", "debug"]),
2077
+ var diagnosticsPolicySchema = z14.strictObject({
2078
+ logLevel: z14.enum(["silent", "error", "warn", "info", "debug"]),
1738
2079
  /** Emit `error.raised` events for contained failures. */
1739
- emitErrorEvents: z13.boolean()
2080
+ emitErrorEvents: z14.boolean()
1740
2081
  });
1741
- var otelHookConfigSchema = z13.strictObject({
2082
+ var otelHookConfigSchema = z14.strictObject({
1742
2083
  exporter: exporterPolicySchema,
1743
2084
  privacy: privacyPolicySchema,
1744
2085
  detection: detectionPolicySchema,
1745
2086
  diagnostics: diagnosticsPolicySchema
1746
2087
  });
1747
- var otelHookConfigPatchSchema = z13.strictObject({
2088
+ var otelHookConfigPatchSchema = z14.strictObject({
1748
2089
  // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
1749
2090
  // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
1750
2091
  // without also restating the endpoint and the batch size.
1751
- exporter: exporterPolicySchema.omit({ logs: true }).partial().extend({ logs: logsPolicySchema.partial().optional() }).optional(),
2092
+ exporter: exporterPolicySchema.omit({ logs: true, spool: true }).partial().extend({
2093
+ logs: logsPolicySchema.partial().optional(),
2094
+ spool: spoolPolicySchema.partial().optional()
2095
+ }).optional(),
1752
2096
  privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
1753
2097
  detection: detectionPolicySchema.partial().optional(),
1754
2098
  diagnostics: diagnosticsPolicySchema.partial().optional()
@@ -1782,9 +2126,9 @@ var DEFAULT_CONFIG = Object.freeze({
1782
2126
  });
1783
2127
 
1784
2128
  // src/config/resolve.ts
1785
- import { z as z14 } from "zod";
2129
+ import { z as z15 } from "zod";
1786
2130
  var CONFIG_SOURCE_PRECEDENCE = ["defaults", "file", "environment", "inline-override"];
1787
- var configSourceSchema = z14.enum(CONFIG_SOURCE_PRECEDENCE);
2131
+ var configSourceSchema = z15.enum(CONFIG_SOURCE_PRECEDENCE);
1788
2132
  var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1789
2133
  var mergeLeaf = (target, patch, source, provenance, path9) => {
1790
2134
  for (const [key, value] of Object.entries(patch)) {
@@ -1793,8 +2137,8 @@ var mergeLeaf = (target, patch, source, provenance, path9) => {
1793
2137
  }
1794
2138
  const childPath = path9 === "" ? key : `${path9}.${key}`;
1795
2139
  const existing = target[key];
1796
- if (isPlainObject(value) && isPlainObject(existing)) {
1797
- const child = { ...existing };
2140
+ if (isPlainObject(value) && (isPlainObject(existing) || existing === void 0)) {
2141
+ const child = { ...existing ?? {} };
1798
2142
  mergeLeaf(child, value, source, provenance, childPath);
1799
2143
  target[key] = child;
1800
2144
  continue;
@@ -1866,10 +2210,27 @@ var resolveConfig = (layers = []) => {
1866
2210
  if (parsed.data.privacy.contentMode === "raw" && !parsed.data.privacy.allowRawContent) {
1867
2211
  notes.push("privacy.contentMode=raw will be downgraded to omit: allowRawContent is false");
1868
2212
  }
1869
- if (parsed.data.exporter.enabled && parsed.data.exporter.protocol !== "none" && parsed.data.exporter.endpoint === void 0) {
2213
+ const withDestinations = hasConfiguredDestinations(parsed.data.exporter);
2214
+ if (parsed.data.exporter.enabled && parsed.data.exporter.protocol !== "none" && parsed.data.exporter.endpoint === void 0 && !withDestinations) {
1870
2215
  notes.push("exporter.enabled is true but no endpoint is configured");
1871
2216
  }
1872
- if (parsed.data.exporter.logs.enabled && parsed.data.exporter.logs.endpoint === void 0 && parsed.data.exporter.endpoint === void 0) {
2217
+ if (withDestinations) {
2218
+ const enabled = (parsed.data.exporter.destinations ?? []).filter(
2219
+ (destination) => destination.enabled !== false
2220
+ );
2221
+ if (enabled.length === 0 && parsed.data.exporter.endpoint === void 0) {
2222
+ notes.push("exporter.destinations is set but every destination is disabled");
2223
+ }
2224
+ if (!parsed.data.exporter.logs.enabled) {
2225
+ const askingForLogs = enabled.filter((destination) => destination.signals?.includes("logs") === true).map((destination) => destination.name);
2226
+ if (askingForLogs.length > 0) {
2227
+ notes.push(
2228
+ `destination(s) ${askingForLogs.join(", ")} list the logs signal but exporter.logs.enabled is false, so only traces are sent`
2229
+ );
2230
+ }
2231
+ }
2232
+ }
2233
+ if (!withDestinations && parsed.data.exporter.logs.enabled && parsed.data.exporter.logs.endpoint === void 0 && parsed.data.exporter.endpoint === void 0) {
1873
2234
  notes.push(
1874
2235
  "exporter.logs.enabled is true but neither a logs endpoint nor a trace endpoint to derive one from is configured"
1875
2236
  );
@@ -1881,6 +2242,35 @@ var resolveConfig = (layers = []) => {
1881
2242
  }
1882
2243
  return { status: "ok", config: parsed.data, provenance, notes };
1883
2244
  };
2245
+ var describeDestinationAttributes = (config) => {
2246
+ const attributes = {};
2247
+ if (config.exporter.spool !== void 0 || hasConfiguredDestinations(config.exporter)) {
2248
+ const spool = effectiveSpoolPolicy(config.exporter);
2249
+ attributes["exporter.spool_max_bytes"] = spool.maxBytes;
2250
+ attributes["exporter.spool_max_age_millis"] = spool.maxAgeMillis;
2251
+ attributes["exporter.spool_max_batches"] = spool.maxBatches;
2252
+ }
2253
+ if (!hasConfiguredDestinations(config.exporter)) {
2254
+ return attributes;
2255
+ }
2256
+ const destinations = describeExportDestinations(config.exporter);
2257
+ attributes["exporter.destination_names"] = destinations.map((destination) => destination.name);
2258
+ for (const destination of destinations) {
2259
+ const prefix = `exporter.destination.${destination.name}`;
2260
+ attributes[`${prefix}.enabled`] = destination.enabled;
2261
+ attributes[`${prefix}.protocol`] = destination.protocol;
2262
+ attributes[`${prefix}.signals`] = [...destination.signals];
2263
+ if (destination.tracesEndpointOrigin !== void 0) {
2264
+ attributes[`${prefix}.traces_endpoint_origin`] = destination.tracesEndpointOrigin;
2265
+ }
2266
+ if (destination.logsEndpointOrigin !== void 0) {
2267
+ attributes[`${prefix}.logs_endpoint_origin`] = destination.logsEndpointOrigin;
2268
+ }
2269
+ attributes[`${prefix}.header_names`] = [...destination.headerNames];
2270
+ attributes[`${prefix}.header_variables`] = [...destination.headerVariables];
2271
+ }
2272
+ return attributes;
2273
+ };
1884
2274
  var describeResolvedConfig = (config) => {
1885
2275
  const originOf = (endpoint) => {
1886
2276
  if (endpoint === void 0) {
@@ -1892,12 +2282,12 @@ var describeResolvedConfig = (config) => {
1892
2282
  return "<unparsable>";
1893
2283
  }
1894
2284
  };
1895
- const endpointOrigin = originOf(config.exporter.endpoint);
2285
+ const endpointOrigin2 = originOf(config.exporter.endpoint);
1896
2286
  const logsEndpointOrigin = originOf(config.exporter.logs.endpoint);
1897
2287
  return {
1898
2288
  "exporter.enabled": config.exporter.enabled,
1899
2289
  "exporter.protocol": config.exporter.protocol,
1900
- ...endpointOrigin === void 0 ? {} : { "exporter.endpoint_origin": endpointOrigin },
2290
+ ...endpointOrigin2 === void 0 ? {} : { "exporter.endpoint_origin": endpointOrigin2 },
1901
2291
  "exporter.logs_enabled": config.exporter.logs.enabled,
1902
2292
  "exporter.logs_include_content": config.exporter.logs.includeContent,
1903
2293
  "exporter.logs_max_batch_size": config.exporter.logs.maxBatchSize,
@@ -1906,151 +2296,60 @@ var describeResolvedConfig = (config) => {
1906
2296
  // Names only. A resource attribute *name* is already on the wire in every
1907
2297
  // exported resource, so disclosing it here adds nothing; a *value* may hold
1908
2298
  // whatever an operator put in a shell profile, so it never appears.
1909
- "exporter.resource_attribute_names": [
1910
- ...describeResourceAttributeNames(config.exporter.resourceAttributes)
1911
- ],
1912
- "exporter.timeout_millis": config.exporter.timeoutMillis,
1913
- "exporter.max_batch_size": config.exporter.maxBatchSize,
1914
- "exporter.service_name": config.exporter.serviceName,
1915
- "privacy.content_mode": config.privacy.contentMode,
1916
- "privacy.allow_raw_content": config.privacy.allowRawContent,
1917
- "privacy.hash_salted": config.privacy.hashSalt.length > 0,
1918
- "privacy.max_string_length": config.privacy.limits.maxStringLength,
1919
- "privacy.max_depth": config.privacy.limits.maxDepth,
1920
- "privacy.max_array_length": config.privacy.limits.maxArrayLength,
1921
- "privacy.max_events_per_invocation": config.privacy.limits.maxEventsPerInvocation,
1922
- "detection.minimum_confidence": config.detection.minimumConfidence,
1923
- "detection.allow_ambiguous_fallback": config.detection.allowAmbiguousFallback,
1924
- "diagnostics.log_level": config.diagnostics.logLevel,
1925
- "diagnostics.emit_error_events": config.diagnostics.emitErrorEvents
1926
- };
1927
- };
1928
-
1929
- // src/config/otlp-headers.ts
1930
- var MAX_OTLP_HEADERS = 32;
1931
- var OTLP_HEADER_VARIABLES = Object.freeze({
1932
- generic: "OTEL_EXPORTER_OTLP_HEADERS",
1933
- traces: "OTEL_EXPORTER_OTLP_TRACES_HEADERS",
1934
- logs: "OTEL_EXPORTER_OTLP_LOGS_HEADERS"
1935
- });
1936
- var HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
1937
- var isUnsafeHeaderValue = (value) => [...value].some((char) => {
1938
- const code = char.codePointAt(0) ?? 0;
1939
- return code < 32 && code !== 9 || code === 127 || code > 255;
1940
- });
1941
- var decode = (raw) => {
1942
- try {
1943
- return decodeURIComponent(raw);
1944
- } catch {
1945
- return void 0;
1946
- }
1947
- };
1948
- var parseOtlpHeadersValue = (raw) => {
1949
- const headers = {};
1950
- const warnings = [];
1951
- let overflowed = false;
1952
- for (const [index, rawEntry] of raw.split(",").entries()) {
1953
- const position = String(index + 1);
1954
- const entry = rawEntry.trim();
1955
- if (entry === "") {
1956
- continue;
1957
- }
1958
- const equals = entry.indexOf("=");
1959
- if (equals <= 0) {
1960
- warnings.push(`entry ${position} is not a key=value pair; ignored`);
1961
- continue;
1962
- }
1963
- const key = decode(entry.slice(0, equals).trim());
1964
- const value = decode(entry.slice(equals + 1).trim());
1965
- if (key === void 0 || value === void 0) {
1966
- warnings.push(`entry ${position} has malformed percent-encoding; ignored`);
1967
- continue;
1968
- }
1969
- const name = key.trim();
1970
- const trimmedValue = value.trim();
1971
- if (!HEADER_NAME_PATTERN.test(name)) {
1972
- warnings.push(`entry ${position} does not name a valid HTTP header; ignored`);
1973
- continue;
1974
- }
1975
- if (trimmedValue === "") {
1976
- warnings.push(`entry ${position} has an empty value; ignored`);
1977
- continue;
1978
- }
1979
- if (isUnsafeHeaderValue(trimmedValue)) {
1980
- warnings.push(`entry ${position} has a character not allowed in an HTTP header value; ignored`);
1981
- continue;
1982
- }
1983
- const existing = findHeaderName(headers, name);
1984
- if (existing === void 0 && Object.keys(headers).length >= MAX_OTLP_HEADERS) {
1985
- overflowed = true;
1986
- continue;
1987
- }
1988
- if (existing !== void 0) {
1989
- delete headers[existing];
1990
- }
1991
- headers[name] = trimmedValue;
1992
- }
1993
- if (overflowed) {
1994
- warnings.push(`more than ${String(MAX_OTLP_HEADERS)} headers were supplied; the excess was ignored`);
1995
- }
1996
- return { headers, warnings };
1997
- };
1998
- var findHeaderName = (headers, name) => {
1999
- const lower = name.toLowerCase();
2000
- return Object.keys(headers).find((candidate) => candidate.toLowerCase() === lower);
2001
- };
2002
- var mergeOtlpHeaders = (...sources) => {
2003
- const merged = {};
2004
- for (const source of sources) {
2005
- for (const [name, value] of Object.entries(source)) {
2006
- const existing = findHeaderName(merged, name);
2007
- if (existing !== void 0) {
2008
- delete merged[existing];
2009
- }
2010
- merged[name] = value;
2011
- }
2012
- }
2013
- return merged;
2014
- };
2015
- var resolveOtlpHeaders = (env, explicit = {}) => {
2016
- const warnings = [];
2017
- const read = (variable) => {
2018
- const raw = env[variable];
2019
- if (raw === void 0 || raw.trim() === "") {
2020
- return {};
2021
- }
2022
- const parsed = parseOtlpHeadersValue(raw);
2023
- for (const detail of parsed.warnings) {
2024
- warnings.push({ variable, detail });
2025
- }
2026
- return parsed.headers;
2027
- };
2028
- const generic = read(OTLP_HEADER_VARIABLES.generic);
2029
- const traces = read(OTLP_HEADER_VARIABLES.traces);
2030
- const logs = read(OTLP_HEADER_VARIABLES.logs);
2031
- return {
2032
- traces: mergeOtlpHeaders(generic, traces, explicit),
2033
- logs: mergeOtlpHeaders(generic, logs, explicit),
2034
- warnings
2299
+ "exporter.resource_attribute_names": [
2300
+ ...describeResourceAttributeNames(config.exporter.resourceAttributes)
2301
+ ],
2302
+ ...describeDestinationAttributes(config),
2303
+ "exporter.timeout_millis": config.exporter.timeoutMillis,
2304
+ "exporter.max_batch_size": config.exporter.maxBatchSize,
2305
+ "exporter.service_name": config.exporter.serviceName,
2306
+ "privacy.content_mode": config.privacy.contentMode,
2307
+ "privacy.allow_raw_content": config.privacy.allowRawContent,
2308
+ "privacy.hash_salted": config.privacy.hashSalt.length > 0,
2309
+ "privacy.max_string_length": config.privacy.limits.maxStringLength,
2310
+ "privacy.max_depth": config.privacy.limits.maxDepth,
2311
+ "privacy.max_array_length": config.privacy.limits.maxArrayLength,
2312
+ "privacy.max_events_per_invocation": config.privacy.limits.maxEventsPerInvocation,
2313
+ "detection.minimum_confidence": config.detection.minimumConfidence,
2314
+ "detection.allow_ambiguous_fallback": config.detection.allowAmbiguousFallback,
2315
+ "diagnostics.log_level": config.diagnostics.logLevel,
2316
+ "diagnostics.emit_error_events": config.diagnostics.emitErrorEvents
2035
2317
  };
2036
2318
  };
2037
- var unionOtlpHeaderNames = (...lists) => {
2038
- const names = [];
2039
- const seen = /* @__PURE__ */ new Set();
2040
- for (const name of lists.flat()) {
2041
- if (!seen.has(name.toLowerCase())) {
2042
- seen.add(name.toLowerCase());
2043
- names.push(name);
2044
- }
2319
+
2320
+ // src/config/otlp-endpoint.ts
2321
+ var OTLP_ENDPOINT_VARIABLES = Object.freeze({
2322
+ generic: "OTEL_EXPORTER_OTLP_ENDPOINT",
2323
+ traces: "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
2324
+ logs: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT"
2325
+ });
2326
+ var OTLP_TRACES_PATH = "/v1/traces";
2327
+ var OTLP_LOGS_PATH = "/v1/logs";
2328
+ var withoutTrailingSlashes = (value) => {
2329
+ let end = value.length;
2330
+ while (end > 0 && value.charCodeAt(end - 1) === 47) {
2331
+ end -= 1;
2045
2332
  }
2046
- return names.sort().slice(0, MAX_OTLP_HEADERS);
2333
+ return value.slice(0, end);
2334
+ };
2335
+ var otlpSignalEndpointFromBase = (base, signal) => {
2336
+ const trimmed = withoutTrailingSlashes(base);
2337
+ if (trimmed.endsWith(OTLP_TRACES_PATH)) {
2338
+ return signal === "traces" ? trimmed : `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${OTLP_LOGS_PATH}`;
2339
+ }
2340
+ return `${trimmed}${signal === "traces" ? OTLP_TRACES_PATH : OTLP_LOGS_PATH}`;
2047
2341
  };
2048
- var describeOtlpHeaderNames = (...sources) => unionOtlpHeaderNames(...sources.map((source) => Object.keys(source)));
2049
2342
 
2050
2343
  // src/config/environment.ts
2051
2344
  var ENVIRONMENT_VARIABLES = Object.freeze({
2052
2345
  exporterEnabled: "OTEL_HOOK_ENABLED",
2346
+ /** Full traces URL; otel-hook's own variable, above the standard ones. */
2053
2347
  exporterEndpoint: "OTEL_HOOK_EXPORTER_ENDPOINT",
2348
+ /**
2349
+ * Standard base URL: `/v1/traces` and `/v1/logs` are appended per signal. A
2350
+ * value already ending in `/v1/traces` is the legacy full traces URL and is
2351
+ * used as-is (see `otlpSignalEndpointFromBase`).
2352
+ */
2054
2353
  otlpEndpoint: "OTEL_EXPORTER_OTLP_ENDPOINT",
2055
2354
  exporterProtocol: "OTEL_HOOK_EXPORTER_PROTOCOL",
2056
2355
  exporterTimeoutMillis: "OTEL_HOOK_EXPORTER_TIMEOUT_MS",
@@ -2124,7 +2423,10 @@ var parseEnvironmentConfig = (env) => {
2124
2423
  return trimmed === "" ? void 0 : trimmed;
2125
2424
  };
2126
2425
  const exporterEnabled = readBoolean(ENVIRONMENT_VARIABLES.exporterEnabled);
2127
- const endpoint = readString(ENVIRONMENT_VARIABLES.exporterEndpoint) ?? readString(ENVIRONMENT_VARIABLES.otlpEndpoint);
2426
+ const hookEndpoint = readString(ENVIRONMENT_VARIABLES.exporterEndpoint);
2427
+ const otlpTracesEndpoint = readString(OTLP_ENDPOINT_VARIABLES.traces);
2428
+ const otlpBaseEndpoint = readString(ENVIRONMENT_VARIABLES.otlpEndpoint);
2429
+ const endpoint = hookEndpoint ?? otlpTracesEndpoint ?? (otlpBaseEndpoint === void 0 ? void 0 : otlpSignalEndpointFromBase(otlpBaseEndpoint, "traces"));
2128
2430
  const timeoutMillis = readInteger(ENVIRONMENT_VARIABLES.exporterTimeoutMillis);
2129
2431
  const resourceRaw = readString(ENVIRONMENT_VARIABLES.resourceAttributes);
2130
2432
  const resource = resourceRaw === void 0 ? void 0 : parseResourceAttributesValue(resourceRaw);
@@ -2210,7 +2512,7 @@ var parseEnvironmentConfig = (env) => {
2210
2512
  const maxEventsPerInvocation = readInteger(ENVIRONMENT_VARIABLES.maxEventsPerInvocation);
2211
2513
  const logsEnabled = readBoolean(ENVIRONMENT_VARIABLES.logsEnabled);
2212
2514
  const logsIncludeContent = readBoolean(ENVIRONMENT_VARIABLES.logsIncludeContent);
2213
- const logsEndpoint = readString(ENVIRONMENT_VARIABLES.logsEndpoint) ?? readString(ENVIRONMENT_VARIABLES.otlpLogsEndpoint);
2515
+ const logsEndpoint = readString(ENVIRONMENT_VARIABLES.logsEndpoint) ?? readString(ENVIRONMENT_VARIABLES.otlpLogsEndpoint) ?? (hookEndpoint === void 0 && otlpTracesEndpoint !== void 0 && otlpBaseEndpoint !== void 0 ? otlpSignalEndpointFromBase(otlpBaseEndpoint, "logs") : void 0);
2214
2516
  const logs = {
2215
2517
  ...logsEnabled === void 0 ? {} : { enabled: logsEnabled },
2216
2518
  ...logsEndpoint === void 0 ? {} : { endpoint: logsEndpoint },
@@ -2256,27 +2558,27 @@ var parseEnvironmentConfig = (env) => {
2256
2558
  };
2257
2559
 
2258
2560
  // src/providers/adapter.ts
2259
- import { z as z15 } from "zod";
2260
- var providerDetectionSchema = z15.strictObject({
2561
+ import { z as z16 } from "zod";
2562
+ var providerDetectionSchema = z16.strictObject({
2261
2563
  providerId: resolvedProviderIdSchema,
2262
2564
  confidence: detectionConfidenceSchema,
2263
2565
  /**
2264
2566
  * Short, non-sensitive justifications, e.g. `"payload.hook_event_name present"`.
2265
2567
  * Reasons are exported in diagnostics, so they must not quote payload values.
2266
2568
  */
2267
- reasons: z15.array(z15.string().min(1).max(160)).max(8),
2569
+ reasons: z16.array(z16.string().min(1).max(160)).max(8),
2268
2570
  providerVersion: nonEmptyStringSchema.optional(),
2269
2571
  /** The provider's own name for this event, when the payload states one. */
2270
2572
  sourceEventName: nonEmptyStringSchema.optional()
2271
2573
  });
2272
- var deliveryIdentifierSupportSchema = z15.enum(["none", "partial", "all"]);
2574
+ var deliveryIdentifierSupportSchema = z16.enum(["none", "partial", "all"]);
2273
2575
  var DELIVERY_COMPONENT_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
2274
- var deliveryComponentSchema = z15.string().regex(
2576
+ var deliveryComponentSchema = z16.string().regex(
2275
2577
  DELIVERY_COMPONENT_PATTERN,
2276
2578
  "delivery component must be identifier-shaped: no whitespace, no path separators"
2277
2579
  );
2278
2580
  var MAX_DELIVERY_COMPONENTS = 8;
2279
- var providerDeliveryClaimSchema = z15.strictObject({
2581
+ var providerDeliveryClaimSchema = z16.strictObject({
2280
2582
  /**
2281
2583
  * The provider's own session/conversation id. Scopes the callback identity, so
2282
2584
  * two sessions reusing one tool-call id never collide.
@@ -2288,26 +2590,26 @@ var providerDeliveryClaimSchema = z15.strictObject({
2288
2590
  * Identifier-shaped payload fields that, together with `sourceEventName`,
2289
2591
  * name this callback within the session exactly once.
2290
2592
  */
2291
- components: z15.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),
2593
+ components: z16.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),
2292
2594
  /**
2293
2595
  * Short, non-sensitive justifications, e.g. `"payload.tool_use_id names one
2294
2596
  * tool call"`. Evidence reaches diagnostics, so it must name fields, never
2295
2597
  * quote their values.
2296
2598
  */
2297
- evidence: z15.array(z15.string().min(1).max(160)).min(1).max(4).readonly()
2599
+ evidence: z16.array(z16.string().min(1).max(160)).min(1).max(4).readonly()
2298
2600
  });
2299
2601
  var DELIVERY_GAP_REASON_PATTERN = /^[^\n\r\t\\/]{1,240}$/;
2300
- var deliveryGapReasonSchema = z15.string().regex(
2602
+ var deliveryGapReasonSchema = z16.string().regex(
2301
2603
  DELIVERY_GAP_REASON_PATTERN,
2302
2604
  "delivery gap reason must be one line of prose: no path separators, no control characters"
2303
2605
  );
2304
2606
  var MAX_DELIVERY_GAPS = 48;
2305
- var providerDeliveryGapsSchema = z15.record(deliveryComponentSchema, deliveryGapReasonSchema).refine((gaps) => Object.keys(gaps).length <= MAX_DELIVERY_GAPS, {
2607
+ var providerDeliveryGapsSchema = z16.record(deliveryComponentSchema, deliveryGapReasonSchema).refine((gaps) => Object.keys(gaps).length <= MAX_DELIVERY_GAPS, {
2306
2608
  message: `at most ${String(MAX_DELIVERY_GAPS)} delivery gaps may be declared`
2307
2609
  });
2308
- var providerCapabilitiesSchema = z15.strictObject({
2610
+ var providerCapabilitiesSchema = z16.strictObject({
2309
2611
  /** Event types the adapter can produce. */
2310
- lifecycleEvents: z15.array(canonicalEventTypeSchema).max(32).readonly(),
2612
+ lifecycleEvents: z16.array(canonicalEventTypeSchema).max(32).readonly(),
2311
2613
  usageTemporality: usageTemporalitySchema,
2312
2614
  /**
2313
2615
  * Which accumulator series a `cumulative` report continues — that is, which
@@ -2326,32 +2628,32 @@ var providerCapabilitiesSchema = z15.strictObject({
2326
2628
  * Subagent snapshots keep their own series regardless: a delegated agent's
2327
2629
  * counter is not a point on the parent session's curve.
2328
2630
  */
2329
- cumulativeUsageSeries: z15.enum(["event-scope", "session-lifetime"]).optional(),
2330
- reportsCachedInput: z15.boolean(),
2331
- reportsCacheCreation: z15.boolean(),
2631
+ cumulativeUsageSeries: z16.enum(["event-scope", "session-lifetime"]).optional(),
2632
+ reportsCachedInput: z16.boolean(),
2633
+ reportsCacheCreation: z16.boolean(),
2332
2634
  cacheCreationAccounting: cacheCreationAccountingSchema,
2333
- reportsReasoningOutput: z15.boolean(),
2334
- reportsProviderTotal: z15.boolean(),
2335
- reportsCost: z15.boolean(),
2336
- emitsSubagentEvents: z15.boolean(),
2337
- emitsCompactionEvents: z15.boolean(),
2635
+ reportsReasoningOutput: z16.boolean(),
2636
+ reportsProviderTotal: z16.boolean(),
2637
+ reportsCost: z16.boolean(),
2638
+ emitsSubagentEvents: z16.boolean(),
2639
+ emitsCompactionEvents: z16.boolean(),
2338
2640
  /** True when the provider reads a structured response from stdout. */
2339
- requiresHookResponse: z15.boolean(),
2641
+ requiresHookResponse: z16.boolean(),
2340
2642
  /** How much of this provider's hook traffic is replay-identifiable. */
2341
2643
  deliveryIdentifier: deliveryIdentifierSupportSchema
2342
2644
  });
2343
- var providerHookResponseSchema = z15.strictObject({
2645
+ var providerHookResponseSchema = z16.strictObject({
2344
2646
  /**
2345
2647
  * Always 0. A telemetry hook that can fail the host agent is a liability, so
2346
2648
  * the type forbids expressing anything else (ADR 0004).
2347
2649
  */
2348
- exitCode: z15.literal(0),
2650
+ exitCode: z16.literal(0),
2349
2651
  /** Protocol response text. Omit to write nothing at all. */
2350
- stdout: z15.string().max(8192).optional(),
2652
+ stdout: z16.string().max(8192).optional(),
2351
2653
  /** Non-sensitive diagnostic text for stderr. */
2352
- stderr: z15.string().max(8192).optional(),
2654
+ stderr: z16.string().max(8192).optional(),
2353
2655
  /** Declares which of the two stdout contracts this response follows. */
2354
- contract: z15.enum(["silent", "provider-protocol"])
2656
+ contract: z16.enum(["silent", "provider-protocol"])
2355
2657
  });
2356
2658
  var SILENT_HOOK_RESPONSE = Object.freeze({
2357
2659
  exitCode: 0,
@@ -2620,35 +2922,35 @@ var CLAUDE_CODE_CAPABILITIES = Object.freeze({
2620
2922
  });
2621
2923
 
2622
2924
  // src/providers/claude/schema.ts
2623
- import { z as z16 } from "zod";
2925
+ import { z as z17 } from "zod";
2624
2926
  var commonFields = {
2625
- session_id: z16.string().min(1),
2626
- transcript_path: z16.string().min(1).optional(),
2627
- cwd: z16.string().min(1).optional(),
2628
- permission_mode: z16.string().min(1).optional(),
2927
+ session_id: z17.string().min(1),
2928
+ transcript_path: z17.string().min(1).optional(),
2929
+ cwd: z17.string().min(1).optional(),
2930
+ permission_mode: z17.string().min(1).optional(),
2629
2931
  /** Correlates a hook firing with the user prompt that triggered it (Claude Code v2.1.196+). */
2630
- prompt_id: z16.string().min(1).optional(),
2932
+ prompt_id: z17.string().min(1).optional(),
2631
2933
  /** Present when the hook fired while running inside a subagent. */
2632
- agent_id: z16.string().min(1).optional(),
2633
- agent_type: z16.string().min(1).optional()
2634
- };
2635
- var claudeCacheCreationSchema = z16.object({
2636
- ephemeral_5m_input_tokens: z16.number().int().min(0).optional(),
2637
- ephemeral_1h_input_tokens: z16.number().int().min(0).optional()
2638
- });
2639
- var claudeUsageIterationSchema = z16.object({
2640
- input_tokens: z16.number().int().min(0).optional(),
2641
- output_tokens: z16.number().int().min(0).optional(),
2642
- cache_creation_input_tokens: z16.number().int().min(0).optional(),
2643
- cache_read_input_tokens: z16.number().int().min(0).optional()
2644
- });
2645
- var claudeUsageSchema = z16.object({
2646
- input_tokens: z16.number().int().min(0),
2647
- output_tokens: z16.number().int().min(0),
2648
- cache_creation_input_tokens: z16.number().int().min(0).optional(),
2649
- cache_read_input_tokens: z16.number().int().min(0).optional(),
2934
+ agent_id: z17.string().min(1).optional(),
2935
+ agent_type: z17.string().min(1).optional()
2936
+ };
2937
+ var claudeCacheCreationSchema = z17.object({
2938
+ ephemeral_5m_input_tokens: z17.number().int().min(0).optional(),
2939
+ ephemeral_1h_input_tokens: z17.number().int().min(0).optional()
2940
+ });
2941
+ var claudeUsageIterationSchema = z17.object({
2942
+ input_tokens: z17.number().int().min(0).optional(),
2943
+ output_tokens: z17.number().int().min(0).optional(),
2944
+ cache_creation_input_tokens: z17.number().int().min(0).optional(),
2945
+ cache_read_input_tokens: z17.number().int().min(0).optional()
2946
+ });
2947
+ var claudeUsageSchema = z17.object({
2948
+ input_tokens: z17.number().int().min(0),
2949
+ output_tokens: z17.number().int().min(0),
2950
+ cache_creation_input_tokens: z17.number().int().min(0).optional(),
2951
+ cache_read_input_tokens: z17.number().int().min(0).optional(),
2650
2952
  cache_creation: claudeCacheCreationSchema.optional(),
2651
- iterations: z16.array(claudeUsageIterationSchema).optional(),
2953
+ iterations: z17.array(claudeUsageIterationSchema).optional(),
2652
2954
  /**
2653
2955
  * Counters the canonical model has a home for but Claude Code never reports:
2654
2956
  * 0 of 4,999 real usage objects carried either (finding 5).
@@ -2657,112 +2959,112 @@ var claudeUsageSchema = z16.object({
2657
2959
  * that a harness attaching one gets told it was excluded, instead of watching
2658
2960
  * it vanish. See `CLAUDE_EXCLUDED_USAGE_COUNTERS`.
2659
2961
  */
2660
- total_tokens: z16.number().int().min(0).optional(),
2661
- reasoning_output_tokens: z16.number().int().min(0).optional()
2962
+ total_tokens: z17.number().int().min(0).optional(),
2963
+ reasoning_output_tokens: z17.number().int().min(0).optional()
2662
2964
  });
2663
- var sessionStartPayloadSchema = z16.object({
2965
+ var sessionStartPayloadSchema = z17.object({
2664
2966
  ...commonFields,
2665
- hook_event_name: z16.literal("SessionStart"),
2967
+ hook_event_name: z17.literal("SessionStart"),
2666
2968
  /** Matcher values: startup | resume | clear | compact | fork. Forward-compatible: any string. */
2667
- source: z16.string().min(1).optional(),
2668
- model: z16.string().min(1).optional(),
2669
- session_title: z16.string().min(1).optional()
2969
+ source: z17.string().min(1).optional(),
2970
+ model: z17.string().min(1).optional(),
2971
+ session_title: z17.string().min(1).optional()
2670
2972
  });
2671
- var sessionEndPayloadSchema = z16.object({
2973
+ var sessionEndPayloadSchema = z17.object({
2672
2974
  ...commonFields,
2673
- hook_event_name: z16.literal("SessionEnd"),
2975
+ hook_event_name: z17.literal("SessionEnd"),
2674
2976
  /** Current Claude Code field; values include clear, logout, prompt_input_exit, and other. */
2675
- reason: z16.string().min(1).optional(),
2977
+ reason: z17.string().min(1).optional(),
2676
2978
  /** Compatibility alias emitted by older wrappers and hook integrations. */
2677
- end_reason: z16.string().min(1).optional()
2979
+ end_reason: z17.string().min(1).optional()
2678
2980
  });
2679
- var userPromptSubmitPayloadSchema = z16.object({
2981
+ var userPromptSubmitPayloadSchema = z17.object({
2680
2982
  ...commonFields,
2681
- hook_event_name: z16.literal("UserPromptSubmit"),
2682
- prompt: z16.string()
2983
+ hook_event_name: z17.literal("UserPromptSubmit"),
2984
+ prompt: z17.string()
2683
2985
  });
2684
- var preToolUsePayloadSchema = z16.object({
2986
+ var preToolUsePayloadSchema = z17.object({
2685
2987
  ...commonFields,
2686
- hook_event_name: z16.literal("PreToolUse"),
2687
- tool_name: z16.string().min(1),
2688
- tool_input: z16.unknown(),
2689
- tool_use_id: z16.string().min(1)
2988
+ hook_event_name: z17.literal("PreToolUse"),
2989
+ tool_name: z17.string().min(1),
2990
+ tool_input: z17.unknown(),
2991
+ tool_use_id: z17.string().min(1)
2690
2992
  });
2691
- var postToolUsePayloadSchema = z16.object({
2993
+ var postToolUsePayloadSchema = z17.object({
2692
2994
  ...commonFields,
2693
- hook_event_name: z16.literal("PostToolUse"),
2694
- tool_name: z16.string().min(1),
2695
- tool_input: z16.unknown().optional(),
2696
- tool_response: z16.unknown(),
2697
- tool_use_id: z16.string().min(1)
2995
+ hook_event_name: z17.literal("PostToolUse"),
2996
+ tool_name: z17.string().min(1),
2997
+ tool_input: z17.unknown().optional(),
2998
+ tool_response: z17.unknown(),
2999
+ tool_use_id: z17.string().min(1)
2698
3000
  });
2699
- var postToolUseFailurePayloadSchema = z16.object({
3001
+ var postToolUseFailurePayloadSchema = z17.object({
2700
3002
  ...commonFields,
2701
- hook_event_name: z16.literal("PostToolUseFailure"),
2702
- tool_name: z16.string().min(1),
2703
- tool_input: z16.unknown().optional(),
2704
- tool_error: z16.unknown(),
2705
- tool_use_id: z16.string().min(1)
3003
+ hook_event_name: z17.literal("PostToolUseFailure"),
3004
+ tool_name: z17.string().min(1),
3005
+ tool_input: z17.unknown().optional(),
3006
+ tool_error: z17.unknown(),
3007
+ tool_use_id: z17.string().min(1)
2706
3008
  });
2707
- var permissionRequestPayloadSchema = z16.object({
3009
+ var permissionRequestPayloadSchema = z17.object({
2708
3010
  ...commonFields,
2709
- hook_event_name: z16.literal("PermissionRequest"),
2710
- tool_name: z16.string().min(1),
2711
- tool_input: z16.unknown().optional(),
2712
- tool_use_id: z16.string().min(1)
3011
+ hook_event_name: z17.literal("PermissionRequest"),
3012
+ tool_name: z17.string().min(1),
3013
+ tool_input: z17.unknown().optional(),
3014
+ tool_use_id: z17.string().min(1)
2713
3015
  });
2714
- var subagentStartPayloadSchema = z16.object({
3016
+ var subagentStartPayloadSchema = z17.object({
2715
3017
  ...commonFields,
2716
- hook_event_name: z16.literal("SubagentStart"),
2717
- agent_type: z16.string().min(1),
2718
- agent_id: z16.string().min(1)
3018
+ hook_event_name: z17.literal("SubagentStart"),
3019
+ agent_type: z17.string().min(1),
3020
+ agent_id: z17.string().min(1)
2719
3021
  });
2720
- var subagentStopPayloadSchema = z16.object({
3022
+ var subagentStopPayloadSchema = z17.object({
2721
3023
  ...commonFields,
2722
- hook_event_name: z16.literal("SubagentStop"),
2723
- agent_type: z16.string().min(1),
2724
- agent_id: z16.string().min(1),
2725
- last_assistant_message: z16.string().optional(),
3024
+ hook_event_name: z17.literal("SubagentStop"),
3025
+ agent_type: z17.string().min(1),
3026
+ agent_id: z17.string().min(1),
3027
+ last_assistant_message: z17.string().optional(),
2726
3028
  /** True when this stop fired because a hook continued the subagent's turn. */
2727
- stop_hook_active: z16.boolean().optional(),
3029
+ stop_hook_active: z17.boolean().optional(),
2728
3030
  usage: claudeUsageSchema.optional()
2729
3031
  });
2730
- var preCompactPayloadSchema = z16.object({
3032
+ var preCompactPayloadSchema = z17.object({
2731
3033
  ...commonFields,
2732
- hook_event_name: z16.literal("PreCompact"),
3034
+ hook_event_name: z17.literal("PreCompact"),
2733
3035
  /** Upstream values: manual | auto. Forward-compatible: any string. */
2734
- trigger: z16.string().min(1).optional(),
3036
+ trigger: z17.string().min(1).optional(),
2735
3037
  /** Compatibility alias emitted by older wrappers and hook integrations. */
2736
- compact_trigger: z16.string().min(1).optional(),
3038
+ compact_trigger: z17.string().min(1).optional(),
2737
3039
  /**
2738
3040
  * Harness-supplied, never upstream. Reported as an explicit exclusion rather
2739
3041
  * than carried across the process boundary: see `events.ts`.
2740
3042
  */
2741
- context_tokens_before: z16.number().int().min(0).optional(),
2742
- estimated_tokens_removed: z16.number().int().min(0).optional()
3043
+ context_tokens_before: z17.number().int().min(0).optional(),
3044
+ estimated_tokens_removed: z17.number().int().min(0).optional()
2743
3045
  });
2744
- var postCompactPayloadSchema = z16.object({
3046
+ var postCompactPayloadSchema = z17.object({
2745
3047
  ...commonFields,
2746
- hook_event_name: z16.literal("PostCompact"),
2747
- trigger: z16.string().min(1).optional(),
2748
- compact_trigger: z16.string().min(1).optional(),
3048
+ hook_event_name: z17.literal("PostCompact"),
3049
+ trigger: z17.string().min(1).optional(),
3050
+ compact_trigger: z17.string().min(1).optional(),
2749
3051
  /** Harness-supplied, never upstream; accepted here because one callback carries both. */
2750
- context_tokens_before: z16.number().int().min(0).optional(),
2751
- context_tokens_after: z16.number().int().min(0).optional(),
2752
- dropped_message_count: z16.number().int().min(0).optional(),
3052
+ context_tokens_before: z17.number().int().min(0).optional(),
3053
+ context_tokens_after: z17.number().int().min(0).optional(),
3054
+ dropped_message_count: z17.number().int().min(0).optional(),
2753
3055
  usage: claudeUsageSchema.optional()
2754
3056
  });
2755
- var stopPayloadSchema = z16.object({
3057
+ var stopPayloadSchema = z17.object({
2756
3058
  ...commonFields,
2757
- hook_event_name: z16.literal("Stop"),
3059
+ hook_event_name: z17.literal("Stop"),
2758
3060
  /**
2759
3061
  * Interactive Stop field (Claude Code ≥ 2.1.47). Print / `-p` / Agent SDK
2760
3062
  * result messages use `result` instead; `events.ts` reads both (and camelCase
2761
3063
  * `lastAssistantMessage`) through `extractClaudeAssistantText`.
2762
3064
  */
2763
- last_assistant_message: z16.string().optional(),
3065
+ last_assistant_message: z17.string().optional(),
2764
3066
  /** Print / `-p` JSON result field; accepted so a harness can attach it as-is. */
2765
- result: z16.string().optional(),
3067
+ result: z17.string().optional(),
2766
3068
  /**
2767
3069
  * True when this stop fired because a hook continued the turn.
2768
3070
  *
@@ -2770,22 +3072,22 @@ var stopPayloadSchema = z16.object({
2770
3072
  * stop from a continuation stop, which is what lets `delivery.ts` deduplicate
2771
3073
  * the former without suppressing the latter.
2772
3074
  */
2773
- stop_hook_active: z16.boolean().optional(),
3075
+ stop_hook_active: z17.boolean().optional(),
2774
3076
  usage: claudeUsageSchema.optional()
2775
3077
  });
2776
- var stopFailurePayloadSchema = z16.object({
3078
+ var stopFailurePayloadSchema = z17.object({
2777
3079
  ...commonFields,
2778
- hook_event_name: z16.literal("StopFailure"),
3080
+ hook_event_name: z17.literal("StopFailure"),
2779
3081
  /**
2780
3082
  * Matcher values: rate_limit | overloaded | authentication_failed |
2781
3083
  * oauth_org_not_allowed | billing_error | invalid_request | model_not_found
2782
3084
  * | server_error | max_output_tokens | unknown.
2783
3085
  */
2784
- error_type: z16.string().min(1),
2785
- error_message: z16.string().optional(),
3086
+ error_type: z17.string().min(1),
3087
+ error_message: z17.string().optional(),
2786
3088
  usage: claudeUsageSchema.optional()
2787
3089
  });
2788
- var claudeHookPayloadSchema = z16.discriminatedUnion("hook_event_name", [
3090
+ var claudeHookPayloadSchema = z17.discriminatedUnion("hook_event_name", [
2789
3091
  sessionStartPayloadSchema,
2790
3092
  sessionEndPayloadSchema,
2791
3093
  userPromptSubmitPayloadSchema,
@@ -2815,15 +3117,15 @@ var CLAUDE_HOOK_EVENT_NAMES = [
2815
3117
  "Stop",
2816
3118
  "StopFailure"
2817
3119
  ];
2818
- var claudeIdentityFieldsSchema = z16.object({
2819
- session_id: z16.string().min(1),
2820
- hook_event_name: z16.string().min(1),
2821
- cwd: z16.string().min(1).optional(),
2822
- prompt_id: z16.string().min(1).optional(),
2823
- agent_id: z16.string().min(1).optional(),
2824
- tool_use_id: z16.string().min(1).optional(),
3120
+ var claudeIdentityFieldsSchema = z17.object({
3121
+ session_id: z17.string().min(1),
3122
+ hook_event_name: z17.string().min(1),
3123
+ cwd: z17.string().min(1).optional(),
3124
+ prompt_id: z17.string().min(1).optional(),
3125
+ agent_id: z17.string().min(1).optional(),
3126
+ tool_use_id: z17.string().min(1).optional(),
2825
3127
  /** Read by `delivery.ts` to tell a once-per-prompt stop from a continuation. */
2826
- stop_hook_active: z16.boolean().optional()
3128
+ stop_hook_active: z17.boolean().optional()
2827
3129
  });
2828
3130
 
2829
3131
  // src/providers/claude/usage.ts
@@ -3564,7 +3866,7 @@ var createClaudeCodeAdapter = (options = {}) => ({
3564
3866
  });
3565
3867
 
3566
3868
  // src/providers/cursor/payload.ts
3567
- import { z as z17 } from "zod";
3869
+ import { z as z18 } from "zod";
3568
3870
  var CURSOR_PROVIDER_ID = "cursor";
3569
3871
  var CURSOR_HOOK_EVENT_NAMES = [
3570
3872
  "sessionStart",
@@ -3599,23 +3901,23 @@ var CURSOR_DECISION_EVENTS = Object.freeze({
3599
3901
  subagentStart: "permission",
3600
3902
  beforeSubmitPrompt: "continue"
3601
3903
  });
3602
- var modelParamSchema = z17.object({
3603
- id: z17.string(),
3604
- value: z17.string()
3904
+ var modelParamSchema = z18.object({
3905
+ id: z18.string(),
3906
+ value: z18.string()
3605
3907
  });
3606
- var attachmentSchema = z17.object({
3607
- type: z17.string().optional(),
3608
- file_path: z17.string().optional()
3908
+ var attachmentSchema = z18.object({
3909
+ type: z18.string().optional(),
3910
+ file_path: z18.string().optional()
3609
3911
  });
3610
- var fileEditSchema = z17.object({
3611
- old_string: z17.string().optional(),
3612
- new_string: z17.string().optional()
3912
+ var fileEditSchema = z18.object({
3913
+ old_string: z18.string().optional(),
3914
+ new_string: z18.string().optional()
3613
3915
  });
3614
3916
  var usageFields = {
3615
- input_tokens: z17.number().int().min(0).optional(),
3616
- output_tokens: z17.number().int().min(0).optional(),
3617
- cache_read_tokens: z17.number().int().min(0).optional(),
3618
- cache_write_tokens: z17.number().int().min(0).optional()
3917
+ input_tokens: z18.number().int().min(0).optional(),
3918
+ output_tokens: z18.number().int().min(0).optional(),
3919
+ cache_read_tokens: z18.number().int().min(0).optional(),
3920
+ cache_write_tokens: z18.number().int().min(0).optional()
3619
3921
  };
3620
3922
  var envelopeShape = {
3621
3923
  // Not `.min(1)`: see `cursorSessionId`. A payload naming neither
@@ -3623,136 +3925,136 @@ var envelopeShape = {
3623
3925
  // `recognizeCursorPayload`'s post-parse check — but rejecting it here would
3624
3926
  // fail the whole discriminated union on a field the adapter can source from
3625
3927
  // either name.
3626
- conversation_id: z17.string().optional(),
3627
- generation_id: z17.string().optional(),
3628
- session_id: z17.string().optional(),
3629
- model: z17.string().optional(),
3630
- model_id: z17.string().optional(),
3631
- model_params: z17.array(modelParamSchema).max(64).optional(),
3632
- cursor_version: z17.string().optional(),
3633
- workspace_roots: z17.array(z17.string()).max(64).optional(),
3634
- cwd: z17.string().optional(),
3928
+ conversation_id: z18.string().optional(),
3929
+ generation_id: z18.string().optional(),
3930
+ session_id: z18.string().optional(),
3931
+ model: z18.string().optional(),
3932
+ model_id: z18.string().optional(),
3933
+ model_params: z18.array(modelParamSchema).max(64).optional(),
3934
+ cursor_version: z18.string().optional(),
3935
+ workspace_roots: z18.array(z18.string()).max(64).optional(),
3936
+ cwd: z18.string().optional(),
3635
3937
  /** Never propagated. */
3636
- user_email: z17.string().nullish(),
3938
+ user_email: z18.string().nullish(),
3637
3939
  /** Never propagated. */
3638
- transcript_path: z17.string().nullish()
3940
+ transcript_path: z18.string().nullish()
3639
3941
  };
3640
- var event2 = (name, shape) => z17.object({ ...envelopeShape, hook_event_name: z17.literal(name), ...shape });
3942
+ var event2 = (name, shape) => z18.object({ ...envelopeShape, hook_event_name: z18.literal(name), ...shape });
3641
3943
  var sessionStartPayloadSchema2 = event2("sessionStart", {
3642
- is_background_agent: z17.boolean().optional(),
3643
- composer_mode: z17.string().optional()
3944
+ is_background_agent: z18.boolean().optional(),
3945
+ composer_mode: z18.string().optional()
3644
3946
  });
3645
3947
  var sessionEndPayloadSchema2 = event2("sessionEnd", {
3646
- reason: z17.string().optional(),
3647
- duration_ms: z17.number().min(0).optional(),
3648
- is_background_agent: z17.boolean().optional(),
3649
- final_status: z17.string().optional(),
3650
- error_message: z17.string().optional()
3948
+ reason: z18.string().optional(),
3949
+ duration_ms: z18.number().min(0).optional(),
3950
+ is_background_agent: z18.boolean().optional(),
3951
+ final_status: z18.string().optional(),
3952
+ error_message: z18.string().optional()
3651
3953
  });
3652
3954
  var beforeSubmitPromptPayloadSchema = event2("beforeSubmitPrompt", {
3653
- prompt: z17.string().optional(),
3654
- attachments: z17.array(attachmentSchema).max(256).optional(),
3655
- composer_mode: z17.string().optional()
3955
+ prompt: z18.string().optional(),
3956
+ attachments: z18.array(attachmentSchema).max(256).optional(),
3957
+ composer_mode: z18.string().optional()
3656
3958
  });
3657
3959
  var afterAgentResponsePayloadSchema = event2("afterAgentResponse", {
3658
- text: z17.string().optional(),
3960
+ text: z18.string().optional(),
3659
3961
  ...usageFields
3660
3962
  });
3661
3963
  var afterAgentThoughtPayloadSchema = event2("afterAgentThought", {
3662
- text: z17.string().optional(),
3663
- duration_ms: z17.number().min(0).optional()
3964
+ text: z18.string().optional(),
3965
+ duration_ms: z18.number().min(0).optional()
3664
3966
  });
3665
3967
  var preToolUsePayloadSchema2 = event2("preToolUse", {
3666
- tool_name: z17.string().min(1),
3667
- tool_input: z17.unknown().optional(),
3668
- tool_use_id: z17.string().optional(),
3669
- agent_message: z17.string().optional()
3968
+ tool_name: z18.string().min(1),
3969
+ tool_input: z18.unknown().optional(),
3970
+ tool_use_id: z18.string().optional(),
3971
+ agent_message: z18.string().optional()
3670
3972
  });
3671
3973
  var postToolUsePayloadSchema2 = event2("postToolUse", {
3672
- tool_name: z17.string().min(1),
3673
- tool_input: z17.unknown().optional(),
3674
- tool_output: z17.unknown().optional(),
3675
- tool_use_id: z17.string().optional(),
3676
- duration: z17.number().min(0).optional()
3974
+ tool_name: z18.string().min(1),
3975
+ tool_input: z18.unknown().optional(),
3976
+ tool_output: z18.unknown().optional(),
3977
+ tool_use_id: z18.string().optional(),
3978
+ duration: z18.number().min(0).optional()
3677
3979
  });
3678
3980
  var postToolUseFailurePayloadSchema2 = event2("postToolUseFailure", {
3679
- tool_name: z17.string().min(1),
3680
- tool_input: z17.unknown().optional(),
3681
- tool_use_id: z17.string().optional(),
3682
- error_message: z17.string().optional(),
3683
- failure_type: z17.string().optional(),
3684
- duration: z17.number().min(0).optional(),
3685
- is_interrupt: z17.boolean().optional()
3981
+ tool_name: z18.string().min(1),
3982
+ tool_input: z18.unknown().optional(),
3983
+ tool_use_id: z18.string().optional(),
3984
+ error_message: z18.string().optional(),
3985
+ failure_type: z18.string().optional(),
3986
+ duration: z18.number().min(0).optional(),
3987
+ is_interrupt: z18.boolean().optional()
3686
3988
  });
3687
3989
  var beforeShellExecutionPayloadSchema = event2("beforeShellExecution", {
3688
- command: z17.string(),
3689
- sandbox: z17.boolean().optional()
3990
+ command: z18.string(),
3991
+ sandbox: z18.boolean().optional()
3690
3992
  });
3691
3993
  var afterShellExecutionPayloadSchema = event2("afterShellExecution", {
3692
- command: z17.string(),
3693
- output: z17.string().optional(),
3694
- duration: z17.number().min(0).optional(),
3695
- sandbox: z17.boolean().optional()
3994
+ command: z18.string(),
3995
+ output: z18.string().optional(),
3996
+ duration: z18.number().min(0).optional(),
3997
+ sandbox: z18.boolean().optional()
3696
3998
  });
3697
3999
  var beforeMcpExecutionPayloadSchema = event2("beforeMCPExecution", {
3698
- tool_name: z17.string().min(1),
3699
- tool_input: z17.unknown().optional(),
3700
- url: z17.string().optional(),
3701
- command: z17.string().optional()
4000
+ tool_name: z18.string().min(1),
4001
+ tool_input: z18.unknown().optional(),
4002
+ url: z18.string().optional(),
4003
+ command: z18.string().optional()
3702
4004
  });
3703
4005
  var afterMcpExecutionPayloadSchema = event2("afterMCPExecution", {
3704
- tool_name: z17.string().min(1),
3705
- tool_input: z17.unknown().optional(),
3706
- result_json: z17.string().optional(),
3707
- duration: z17.number().min(0).optional()
4006
+ tool_name: z18.string().min(1),
4007
+ tool_input: z18.unknown().optional(),
4008
+ result_json: z18.string().optional(),
4009
+ duration: z18.number().min(0).optional()
3708
4010
  });
3709
4011
  var beforeReadFilePayloadSchema = event2("beforeReadFile", {
3710
- file_path: z17.string(),
3711
- content: z17.string().optional(),
3712
- attachments: z17.array(attachmentSchema).max(256).optional()
4012
+ file_path: z18.string(),
4013
+ content: z18.string().optional(),
4014
+ attachments: z18.array(attachmentSchema).max(256).optional()
3713
4015
  });
3714
4016
  var afterFileEditPayloadSchema = event2("afterFileEdit", {
3715
- file_path: z17.string(),
3716
- edits: z17.array(fileEditSchema).max(1024).optional()
4017
+ file_path: z18.string(),
4018
+ edits: z18.array(fileEditSchema).max(1024).optional()
3717
4019
  });
3718
4020
  var subagentStartPayloadSchema2 = event2("subagentStart", {
3719
- subagent_id: z17.string().optional(),
3720
- subagent_type: z17.string().optional(),
3721
- task: z17.string().optional(),
3722
- parent_conversation_id: z17.string().optional(),
3723
- tool_call_id: z17.string().optional(),
3724
- subagent_model: z17.string().optional(),
3725
- is_parallel_worker: z17.boolean().optional(),
3726
- git_branch: z17.string().optional()
4021
+ subagent_id: z18.string().optional(),
4022
+ subagent_type: z18.string().optional(),
4023
+ task: z18.string().optional(),
4024
+ parent_conversation_id: z18.string().optional(),
4025
+ tool_call_id: z18.string().optional(),
4026
+ subagent_model: z18.string().optional(),
4027
+ is_parallel_worker: z18.boolean().optional(),
4028
+ git_branch: z18.string().optional()
3727
4029
  });
3728
4030
  var subagentStopPayloadSchema2 = event2("subagentStop", {
3729
- subagent_type: z17.string().optional(),
3730
- status: z17.string().optional(),
3731
- task: z17.string().optional(),
3732
- description: z17.string().optional(),
3733
- summary: z17.string().optional(),
3734
- duration_ms: z17.number().min(0).optional(),
3735
- message_count: z17.number().int().min(0).optional(),
3736
- tool_call_count: z17.number().int().min(0).optional(),
3737
- loop_count: z17.number().int().min(0).optional(),
3738
- modified_files: z17.array(z17.string()).max(1024).optional(),
3739
- agent_transcript_path: z17.string().nullish()
4031
+ subagent_type: z18.string().optional(),
4032
+ status: z18.string().optional(),
4033
+ task: z18.string().optional(),
4034
+ description: z18.string().optional(),
4035
+ summary: z18.string().optional(),
4036
+ duration_ms: z18.number().min(0).optional(),
4037
+ message_count: z18.number().int().min(0).optional(),
4038
+ tool_call_count: z18.number().int().min(0).optional(),
4039
+ loop_count: z18.number().int().min(0).optional(),
4040
+ modified_files: z18.array(z18.string()).max(1024).optional(),
4041
+ agent_transcript_path: z18.string().nullish()
3740
4042
  });
3741
4043
  var preCompactPayloadSchema2 = event2("preCompact", {
3742
- trigger: z17.string().optional(),
3743
- context_usage_percent: z17.number().optional(),
3744
- context_tokens: z17.number().int().min(0).optional(),
3745
- context_window_size: z17.number().int().min(0).optional(),
3746
- message_count: z17.number().int().min(0).optional(),
3747
- messages_to_compact: z17.number().int().min(0).optional(),
3748
- is_first_compaction: z17.boolean().optional()
4044
+ trigger: z18.string().optional(),
4045
+ context_usage_percent: z18.number().optional(),
4046
+ context_tokens: z18.number().int().min(0).optional(),
4047
+ context_window_size: z18.number().int().min(0).optional(),
4048
+ message_count: z18.number().int().min(0).optional(),
4049
+ messages_to_compact: z18.number().int().min(0).optional(),
4050
+ is_first_compaction: z18.boolean().optional()
3749
4051
  });
3750
4052
  var stopPayloadSchema2 = event2("stop", {
3751
- status: z17.string().optional(),
3752
- loop_count: z17.number().int().min(0).optional(),
4053
+ status: z18.string().optional(),
4054
+ loop_count: z18.number().int().min(0).optional(),
3753
4055
  ...usageFields
3754
4056
  });
3755
- var cursorPayloadSchema = z17.discriminatedUnion("hook_event_name", [
4057
+ var cursorPayloadSchema = z18.discriminatedUnion("hook_event_name", [
3756
4058
  sessionStartPayloadSchema2,
3757
4059
  sessionEndPayloadSchema2,
3758
4060
  beforeSubmitPromptPayloadSchema,
@@ -4528,105 +4830,105 @@ var createCursorAdapter = (options = {}) => {
4528
4830
  };
4529
4831
 
4530
4832
  // src/providers/codex/payload.ts
4531
- import { z as z18 } from "zod";
4532
- var permissionModeSchema = z18.enum([
4833
+ import { z as z19 } from "zod";
4834
+ var permissionModeSchema = z19.enum([
4533
4835
  "default",
4534
4836
  "acceptEdits",
4535
4837
  "plan",
4536
4838
  "dontAsk",
4537
4839
  "bypassPermissions"
4538
4840
  ]);
4539
- var codexUsageSchema = z18.object({
4540
- input_tokens: z18.number().int().min(0).optional(),
4541
- cached_input_tokens: z18.number().int().min(0).optional(),
4542
- output_tokens: z18.number().int().min(0).optional(),
4543
- reasoning_output_tokens: z18.number().int().min(0).optional(),
4544
- total_tokens: z18.number().int().min(0).optional()
4841
+ var codexUsageSchema = z19.object({
4842
+ input_tokens: z19.number().int().min(0).optional(),
4843
+ cached_input_tokens: z19.number().int().min(0).optional(),
4844
+ output_tokens: z19.number().int().min(0).optional(),
4845
+ reasoning_output_tokens: z19.number().int().min(0).optional(),
4846
+ total_tokens: z19.number().int().min(0).optional()
4545
4847
  });
4546
4848
  var baseFields = {
4547
- session_id: z18.string().min(1).max(256),
4548
- cwd: z18.string().min(1).max(4096).optional(),
4549
- model: z18.string().min(1).max(256).optional(),
4849
+ session_id: z19.string().min(1).max(256),
4850
+ cwd: z19.string().min(1).max(4096).optional(),
4851
+ model: z19.string().min(1).max(256).optional(),
4550
4852
  permission_mode: permissionModeSchema.optional(),
4551
- transcript_path: z18.string().min(1).max(4096).optional(),
4552
- codex_version: z18.string().min(1).max(64).optional(),
4853
+ transcript_path: z19.string().min(1).max(4096).optional(),
4854
+ codex_version: z19.string().min(1).max(64).optional(),
4553
4855
  /** Not part of the documented protocol; lets tests and replay stay deterministic. */
4554
- occurred_at: z18.number().int().min(0).optional()
4856
+ occurred_at: z19.number().int().min(0).optional()
4555
4857
  };
4556
- var codexSessionStartPayloadSchema = z18.object({
4858
+ var codexSessionStartPayloadSchema = z19.object({
4557
4859
  ...baseFields,
4558
- hook_event_name: z18.literal("SessionStart"),
4559
- source: z18.enum(["startup", "resume", "clear", "compact"]).optional()
4860
+ hook_event_name: z19.literal("SessionStart"),
4861
+ source: z19.enum(["startup", "resume", "clear", "compact"]).optional()
4560
4862
  });
4561
- var codexUserPromptSubmitPayloadSchema = z18.object({
4863
+ var codexUserPromptSubmitPayloadSchema = z19.object({
4562
4864
  ...baseFields,
4563
- hook_event_name: z18.literal("UserPromptSubmit"),
4564
- turn_id: z18.string().min(1).max(256).optional(),
4565
- prompt: z18.string().max(1e6).optional()
4865
+ hook_event_name: z19.literal("UserPromptSubmit"),
4866
+ turn_id: z19.string().min(1).max(256).optional(),
4867
+ prompt: z19.string().max(1e6).optional()
4566
4868
  });
4567
- var codexPreToolUsePayloadSchema = z18.object({
4869
+ var codexPreToolUsePayloadSchema = z19.object({
4568
4870
  ...baseFields,
4569
- hook_event_name: z18.literal("PreToolUse"),
4570
- turn_id: z18.string().min(1).max(256).optional(),
4571
- tool_name: z18.string().min(1).max(256),
4572
- tool_call_id: z18.string().min(1).max(256).optional(),
4573
- tool_input: z18.unknown().optional()
4871
+ hook_event_name: z19.literal("PreToolUse"),
4872
+ turn_id: z19.string().min(1).max(256).optional(),
4873
+ tool_name: z19.string().min(1).max(256),
4874
+ tool_call_id: z19.string().min(1).max(256).optional(),
4875
+ tool_input: z19.unknown().optional()
4574
4876
  });
4575
- var codexPermissionRequestPayloadSchema = z18.object({
4877
+ var codexPermissionRequestPayloadSchema = z19.object({
4576
4878
  ...baseFields,
4577
- hook_event_name: z18.literal("PermissionRequest"),
4578
- turn_id: z18.string().min(1).max(256).optional(),
4579
- tool_name: z18.string().min(1).max(256).optional(),
4580
- tool_call_id: z18.string().min(1).max(256).optional(),
4581
- tool_input: z18.unknown().optional()
4879
+ hook_event_name: z19.literal("PermissionRequest"),
4880
+ turn_id: z19.string().min(1).max(256).optional(),
4881
+ tool_name: z19.string().min(1).max(256).optional(),
4882
+ tool_call_id: z19.string().min(1).max(256).optional(),
4883
+ tool_input: z19.unknown().optional()
4582
4884
  });
4583
- var codexPostToolUsePayloadSchema = z18.object({
4885
+ var codexPostToolUsePayloadSchema = z19.object({
4584
4886
  ...baseFields,
4585
- hook_event_name: z18.literal("PostToolUse"),
4586
- turn_id: z18.string().min(1).max(256).optional(),
4587
- tool_name: z18.string().min(1).max(256),
4588
- tool_call_id: z18.string().min(1).max(256).optional(),
4589
- tool_input: z18.unknown().optional(),
4590
- tool_response: z18.unknown().optional(),
4591
- permission_decision: z18.enum(["allowed", "denied", "deferred"]).optional(),
4592
- duration_ms: z18.number().min(0).optional()
4887
+ hook_event_name: z19.literal("PostToolUse"),
4888
+ turn_id: z19.string().min(1).max(256).optional(),
4889
+ tool_name: z19.string().min(1).max(256),
4890
+ tool_call_id: z19.string().min(1).max(256).optional(),
4891
+ tool_input: z19.unknown().optional(),
4892
+ tool_response: z19.unknown().optional(),
4893
+ permission_decision: z19.enum(["allowed", "denied", "deferred"]).optional(),
4894
+ duration_ms: z19.number().min(0).optional()
4593
4895
  });
4594
- var codexPreCompactPayloadSchema = z18.object({
4896
+ var codexPreCompactPayloadSchema = z19.object({
4595
4897
  ...baseFields,
4596
- hook_event_name: z18.literal("PreCompact"),
4597
- trigger: z18.enum(["auto", "manual"]).optional(),
4598
- context_tokens_before: z18.number().int().min(0).optional()
4898
+ hook_event_name: z19.literal("PreCompact"),
4899
+ trigger: z19.enum(["auto", "manual"]).optional(),
4900
+ context_tokens_before: z19.number().int().min(0).optional()
4599
4901
  });
4600
- var codexPostCompactPayloadSchema = z18.object({
4902
+ var codexPostCompactPayloadSchema = z19.object({
4601
4903
  ...baseFields,
4602
- hook_event_name: z18.literal("PostCompact"),
4603
- trigger: z18.enum(["auto", "manual"]).optional(),
4604
- context_tokens_after: z18.number().int().min(0).optional(),
4605
- dropped_message_count: z18.number().int().min(0).optional(),
4904
+ hook_event_name: z19.literal("PostCompact"),
4905
+ trigger: z19.enum(["auto", "manual"]).optional(),
4906
+ context_tokens_after: z19.number().int().min(0).optional(),
4907
+ dropped_message_count: z19.number().int().min(0).optional(),
4606
4908
  usage: codexUsageSchema.optional()
4607
4909
  });
4608
- var codexSubagentStartPayloadSchema = z18.object({
4910
+ var codexSubagentStartPayloadSchema = z19.object({
4609
4911
  ...baseFields,
4610
- hook_event_name: z18.literal("SubagentStart"),
4611
- turn_id: z18.string().min(1).max(256).optional(),
4612
- subagent_id: z18.string().min(1).max(256),
4613
- subagent_type: z18.string().min(1).max(256).optional()
4912
+ hook_event_name: z19.literal("SubagentStart"),
4913
+ turn_id: z19.string().min(1).max(256).optional(),
4914
+ subagent_id: z19.string().min(1).max(256),
4915
+ subagent_type: z19.string().min(1).max(256).optional()
4614
4916
  });
4615
- var codexSubagentStopPayloadSchema = z18.object({
4917
+ var codexSubagentStopPayloadSchema = z19.object({
4616
4918
  ...baseFields,
4617
- hook_event_name: z18.literal("SubagentStop"),
4618
- turn_id: z18.string().min(1).max(256).optional(),
4619
- subagent_id: z18.string().min(1).max(256),
4620
- status: z18.enum(["completed", "failed", "cancelled"]).optional(),
4919
+ hook_event_name: z19.literal("SubagentStop"),
4920
+ turn_id: z19.string().min(1).max(256).optional(),
4921
+ subagent_id: z19.string().min(1).max(256),
4922
+ status: z19.enum(["completed", "failed", "cancelled"]).optional(),
4621
4923
  usage: codexUsageSchema.optional()
4622
4924
  });
4623
- var codexStopPayloadSchema = z18.object({
4925
+ var codexStopPayloadSchema = z19.object({
4624
4926
  ...baseFields,
4625
- hook_event_name: z18.literal("Stop"),
4626
- turn_id: z18.string().min(1).max(256).optional(),
4627
- stop_reason: z18.string().min(1).max(256).optional(),
4927
+ hook_event_name: z19.literal("Stop"),
4928
+ turn_id: z19.string().min(1).max(256).optional(),
4929
+ stop_reason: z19.string().min(1).max(256).optional(),
4628
4930
  usage: codexUsageSchema.optional(),
4629
- duration_ms: z18.number().min(0).optional()
4931
+ duration_ms: z19.number().min(0).optional()
4630
4932
  });
4631
4933
  var CODEX_HOOK_EVENT_NAMES = [
4632
4934
  "SessionStart",
@@ -4640,7 +4942,7 @@ var CODEX_HOOK_EVENT_NAMES = [
4640
4942
  "SubagentStop",
4641
4943
  "Stop"
4642
4944
  ];
4643
- var codexHookPayloadSchema = z18.discriminatedUnion("hook_event_name", [
4945
+ var codexHookPayloadSchema = z19.discriminatedUnion("hook_event_name", [
4644
4946
  codexSessionStartPayloadSchema,
4645
4947
  codexUserPromptSubmitPayloadSchema,
4646
4948
  codexPreToolUsePayloadSchema,
@@ -4652,9 +4954,9 @@ var codexHookPayloadSchema = z18.discriminatedUnion("hook_event_name", [
4652
4954
  codexSubagentStopPayloadSchema,
4653
4955
  codexStopPayloadSchema
4654
4956
  ]);
4655
- var codexHookEnvelopeSchema = z18.object({
4656
- session_id: z18.string().min(1),
4657
- hook_event_name: z18.enum(CODEX_HOOK_EVENT_NAMES)
4957
+ var codexHookEnvelopeSchema = z19.object({
4958
+ session_id: z19.string().min(1),
4959
+ hook_event_name: z19.enum(CODEX_HOOK_EVENT_NAMES)
4658
4960
  });
4659
4961
 
4660
4962
  // src/providers/codex/delivery.ts
@@ -5273,7 +5575,7 @@ var geminiCorrelationSeed = (input) => {
5273
5575
  };
5274
5576
 
5275
5577
  // src/providers/gemini/schema.ts
5276
- import { z as z19 } from "zod";
5578
+ import { z as z20 } from "zod";
5277
5579
  var GEMINI_HOOK_EVENT_NAMES = [
5278
5580
  "SessionStart",
5279
5581
  "SessionEnd",
@@ -5287,113 +5589,113 @@ var GEMINI_HOOK_EVENT_NAMES = [
5287
5589
  "PreCompress",
5288
5590
  "Notification"
5289
5591
  ];
5290
- var baseHookInputSchema = z19.object({
5291
- session_id: z19.string().min(1),
5292
- transcript_path: z19.string().optional(),
5293
- cwd: z19.string().optional(),
5294
- timestamp: z19.string().min(1).optional()
5295
- });
5296
- var llmMessageSchema = z19.object({
5297
- role: z19.enum(["user", "model", "system"]).optional(),
5298
- content: z19.union([z19.string(), z19.array(z19.unknown())]).optional()
5592
+ var baseHookInputSchema = z20.object({
5593
+ session_id: z20.string().min(1),
5594
+ transcript_path: z20.string().optional(),
5595
+ cwd: z20.string().optional(),
5596
+ timestamp: z20.string().min(1).optional()
5597
+ });
5598
+ var llmMessageSchema = z20.object({
5599
+ role: z20.enum(["user", "model", "system"]).optional(),
5600
+ content: z20.union([z20.string(), z20.array(z20.unknown())]).optional()
5299
5601
  }).loose();
5300
- var llmRequestConfigSchema = z19.object({
5301
- temperature: z19.number().optional(),
5302
- maxOutputTokens: z19.number().int().min(0).optional()
5602
+ var llmRequestConfigSchema = z20.object({
5603
+ temperature: z20.number().optional(),
5604
+ maxOutputTokens: z20.number().int().min(0).optional()
5303
5605
  }).loose();
5304
- var geminiLlmRequestSchema = z19.object({
5305
- model: z19.string().min(1).optional(),
5306
- messages: z19.array(llmMessageSchema).optional(),
5606
+ var geminiLlmRequestSchema = z20.object({
5607
+ model: z20.string().min(1).optional(),
5608
+ messages: z20.array(llmMessageSchema).optional(),
5307
5609
  config: llmRequestConfigSchema.optional(),
5308
- toolConfig: z19.unknown().optional()
5610
+ toolConfig: z20.unknown().optional()
5309
5611
  }).loose();
5310
- var geminiUsageMetadataSchema = z19.object({
5311
- promptTokenCount: z19.number().int().min(0).optional(),
5312
- cachedContentTokenCount: z19.number().int().min(0).optional(),
5313
- candidatesTokenCount: z19.number().int().min(0).optional(),
5314
- thoughtsTokenCount: z19.number().int().min(0).optional(),
5315
- totalTokenCount: z19.number().int().min(0).optional()
5612
+ var geminiUsageMetadataSchema = z20.object({
5613
+ promptTokenCount: z20.number().int().min(0).optional(),
5614
+ cachedContentTokenCount: z20.number().int().min(0).optional(),
5615
+ candidatesTokenCount: z20.number().int().min(0).optional(),
5616
+ thoughtsTokenCount: z20.number().int().min(0).optional(),
5617
+ totalTokenCount: z20.number().int().min(0).optional()
5316
5618
  }).loose();
5317
- var geminiCandidateSchema = z19.object({
5318
- content: z19.object({
5319
- role: z19.string().optional(),
5320
- parts: z19.array(z19.unknown()).optional()
5619
+ var geminiCandidateSchema = z20.object({
5620
+ content: z20.object({
5621
+ role: z20.string().optional(),
5622
+ parts: z20.array(z20.unknown()).optional()
5321
5623
  }).loose().optional(),
5322
- finishReason: z19.string().optional(),
5323
- index: z19.number().int().min(0).optional()
5624
+ finishReason: z20.string().optional(),
5625
+ index: z20.number().int().min(0).optional()
5324
5626
  }).loose();
5325
- var geminiLlmResponseSchema = z19.object({
5627
+ var geminiLlmResponseSchema = z20.object({
5326
5628
  /** Whole-response text, set by the translator from `getResponseText`. */
5327
- text: z19.string().optional(),
5328
- candidates: z19.array(geminiCandidateSchema).optional(),
5629
+ text: z20.string().optional(),
5630
+ candidates: z20.array(geminiCandidateSchema).optional(),
5329
5631
  usageMetadata: geminiUsageMetadataSchema.optional()
5330
5632
  }).loose();
5331
- var geminiMcpContextSchema = z19.object({
5332
- server_name: z19.string().optional(),
5333
- tool_name: z19.string().optional()
5633
+ var geminiMcpContextSchema = z20.object({
5634
+ server_name: z20.string().optional(),
5635
+ tool_name: z20.string().optional()
5334
5636
  }).loose();
5335
- var geminiToolResponseSchema = z19.object({
5336
- llmContent: z19.unknown().optional(),
5337
- returnDisplay: z19.unknown().optional(),
5338
- error: z19.unknown().optional()
5637
+ var geminiToolResponseSchema = z20.object({
5638
+ llmContent: z20.unknown().optional(),
5639
+ returnDisplay: z20.unknown().optional(),
5640
+ error: z20.unknown().optional()
5339
5641
  }).loose();
5340
5642
  var sessionStartInputSchema = baseHookInputSchema.extend({
5341
- hook_event_name: z19.literal("SessionStart"),
5342
- source: z19.enum(["startup", "resume", "clear"]).optional()
5643
+ hook_event_name: z20.literal("SessionStart"),
5644
+ source: z20.enum(["startup", "resume", "clear"]).optional()
5343
5645
  });
5344
5646
  var sessionEndInputSchema = baseHookInputSchema.extend({
5345
- hook_event_name: z19.literal("SessionEnd"),
5346
- reason: z19.enum(["exit", "clear", "logout", "prompt_input_exit", "other"]).optional()
5647
+ hook_event_name: z20.literal("SessionEnd"),
5648
+ reason: z20.enum(["exit", "clear", "logout", "prompt_input_exit", "other"]).optional()
5347
5649
  });
5348
5650
  var beforeAgentInputSchema = baseHookInputSchema.extend({
5349
- hook_event_name: z19.literal("BeforeAgent"),
5350
- prompt: z19.string().optional()
5651
+ hook_event_name: z20.literal("BeforeAgent"),
5652
+ prompt: z20.string().optional()
5351
5653
  });
5352
5654
  var afterAgentInputSchema = baseHookInputSchema.extend({
5353
- hook_event_name: z19.literal("AfterAgent"),
5354
- prompt: z19.string().optional(),
5355
- prompt_response: z19.string().optional(),
5356
- stop_hook_active: z19.boolean().optional()
5655
+ hook_event_name: z20.literal("AfterAgent"),
5656
+ prompt: z20.string().optional(),
5657
+ prompt_response: z20.string().optional(),
5658
+ stop_hook_active: z20.boolean().optional()
5357
5659
  });
5358
5660
  var beforeModelInputSchema = baseHookInputSchema.extend({
5359
- hook_event_name: z19.literal("BeforeModel"),
5661
+ hook_event_name: z20.literal("BeforeModel"),
5360
5662
  llm_request: geminiLlmRequestSchema
5361
5663
  });
5362
5664
  var afterModelInputSchema = baseHookInputSchema.extend({
5363
- hook_event_name: z19.literal("AfterModel"),
5665
+ hook_event_name: z20.literal("AfterModel"),
5364
5666
  llm_request: geminiLlmRequestSchema,
5365
5667
  llm_response: geminiLlmResponseSchema
5366
5668
  });
5367
5669
  var beforeToolSelectionInputSchema = baseHookInputSchema.extend({
5368
- hook_event_name: z19.literal("BeforeToolSelection"),
5670
+ hook_event_name: z20.literal("BeforeToolSelection"),
5369
5671
  llm_request: geminiLlmRequestSchema
5370
5672
  });
5371
5673
  var beforeToolInputSchema = baseHookInputSchema.extend({
5372
- hook_event_name: z19.literal("BeforeTool"),
5373
- tool_name: z19.string().min(1),
5374
- tool_input: z19.unknown().optional(),
5674
+ hook_event_name: z20.literal("BeforeTool"),
5675
+ tool_name: z20.string().min(1),
5676
+ tool_input: z20.unknown().optional(),
5375
5677
  mcp_context: geminiMcpContextSchema.optional(),
5376
- original_request_name: z19.string().min(1).optional()
5678
+ original_request_name: z20.string().min(1).optional()
5377
5679
  });
5378
5680
  var afterToolInputSchema = baseHookInputSchema.extend({
5379
- hook_event_name: z19.literal("AfterTool"),
5380
- tool_name: z19.string().min(1),
5381
- tool_input: z19.unknown().optional(),
5681
+ hook_event_name: z20.literal("AfterTool"),
5682
+ tool_name: z20.string().min(1),
5683
+ tool_input: z20.unknown().optional(),
5382
5684
  tool_response: geminiToolResponseSchema.optional(),
5383
5685
  mcp_context: geminiMcpContextSchema.optional(),
5384
- original_request_name: z19.string().min(1).optional()
5686
+ original_request_name: z20.string().min(1).optional()
5385
5687
  });
5386
5688
  var preCompressInputSchema = baseHookInputSchema.extend({
5387
- hook_event_name: z19.literal("PreCompress"),
5388
- trigger: z19.enum(["auto", "manual"]).optional()
5689
+ hook_event_name: z20.literal("PreCompress"),
5690
+ trigger: z20.enum(["auto", "manual"]).optional()
5389
5691
  });
5390
5692
  var notificationInputSchema = baseHookInputSchema.extend({
5391
- hook_event_name: z19.literal("Notification"),
5392
- notification_type: z19.string().optional(),
5393
- message: z19.string().optional(),
5394
- details: z19.unknown().optional()
5693
+ hook_event_name: z20.literal("Notification"),
5694
+ notification_type: z20.string().optional(),
5695
+ message: z20.string().optional(),
5696
+ details: z20.unknown().optional()
5395
5697
  });
5396
- var geminiHookInputSchema = z19.discriminatedUnion("hook_event_name", [
5698
+ var geminiHookInputSchema = z20.discriminatedUnion("hook_event_name", [
5397
5699
  sessionStartInputSchema,
5398
5700
  sessionEndInputSchema,
5399
5701
  beforeAgentInputSchema,
@@ -5838,7 +6140,7 @@ var normalizeUsageOrWarn = (usage, warnings) => {
5838
6140
  };
5839
6141
 
5840
6142
  // src/providers/antigravity/payload.ts
5841
- import { z as z20 } from "zod";
6143
+ import { z as z21 } from "zod";
5842
6144
  var ANTIGRAVITY_HOOK_EVENT_NAMES = [
5843
6145
  "PreInvocation",
5844
6146
  "PostInvocation",
@@ -5846,48 +6148,48 @@ var ANTIGRAVITY_HOOK_EVENT_NAMES = [
5846
6148
  "PostToolUse",
5847
6149
  "Stop"
5848
6150
  ];
5849
- var hookEventNameSchema = z20.enum(ANTIGRAVITY_HOOK_EVENT_NAMES);
5850
- var antigravityWeakShapeSchema = z20.object({ hookEventName: hookEventNameSchema }).passthrough();
6151
+ var hookEventNameSchema = z21.enum(ANTIGRAVITY_HOOK_EVENT_NAMES);
6152
+ var antigravityWeakShapeSchema = z21.object({ hookEventName: hookEventNameSchema }).passthrough();
5851
6153
  var commonFields2 = {
5852
- conversationId: z20.string().min(1),
5853
- workspacePaths: z20.array(z20.string().min(1)).max(64),
5854
- invocationNum: z20.number().int().min(0),
6154
+ conversationId: z21.string().min(1),
6155
+ workspacePaths: z21.array(z21.string().min(1)).max(64),
6156
+ invocationNum: z21.number().int().min(0),
5855
6157
  /** Never disclosed: a real filesystem path. Accepted, never propagated. */
5856
- transcriptPath: z20.string().min(1).optional(),
6158
+ transcriptPath: z21.string().min(1).optional(),
5857
6159
  /** Never disclosed: a real filesystem path. Accepted, never propagated. */
5858
- artifactDirectoryPath: z20.string().min(1).optional()
6160
+ artifactDirectoryPath: z21.string().min(1).optional()
5859
6161
  };
5860
- var preInvocationPayloadSchema = z20.object({
5861
- hookEventName: z20.literal("PreInvocation"),
6162
+ var preInvocationPayloadSchema = z21.object({
6163
+ hookEventName: z21.literal("PreInvocation"),
5862
6164
  ...commonFields2,
5863
- agentVersion: z20.string().min(1).optional()
6165
+ agentVersion: z21.string().min(1).optional()
5864
6166
  });
5865
- var postInvocationPayloadSchema = z20.object({
5866
- hookEventName: z20.literal("PostInvocation"),
6167
+ var postInvocationPayloadSchema = z21.object({
6168
+ hookEventName: z21.literal("PostInvocation"),
5867
6169
  ...commonFields2,
5868
- agentVersion: z20.string().min(1).optional()
6170
+ agentVersion: z21.string().min(1).optional()
5869
6171
  });
5870
- var preToolUsePayloadSchema3 = z20.object({
5871
- hookEventName: z20.literal("PreToolUse"),
6172
+ var preToolUsePayloadSchema3 = z21.object({
6173
+ hookEventName: z21.literal("PreToolUse"),
5872
6174
  ...commonFields2,
5873
- stepIdx: z20.number().int().min(0),
5874
- toolName: z20.string().min(1),
5875
- toolInput: z20.unknown().optional()
6175
+ stepIdx: z21.number().int().min(0),
6176
+ toolName: z21.string().min(1),
6177
+ toolInput: z21.unknown().optional()
5876
6178
  });
5877
- var postToolUsePayloadSchema3 = z20.object({
5878
- hookEventName: z20.literal("PostToolUse"),
6179
+ var postToolUsePayloadSchema3 = z21.object({
6180
+ hookEventName: z21.literal("PostToolUse"),
5879
6181
  ...commonFields2,
5880
- stepIdx: z20.number().int().min(0),
5881
- toolName: z20.string().min(1),
5882
- toolResponse: z20.unknown().optional(),
5883
- isError: z20.boolean().optional()
6182
+ stepIdx: z21.number().int().min(0),
6183
+ toolName: z21.string().min(1),
6184
+ toolResponse: z21.unknown().optional(),
6185
+ isError: z21.boolean().optional()
5884
6186
  });
5885
- var stopPayloadSchema3 = z20.object({
5886
- hookEventName: z20.literal("Stop"),
6187
+ var stopPayloadSchema3 = z21.object({
6188
+ hookEventName: z21.literal("Stop"),
5887
6189
  ...commonFields2,
5888
- fullyIdle: z20.boolean()
6190
+ fullyIdle: z21.boolean()
5889
6191
  });
5890
- var antigravityHookPayloadSchema = z20.discriminatedUnion("hookEventName", [
6192
+ var antigravityHookPayloadSchema = z21.discriminatedUnion("hookEventName", [
5891
6193
  preInvocationPayloadSchema,
5892
6194
  postInvocationPayloadSchema,
5893
6195
  preToolUsePayloadSchema3,
@@ -6201,15 +6503,15 @@ var describeProviderCatalog = (options = {}) => {
6201
6503
  };
6202
6504
 
6203
6505
  // src/runtime/ports.ts
6204
- import { z as z21 } from "zod";
6205
- var appliedDeliverySchema = z21.strictObject({
6206
- callbackId: z21.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
6506
+ import { z as z22 } from "zod";
6507
+ var appliedDeliverySchema = z22.strictObject({
6508
+ callbackId: z22.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
6207
6509
  /** How many of that delivery's observations are folded in, counted from one. */
6208
- applications: z21.number().int().min(1).max(4096)
6510
+ applications: z22.number().int().min(1).max(4096)
6209
6511
  });
6210
- var stateValueSchema = z21.discriminatedUnion("kind", [
6211
- z21.strictObject({
6212
- kind: z21.literal("usage-cumulative"),
6512
+ var stateValueSchema = z22.discriminatedUnion("kind", [
6513
+ z22.strictObject({
6514
+ kind: z22.literal("usage-cumulative"),
6213
6515
  usage: canonicalUsageSchema,
6214
6516
  /**
6215
6517
  * Optional: absent on every record written before this field existed, which
@@ -6218,22 +6520,22 @@ var stateValueSchema = z21.discriminatedUnion("kind", [
6218
6520
  */
6219
6521
  appliedDelivery: appliedDeliverySchema.optional()
6220
6522
  }),
6221
- z21.strictObject({
6222
- kind: z21.literal("sequence"),
6523
+ z22.strictObject({
6524
+ kind: z22.literal("sequence"),
6223
6525
  next: sequenceNumberSchema
6224
6526
  }),
6225
- z21.strictObject({
6226
- kind: z21.literal("attributes"),
6527
+ z22.strictObject({
6528
+ kind: z22.literal("attributes"),
6227
6529
  attributes: attributesSchema
6228
6530
  })
6229
6531
  ]);
6230
- var stateRecordSchema = z21.strictObject({
6532
+ var stateRecordSchema = z22.strictObject({
6231
6533
  /** Incremented on each write; lets callers detect lost updates. */
6232
- revision: z21.number().int().min(0),
6534
+ revision: z22.number().int().min(0),
6233
6535
  updatedAt: epochMillisSchema,
6234
6536
  value: stateValueSchema
6235
6537
  });
6236
- var logLevelSchema = z21.enum(["silent", "error", "warn", "info", "debug"]);
6538
+ var logLevelSchema = z22.enum(["silent", "error", "warn", "info", "debug"]);
6237
6539
  var LOG_LEVEL_RANK = Object.freeze({
6238
6540
  silent: 0,
6239
6541
  error: 1,
@@ -6505,7 +6807,7 @@ var resolveDeliveryIdentity = (input) => {
6505
6807
  };
6506
6808
 
6507
6809
  // src/runtime/hook.ts
6508
- import { z as z22 } from "zod";
6810
+ import { z as z23 } from "zod";
6509
6811
 
6510
6812
  // src/runtime/target-resolution.ts
6511
6813
  import * as path from "path";
@@ -6675,7 +6977,7 @@ var withOptionalSessionLock = async (store, sessionId, fn, options) => {
6675
6977
  };
6676
6978
 
6677
6979
  // src/runtime/hook.ts
6678
- var usageScopeSchema = z22.enum(["session", "generation", "subagent"]);
6980
+ var usageScopeSchema = z23.enum(["session", "generation", "subagent"]);
6679
6981
  var classifyDurability = (input) => {
6680
6982
  if (!input.attempted) {
6681
6983
  return "nothing-to-deliver";
@@ -7771,27 +8073,7 @@ var createCallbackDeduplicator = (deps) => {
7771
8073
  // src/telemetry/semconv.ts
7772
8074
  import { createHash as createHash3 } from "crypto";
7773
8075
  import { SpanKind, SpanStatusCode, TraceFlags } from "@opentelemetry/api";
7774
-
7775
- // node_modules/@opentelemetry/core/build/esm/common/time.js
7776
- var NANOSECOND_DIGITS = 9;
7777
- var NANOSECOND_DIGITS_IN_MILLIS = 6;
7778
- var MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);
7779
- var SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);
7780
- function millisToHrTime(epochMillis) {
7781
- const epochSeconds = epochMillis / 1e3;
7782
- const seconds = Math.trunc(epochSeconds);
7783
- const nanos = Math.round(epochMillis % 1e3 * MILLISECONDS_TO_NANOSECONDS);
7784
- return [seconds, nanos];
7785
- }
7786
-
7787
- // node_modules/@opentelemetry/core/build/esm/ExportResult.js
7788
- var ExportResultCode;
7789
- (function(ExportResultCode2) {
7790
- ExportResultCode2[ExportResultCode2["SUCCESS"] = 0] = "SUCCESS";
7791
- ExportResultCode2[ExportResultCode2["FAILED"] = 1] = "FAILED";
7792
- })(ExportResultCode || (ExportResultCode = {}));
7793
-
7794
- // src/telemetry/semconv.ts
8076
+ import { millisToHrTime } from "@opentelemetry/core";
7795
8077
  import {
7796
8078
  ATTR_ERROR_TYPE,
7797
8079
  ATTR_GEN_AI_OPERATION_NAME,
@@ -7808,7 +8090,7 @@ import {
7808
8090
  } from "@opentelemetry/semantic-conventions/incubating";
7809
8091
 
7810
8092
  // src/version.ts
7811
- var VERSION = "0.7.0";
8093
+ var VERSION = "0.9.0";
7812
8094
 
7813
8095
  // src/telemetry/export-identity.ts
7814
8096
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -7849,10 +8131,13 @@ var targetAttributes = (event3) => {
7849
8131
  };
7850
8132
  var usageTemporalityAttributes = (usage) => usage === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_TEMPORALITY]: usage.temporality };
7851
8133
  var isPrimitiveAttribute = (value) => typeof value === "string" || typeof value === "number" || typeof value === "boolean";
7852
- var passthroughHarAttributes = (resource) => {
8134
+ var PASSTHROUGH_RESOURCE_PREFIXES = Object.freeze(["har.", "factory.", "vcs."]);
8135
+ var LOCAL_ONLY_RESOURCE_PREFIX = "factory.local.";
8136
+ var isPassthroughKey = (key) => PASSTHROUGH_RESOURCE_PREFIXES.some((prefix) => key.startsWith(prefix)) && !key.startsWith(LOCAL_ONLY_RESOURCE_PREFIX) && key !== "factory.local";
8137
+ var passthroughResourceAttributes = (resource) => {
7853
8138
  const attributes = {};
7854
8139
  for (const [key, value] of Object.entries(resource.attributes)) {
7855
- if (key.startsWith("har.") && isPrimitiveAttribute(value)) {
8140
+ if (isPassthroughKey(key) && isPrimitiveAttribute(value)) {
7856
8141
  attributes[key] = value;
7857
8142
  }
7858
8143
  }
@@ -7886,7 +8171,7 @@ var exportIdentityAttributes = (event3, resource, ids) => {
7886
8171
  ...event3.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event3.provenance.providerVersion },
7887
8172
  [ATTR_OTELHOOK_WORKSPACE_ID]: event3.workspace.workspaceId,
7888
8173
  ...event3.subagentId === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event3.subagentId },
7889
- ...passthroughHarAttributes(resource),
8174
+ ...passthroughResourceAttributes(resource),
7890
8175
  ...hexTraceAttributes(ids)
7891
8176
  };
7892
8177
  };
@@ -8036,12 +8321,12 @@ var pickTarget = (attributes) => {
8036
8321
  }
8037
8322
  return picked;
8038
8323
  };
8039
- var withoutTarget = (attributes) => {
8324
+ var withoutTarget = (attributes, resource) => {
8040
8325
  const rest = { ...attributes };
8041
8326
  for (const key of TARGET_KEYS) {
8042
8327
  delete rest[key];
8043
8328
  }
8044
- return rest;
8329
+ return { ...rest, ...pickTarget(passthroughResourceAttributes(resource)) };
8045
8330
  };
8046
8331
  var rankOf = (candidate) => {
8047
8332
  const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];
@@ -8146,7 +8431,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
8146
8431
  name = "session";
8147
8432
  kind = SpanKind.INTERNAL;
8148
8433
  attributes = {
8149
- ...withoutTarget(attributes),
8434
+ ...withoutTarget(attributes, resource),
8150
8435
  ...strongestTarget([pickTarget(resolved.recovered), start === void 0 ? {} : targetAttributes(start)]),
8151
8436
  ...start?.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName },
8152
8437
  ...start?.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion },
@@ -8187,7 +8472,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
8187
8472
  kind = SpanKind.CLIENT;
8188
8473
  attributes = {
8189
8474
  // Target keys are re-chosen below as one unit, never mixed across edges.
8190
- ...withoutTarget(attributes),
8475
+ ...withoutTarget(attributes, resource),
8191
8476
  [ATTR_GEN_AI_TOOL_NAME]: toolName,
8192
8477
  [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,
8193
8478
  ...start?.toolKind === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind },
@@ -9314,8 +9599,64 @@ var createFilesystemStateStore = (options) => {
9314
9599
 
9315
9600
  // src/telemetry/spool-queue.ts
9316
9601
  import { randomBytes as randomBytes3 } from "crypto";
9317
- import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, rename as rename2, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
9602
+ import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, rename as rename2, stat as stat2, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
9318
9603
  import * as path4 from "path";
9604
+ var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
9605
+ total: 0,
9606
+ age: 0,
9607
+ size: 0,
9608
+ count: 0,
9609
+ rejected: 0
9610
+ });
9611
+ var SPOOL_DROPS_FILE = ".drops";
9612
+ var enqueuedAtOf = (fileName) => {
9613
+ const match = /^(\d{16})-/.exec(fileName);
9614
+ return match?.[1] === void 0 ? void 0 : Number(match[1]);
9615
+ };
9616
+ var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
9617
+ var readSpoolDropCounts = async (queueDir) => {
9618
+ try {
9619
+ const parsed = JSON.parse(await readFile2(path4.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
9620
+ if (typeof parsed !== "object" || parsed === null) {
9621
+ return EMPTY_SPOOL_DROP_COUNTS;
9622
+ }
9623
+ const record = parsed;
9624
+ const field = (name) => isCount(record[name]) ? record[name] : 0;
9625
+ return {
9626
+ total: field("total"),
9627
+ age: field("age"),
9628
+ size: field("size"),
9629
+ count: field("count"),
9630
+ rejected: field("rejected"),
9631
+ ...isCount(record.lastDroppedAt) ? { lastDroppedAt: record.lastDroppedAt } : {}
9632
+ };
9633
+ } catch {
9634
+ return EMPTY_SPOOL_DROP_COUNTS;
9635
+ }
9636
+ };
9637
+ var readSpoolQueueStats = async (queueDir) => {
9638
+ let entries;
9639
+ try {
9640
+ entries = await readdir2(queueDir);
9641
+ } catch {
9642
+ return { batches: 0, bytes: 0, dropped: await readSpoolDropCounts(queueDir) };
9643
+ }
9644
+ const files = entries.filter((entry) => entry.endsWith(".json") && !entry.startsWith(".tmp-")).sort();
9645
+ let bytes = 0;
9646
+ for (const file of files) {
9647
+ try {
9648
+ bytes += (await stat2(path4.join(queueDir, file))).size;
9649
+ } catch {
9650
+ }
9651
+ }
9652
+ const oldest = files[0] === void 0 ? void 0 : enqueuedAtOf(files[0]);
9653
+ return {
9654
+ batches: files.length,
9655
+ bytes,
9656
+ ...oldest === void 0 ? {} : { oldestEnqueuedAt: oldest },
9657
+ dropped: await readSpoolDropCounts(queueDir)
9658
+ };
9659
+ };
9319
9660
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
9320
9661
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
9321
9662
  var createSpoolQueue = (options) => {
@@ -9356,27 +9697,132 @@ var createSpoolQueue = (options) => {
9356
9697
  }
9357
9698
  return entries.filter((entry) => entry.endsWith(".json") && !entry.startsWith(".tmp-")).sort();
9358
9699
  };
9700
+ const recordDrops = async (reason, dropped) => {
9701
+ if (dropped <= 0) {
9702
+ return;
9703
+ }
9704
+ try {
9705
+ const current = await readSpoolDropCounts(queueDir);
9706
+ const next = {
9707
+ ...current,
9708
+ total: current.total + dropped,
9709
+ [reason]: current[reason] + dropped,
9710
+ lastDroppedAt: options.clock.now()
9711
+ };
9712
+ const tmp = path4.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
9713
+ await writeFile2(tmp, JSON.stringify(next), "utf8");
9714
+ await rename2(tmp, path4.join(queueDir, SPOOL_DROPS_FILE));
9715
+ } catch {
9716
+ }
9717
+ options.logger?.warn("durable spool dropped batches", {
9718
+ "spool.queue": options.queueName,
9719
+ "spool.drop_reason": reason,
9720
+ "spool.dropped": dropped
9721
+ });
9722
+ };
9723
+ const listWithSizes = async () => {
9724
+ const names = await listSorted();
9725
+ const files = [];
9726
+ for (const name of names) {
9727
+ let bytes = 0;
9728
+ if (options.maxBytes !== void 0) {
9729
+ try {
9730
+ bytes = (await stat2(path4.join(queueDir, name))).size;
9731
+ } catch {
9732
+ continue;
9733
+ }
9734
+ }
9735
+ const enqueuedAt = enqueuedAtOf(name);
9736
+ files.push({ name, bytes, ...enqueuedAt === void 0 ? {} : { enqueuedAt } });
9737
+ }
9738
+ return files;
9739
+ };
9740
+ const evict = async (files) => {
9741
+ let removed = 0;
9742
+ for (const file of files) {
9743
+ try {
9744
+ await unlink2(path4.join(queueDir, file.name));
9745
+ removed += 1;
9746
+ } catch {
9747
+ }
9748
+ }
9749
+ return removed;
9750
+ };
9751
+ const isExpired = (file, now) => options.maxAgeMillis !== void 0 && file.enqueuedAt !== void 0 && now - file.enqueuedAt > options.maxAgeMillis;
9359
9752
  const enqueue = async (batch) => {
9360
9753
  await ensureDirs();
9361
- const existing = await listSorted();
9362
- if (existing.length >= options.maxFiles) {
9754
+ const serialized = JSON.stringify(batch);
9755
+ const bytes = Buffer.byteLength(serialized, "utf8");
9756
+ const refuse = async (reason) => {
9363
9757
  options.logger?.warn("durable spool at capacity; batch dropped", {
9364
9758
  "spool.max_files": options.maxFiles,
9759
+ ...options.maxBytes === void 0 ? {} : { "spool.max_bytes": options.maxBytes },
9365
9760
  "spool.queue": options.queueName
9366
9761
  });
9762
+ await recordDrops(reason, 1);
9367
9763
  return { spooled: false, reason: "capacity-exceeded" };
9764
+ };
9765
+ if (options.maxBytes !== void 0 && bytes > options.maxBytes) {
9766
+ return refuse("size");
9767
+ }
9768
+ let queued = await listWithSizes();
9769
+ const now = options.clock.now();
9770
+ const expired = queued.filter((file) => isExpired(file, now));
9771
+ if (expired.length > 0) {
9772
+ await recordDrops("age", await evict(expired));
9773
+ queued = queued.filter((file) => !isExpired(file, now));
9774
+ }
9775
+ const overflow = options.overflow ?? "refuse-new";
9776
+ const totalBytes = () => queued.reduce((sum, file) => sum + file.bytes, 0);
9777
+ if (overflow === "refuse-new") {
9778
+ if (queued.length >= options.maxFiles) {
9779
+ return refuse("count");
9780
+ }
9781
+ if (options.maxBytes !== void 0 && totalBytes() + bytes > options.maxBytes) {
9782
+ return refuse("size");
9783
+ }
9784
+ } else {
9785
+ const overCount = Math.max(0, queued.length + 1 - options.maxFiles);
9786
+ if (overCount > 0) {
9787
+ await recordDrops("count", await evict(queued.slice(0, overCount)));
9788
+ queued = queued.slice(overCount);
9789
+ }
9790
+ if (options.maxBytes !== void 0) {
9791
+ let excess = totalBytes() + bytes - options.maxBytes;
9792
+ let cut = 0;
9793
+ while (excess > 0 && cut < queued.length) {
9794
+ excess -= queued[cut]?.bytes ?? 0;
9795
+ cut += 1;
9796
+ }
9797
+ if (cut > 0) {
9798
+ await recordDrops("size", await evict(queued.slice(0, cut)));
9799
+ queued = queued.slice(cut);
9800
+ }
9801
+ }
9368
9802
  }
9369
- const fileName = `${String(options.clock.now()).padStart(16, "0")}-${randomBytes3(6).toString("hex")}.json`;
9803
+ const fileName = `${String(now).padStart(16, "0")}-${randomBytes3(6).toString("hex")}.json`;
9370
9804
  const target = path4.join(queueDir, fileName);
9371
9805
  const tmp = path4.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
9372
- await writeFile2(tmp, JSON.stringify(batch), "utf8");
9806
+ await writeFile2(tmp, serialized, "utf8");
9373
9807
  await rename2(tmp, target);
9374
9808
  return { spooled: true };
9375
9809
  };
9376
9810
  const drain = async (send, drainOptions) => {
9377
9811
  await ensureDirs();
9378
9812
  const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;
9379
- const files = await listSorted();
9813
+ let files = await listSorted();
9814
+ if (options.maxAgeMillis !== void 0) {
9815
+ const now = options.clock.now();
9816
+ const expired = files.map((name) => {
9817
+ const enqueuedAt = enqueuedAtOf(name);
9818
+ return { name, bytes: 0, ...enqueuedAt === void 0 ? {} : { enqueuedAt } };
9819
+ }).filter((file) => isExpired(file, now));
9820
+ if (expired.length > 0) {
9821
+ await recordDrops("age", await evict(expired));
9822
+ const gone = new Set(expired.map((file) => file.name));
9823
+ files = files.filter((name) => !gone.has(name));
9824
+ }
9825
+ }
9380
9826
  let drained = 0;
9381
9827
  let failed = 0;
9382
9828
  let quarantined = 0;
@@ -9421,6 +9867,12 @@ var createSpoolQueue = (options) => {
9421
9867
  } catch {
9422
9868
  delivered = false;
9423
9869
  }
9870
+ if (delivered === "discard") {
9871
+ if (await unlink2(filePath).then(() => true, () => false)) {
9872
+ await recordDrops("rejected", 1);
9873
+ }
9874
+ continue;
9875
+ }
9424
9876
  if (delivered) {
9425
9877
  await unlink2(filePath).catch(() => void 0);
9426
9878
  drained += 1;
@@ -9438,7 +9890,8 @@ var createSpoolQueue = (options) => {
9438
9890
  size: async () => {
9439
9891
  await ensureDirs();
9440
9892
  return (await listSorted()).length;
9441
- }
9893
+ },
9894
+ stats: () => readSpoolQueueStats(queueDir)
9442
9895
  };
9443
9896
  };
9444
9897
 
@@ -9530,11 +9983,15 @@ var createFileDurableSpool = (options) => createSpoolQueue({
9530
9983
  clock: options.clock,
9531
9984
  ...options.logger === void 0 ? {} : { logger: options.logger },
9532
9985
  maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_SPOOL_FILES,
9533
- queueName: "spool",
9986
+ queueName: options.queueName ?? "spool",
9987
+ ...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
9988
+ ...options.maxAgeMillis === void 0 ? {} : { maxAgeMillis: options.maxAgeMillis },
9989
+ ...options.overflow === void 0 ? {} : { overflow: options.overflow },
9534
9990
  validate: validateSpoolBatch
9535
9991
  });
9536
9992
 
9537
9993
  // src/telemetry/otlp-sink.ts
9994
+ import { ExportResultCode } from "@opentelemetry/core";
9538
9995
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
9539
9996
 
9540
9997
  // src/diagnostics/health.ts
@@ -9570,7 +10027,8 @@ var createHealthTracker = (subsystem, options = {}) => {
9570
10027
  consecutiveFailures,
9571
10028
  ...lastSuccessAt === void 0 ? {} : { lastSuccessAt },
9572
10029
  ...lastFailureAt === void 0 ? {} : { lastFailureAt },
9573
- ...lastErrorCode === void 0 ? {} : { lastErrorCode }
10030
+ ...lastErrorCode === void 0 ? {} : { lastErrorCode },
10031
+ ...options.destination === void 0 ? {} : { destination: options.destination }
9574
10032
  })
9575
10033
  };
9576
10034
  };
@@ -9579,6 +10037,13 @@ var summarizeHealth = (snapshots) => ({
9579
10037
  subsystems: [...snapshots]
9580
10038
  });
9581
10039
 
10040
+ // src/telemetry/export-failure.ts
10041
+ var RETRYABLE_HTTP_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
10042
+ var isPermanentExportFailure = (result) => {
10043
+ const code = result.error?.code;
10044
+ return typeof code === "number" && Number.isInteger(code) && code >= 400 && code < 600 && !RETRYABLE_HTTP_STATUSES.has(code);
10045
+ };
10046
+
9582
10047
  // src/telemetry/exporter-resource.ts
9583
10048
  import { resourceFromAttributes } from "@opentelemetry/resources";
9584
10049
  var resourceFromExporterPolicy = (policy) => resourceFromAttributes({
@@ -9650,8 +10115,11 @@ var deserializeSpan = (serialized, resource, scope) => assembleReadableSpan({
9650
10115
  resource,
9651
10116
  instrumentationScope: scope
9652
10117
  });
9653
- var createDisabledSink = () => {
9654
- const health = createHealthTracker("telemetry-sink");
10118
+ var createDisabledSink = (destination) => {
10119
+ const health = createHealthTracker(
10120
+ "telemetry-sink",
10121
+ destination === void 0 ? {} : { destination }
10122
+ );
9655
10123
  return {
9656
10124
  emit: (events) => {
9657
10125
  health.recordSuccess(events.length);
@@ -9664,22 +10132,27 @@ var createDisabledSink = () => {
9664
10132
  };
9665
10133
  };
9666
10134
  var createOtlpTraceSink = (options) => {
10135
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
9667
10136
  if (!options.exporter.enabled || options.exporter.protocol === "none") {
9668
- return createDisabledSink();
10137
+ return createDisabledSink(options.destination);
9669
10138
  }
9670
10139
  if (options.exporter.endpoint === void 0) {
9671
- options.logger?.warn("otlp sink disabled: no endpoint configured", {});
9672
- return createDisabledSink();
10140
+ options.logger?.warn("otlp sink disabled: no endpoint configured", destinationFields);
10141
+ return createDisabledSink(options.destination);
9673
10142
  }
9674
10143
  if (options.exporter.protocol !== "http/protobuf") {
9675
10144
  options.logger?.warn("otlp sink: protocol not supported by this build, falling back to disabled", {
9676
- "exporter.protocol": options.exporter.protocol
10145
+ "exporter.protocol": options.exporter.protocol,
10146
+ ...destinationFields
9677
10147
  });
9678
- return createDisabledSink();
10148
+ return createDisabledSink(options.destination);
9679
10149
  }
9680
10150
  const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
9681
10151
  const resource = resourceFromExporterPolicy(options.exporter);
9682
- const health = createHealthTracker("telemetry-sink");
10152
+ const health = createHealthTracker(
10153
+ "telemetry-sink",
10154
+ options.destination === void 0 ? {} : { destination: options.destination }
10155
+ );
9683
10156
  const exporter = new OTLPTraceExporter({
9684
10157
  url: options.exporter.endpoint,
9685
10158
  headers: { ...options.headers },
@@ -9701,7 +10174,10 @@ var createOtlpTraceSink = (options) => {
9701
10174
  const batchResource = replayResource(batch.resourceAttributes, options.exporter);
9702
10175
  const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));
9703
10176
  const result = await exportSpans(spans);
9704
- return result.code === ExportResultCode.SUCCESS;
10177
+ if (result.code === ExportResultCode.SUCCESS) {
10178
+ return true;
10179
+ }
10180
+ return isPermanentExportFailure(result) ? "discard" : false;
9705
10181
  };
9706
10182
  const resolveCorrelations = async (events) => {
9707
10183
  if (options.correlate === void 0) {
@@ -9729,6 +10205,9 @@ var createOtlpTraceSink = (options) => {
9729
10205
  let accepted = 0;
9730
10206
  let rejected = 0;
9731
10207
  for (const batch of chunk(spans, options.exporter.maxBatchSize)) {
10208
+ if (batch.length === 0) {
10209
+ continue;
10210
+ }
9732
10211
  let result;
9733
10212
  try {
9734
10213
  result = await exportSpans(batch);
@@ -9741,13 +10220,18 @@ var createOtlpTraceSink = (options) => {
9741
10220
  continue;
9742
10221
  }
9743
10222
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
9744
- if (options.spool !== void 0) {
10223
+ const permanent = isPermanentExportFailure(result);
10224
+ if (options.spool !== void 0 && !permanent) {
9745
10225
  const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
9746
10226
  spooled: false,
9747
10227
  reason: "capacity-exceeded"
9748
10228
  }));
9749
10229
  if (spoolResult.spooled) {
9750
10230
  accepted += batch.length;
10231
+ options.logger?.warn("span batch not delivered; spooled for the next invocation", {
10232
+ "export.batch_size": batch.length,
10233
+ ...destinationFields
10234
+ });
9751
10235
  continue;
9752
10236
  }
9753
10237
  }
@@ -9756,8 +10240,8 @@ var createOtlpTraceSink = (options) => {
9756
10240
  createErrorInfo({
9757
10241
  code: "telemetry-export-failure",
9758
10242
  phase: "export",
9759
- detail: "collector rejected or was unreachable for a span batch",
9760
- details: { "export.batch_size": batch.length }
10243
+ detail: permanent ? "collector refused a span batch with a non-retryable status" : "collector rejected or was unreachable for a span batch",
10244
+ details: { "export.batch_size": batch.length, ...destinationFields }
9761
10245
  })
9762
10246
  );
9763
10247
  }
@@ -9801,8 +10285,8 @@ var createOtlpTraceSink = (options) => {
9801
10285
  };
9802
10286
 
9803
10287
  // src/telemetry/log-records.ts
9804
- import { TraceFlags as TraceFlags2 } from "@opentelemetry/api";
9805
- import { SeverityNumber } from "@opentelemetry/api-logs";
10288
+ import { SeverityNumber, TraceFlags as TraceFlags2 } from "@opentelemetry/api";
10289
+ import { millisToHrTime as millisToHrTime2 } from "@opentelemetry/core";
9806
10290
  import {
9807
10291
  ATTR_ERROR_TYPE as ATTR_ERROR_TYPE2,
9808
10292
  ATTR_GEN_AI_OPERATION_NAME as ATTR_GEN_AI_OPERATION_NAME2,
@@ -10123,14 +10607,14 @@ var contentAttributes = (fact, body) => ({
10123
10607
  });
10124
10608
  var buildRecord = (input) => {
10125
10609
  const severityNumber = severityFor(input.event);
10126
- const hrTime2 = millisToHrTime(input.event.occurredAt);
10610
+ const hrTime = millisToHrTime2(input.event.occurredAt);
10127
10611
  return {
10128
- hrTime: hrTime2,
10612
+ hrTime,
10129
10613
  // A hook observes an event that already happened, and this mapping is pure —
10130
10614
  // there is no clock here to read a real observation time from. Reporting the
10131
10615
  // occurrence time for both is the honest answer: it says "this is when it
10132
10616
  // happened" twice rather than inventing a second, wrong timestamp.
10133
- hrTimeObserved: hrTime2,
10617
+ hrTimeObserved: hrTime,
10134
10618
  spanContext: input.spanContext,
10135
10619
  severityNumber,
10136
10620
  severityText: SEVERITY_TEXT[severityNumber] ?? "INFO",
@@ -10314,22 +10798,18 @@ var createFileDurableLogSpool = (options) => createSpoolQueue({
10314
10798
  clock: options.clock,
10315
10799
  ...options.logger === void 0 ? {} : { logger: options.logger },
10316
10800
  maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_LOG_SPOOL_FILES,
10317
- queueName: "spool-logs",
10801
+ queueName: options.queueName ?? "spool-logs",
10802
+ ...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
10803
+ ...options.maxAgeMillis === void 0 ? {} : { maxAgeMillis: options.maxAgeMillis },
10804
+ ...options.overflow === void 0 ? {} : { overflow: options.overflow },
10318
10805
  validate: validateLogSpoolBatch
10319
10806
  });
10320
10807
 
10321
10808
  // src/telemetry/otlp-log-sink.ts
10322
10809
  import { TraceFlags as TraceFlags3 } from "@opentelemetry/api";
10810
+ import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
10811
+ import { millisToHrTime as millisToHrTime3 } from "@opentelemetry/core";
10323
10812
  import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
10324
- var OTLP_TRACES_PATH = "/v1/traces";
10325
- var OTLP_LOGS_PATH = "/v1/logs";
10326
- var withoutTrailingSlashes = (value) => {
10327
- let end = value.length;
10328
- while (end > 0 && value.charCodeAt(end - 1) === 47) {
10329
- end -= 1;
10330
- }
10331
- return value.slice(0, end);
10332
- };
10333
10813
  var resolveLogsEndpoint = (exporter) => {
10334
10814
  if (exporter.logs.endpoint !== void 0) {
10335
10815
  return { endpoint: exporter.logs.endpoint, derived: false };
@@ -10383,8 +10863,8 @@ var deserializeRecord = (serialized, resource, scope) => {
10383
10863
  isRemote: false
10384
10864
  };
10385
10865
  return {
10386
- hrTime: millisToHrTime(serialized.timeMillis),
10387
- hrTimeObserved: millisToHrTime(serialized.observedTimeMillis),
10866
+ hrTime: millisToHrTime3(serialized.timeMillis),
10867
+ hrTimeObserved: millisToHrTime3(serialized.observedTimeMillis),
10388
10868
  ...spanContext === void 0 ? {} : { spanContext },
10389
10869
  severityNumber: serialized.severityNumber,
10390
10870
  ...serialized.severityText === void 0 ? {} : { severityText: serialized.severityText },
@@ -10406,8 +10886,11 @@ var chunk2 = (items, size) => {
10406
10886
  }
10407
10887
  return chunks;
10408
10888
  };
10409
- var createDisabledSink2 = () => {
10410
- const health = createHealthTracker("telemetry-log-sink");
10889
+ var createDisabledSink2 = (destination) => {
10890
+ const health = createHealthTracker(
10891
+ "telemetry-log-sink",
10892
+ destination === void 0 ? {} : { destination }
10893
+ );
10411
10894
  return {
10412
10895
  emit: (events) => {
10413
10896
  health.recordSuccess(events.length);
@@ -10446,19 +10929,24 @@ var DISABLED_DETAIL = Object.freeze({
10446
10929
  "no-endpoint": "otlp log sink disabled: no logs endpoint configured and none could be derived"
10447
10930
  });
10448
10931
  var createOtlpLogSink = (options) => {
10932
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
10449
10933
  const deliverability = describeLogsDeliverability(options.exporter);
10450
10934
  if (deliverability.status === "disabled") {
10451
10935
  if (deliverability.reason !== "logs-disabled") {
10452
10936
  options.logger?.warn(DISABLED_DETAIL[deliverability.reason], {
10453
- "exporter.protocol": options.exporter.protocol
10937
+ "exporter.protocol": options.exporter.protocol,
10938
+ ...destinationFields
10454
10939
  });
10455
10940
  }
10456
- return createDisabledSink2();
10941
+ return createDisabledSink2(options.destination);
10457
10942
  }
10458
10943
  const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
10459
10944
  const resource = resourceFromExporterPolicy(options.exporter);
10460
10945
  const content = options.content ?? NO_LOG_CONTENT;
10461
- const health = createHealthTracker("telemetry-log-sink");
10946
+ const health = createHealthTracker(
10947
+ "telemetry-log-sink",
10948
+ options.destination === void 0 ? {} : { destination: options.destination }
10949
+ );
10462
10950
  const exporter = new OTLPLogExporter({
10463
10951
  url: deliverability.endpoint,
10464
10952
  headers: { ...options.headers },
@@ -10485,7 +10973,10 @@ var createOtlpLogSink = (options) => {
10485
10973
  (record) => deserializeRecord(record, batchResource, batch.instrumentationScope)
10486
10974
  );
10487
10975
  const result = await exportRecords(records);
10488
- return result.code === ExportResultCode.SUCCESS;
10976
+ if (result.code === ExportResultCode2.SUCCESS) {
10977
+ return true;
10978
+ }
10979
+ return isPermanentExportFailure(result) ? "discard" : false;
10489
10980
  };
10490
10981
  const resolveCorrelations = async (events) => {
10491
10982
  if (options.correlate === void 0) {
@@ -10527,23 +11018,28 @@ var createOtlpLogSink = (options) => {
10527
11018
  result = await exportRecords(batch);
10528
11019
  } catch (thrown) {
10529
11020
  result = {
10530
- code: ExportResultCode.FAILED,
11021
+ code: ExportResultCode2.FAILED,
10531
11022
  error: thrown instanceof Error ? thrown : new Error("export threw")
10532
11023
  };
10533
11024
  }
10534
- if (result.code === ExportResultCode.SUCCESS) {
11025
+ if (result.code === ExportResultCode2.SUCCESS) {
10535
11026
  accepted += batch.length;
10536
11027
  health.recordSuccess(batch.length, options.clock.now());
10537
11028
  continue;
10538
11029
  }
10539
11030
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
10540
- if (options.spool !== void 0) {
11031
+ const permanent = isPermanentExportFailure(result);
11032
+ if (options.spool !== void 0 && !permanent) {
10541
11033
  const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
10542
11034
  spooled: false,
10543
11035
  reason: "capacity-exceeded"
10544
11036
  }));
10545
11037
  if (spoolResult.spooled) {
10546
11038
  accepted += batch.length;
11039
+ options.logger?.warn("log record batch not delivered; spooled for the next invocation", {
11040
+ "export.batch_size": batch.length,
11041
+ ...destinationFields
11042
+ });
10547
11043
  continue;
10548
11044
  }
10549
11045
  }
@@ -10552,8 +11048,12 @@ var createOtlpLogSink = (options) => {
10552
11048
  createErrorInfo({
10553
11049
  code: "telemetry-export-failure",
10554
11050
  phase: "export",
10555
- detail: "collector rejected or was unreachable for a log record batch",
10556
- details: { "export.batch_size": batch.length, "export.signal": "logs" }
11051
+ detail: permanent ? "collector refused a log record batch with a non-retryable status" : "collector rejected or was unreachable for a log record batch",
11052
+ details: {
11053
+ "export.batch_size": batch.length,
11054
+ "export.signal": "logs",
11055
+ ...destinationFields
11056
+ }
10557
11057
  })
10558
11058
  );
10559
11059
  }
@@ -10640,6 +11140,172 @@ var shareCorrelationPerBatch = (correlate) => {
10640
11140
  };
10641
11141
  };
10642
11142
 
11143
+ // src/telemetry/export-destinations.ts
11144
+ var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs" } : { traces: `destinations/${destination}/spool`, logs: `destinations/${destination}/spool-logs` };
11145
+ var exporterPolicyForDestination = (exporter, destination) => {
11146
+ if (destination.source === "exporter") {
11147
+ return exporter;
11148
+ }
11149
+ const { destinations, endpoint, logs, ...shared } = exporter;
11150
+ void destinations;
11151
+ void endpoint;
11152
+ const tracesEndpoint = destination.tracesEndpoint ?? destination.endpoint;
11153
+ const derivedLogs = destination.logsEndpoint ?? (destination.endpoint === void 0 ? void 0 : (() => {
11154
+ const derived = resolveLogsEndpoint({
11155
+ ...exporter,
11156
+ endpoint: destination.endpoint,
11157
+ logs: { enabled: true, includeContent: false, maxBatchSize: logs.maxBatchSize }
11158
+ });
11159
+ return "endpoint" in derived ? derived.endpoint : void 0;
11160
+ })());
11161
+ return {
11162
+ ...shared,
11163
+ protocol: destination.protocol,
11164
+ ...tracesEndpoint === void 0 ? {} : { endpoint: tracesEndpoint },
11165
+ headerNames: Object.keys(destination.headers).sort(),
11166
+ logs: {
11167
+ ...logs,
11168
+ enabled: destination.signals.logs,
11169
+ ...derivedLogs === void 0 ? {} : { endpoint: derivedLogs }
11170
+ }
11171
+ };
11172
+ };
11173
+ var createOptedOutTraceSink = (destination) => {
11174
+ const health = createHealthTracker(
11175
+ "telemetry-sink",
11176
+ destination === void 0 ? {} : { destination }
11177
+ );
11178
+ return {
11179
+ emit: () => Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),
11180
+ flush: () => Promise.resolve(),
11181
+ shutdown: () => Promise.resolve(),
11182
+ health: () => health.snapshot(),
11183
+ drainSpool: () => Promise.resolve({ drained: 0, remaining: 0, failed: 0 })
11184
+ };
11185
+ };
11186
+ var createExportDestinationSinks = (options) => {
11187
+ const labelled = hasConfiguredDestinations(options.exporter);
11188
+ const spoolPolicy = effectiveSpoolPolicy(options.exporter);
11189
+ const destinations = [];
11190
+ const skipped = [];
11191
+ for (const destination of resolveExportDestinations(options.exporter)) {
11192
+ let headers;
11193
+ let logHeaders;
11194
+ if (destination.source === "exporter") {
11195
+ headers = options.defaultHeaders;
11196
+ logHeaders = options.defaultLogHeaders ?? options.defaultHeaders;
11197
+ } else {
11198
+ const resolved = resolveDestinationHeaders(destination.headers, options.headerEnvironment);
11199
+ if (resolved.missingVariables.length > 0) {
11200
+ options.logger?.warn("export destination skipped: a header references an unset environment variable", {
11201
+ "export.destination": destination.name,
11202
+ "config.variables": [...resolved.missingVariables]
11203
+ });
11204
+ skipped.push({
11205
+ name: destination.name,
11206
+ reason: "header-variable-missing",
11207
+ missingVariables: resolved.missingVariables
11208
+ });
11209
+ continue;
11210
+ }
11211
+ headers = resolved.values;
11212
+ logHeaders = resolved.values;
11213
+ }
11214
+ const label = labelled ? destination.name : void 0;
11215
+ const policy = exporterPolicyForDestination(options.exporter, destination);
11216
+ const queues = spoolQueueNamesFor(destination.name);
11217
+ const bounds = {
11218
+ maxSpoolFiles: spoolPolicy.maxBatches,
11219
+ maxBytes: spoolPolicy.maxBytes,
11220
+ maxAgeMillis: spoolPolicy.maxAgeMillis,
11221
+ overflow: "drop-oldest"
11222
+ };
11223
+ const shared = {
11224
+ providerId: options.providerId,
11225
+ installationId: options.installationId,
11226
+ clock: options.clock,
11227
+ ...options.logger === void 0 ? {} : { logger: options.logger }
11228
+ };
11229
+ const spool = options.spoolRootDir === void 0 || !destination.signals.traces ? void 0 : createFileDurableSpool({
11230
+ rootDir: options.spoolRootDir,
11231
+ ...shared,
11232
+ ...bounds,
11233
+ queueName: queues.traces
11234
+ });
11235
+ const logSpool = options.spoolRootDir === void 0 || !destination.signals.logs ? void 0 : createFileDurableLogSpool({
11236
+ rootDir: options.spoolRootDir,
11237
+ ...shared,
11238
+ ...bounds,
11239
+ queueName: queues.logs
11240
+ });
11241
+ const sinkShared = {
11242
+ exporter: policy,
11243
+ ...shared,
11244
+ ...options.correlate === void 0 ? {} : { correlate: options.correlate },
11245
+ ...label === void 0 ? {} : { destination: label }
11246
+ };
11247
+ const traces = destination.signals.traces ? createOtlpTraceSink({
11248
+ ...sinkShared,
11249
+ ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
11250
+ ...spool === void 0 ? {} : { spool }
11251
+ }) : createOptedOutTraceSink(label);
11252
+ const logs = createOtlpLogSink({
11253
+ ...sinkShared,
11254
+ ...logHeaders === void 0 || Object.keys(logHeaders).length === 0 ? {} : { headers: logHeaders },
11255
+ ...logSpool === void 0 ? {} : { spool: logSpool },
11256
+ content: options.logContent
11257
+ });
11258
+ destinations.push({
11259
+ name: destination.name,
11260
+ traces,
11261
+ logs,
11262
+ ...spool === void 0 ? {} : { spool },
11263
+ ...logSpool === void 0 ? {} : { logSpool }
11264
+ });
11265
+ }
11266
+ return { destinations, skipped };
11267
+ };
11268
+ var createDestinationFanout = (destinations) => {
11269
+ const fanouts = destinations.map((destination) => ({
11270
+ name: destination.name,
11271
+ sink: createSignalFanout({ traces: destination.traces, logs: destination.logs })
11272
+ }));
11273
+ const only = fanouts.length === 1 ? fanouts[0] : void 0;
11274
+ if (only !== void 0) {
11275
+ return only.sink;
11276
+ }
11277
+ const emit = async (events) => {
11278
+ const results = await Promise.all(
11279
+ fanouts.map(
11280
+ (fanout) => fanout.sink.emit(events).catch(
11281
+ (thrown) => ({
11282
+ accepted: 0,
11283
+ rejected: events.length,
11284
+ errors: [errorInfoFromThrown(thrown, { code: "telemetry-export-failure", phase: "export" })]
11285
+ })
11286
+ )
11287
+ )
11288
+ );
11289
+ const errors = results.flatMap((result) => result.errors);
11290
+ return {
11291
+ accepted: results.reduce((sum, result) => sum + result.accepted, 0),
11292
+ rejected: results.reduce((sum, result) => sum + result.rejected, 0),
11293
+ errors
11294
+ };
11295
+ };
11296
+ const settleAll = async (run) => {
11297
+ await Promise.all(fanouts.map((fanout) => run(fanout.sink).catch(() => void 0)));
11298
+ };
11299
+ return {
11300
+ emit,
11301
+ // Each destination drains its own spool in its flush; in parallel, so one
11302
+ // unreachable destination's drain cannot use up the others' flush window.
11303
+ flush: () => settleAll((sink) => sink.flush()),
11304
+ shutdown: () => settleAll((sink) => sink.shutdown()),
11305
+ health: () => fanouts.flatMap((fanout) => fanout.sink.health())
11306
+ };
11307
+ };
11308
+
10643
11309
  // src/integration/hook-runtime.ts
10644
11310
  var DEFAULT_FLUSH_TIMEOUT_MILLIS = 2e3;
10645
11311
  var DEFAULT_STATE_LOCK_TIMEOUT_MILLIS = 1e3;
@@ -10702,46 +11368,23 @@ var createHookRuntime = (options) => {
10702
11368
  logger,
10703
11369
  lockTimeoutMillis: stateLockTimeoutMillis
10704
11370
  });
10705
- const spool = options.enableSpool === false ? void 0 : createFileDurableSpool({
10706
- rootDir: options.stateRootDir,
10707
- providerId: options.providerNamespace,
10708
- installationId: options.installationId,
10709
- clock,
10710
- logger
10711
- });
10712
- const logSpool = options.enableSpool === false || !options.config.exporter.logs.enabled ? void 0 : createFileDurableLogSpool({
10713
- rootDir: options.stateRootDir,
10714
- providerId: options.providerNamespace,
10715
- installationId: options.installationId,
10716
- clock,
10717
- logger
10718
- });
10719
11371
  const spanCorrelator = createSpanCorrelator({
10720
11372
  stateStore,
10721
11373
  clock,
10722
11374
  maxStartAgeMillis: lifecycleMaxAge
10723
11375
  });
10724
11376
  const correlate = shareCorrelationPerBatch((events) => spanCorrelator.correlateBatch(events));
10725
- const traceSink = createOtlpTraceSink({
10726
- exporter: options.config.exporter,
10727
- ...options.headers === void 0 ? {} : { headers: options.headers },
10728
- providerId: options.providerNamespace,
10729
- installationId: options.installationId,
10730
- clock,
10731
- logger,
10732
- ...spool === void 0 ? {} : { spool },
10733
- correlate
10734
- });
10735
- const logHeaders = options.logHeaders ?? options.headers;
10736
- const logSink = createOtlpLogSink({
11377
+ const exportDestinations = createExportDestinationSinks({
10737
11378
  exporter: options.config.exporter,
10738
- ...logHeaders === void 0 ? {} : { headers: logHeaders },
11379
+ ...options.headers === void 0 ? {} : { defaultHeaders: options.headers },
11380
+ ...options.logHeaders === void 0 ? {} : { defaultLogHeaders: options.logHeaders },
11381
+ ...options.headerEnvironment === void 0 ? {} : { headerEnvironment: options.headerEnvironment },
10739
11382
  providerId: options.providerNamespace,
10740
11383
  installationId: options.installationId,
10741
11384
  clock,
10742
11385
  logger,
10743
- ...logSpool === void 0 ? {} : { spool: logSpool },
10744
- content: {
11386
+ ...options.enableSpool === false ? {} : { spoolRootDir: options.stateRootDir },
11387
+ logContent: {
10745
11388
  includeContent: options.config.exporter.logs.includeContent,
10746
11389
  // The pre-existing verbatim-content opt-in, passed through rather than
10747
11390
  // re-derived: `raw` disclosure in a log body is governed by the same flag it
@@ -10750,7 +11393,22 @@ var createHookRuntime = (options) => {
10750
11393
  },
10751
11394
  correlate
10752
11395
  });
10753
- const sink = createSignalFanout({ traces: traceSink, logs: logSink });
11396
+ const primary = exportDestinations.destinations[0];
11397
+ const traceSink = primary?.traces ?? createOtlpTraceSink({
11398
+ exporter: { ...options.config.exporter, enabled: false },
11399
+ providerId: options.providerNamespace,
11400
+ installationId: options.installationId,
11401
+ clock
11402
+ });
11403
+ const logSink = primary?.logs ?? createOtlpLogSink({
11404
+ exporter: { ...options.config.exporter, logs: { ...options.config.exporter.logs, enabled: false } },
11405
+ providerId: options.providerNamespace,
11406
+ installationId: options.installationId,
11407
+ clock
11408
+ });
11409
+ const spool = primary?.spool;
11410
+ const logSpool = primary?.logSpool;
11411
+ const sink = createDestinationFanout(exportDestinations.destinations);
10754
11412
  const hookDeps = {
10755
11413
  stateStore,
10756
11414
  config: options.config,
@@ -11019,6 +11677,8 @@ var createHookRuntime = (options) => {
11019
11677
  logSink,
11020
11678
  ...spool === void 0 ? {} : { spool },
11021
11679
  ...logSpool === void 0 ? {} : { logSpool },
11680
+ destinations: exportDestinations.destinations,
11681
+ skippedDestinations: exportDestinations.skipped,
11022
11682
  privacy,
11023
11683
  deduplicator,
11024
11684
  usageAccumulator,
@@ -11966,7 +12626,7 @@ var resolveInstallPath = (location, roots) => path5.resolve(
11966
12626
 
11967
12627
  // src/install/document.ts
11968
12628
  import { randomBytes as randomBytes4 } from "crypto";
11969
- import { chmod, mkdir as mkdir3, open as open3, readFile as readFile3, rename as rename3, stat as stat2, unlink as unlink3 } from "fs/promises";
12629
+ import { chmod, mkdir as mkdir3, open as open3, readFile as readFile3, rename as rename3, stat as stat3, unlink as unlink3 } from "fs/promises";
11970
12630
  import * as path6 from "path";
11971
12631
  var DEFAULT_DOCUMENT_FORMAT = Object.freeze({
11972
12632
  indent: " ",
@@ -12046,7 +12706,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
12046
12706
  );
12047
12707
  let existingMode;
12048
12708
  try {
12049
- existingMode = (await stat2(filePath)).mode & 4095;
12709
+ existingMode = (await stat3(filePath)).mode & 4095;
12050
12710
  } catch (thrown) {
12051
12711
  if (!isErrnoException3(thrown, "ENOENT")) {
12052
12712
  throw thrown;
@@ -12071,7 +12731,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
12071
12731
 
12072
12732
  // src/install/file-lock.ts
12073
12733
  import { randomBytes as randomBytes5 } from "crypto";
12074
- import { mkdir as mkdir4, open as open4, readFile as readFile4, rename as rename4, stat as stat3, unlink as unlink4 } from "fs/promises";
12734
+ import { mkdir as mkdir4, open as open4, readFile as readFile4, rename as rename4, stat as stat4, unlink as unlink4 } from "fs/promises";
12075
12735
  import * as path7 from "path";
12076
12736
  var FileLockTimeoutError = class extends Error {
12077
12737
  constructor(lockPath, timeoutMillis) {
@@ -12136,7 +12796,7 @@ var isStale = async (lockPath, clock, staleMillis) => {
12136
12796
  } catch {
12137
12797
  }
12138
12798
  try {
12139
- const stats = await stat3(lockPath);
12799
+ const stats = await stat4(lockPath);
12140
12800
  return { stale: clock.now() - stats.mtimeMs > staleMillis };
12141
12801
  } catch (thrown) {
12142
12802
  return { stale: !isErrnoException4(thrown, "ENOENT") };
@@ -12562,6 +13222,7 @@ export {
12562
13222
  CURSOR_UNMODELLED_HOOK_EVENT_NAMES,
12563
13223
  CURSOR_UNREGISTERED_HOOK_EVENTS,
12564
13224
  DEFAULT_CONFIG,
13225
+ DEFAULT_DESTINATION_NAME,
12565
13226
  DEFAULT_DETECTION_POLICY,
12566
13227
  DEFAULT_DIAGNOSTICS_POLICY,
12567
13228
  DEFAULT_DOCUMENT_FORMAT,
@@ -12574,11 +13235,13 @@ export {
12574
13235
  DEFAULT_PRIVACY_POLICY,
12575
13236
  DEFAULT_SECRET_KEY_PATTERNS,
12576
13237
  DEFAULT_SECRET_VALUE_PATTERNS,
13238
+ DEFAULT_SPOOL_POLICY,
12577
13239
  DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS,
12578
13240
  DEFAULT_WORKTREE_CACHE_TTL_MILLIS,
12579
13241
  DELIVERY_COMPONENT_PATTERN,
12580
13242
  DELIVERY_GAP_REASON_PATTERN,
12581
13243
  DELIVERY_IDENTIFIER_SUMMARY,
13244
+ DESTINATION_NAME_PATTERN,
12582
13245
  DETECTION_CONFIDENCE_RANK,
12583
13246
  EMPTY_DELTA_USAGE,
12584
13247
  EMPTY_EXTENSIONS,
@@ -12591,6 +13254,7 @@ export {
12591
13254
  GEMINI_ADAPTER_VERSION,
12592
13255
  GEMINI_HOOK_EVENT_NAMES,
12593
13256
  GEMINI_PROVIDER_ID,
13257
+ HEADER_ENV_REFERENCE_PREFIX,
12594
13258
  LOG_LEVEL_RANK,
12595
13259
  LOG_MAPPING_VERSION,
12596
13260
  LOG_SIGNALS,
@@ -12601,6 +13265,8 @@ export {
12601
13265
  MAX_ATTRIBUTE_STRING_LENGTH,
12602
13266
  MAX_DELIVERY_COMPONENTS,
12603
13267
  MAX_DELIVERY_GAPS,
13268
+ MAX_DESTINATION_HEADERS,
13269
+ MAX_EXPORT_DESTINATIONS,
12604
13270
  MAX_EXTENSION_ENTRIES,
12605
13271
  MAX_IDENTIFIER_LENGTH,
12606
13272
  MAX_LOG_BODY_CHARACTERS,
@@ -12616,6 +13282,7 @@ export {
12616
13282
  MAX_WORKTREE_WALK_DEPTH,
12617
13283
  MCP_TOOL_NAME_PATTERN,
12618
13284
  NO_LOG_CONTENT,
13285
+ OTLP_ENDPOINT_VARIABLES,
12619
13286
  OTLP_HEADER_VARIABLES,
12620
13287
  OtelHookError,
12621
13288
  PROVIDERS_WITHOUT_VERIFIED_LOCATION,
@@ -12680,9 +13347,11 @@ export {
12680
13347
  createCodexAdapter,
12681
13348
  createCursorAdapter,
12682
13349
  createDefaultProviderRegistry,
13350
+ createDestinationFanout,
12683
13351
  createDeterministicIdGenerator,
12684
13352
  createErrorInfo,
12685
13353
  createEventFactory,
13354
+ createExportDestinationSinks,
12686
13355
  createFileDurableLogSpool,
12687
13356
  createFileDurableSpool,
12688
13357
  createFilesystemStateStore,
@@ -12716,6 +13385,7 @@ export {
12716
13385
  deriveWorkspaceIdentity,
12717
13386
  describeAdapter,
12718
13387
  describeErrorCode,
13388
+ describeExportDestinations,
12719
13389
  describeLogsDeliverability,
12720
13390
  describeOtlpHeaderNames,
12721
13391
  describeProviderCatalog,
@@ -12727,7 +13397,9 @@ export {
12727
13397
  detectionPolicySchema,
12728
13398
  diagnosticsPolicySchema,
12729
13399
  durationMillisSchema,
13400
+ effectiveSpoolPolicy,
12730
13401
  emptyExtensions,
13402
+ endpointOrigin,
12731
13403
  epochMillisSchema,
12732
13404
  errorInfoFromThrown,
12733
13405
  errorPhaseSchema,
@@ -12735,6 +13407,10 @@ export {
12735
13407
  errorSeveritySchema,
12736
13408
  eventIdSchema,
12737
13409
  eventUsage,
13410
+ exportDestinationSchema,
13411
+ exportDestinationsSchema,
13412
+ exportSignalSchema,
13413
+ exporterPolicyForDestination,
12738
13414
  exporterPolicySchema,
12739
13415
  extensionKeyNamespace,
12740
13416
  extensionsSchema,
@@ -12745,6 +13421,7 @@ export {
12745
13421
  findRegistrationSupport,
12746
13422
  generationEndEventSchema,
12747
13423
  generationStartEventSchema,
13424
+ hasConfiguredDestinations,
12748
13425
  hostDeliveryIdentity,
12749
13426
  identityClaimFieldsSchema,
12750
13427
  identityClaimSchema,
@@ -12755,6 +13432,7 @@ export {
12755
13432
  isExperimentalProvider,
12756
13433
  isLockingStateStore,
12757
13434
  isOtelHookError,
13435
+ isPermanentExportFailure,
12758
13436
  isReservedExtensionNamespace,
12759
13437
  isReservedResourceAttributeKey,
12760
13438
  isSecretResourceAttributeKey,
@@ -12784,12 +13462,14 @@ export {
12784
13462
  otelHookConfigSchema,
12785
13463
  otelHookErrorCodeSchema,
12786
13464
  otelHookErrorInfoSchema,
13465
+ otlpSignalEndpointFromBase,
12787
13466
  parentScopeRefOf,
12788
13467
  parseCanonicalEvent,
12789
13468
  parseCommonDirFile,
12790
13469
  parseEnvironmentConfig,
12791
13470
  parseGitDirFile,
12792
13471
  parseHeadBranch,
13472
+ parseHeaderValueReference,
12793
13473
  parseOtlpHeadersValue,
12794
13474
  parseResourceAttributesValue,
12795
13475
  planProviderRegistration,
@@ -12822,7 +13502,9 @@ export {
12822
13502
  renderJsonDocument,
12823
13503
  resolveConfig,
12824
13504
  resolveDeliveryIdentity,
13505
+ resolveDestinationHeaders,
12825
13506
  resolveEventTargets,
13507
+ resolveExportDestinations,
12826
13508
  resolveInstallPath,
12827
13509
  resolveInvocationIdentity,
12828
13510
  resolveLogsEndpoint,
@@ -12842,6 +13524,8 @@ export {
12842
13524
  sourceProvenanceSchema,
12843
13525
  sourceTransportSchema,
12844
13526
  spanScopeRefOf,
13527
+ spoolPolicySchema,
13528
+ spoolQueueNamesFor,
12845
13529
  startOnlySpanAttributes,
12846
13530
  stateRecordSchema,
12847
13531
  stateValueSchema,