@osfactory/otel-hook 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +159 -2
  2. package/dist/{adapter-BJiz6lqM.d.ts → adapter-B9RwW6TO.d.ts} +14 -2
  3. package/dist/cli.js +2514 -1238
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +5 -2
  6. package/dist/config.js +479 -169
  7. package/dist/config.js.map +1 -1
  8. package/dist/destinations-DWOkVxV1.d.ts +169 -0
  9. package/dist/diagnostics.d.ts +8 -0
  10. package/dist/diagnostics.js +2 -1
  11. package/dist/diagnostics.js.map +1 -1
  12. package/dist/{events-B3MHoJTD.d.ts → events-CSD_YiJ2.d.ts} +2 -0
  13. package/dist/{otlp-log-sink-zuHojHSP.d.ts → export-destinations-lORbe25J.d.ts} +241 -9
  14. package/dist/{filesystem-store-r-nNA3BA.d.ts → filesystem-store-DX3dGIgu.d.ts} +1 -1
  15. package/dist/{hook-Dh8OO4Wa.d.ts → hook-BAxXoKsp.d.ts} +10 -5
  16. package/dist/index.d.ts +15 -14
  17. package/dist/index.js +1936 -730
  18. package/dist/index.js.map +1 -1
  19. package/dist/install.d.ts +4 -4
  20. package/dist/install.js +31 -2
  21. package/dist/install.js.map +1 -1
  22. package/dist/integration.d.ts +37 -12
  23. package/dist/integration.js +1942 -617
  24. package/dist/integration.js.map +1 -1
  25. package/dist/lifecycle.d.ts +3 -3
  26. package/dist/lifecycle.js +8 -1
  27. package/dist/lifecycle.js.map +1 -1
  28. package/dist/{memory-Bl9ANVff.d.ts → memory-aJilVG4R.d.ts} +2 -2
  29. package/dist/model.d.ts +1 -1
  30. package/dist/model.js +7 -0
  31. package/dist/model.js.map +1 -1
  32. package/dist/{payload-Ci8_ERm6.d.ts → payload-D7gc0-WQ.d.ts} +41 -2
  33. package/dist/{ports-n7KFOpKo.d.ts → ports-plO5MKrY.d.ts} +63 -2
  34. package/dist/providers.d.ts +146 -10
  35. package/dist/providers.js +397 -13
  36. package/dist/providers.js.map +1 -1
  37. package/dist/{registry-CIVvRlVK.d.ts → registry-C7XO4DzD.d.ts} +2 -2
  38. package/dist/runtime.d.ts +8 -8
  39. package/dist/runtime.js +1426 -1163
  40. package/dist/runtime.js.map +1 -1
  41. package/dist/{schema-Cn0-xz8L.d.ts → schema-CHb3GU1r.d.ts} +98 -3
  42. package/dist/{semconv-fPRb-dpU.d.ts → semconv-Dw7gcQcg.d.ts} +1 -1
  43. package/dist/state.d.ts +4 -4
  44. package/dist/state.js +607 -39
  45. package/dist/state.js.map +1 -1
  46. package/dist/telemetry.d.ts +23 -66
  47. package/dist/telemetry.js +637 -34
  48. package/dist/telemetry.js.map +1 -1
  49. package/dist/testing.d.ts +10 -8
  50. package/dist/testing.js +868 -560
  51. package/dist/testing.js.map +1 -1
  52. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -876,6 +876,13 @@ var generationEndEventSchema = event({
876
876
  stopReason: nonEmptyStringSchema.optional(),
877
877
  durationMillis: durationMillisSchema.optional(),
878
878
  usage: canonicalUsageSchema.optional(),
879
+ /**
880
+ * True when `usage` is known to cover only part of the generation (for
881
+ * example the last model request of a multi-request turn); false when the
882
+ * provider or harness said it is the whole. Absent: not stated. Meaningless
883
+ * without `usage`.
884
+ */
885
+ usagePartial: z9.boolean().optional(),
879
886
  cost: costFactsSchema.optional(),
880
887
  outputContent: contentFactsSchema.optional()
881
888
  });
@@ -1345,11 +1352,11 @@ var createPrivacyService = (policyInput) => {
1345
1352
  };
1346
1353
  const flattenToAttributes = (value, prefix) => {
1347
1354
  const attributes = {};
1348
- const walk = (current, path9) => {
1355
+ const walk = (current, path10) => {
1349
1356
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
1350
1357
  const primitive = toAttributePrimitive(current);
1351
1358
  if (primitive !== void 0) {
1352
- attributes[path9] = primitive;
1359
+ attributes[path10] = primitive;
1353
1360
  }
1354
1361
  return;
1355
1362
  }
@@ -1368,16 +1375,16 @@ var createPrivacyService = (policyInput) => {
1368
1375
  primitives.push(entryPrimitive);
1369
1376
  }
1370
1377
  if (uniform) {
1371
- attributes[path9] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
1378
+ attributes[path10] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
1372
1379
  return;
1373
1380
  }
1374
1381
  for (const [index, entry] of current.entries()) {
1375
- walk(entry, `${path9}.${index}`);
1382
+ walk(entry, `${path10}.${index}`);
1376
1383
  }
1377
1384
  return;
1378
1385
  }
1379
1386
  for (const [key, entry] of Object.entries(current)) {
1380
- walk(entry, path9 === "" ? key : `${path9}.${key}`);
1387
+ walk(entry, path10 === "" ? key : `${path10}.${key}`);
1381
1388
  }
1382
1389
  };
1383
1390
  walk(value, prefix);
@@ -1676,37 +1683,361 @@ var sanitizeResourceAttributes = (attributes) => {
1676
1683
  var describeResourceAttributeNames = (attributes) => Object.keys(attributes).sort();
1677
1684
 
1678
1685
  // src/config/schema.ts
1686
+ import { z as z14 } from "zod";
1687
+
1688
+ // src/config/destinations.ts
1679
1689
  import { z as z13 } from "zod";
1680
- var logsPolicySchema = z13.strictObject({
1681
- enabled: z13.boolean(),
1690
+
1691
+ // src/config/header-value.ts
1692
+ var isUnsafeHeaderValue = (value) => [...value].some((char) => {
1693
+ const code = char.codePointAt(0) ?? 0;
1694
+ return code < 32 && code !== 9 || code === 127 || code > 255;
1695
+ });
1696
+
1697
+ // src/config/otlp-headers.ts
1698
+ var MAX_OTLP_HEADERS = 32;
1699
+ var OTLP_HEADER_VARIABLES = Object.freeze({
1700
+ generic: "OTEL_EXPORTER_OTLP_HEADERS",
1701
+ traces: "OTEL_EXPORTER_OTLP_TRACES_HEADERS",
1702
+ logs: "OTEL_EXPORTER_OTLP_LOGS_HEADERS"
1703
+ });
1704
+ var HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
1705
+ var decode = (raw) => {
1706
+ try {
1707
+ return decodeURIComponent(raw);
1708
+ } catch {
1709
+ return void 0;
1710
+ }
1711
+ };
1712
+ var parseOtlpHeadersValue = (raw) => {
1713
+ const headers = {};
1714
+ const warnings = [];
1715
+ let overflowed = false;
1716
+ for (const [index, rawEntry] of raw.split(",").entries()) {
1717
+ const position = String(index + 1);
1718
+ const entry = rawEntry.trim();
1719
+ if (entry === "") {
1720
+ continue;
1721
+ }
1722
+ const equals = entry.indexOf("=");
1723
+ if (equals <= 0) {
1724
+ warnings.push(`entry ${position} is not a key=value pair; ignored`);
1725
+ continue;
1726
+ }
1727
+ const key = decode(entry.slice(0, equals).trim());
1728
+ const value = decode(entry.slice(equals + 1).trim());
1729
+ if (key === void 0 || value === void 0) {
1730
+ warnings.push(`entry ${position} has malformed percent-encoding; ignored`);
1731
+ continue;
1732
+ }
1733
+ const name = key.trim();
1734
+ const trimmedValue = value.trim();
1735
+ if (!HEADER_NAME_PATTERN.test(name)) {
1736
+ warnings.push(`entry ${position} does not name a valid HTTP header; ignored`);
1737
+ continue;
1738
+ }
1739
+ if (trimmedValue === "") {
1740
+ warnings.push(`entry ${position} has an empty value; ignored`);
1741
+ continue;
1742
+ }
1743
+ if (isUnsafeHeaderValue(trimmedValue)) {
1744
+ warnings.push(`entry ${position} has a character not allowed in an HTTP header value; ignored`);
1745
+ continue;
1746
+ }
1747
+ const existing = findHeaderName(headers, name);
1748
+ if (existing === void 0 && Object.keys(headers).length >= MAX_OTLP_HEADERS) {
1749
+ overflowed = true;
1750
+ continue;
1751
+ }
1752
+ if (existing !== void 0) {
1753
+ delete headers[existing];
1754
+ }
1755
+ headers[name] = trimmedValue;
1756
+ }
1757
+ if (overflowed) {
1758
+ warnings.push(`more than ${String(MAX_OTLP_HEADERS)} headers were supplied; the excess was ignored`);
1759
+ }
1760
+ return { headers, warnings };
1761
+ };
1762
+ var findHeaderName = (headers, name) => {
1763
+ const lower = name.toLowerCase();
1764
+ return Object.keys(headers).find((candidate) => candidate.toLowerCase() === lower);
1765
+ };
1766
+ var mergeOtlpHeaders = (...sources) => {
1767
+ const merged = {};
1768
+ for (const source of sources) {
1769
+ for (const [name, value] of Object.entries(source)) {
1770
+ const existing = findHeaderName(merged, name);
1771
+ if (existing !== void 0) {
1772
+ delete merged[existing];
1773
+ }
1774
+ merged[name] = value;
1775
+ }
1776
+ }
1777
+ return merged;
1778
+ };
1779
+ var resolveOtlpHeaders = (env, explicit = {}) => {
1780
+ const warnings = [];
1781
+ const read = (variable) => {
1782
+ const raw = env[variable];
1783
+ if (raw === void 0 || raw.trim() === "") {
1784
+ return {};
1785
+ }
1786
+ const parsed = parseOtlpHeadersValue(raw);
1787
+ for (const detail of parsed.warnings) {
1788
+ warnings.push({ variable, detail });
1789
+ }
1790
+ return parsed.headers;
1791
+ };
1792
+ const generic = read(OTLP_HEADER_VARIABLES.generic);
1793
+ const traces = read(OTLP_HEADER_VARIABLES.traces);
1794
+ const logs = read(OTLP_HEADER_VARIABLES.logs);
1795
+ return {
1796
+ traces: mergeOtlpHeaders(generic, traces, explicit),
1797
+ logs: mergeOtlpHeaders(generic, logs, explicit),
1798
+ warnings
1799
+ };
1800
+ };
1801
+ var unionOtlpHeaderNames = (...lists) => {
1802
+ const names = [];
1803
+ const seen = /* @__PURE__ */ new Set();
1804
+ for (const name of lists.flat()) {
1805
+ if (!seen.has(name.toLowerCase())) {
1806
+ seen.add(name.toLowerCase());
1807
+ names.push(name);
1808
+ }
1809
+ }
1810
+ return names.sort().slice(0, MAX_OTLP_HEADERS);
1811
+ };
1812
+ var describeOtlpHeaderNames = (...sources) => unionOtlpHeaderNames(...sources.map((source) => Object.keys(source)));
1813
+
1814
+ // src/config/destinations.ts
1815
+ var DEFAULT_DESTINATION_NAME = "default";
1816
+ var DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;
1817
+ var MAX_EXPORT_DESTINATIONS = 16;
1818
+ var MAX_DESTINATION_HEADERS = MAX_OTLP_HEADERS;
1819
+ var HEADER_ENV_REFERENCE_PREFIX = "env:";
1820
+ var HEADER_NAME_PATTERN2 = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
1821
+ var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
1822
+ var MAX_HEADER_VALUE_LENGTH = 8192;
1823
+ var exportSignalSchema = z13.enum(["traces", "logs"]);
1824
+ var headerValueSchema = z13.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
1825
+ (value) => !isUnsafeHeaderValue(value),
1826
+ "header values may not contain line breaks, control characters, or characters beyond Latin-1"
1827
+ ).refine(
1828
+ (value) => !value.startsWith(HEADER_ENV_REFERENCE_PREFIX) || ENV_VARIABLE_NAME_PATTERN.test(value.slice(HEADER_ENV_REFERENCE_PREFIX.length)),
1829
+ "an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN"
1830
+ );
1831
+ var endpointSchema = z13.string().url().max(2048);
1832
+ var exportDestinationSchema = z13.strictObject({
1833
+ /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */
1834
+ name: z13.string().regex(DESTINATION_NAME_PATTERN, "destination names are lowercase letters, digits, _ and -"),
1835
+ /** Default true. A disabled destination is neither sent to nor drained. */
1836
+ enabled: z13.boolean().optional(),
1837
+ /**
1838
+ * Traces URL, with the same meaning as `exporter.endpoint`: the logs URL is
1839
+ * derived from it (`/v1/traces` becomes `/v1/logs`) unless `logsEndpoint` is set.
1840
+ */
1841
+ endpoint: endpointSchema.optional(),
1842
+ /** Per-signal override of `endpoint` for traces. */
1843
+ tracesEndpoint: endpointSchema.optional(),
1844
+ /** Per-signal override of the derived logs URL. */
1845
+ logsEndpoint: endpointSchema.optional(),
1846
+ /** Defaults to `exporter.protocol`. */
1847
+ protocol: z13.enum(["http/protobuf", "http/json", "none"]).optional(),
1848
+ /**
1849
+ * Header name to value. A value of the form `env:NAME` is read from that
1850
+ * environment variable at send time, so a credential never has to be written
1851
+ * into the file. Values never appear in a snapshot, a diagnostic, or `doctor`.
1852
+ */
1853
+ headers: z13.record(z13.string().regex(HEADER_NAME_PATTERN2, "not a valid header name"), headerValueSchema).refine(
1854
+ (headers) => Object.keys(headers).length <= MAX_DESTINATION_HEADERS,
1855
+ `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
1856
+ ).optional(),
1857
+ /**
1858
+ * Which signals this destination receives. Default: both. The logs signal is
1859
+ * still governed by `exporter.logs.enabled`, which stays the one opt-in for a
1860
+ * second stream leaving the host.
1861
+ */
1862
+ signals: z13.array(exportSignalSchema).min(1).max(2).readonly().optional()
1863
+ }).refine(
1864
+ (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0,
1865
+ "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint"
1866
+ );
1867
+ var exportDestinationsSchema = z13.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
1868
+ const seen = /* @__PURE__ */ new Set();
1869
+ destinations.forEach((destination, index) => {
1870
+ if (destination.name === DEFAULT_DESTINATION_NAME) {
1871
+ context.addIssue({
1872
+ code: "custom",
1873
+ path: [index, "name"],
1874
+ message: 'the name "default" is reserved for exporter.endpoint and the OTEL_EXPORTER_OTLP_* variables'
1875
+ });
1876
+ }
1877
+ if (seen.has(destination.name)) {
1878
+ context.addIssue({
1879
+ code: "custom",
1880
+ path: [index, "name"],
1881
+ message: `duplicate destination name "${destination.name}"`
1882
+ });
1883
+ }
1884
+ seen.add(destination.name);
1885
+ });
1886
+ });
1887
+ var spoolPolicySchema = z13.strictObject({
1888
+ /** Total bytes of queued batches. Default 16 MiB. */
1889
+ maxBytes: z13.number().int().min(1024).max(1073741824),
1890
+ /** A batch older than this is dropped instead of sent. Default 72 hours. */
1891
+ maxAgeMillis: z13.number().int().min(1e3).max(30 * 24 * 60 * 60 * 1e3),
1892
+ /** Number of queued batches. Default 500. */
1893
+ maxBatches: z13.number().int().min(1).max(65536)
1894
+ });
1895
+ var DEFAULT_SPOOL_POLICY = Object.freeze({
1896
+ maxBytes: 16 * 1024 * 1024,
1897
+ maxAgeMillis: 72 * 60 * 60 * 1e3,
1898
+ maxBatches: 500
1899
+ });
1900
+ var effectiveSpoolPolicy = (exporter) => ({
1901
+ maxBytes: exporter.spool?.maxBytes ?? DEFAULT_SPOOL_POLICY.maxBytes,
1902
+ maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,
1903
+ maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches
1904
+ });
1905
+ var legacyDestination = (exporter) => ({
1906
+ name: DEFAULT_DESTINATION_NAME,
1907
+ source: "exporter",
1908
+ protocol: exporter.protocol,
1909
+ ...exporter.endpoint === void 0 ? {} : { endpoint: exporter.endpoint },
1910
+ ...exporter.logs.endpoint === void 0 ? {} : { logsEndpoint: exporter.logs.endpoint },
1911
+ signals: { traces: true, logs: exporter.logs.enabled },
1912
+ headers: {}
1913
+ });
1914
+ var hasConfiguredDestinations = (exporter) => exporter.destinations !== void 0 && exporter.destinations.length > 0;
1915
+ var resolveExportDestinations = (exporter) => {
1916
+ if (!hasConfiguredDestinations(exporter)) {
1917
+ return [legacyDestination(exporter)];
1918
+ }
1919
+ const resolved = [];
1920
+ if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0) {
1921
+ resolved.push(legacyDestination(exporter));
1922
+ }
1923
+ for (const destination of exporter.destinations ?? []) {
1924
+ if (destination.enabled === false) {
1925
+ continue;
1926
+ }
1927
+ const signals = destination.signals ?? exportSignalSchema.options;
1928
+ resolved.push({
1929
+ name: destination.name,
1930
+ source: "destinations",
1931
+ protocol: destination.protocol ?? exporter.protocol,
1932
+ ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
1933
+ ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
1934
+ ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
1935
+ signals: {
1936
+ traces: signals.includes("traces"),
1937
+ logs: exporter.logs.enabled && signals.includes("logs")
1938
+ },
1939
+ headers: { ...destination.headers ?? {} }
1940
+ });
1941
+ }
1942
+ return resolved;
1943
+ };
1944
+ var parseHeaderValueReference = (value) => value.startsWith(HEADER_ENV_REFERENCE_PREFIX) ? { kind: "env", variable: value.slice(HEADER_ENV_REFERENCE_PREFIX.length) } : { kind: "literal" };
1945
+ var resolveDestinationHeaders = (headers, environment) => {
1946
+ const values = {};
1947
+ const missing = [];
1948
+ for (const [name, value] of Object.entries(headers)) {
1949
+ const reference = parseHeaderValueReference(value);
1950
+ if (reference.kind === "literal") {
1951
+ values[name] = value;
1952
+ continue;
1953
+ }
1954
+ const resolved = environment?.[reference.variable];
1955
+ if (resolved === void 0 || resolved === "") {
1956
+ missing.push(reference.variable);
1957
+ continue;
1958
+ }
1959
+ values[name] = resolved;
1960
+ }
1961
+ return { values, missingVariables: [...new Set(missing)].sort() };
1962
+ };
1963
+ var endpointOrigin = (endpoint) => {
1964
+ if (endpoint === void 0) {
1965
+ return void 0;
1966
+ }
1967
+ try {
1968
+ return new URL(endpoint).origin;
1969
+ } catch {
1970
+ return "<unparsable>";
1971
+ }
1972
+ };
1973
+ var describeExportDestinations = (exporter) => {
1974
+ const describe = (destination, enabled2) => {
1975
+ const tracesOrigin = endpointOrigin(destination.tracesEndpoint ?? destination.endpoint);
1976
+ const logsOrigin = endpointOrigin(
1977
+ destination.logsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint
1978
+ );
1979
+ const variables = Object.values(destination.headers).map(parseHeaderValueReference).flatMap((reference) => reference.kind === "env" ? [reference.variable] : []);
1980
+ return {
1981
+ name: destination.name,
1982
+ enabled: enabled2,
1983
+ protocol: destination.protocol,
1984
+ signals: exportSignalSchema.options.filter((signal) => destination.signals[signal]),
1985
+ ...tracesOrigin === void 0 || !destination.signals.traces ? {} : { tracesEndpointOrigin: tracesOrigin },
1986
+ ...logsOrigin === void 0 || !destination.signals.logs ? {} : { logsEndpointOrigin: logsOrigin },
1987
+ headerNames: destination.source === "exporter" ? [...exporter.headerNames].sort() : Object.keys(destination.headers).sort(),
1988
+ headerVariables: [...new Set(variables)].sort()
1989
+ };
1990
+ };
1991
+ const enabled = resolveExportDestinations(exporter).map(
1992
+ (destination) => describe(destination, true)
1993
+ );
1994
+ const disabled = (exporter.destinations ?? []).filter((destination) => destination.enabled === false).map(
1995
+ (destination) => describe(
1996
+ {
1997
+ name: destination.name,
1998
+ source: "destinations",
1999
+ protocol: destination.protocol ?? exporter.protocol,
2000
+ ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
2001
+ signals: { traces: false, logs: false },
2002
+ headers: { ...destination.headers ?? {} }
2003
+ },
2004
+ false
2005
+ )
2006
+ );
2007
+ return [...enabled, ...disabled];
2008
+ };
2009
+
2010
+ // src/config/schema.ts
2011
+ var logsPolicySchema = z14.strictObject({
2012
+ enabled: z14.boolean(),
1682
2013
  /**
1683
2014
  * Full URL for the logs signal.
1684
2015
  *
1685
2016
  * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes
1686
2017
  * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.
1687
2018
  */
1688
- endpoint: z13.string().url().max(2048).optional(),
1689
- includeContent: z13.boolean(),
1690
- maxBatchSize: z13.number().int().min(1).max(4096)
2019
+ endpoint: z14.string().url().max(2048).optional(),
2020
+ includeContent: z14.boolean(),
2021
+ maxBatchSize: z14.number().int().min(1).max(4096)
1691
2022
  });
1692
2023
  var DEFAULT_LOGS_POLICY = Object.freeze({
1693
2024
  enabled: false,
1694
2025
  includeContent: false,
1695
2026
  maxBatchSize: 128
1696
2027
  });
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(),
2028
+ var exporterPolicySchema = z14.strictObject({
2029
+ enabled: z14.boolean(),
2030
+ protocol: z14.enum(["http/protobuf", "http/json", "none"]),
2031
+ endpoint: z14.string().url().max(2048).optional(),
1701
2032
  /**
1702
2033
  * Header names only. Values are supplied separately at construction time and
1703
2034
  * are never part of a resolved-config snapshot, which is logged and exported.
1704
2035
  */
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),
2036
+ headerNames: z14.array(nonEmptyStringSchema).max(32).readonly(),
2037
+ timeoutMillis: z14.number().int().min(1).max(6e5),
2038
+ maxBatchSize: z14.number().int().min(1).max(4096),
2039
+ maxQueueSize: z14.number().int().min(1).max(65536),
2040
+ maxRetryAttempts: z14.number().int().min(0).max(10),
1710
2041
  serviceName: nonEmptyStringSchema,
1711
2042
  serviceNamespace: nonEmptyStringSchema.optional(),
1712
2043
  /**
@@ -1723,35 +2054,65 @@ var exporterPolicySchema = z13.strictObject({
1723
2054
  * headers, timeout, protocol, service identity, and resource attributes above —
1724
2055
  * a second top-level section would invite two of each to drift apart.
1725
2056
  */
1726
- logs: logsPolicySchema
2057
+ logs: logsPolicySchema,
2058
+ /**
2059
+ * Additional OTLP destinations, each sent every batch in parallel.
2060
+ *
2061
+ * Absent (the default), the exporter has exactly one destination — the
2062
+ * single-endpoint settings above, named `default` — and behaves exactly as it
2063
+ * did before this list existed. See `destinations.ts`.
2064
+ *
2065
+ * Merged as one leaf: a higher layer that sets the list replaces it whole,
2066
+ * because "the union of two partial lists" has no answer an operator could
2067
+ * predict.
2068
+ */
2069
+ destinations: exportDestinationsSchema.optional(),
2070
+ /**
2071
+ * Per-destination retry spool bounds, each optional and merged per leaf; any
2072
+ * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.
2073
+ */
2074
+ spool: spoolPolicySchema.partial().optional()
1727
2075
  });
1728
- var detectionPolicySchema = z13.strictObject({
2076
+ var detectionPolicySchema = z14.strictObject({
1729
2077
  /** Detections below this confidence resolve to the unknown provider. */
1730
2078
  minimumConfidence: detectionConfidenceSchema,
1731
2079
  /** When false, an ambiguous detection is an error rather than unknown. */
1732
- allowAmbiguousFallback: z13.boolean(),
2080
+ allowAmbiguousFallback: z14.boolean(),
1733
2081
  /** Optional allow-list of provider ids; empty means "any registered". */
1734
- allowedProviderIds: z13.array(nonEmptyStringSchema).max(32).readonly()
2082
+ allowedProviderIds: z14.array(nonEmptyStringSchema).max(32).readonly()
1735
2083
  });
1736
- var diagnosticsPolicySchema = z13.strictObject({
1737
- logLevel: z13.enum(["silent", "error", "warn", "info", "debug"]),
2084
+ var diagnosticsPolicySchema = z14.strictObject({
2085
+ logLevel: z14.enum(["silent", "error", "warn", "info", "debug"]),
1738
2086
  /** Emit `error.raised` events for contained failures. */
1739
- emitErrorEvents: z13.boolean()
2087
+ emitErrorEvents: z14.boolean()
1740
2088
  });
1741
- var otelHookConfigSchema = z13.strictObject({
2089
+ var providersPolicySchema = z14.strictObject({
2090
+ claudeCode: z14.strictObject({
2091
+ readTranscriptUsage: z14.boolean()
2092
+ }).optional()
2093
+ });
2094
+ var otelHookConfigSchema = z14.strictObject({
1742
2095
  exporter: exporterPolicySchema,
1743
2096
  privacy: privacyPolicySchema,
1744
2097
  detection: detectionPolicySchema,
1745
- diagnostics: diagnosticsPolicySchema
2098
+ diagnostics: diagnosticsPolicySchema,
2099
+ /** Optional so a hand-built configuration from before it existed stays valid. */
2100
+ providers: providersPolicySchema.optional()
1746
2101
  });
1747
- var otelHookConfigPatchSchema = z13.strictObject({
2102
+ var otelHookConfigPatchSchema = z14.strictObject({
1748
2103
  // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
1749
2104
  // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
1750
2105
  // without also restating the endpoint and the batch size.
1751
- exporter: exporterPolicySchema.omit({ logs: true }).partial().extend({ logs: logsPolicySchema.partial().optional() }).optional(),
2106
+ exporter: exporterPolicySchema.omit({ logs: true, spool: true }).partial().extend({
2107
+ logs: logsPolicySchema.partial().optional(),
2108
+ spool: spoolPolicySchema.partial().optional()
2109
+ }).optional(),
1752
2110
  privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
1753
2111
  detection: detectionPolicySchema.partial().optional(),
1754
- diagnostics: diagnosticsPolicySchema.partial().optional()
2112
+ diagnostics: diagnosticsPolicySchema.partial().optional(),
2113
+ providers: z14.strictObject({
2114
+ claudeCode: z14.strictObject({ readTranscriptUsage: z14.boolean() }).partial().optional()
2115
+ }).partial().optional()
1755
2116
  });
1756
2117
  var DEFAULT_EXPORTER_POLICY = Object.freeze({
1757
2118
  enabled: true,
@@ -1774,27 +2135,32 @@ var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
1774
2135
  logLevel: "warn",
1775
2136
  emitErrorEvents: true
1776
2137
  });
2138
+ var DEFAULT_PROVIDERS_POLICY = Object.freeze({
2139
+ claudeCode: Object.freeze({ readTranscriptUsage: false })
2140
+ });
1777
2141
  var DEFAULT_CONFIG = Object.freeze({
1778
2142
  exporter: DEFAULT_EXPORTER_POLICY,
1779
2143
  privacy: DEFAULT_PRIVACY_POLICY,
1780
2144
  detection: DEFAULT_DETECTION_POLICY,
1781
- diagnostics: DEFAULT_DIAGNOSTICS_POLICY
2145
+ diagnostics: DEFAULT_DIAGNOSTICS_POLICY,
2146
+ providers: DEFAULT_PROVIDERS_POLICY
1782
2147
  });
2148
+ var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
1783
2149
 
1784
2150
  // src/config/resolve.ts
1785
- import { z as z14 } from "zod";
2151
+ import { z as z15 } from "zod";
1786
2152
  var CONFIG_SOURCE_PRECEDENCE = ["defaults", "file", "environment", "inline-override"];
1787
- var configSourceSchema = z14.enum(CONFIG_SOURCE_PRECEDENCE);
2153
+ var configSourceSchema = z15.enum(CONFIG_SOURCE_PRECEDENCE);
1788
2154
  var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1789
- var mergeLeaf = (target, patch, source, provenance, path9) => {
2155
+ var mergeLeaf = (target, patch, source, provenance, path10) => {
1790
2156
  for (const [key, value] of Object.entries(patch)) {
1791
2157
  if (value === void 0) {
1792
2158
  continue;
1793
2159
  }
1794
- const childPath = path9 === "" ? key : `${path9}.${key}`;
2160
+ const childPath = path10 === "" ? key : `${path10}.${key}`;
1795
2161
  const existing = target[key];
1796
- if (isPlainObject(value) && isPlainObject(existing)) {
1797
- const child = { ...existing };
2162
+ if (isPlainObject(value) && (isPlainObject(existing) || existing === void 0)) {
2163
+ const child = { ...existing ?? {} };
1798
2164
  mergeLeaf(child, value, source, provenance, childPath);
1799
2165
  target[key] = child;
1800
2166
  continue;
@@ -1805,14 +2171,14 @@ var mergeLeaf = (target, patch, source, provenance, path9) => {
1805
2171
  };
1806
2172
  var initialProvenance = (config) => {
1807
2173
  const provenance = {};
1808
- const walk = (value, path9) => {
2174
+ const walk = (value, path10) => {
1809
2175
  if (isPlainObject(value)) {
1810
2176
  for (const [key, child] of Object.entries(value)) {
1811
- walk(child, path9 === "" ? key : `${path9}.${key}`);
2177
+ walk(child, path10 === "" ? key : `${path10}.${key}`);
1812
2178
  }
1813
2179
  return;
1814
2180
  }
1815
- provenance[path9] = "defaults";
2181
+ provenance[path10] = "defaults";
1816
2182
  };
1817
2183
  walk(config, "");
1818
2184
  return provenance;
@@ -1866,10 +2232,27 @@ var resolveConfig = (layers = []) => {
1866
2232
  if (parsed.data.privacy.contentMode === "raw" && !parsed.data.privacy.allowRawContent) {
1867
2233
  notes.push("privacy.contentMode=raw will be downgraded to omit: allowRawContent is false");
1868
2234
  }
1869
- if (parsed.data.exporter.enabled && parsed.data.exporter.protocol !== "none" && parsed.data.exporter.endpoint === void 0) {
2235
+ const withDestinations = hasConfiguredDestinations(parsed.data.exporter);
2236
+ if (parsed.data.exporter.enabled && parsed.data.exporter.protocol !== "none" && parsed.data.exporter.endpoint === void 0 && !withDestinations) {
1870
2237
  notes.push("exporter.enabled is true but no endpoint is configured");
1871
2238
  }
1872
- if (parsed.data.exporter.logs.enabled && parsed.data.exporter.logs.endpoint === void 0 && parsed.data.exporter.endpoint === void 0) {
2239
+ if (withDestinations) {
2240
+ const enabled = (parsed.data.exporter.destinations ?? []).filter(
2241
+ (destination) => destination.enabled !== false
2242
+ );
2243
+ if (enabled.length === 0 && parsed.data.exporter.endpoint === void 0) {
2244
+ notes.push("exporter.destinations is set but every destination is disabled");
2245
+ }
2246
+ if (!parsed.data.exporter.logs.enabled) {
2247
+ const askingForLogs = enabled.filter((destination) => destination.signals?.includes("logs") === true).map((destination) => destination.name);
2248
+ if (askingForLogs.length > 0) {
2249
+ notes.push(
2250
+ `destination(s) ${askingForLogs.join(", ")} list the logs signal but exporter.logs.enabled is false, so only traces are sent`
2251
+ );
2252
+ }
2253
+ }
2254
+ }
2255
+ if (!withDestinations && parsed.data.exporter.logs.enabled && parsed.data.exporter.logs.endpoint === void 0 && parsed.data.exporter.endpoint === void 0) {
1873
2256
  notes.push(
1874
2257
  "exporter.logs.enabled is true but neither a logs endpoint nor a trace endpoint to derive one from is configured"
1875
2258
  );
@@ -1881,6 +2264,35 @@ var resolveConfig = (layers = []) => {
1881
2264
  }
1882
2265
  return { status: "ok", config: parsed.data, provenance, notes };
1883
2266
  };
2267
+ var describeDestinationAttributes = (config) => {
2268
+ const attributes = {};
2269
+ if (config.exporter.spool !== void 0 || hasConfiguredDestinations(config.exporter)) {
2270
+ const spool = effectiveSpoolPolicy(config.exporter);
2271
+ attributes["exporter.spool_max_bytes"] = spool.maxBytes;
2272
+ attributes["exporter.spool_max_age_millis"] = spool.maxAgeMillis;
2273
+ attributes["exporter.spool_max_batches"] = spool.maxBatches;
2274
+ }
2275
+ if (!hasConfiguredDestinations(config.exporter)) {
2276
+ return attributes;
2277
+ }
2278
+ const destinations = describeExportDestinations(config.exporter);
2279
+ attributes["exporter.destination_names"] = destinations.map((destination) => destination.name);
2280
+ for (const destination of destinations) {
2281
+ const prefix = `exporter.destination.${destination.name}`;
2282
+ attributes[`${prefix}.enabled`] = destination.enabled;
2283
+ attributes[`${prefix}.protocol`] = destination.protocol;
2284
+ attributes[`${prefix}.signals`] = [...destination.signals];
2285
+ if (destination.tracesEndpointOrigin !== void 0) {
2286
+ attributes[`${prefix}.traces_endpoint_origin`] = destination.tracesEndpointOrigin;
2287
+ }
2288
+ if (destination.logsEndpointOrigin !== void 0) {
2289
+ attributes[`${prefix}.logs_endpoint_origin`] = destination.logsEndpointOrigin;
2290
+ }
2291
+ attributes[`${prefix}.header_names`] = [...destination.headerNames];
2292
+ attributes[`${prefix}.header_variables`] = [...destination.headerVariables];
2293
+ }
2294
+ return attributes;
2295
+ };
1884
2296
  var describeResolvedConfig = (config) => {
1885
2297
  const originOf = (endpoint) => {
1886
2298
  if (endpoint === void 0) {
@@ -1892,12 +2304,12 @@ var describeResolvedConfig = (config) => {
1892
2304
  return "<unparsable>";
1893
2305
  }
1894
2306
  };
1895
- const endpointOrigin = originOf(config.exporter.endpoint);
2307
+ const endpointOrigin2 = originOf(config.exporter.endpoint);
1896
2308
  const logsEndpointOrigin = originOf(config.exporter.logs.endpoint);
1897
2309
  return {
1898
2310
  "exporter.enabled": config.exporter.enabled,
1899
2311
  "exporter.protocol": config.exporter.protocol,
1900
- ...endpointOrigin === void 0 ? {} : { "exporter.endpoint_origin": endpointOrigin },
2312
+ ...endpointOrigin2 === void 0 ? {} : { "exporter.endpoint_origin": endpointOrigin2 },
1901
2313
  "exporter.logs_enabled": config.exporter.logs.enabled,
1902
2314
  "exporter.logs_include_content": config.exporter.logs.includeContent,
1903
2315
  "exporter.logs_max_batch_size": config.exporter.logs.maxBatchSize,
@@ -1909,6 +2321,7 @@ var describeResolvedConfig = (config) => {
1909
2321
  "exporter.resource_attribute_names": [
1910
2322
  ...describeResourceAttributeNames(config.exporter.resourceAttributes)
1911
2323
  ],
2324
+ ...describeDestinationAttributes(config),
1912
2325
  "exporter.timeout_millis": config.exporter.timeoutMillis,
1913
2326
  "exporter.max_batch_size": config.exporter.maxBatchSize,
1914
2327
  "exporter.service_name": config.exporter.serviceName,
@@ -1949,127 +2362,6 @@ var otlpSignalEndpointFromBase = (base, signal) => {
1949
2362
  return `${trimmed}${signal === "traces" ? OTLP_TRACES_PATH : OTLP_LOGS_PATH}`;
1950
2363
  };
1951
2364
 
1952
- // src/config/otlp-headers.ts
1953
- var MAX_OTLP_HEADERS = 32;
1954
- var OTLP_HEADER_VARIABLES = Object.freeze({
1955
- generic: "OTEL_EXPORTER_OTLP_HEADERS",
1956
- traces: "OTEL_EXPORTER_OTLP_TRACES_HEADERS",
1957
- logs: "OTEL_EXPORTER_OTLP_LOGS_HEADERS"
1958
- });
1959
- var HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
1960
- var isUnsafeHeaderValue = (value) => [...value].some((char) => {
1961
- const code = char.codePointAt(0) ?? 0;
1962
- return code < 32 && code !== 9 || code === 127 || code > 255;
1963
- });
1964
- var decode = (raw) => {
1965
- try {
1966
- return decodeURIComponent(raw);
1967
- } catch {
1968
- return void 0;
1969
- }
1970
- };
1971
- var parseOtlpHeadersValue = (raw) => {
1972
- const headers = {};
1973
- const warnings = [];
1974
- let overflowed = false;
1975
- for (const [index, rawEntry] of raw.split(",").entries()) {
1976
- const position = String(index + 1);
1977
- const entry = rawEntry.trim();
1978
- if (entry === "") {
1979
- continue;
1980
- }
1981
- const equals = entry.indexOf("=");
1982
- if (equals <= 0) {
1983
- warnings.push(`entry ${position} is not a key=value pair; ignored`);
1984
- continue;
1985
- }
1986
- const key = decode(entry.slice(0, equals).trim());
1987
- const value = decode(entry.slice(equals + 1).trim());
1988
- if (key === void 0 || value === void 0) {
1989
- warnings.push(`entry ${position} has malformed percent-encoding; ignored`);
1990
- continue;
1991
- }
1992
- const name = key.trim();
1993
- const trimmedValue = value.trim();
1994
- if (!HEADER_NAME_PATTERN.test(name)) {
1995
- warnings.push(`entry ${position} does not name a valid HTTP header; ignored`);
1996
- continue;
1997
- }
1998
- if (trimmedValue === "") {
1999
- warnings.push(`entry ${position} has an empty value; ignored`);
2000
- continue;
2001
- }
2002
- if (isUnsafeHeaderValue(trimmedValue)) {
2003
- warnings.push(`entry ${position} has a character not allowed in an HTTP header value; ignored`);
2004
- continue;
2005
- }
2006
- const existing = findHeaderName(headers, name);
2007
- if (existing === void 0 && Object.keys(headers).length >= MAX_OTLP_HEADERS) {
2008
- overflowed = true;
2009
- continue;
2010
- }
2011
- if (existing !== void 0) {
2012
- delete headers[existing];
2013
- }
2014
- headers[name] = trimmedValue;
2015
- }
2016
- if (overflowed) {
2017
- warnings.push(`more than ${String(MAX_OTLP_HEADERS)} headers were supplied; the excess was ignored`);
2018
- }
2019
- return { headers, warnings };
2020
- };
2021
- var findHeaderName = (headers, name) => {
2022
- const lower = name.toLowerCase();
2023
- return Object.keys(headers).find((candidate) => candidate.toLowerCase() === lower);
2024
- };
2025
- var mergeOtlpHeaders = (...sources) => {
2026
- const merged = {};
2027
- for (const source of sources) {
2028
- for (const [name, value] of Object.entries(source)) {
2029
- const existing = findHeaderName(merged, name);
2030
- if (existing !== void 0) {
2031
- delete merged[existing];
2032
- }
2033
- merged[name] = value;
2034
- }
2035
- }
2036
- return merged;
2037
- };
2038
- var resolveOtlpHeaders = (env, explicit = {}) => {
2039
- const warnings = [];
2040
- const read = (variable) => {
2041
- const raw = env[variable];
2042
- if (raw === void 0 || raw.trim() === "") {
2043
- return {};
2044
- }
2045
- const parsed = parseOtlpHeadersValue(raw);
2046
- for (const detail of parsed.warnings) {
2047
- warnings.push({ variable, detail });
2048
- }
2049
- return parsed.headers;
2050
- };
2051
- const generic = read(OTLP_HEADER_VARIABLES.generic);
2052
- const traces = read(OTLP_HEADER_VARIABLES.traces);
2053
- const logs = read(OTLP_HEADER_VARIABLES.logs);
2054
- return {
2055
- traces: mergeOtlpHeaders(generic, traces, explicit),
2056
- logs: mergeOtlpHeaders(generic, logs, explicit),
2057
- warnings
2058
- };
2059
- };
2060
- var unionOtlpHeaderNames = (...lists) => {
2061
- const names = [];
2062
- const seen = /* @__PURE__ */ new Set();
2063
- for (const name of lists.flat()) {
2064
- if (!seen.has(name.toLowerCase())) {
2065
- seen.add(name.toLowerCase());
2066
- names.push(name);
2067
- }
2068
- }
2069
- return names.sort().slice(0, MAX_OTLP_HEADERS);
2070
- };
2071
- var describeOtlpHeaderNames = (...sources) => unionOtlpHeaderNames(...sources.map((source) => Object.keys(source)));
2072
-
2073
2365
  // src/config/environment.ts
2074
2366
  var ENVIRONMENT_VARIABLES = Object.freeze({
2075
2367
  exporterEnabled: "OTEL_HOOK_ENABLED",
@@ -2101,7 +2393,9 @@ var ENVIRONMENT_VARIABLES = Object.freeze({
2101
2393
  maxArrayLength: "OTEL_HOOK_MAX_ARRAY_LENGTH",
2102
2394
  maxEventsPerInvocation: "OTEL_HOOK_MAX_EVENTS_PER_INVOCATION",
2103
2395
  minimumConfidence: "OTEL_HOOK_MIN_DETECTION_CONFIDENCE",
2104
- logLevel: "OTEL_HOOK_LOG_LEVEL"
2396
+ logLevel: "OTEL_HOOK_LOG_LEVEL",
2397
+ /** `providers.claudeCode.readTranscriptUsage`; see `providersPolicySchema`. */
2398
+ claudeTranscriptUsage: "OTEL_HOOK_CLAUDE_TRANSCRIPT_USAGE"
2105
2399
  });
2106
2400
  var BOOLEAN_TRUE = /* @__PURE__ */ new Set(["1", "true", "yes", "on"]);
2107
2401
  var BOOLEAN_FALSE = /* @__PURE__ */ new Set(["0", "false", "no", "off"]);
@@ -2278,37 +2572,40 @@ var parseEnvironmentConfig = (env) => {
2278
2572
  };
2279
2573
  const detection = confidenceParsed?.success === true ? { minimumConfidence: confidenceParsed.data } : {};
2280
2574
  const diagnostics = logLevel === void 0 ? {} : { logLevel };
2575
+ const claudeTranscriptUsage = readBoolean(ENVIRONMENT_VARIABLES.claudeTranscriptUsage);
2576
+ const providers = claudeTranscriptUsage === void 0 ? {} : { claudeCode: { readTranscriptUsage: claudeTranscriptUsage } };
2281
2577
  const patch = {
2282
2578
  ...Object.keys(exporter).length === 0 ? {} : { exporter },
2283
2579
  ...Object.keys(privacy).length === 0 ? {} : { privacy },
2284
2580
  ...Object.keys(detection).length === 0 ? {} : { detection },
2285
- ...Object.keys(diagnostics).length === 0 ? {} : { diagnostics }
2581
+ ...Object.keys(diagnostics).length === 0 ? {} : { diagnostics },
2582
+ ...Object.keys(providers).length === 0 ? {} : { providers }
2286
2583
  };
2287
2584
  return { patch, warnings };
2288
2585
  };
2289
2586
 
2290
2587
  // src/providers/adapter.ts
2291
- import { z as z15 } from "zod";
2292
- var providerDetectionSchema = z15.strictObject({
2588
+ import { z as z16 } from "zod";
2589
+ var providerDetectionSchema = z16.strictObject({
2293
2590
  providerId: resolvedProviderIdSchema,
2294
2591
  confidence: detectionConfidenceSchema,
2295
2592
  /**
2296
2593
  * Short, non-sensitive justifications, e.g. `"payload.hook_event_name present"`.
2297
2594
  * Reasons are exported in diagnostics, so they must not quote payload values.
2298
2595
  */
2299
- reasons: z15.array(z15.string().min(1).max(160)).max(8),
2596
+ reasons: z16.array(z16.string().min(1).max(160)).max(8),
2300
2597
  providerVersion: nonEmptyStringSchema.optional(),
2301
2598
  /** The provider's own name for this event, when the payload states one. */
2302
2599
  sourceEventName: nonEmptyStringSchema.optional()
2303
2600
  });
2304
- var deliveryIdentifierSupportSchema = z15.enum(["none", "partial", "all"]);
2601
+ var deliveryIdentifierSupportSchema = z16.enum(["none", "partial", "all"]);
2305
2602
  var DELIVERY_COMPONENT_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
2306
- var deliveryComponentSchema = z15.string().regex(
2603
+ var deliveryComponentSchema = z16.string().regex(
2307
2604
  DELIVERY_COMPONENT_PATTERN,
2308
2605
  "delivery component must be identifier-shaped: no whitespace, no path separators"
2309
2606
  );
2310
2607
  var MAX_DELIVERY_COMPONENTS = 8;
2311
- var providerDeliveryClaimSchema = z15.strictObject({
2608
+ var providerDeliveryClaimSchema = z16.strictObject({
2312
2609
  /**
2313
2610
  * The provider's own session/conversation id. Scopes the callback identity, so
2314
2611
  * two sessions reusing one tool-call id never collide.
@@ -2320,26 +2617,26 @@ var providerDeliveryClaimSchema = z15.strictObject({
2320
2617
  * Identifier-shaped payload fields that, together with `sourceEventName`,
2321
2618
  * name this callback within the session exactly once.
2322
2619
  */
2323
- components: z15.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),
2620
+ components: z16.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),
2324
2621
  /**
2325
2622
  * Short, non-sensitive justifications, e.g. `"payload.tool_use_id names one
2326
2623
  * tool call"`. Evidence reaches diagnostics, so it must name fields, never
2327
2624
  * quote their values.
2328
2625
  */
2329
- evidence: z15.array(z15.string().min(1).max(160)).min(1).max(4).readonly()
2626
+ evidence: z16.array(z16.string().min(1).max(160)).min(1).max(4).readonly()
2330
2627
  });
2331
2628
  var DELIVERY_GAP_REASON_PATTERN = /^[^\n\r\t\\/]{1,240}$/;
2332
- var deliveryGapReasonSchema = z15.string().regex(
2629
+ var deliveryGapReasonSchema = z16.string().regex(
2333
2630
  DELIVERY_GAP_REASON_PATTERN,
2334
2631
  "delivery gap reason must be one line of prose: no path separators, no control characters"
2335
2632
  );
2336
2633
  var MAX_DELIVERY_GAPS = 48;
2337
- var providerDeliveryGapsSchema = z15.record(deliveryComponentSchema, deliveryGapReasonSchema).refine((gaps) => Object.keys(gaps).length <= MAX_DELIVERY_GAPS, {
2634
+ var providerDeliveryGapsSchema = z16.record(deliveryComponentSchema, deliveryGapReasonSchema).refine((gaps) => Object.keys(gaps).length <= MAX_DELIVERY_GAPS, {
2338
2635
  message: `at most ${String(MAX_DELIVERY_GAPS)} delivery gaps may be declared`
2339
2636
  });
2340
- var providerCapabilitiesSchema = z15.strictObject({
2637
+ var providerCapabilitiesSchema = z16.strictObject({
2341
2638
  /** Event types the adapter can produce. */
2342
- lifecycleEvents: z15.array(canonicalEventTypeSchema).max(32).readonly(),
2639
+ lifecycleEvents: z16.array(canonicalEventTypeSchema).max(32).readonly(),
2343
2640
  usageTemporality: usageTemporalitySchema,
2344
2641
  /**
2345
2642
  * Which accumulator series a `cumulative` report continues — that is, which
@@ -2358,32 +2655,32 @@ var providerCapabilitiesSchema = z15.strictObject({
2358
2655
  * Subagent snapshots keep their own series regardless: a delegated agent's
2359
2656
  * counter is not a point on the parent session's curve.
2360
2657
  */
2361
- cumulativeUsageSeries: z15.enum(["event-scope", "session-lifetime"]).optional(),
2362
- reportsCachedInput: z15.boolean(),
2363
- reportsCacheCreation: z15.boolean(),
2658
+ cumulativeUsageSeries: z16.enum(["event-scope", "session-lifetime"]).optional(),
2659
+ reportsCachedInput: z16.boolean(),
2660
+ reportsCacheCreation: z16.boolean(),
2364
2661
  cacheCreationAccounting: cacheCreationAccountingSchema,
2365
- reportsReasoningOutput: z15.boolean(),
2366
- reportsProviderTotal: z15.boolean(),
2367
- reportsCost: z15.boolean(),
2368
- emitsSubagentEvents: z15.boolean(),
2369
- emitsCompactionEvents: z15.boolean(),
2662
+ reportsReasoningOutput: z16.boolean(),
2663
+ reportsProviderTotal: z16.boolean(),
2664
+ reportsCost: z16.boolean(),
2665
+ emitsSubagentEvents: z16.boolean(),
2666
+ emitsCompactionEvents: z16.boolean(),
2370
2667
  /** True when the provider reads a structured response from stdout. */
2371
- requiresHookResponse: z15.boolean(),
2668
+ requiresHookResponse: z16.boolean(),
2372
2669
  /** How much of this provider's hook traffic is replay-identifiable. */
2373
2670
  deliveryIdentifier: deliveryIdentifierSupportSchema
2374
2671
  });
2375
- var providerHookResponseSchema = z15.strictObject({
2672
+ var providerHookResponseSchema = z16.strictObject({
2376
2673
  /**
2377
2674
  * Always 0. A telemetry hook that can fail the host agent is a liability, so
2378
2675
  * the type forbids expressing anything else (ADR 0004).
2379
2676
  */
2380
- exitCode: z15.literal(0),
2677
+ exitCode: z16.literal(0),
2381
2678
  /** Protocol response text. Omit to write nothing at all. */
2382
- stdout: z15.string().max(8192).optional(),
2679
+ stdout: z16.string().max(8192).optional(),
2383
2680
  /** Non-sensitive diagnostic text for stderr. */
2384
- stderr: z15.string().max(8192).optional(),
2681
+ stderr: z16.string().max(8192).optional(),
2385
2682
  /** Declares which of the two stdout contracts this response follows. */
2386
- contract: z15.enum(["silent", "provider-protocol"])
2683
+ contract: z16.enum(["silent", "provider-protocol"])
2387
2684
  });
2388
2685
  var SILENT_HOOK_RESPONSE = Object.freeze({
2389
2686
  exitCode: 0,
@@ -2652,35 +2949,35 @@ var CLAUDE_CODE_CAPABILITIES = Object.freeze({
2652
2949
  });
2653
2950
 
2654
2951
  // src/providers/claude/schema.ts
2655
- import { z as z16 } from "zod";
2952
+ import { z as z17 } from "zod";
2656
2953
  var commonFields = {
2657
- session_id: z16.string().min(1),
2658
- transcript_path: z16.string().min(1).optional(),
2659
- cwd: z16.string().min(1).optional(),
2660
- permission_mode: z16.string().min(1).optional(),
2954
+ session_id: z17.string().min(1),
2955
+ transcript_path: z17.string().min(1).optional(),
2956
+ cwd: z17.string().min(1).optional(),
2957
+ permission_mode: z17.string().min(1).optional(),
2661
2958
  /** Correlates a hook firing with the user prompt that triggered it (Claude Code v2.1.196+). */
2662
- prompt_id: z16.string().min(1).optional(),
2959
+ prompt_id: z17.string().min(1).optional(),
2663
2960
  /** Present when the hook fired while running inside a subagent. */
2664
- agent_id: z16.string().min(1).optional(),
2665
- agent_type: z16.string().min(1).optional()
2666
- };
2667
- var claudeCacheCreationSchema = z16.object({
2668
- ephemeral_5m_input_tokens: z16.number().int().min(0).optional(),
2669
- ephemeral_1h_input_tokens: z16.number().int().min(0).optional()
2670
- });
2671
- var claudeUsageIterationSchema = z16.object({
2672
- input_tokens: z16.number().int().min(0).optional(),
2673
- output_tokens: z16.number().int().min(0).optional(),
2674
- cache_creation_input_tokens: z16.number().int().min(0).optional(),
2675
- cache_read_input_tokens: z16.number().int().min(0).optional()
2676
- });
2677
- var claudeUsageSchema = z16.object({
2678
- input_tokens: z16.number().int().min(0),
2679
- output_tokens: z16.number().int().min(0),
2680
- cache_creation_input_tokens: z16.number().int().min(0).optional(),
2681
- cache_read_input_tokens: z16.number().int().min(0).optional(),
2961
+ agent_id: z17.string().min(1).optional(),
2962
+ agent_type: z17.string().min(1).optional()
2963
+ };
2964
+ var claudeCacheCreationSchema = z17.object({
2965
+ ephemeral_5m_input_tokens: z17.number().int().min(0).optional(),
2966
+ ephemeral_1h_input_tokens: z17.number().int().min(0).optional()
2967
+ });
2968
+ var claudeUsageIterationSchema = z17.object({
2969
+ input_tokens: z17.number().int().min(0).optional(),
2970
+ output_tokens: z17.number().int().min(0).optional(),
2971
+ cache_creation_input_tokens: z17.number().int().min(0).optional(),
2972
+ cache_read_input_tokens: z17.number().int().min(0).optional()
2973
+ });
2974
+ var claudeUsageSchema = z17.object({
2975
+ input_tokens: z17.number().int().min(0),
2976
+ output_tokens: z17.number().int().min(0),
2977
+ cache_creation_input_tokens: z17.number().int().min(0).optional(),
2978
+ cache_read_input_tokens: z17.number().int().min(0).optional(),
2682
2979
  cache_creation: claudeCacheCreationSchema.optional(),
2683
- iterations: z16.array(claudeUsageIterationSchema).optional(),
2980
+ iterations: z17.array(claudeUsageIterationSchema).optional(),
2684
2981
  /**
2685
2982
  * Counters the canonical model has a home for but Claude Code never reports:
2686
2983
  * 0 of 4,999 real usage objects carried either (finding 5).
@@ -2689,112 +2986,112 @@ var claudeUsageSchema = z16.object({
2689
2986
  * that a harness attaching one gets told it was excluded, instead of watching
2690
2987
  * it vanish. See `CLAUDE_EXCLUDED_USAGE_COUNTERS`.
2691
2988
  */
2692
- total_tokens: z16.number().int().min(0).optional(),
2693
- reasoning_output_tokens: z16.number().int().min(0).optional()
2989
+ total_tokens: z17.number().int().min(0).optional(),
2990
+ reasoning_output_tokens: z17.number().int().min(0).optional()
2694
2991
  });
2695
- var sessionStartPayloadSchema = z16.object({
2992
+ var sessionStartPayloadSchema = z17.object({
2696
2993
  ...commonFields,
2697
- hook_event_name: z16.literal("SessionStart"),
2994
+ hook_event_name: z17.literal("SessionStart"),
2698
2995
  /** Matcher values: startup | resume | clear | compact | fork. Forward-compatible: any string. */
2699
- source: z16.string().min(1).optional(),
2700
- model: z16.string().min(1).optional(),
2701
- session_title: z16.string().min(1).optional()
2996
+ source: z17.string().min(1).optional(),
2997
+ model: z17.string().min(1).optional(),
2998
+ session_title: z17.string().min(1).optional()
2702
2999
  });
2703
- var sessionEndPayloadSchema = z16.object({
3000
+ var sessionEndPayloadSchema = z17.object({
2704
3001
  ...commonFields,
2705
- hook_event_name: z16.literal("SessionEnd"),
3002
+ hook_event_name: z17.literal("SessionEnd"),
2706
3003
  /** Current Claude Code field; values include clear, logout, prompt_input_exit, and other. */
2707
- reason: z16.string().min(1).optional(),
3004
+ reason: z17.string().min(1).optional(),
2708
3005
  /** Compatibility alias emitted by older wrappers and hook integrations. */
2709
- end_reason: z16.string().min(1).optional()
3006
+ end_reason: z17.string().min(1).optional()
2710
3007
  });
2711
- var userPromptSubmitPayloadSchema = z16.object({
3008
+ var userPromptSubmitPayloadSchema = z17.object({
2712
3009
  ...commonFields,
2713
- hook_event_name: z16.literal("UserPromptSubmit"),
2714
- prompt: z16.string()
3010
+ hook_event_name: z17.literal("UserPromptSubmit"),
3011
+ prompt: z17.string()
2715
3012
  });
2716
- var preToolUsePayloadSchema = z16.object({
3013
+ var preToolUsePayloadSchema = z17.object({
2717
3014
  ...commonFields,
2718
- hook_event_name: z16.literal("PreToolUse"),
2719
- tool_name: z16.string().min(1),
2720
- tool_input: z16.unknown(),
2721
- tool_use_id: z16.string().min(1)
3015
+ hook_event_name: z17.literal("PreToolUse"),
3016
+ tool_name: z17.string().min(1),
3017
+ tool_input: z17.unknown(),
3018
+ tool_use_id: z17.string().min(1)
2722
3019
  });
2723
- var postToolUsePayloadSchema = z16.object({
3020
+ var postToolUsePayloadSchema = z17.object({
2724
3021
  ...commonFields,
2725
- hook_event_name: z16.literal("PostToolUse"),
2726
- tool_name: z16.string().min(1),
2727
- tool_input: z16.unknown().optional(),
2728
- tool_response: z16.unknown(),
2729
- tool_use_id: z16.string().min(1)
3022
+ hook_event_name: z17.literal("PostToolUse"),
3023
+ tool_name: z17.string().min(1),
3024
+ tool_input: z17.unknown().optional(),
3025
+ tool_response: z17.unknown(),
3026
+ tool_use_id: z17.string().min(1)
2730
3027
  });
2731
- var postToolUseFailurePayloadSchema = z16.object({
3028
+ var postToolUseFailurePayloadSchema = z17.object({
2732
3029
  ...commonFields,
2733
- hook_event_name: z16.literal("PostToolUseFailure"),
2734
- tool_name: z16.string().min(1),
2735
- tool_input: z16.unknown().optional(),
2736
- tool_error: z16.unknown(),
2737
- tool_use_id: z16.string().min(1)
3030
+ hook_event_name: z17.literal("PostToolUseFailure"),
3031
+ tool_name: z17.string().min(1),
3032
+ tool_input: z17.unknown().optional(),
3033
+ tool_error: z17.unknown(),
3034
+ tool_use_id: z17.string().min(1)
2738
3035
  });
2739
- var permissionRequestPayloadSchema = z16.object({
3036
+ var permissionRequestPayloadSchema = z17.object({
2740
3037
  ...commonFields,
2741
- hook_event_name: z16.literal("PermissionRequest"),
2742
- tool_name: z16.string().min(1),
2743
- tool_input: z16.unknown().optional(),
2744
- tool_use_id: z16.string().min(1)
3038
+ hook_event_name: z17.literal("PermissionRequest"),
3039
+ tool_name: z17.string().min(1),
3040
+ tool_input: z17.unknown().optional(),
3041
+ tool_use_id: z17.string().min(1)
2745
3042
  });
2746
- var subagentStartPayloadSchema = z16.object({
3043
+ var subagentStartPayloadSchema = z17.object({
2747
3044
  ...commonFields,
2748
- hook_event_name: z16.literal("SubagentStart"),
2749
- agent_type: z16.string().min(1),
2750
- agent_id: z16.string().min(1)
3045
+ hook_event_name: z17.literal("SubagentStart"),
3046
+ agent_type: z17.string().min(1),
3047
+ agent_id: z17.string().min(1)
2751
3048
  });
2752
- var subagentStopPayloadSchema = z16.object({
3049
+ var subagentStopPayloadSchema = z17.object({
2753
3050
  ...commonFields,
2754
- hook_event_name: z16.literal("SubagentStop"),
2755
- agent_type: z16.string().min(1),
2756
- agent_id: z16.string().min(1),
2757
- last_assistant_message: z16.string().optional(),
3051
+ hook_event_name: z17.literal("SubagentStop"),
3052
+ agent_type: z17.string().min(1),
3053
+ agent_id: z17.string().min(1),
3054
+ last_assistant_message: z17.string().optional(),
2758
3055
  /** True when this stop fired because a hook continued the subagent's turn. */
2759
- stop_hook_active: z16.boolean().optional(),
3056
+ stop_hook_active: z17.boolean().optional(),
2760
3057
  usage: claudeUsageSchema.optional()
2761
3058
  });
2762
- var preCompactPayloadSchema = z16.object({
3059
+ var preCompactPayloadSchema = z17.object({
2763
3060
  ...commonFields,
2764
- hook_event_name: z16.literal("PreCompact"),
3061
+ hook_event_name: z17.literal("PreCompact"),
2765
3062
  /** Upstream values: manual | auto. Forward-compatible: any string. */
2766
- trigger: z16.string().min(1).optional(),
3063
+ trigger: z17.string().min(1).optional(),
2767
3064
  /** Compatibility alias emitted by older wrappers and hook integrations. */
2768
- compact_trigger: z16.string().min(1).optional(),
3065
+ compact_trigger: z17.string().min(1).optional(),
2769
3066
  /**
2770
3067
  * Harness-supplied, never upstream. Reported as an explicit exclusion rather
2771
3068
  * than carried across the process boundary: see `events.ts`.
2772
3069
  */
2773
- context_tokens_before: z16.number().int().min(0).optional(),
2774
- estimated_tokens_removed: z16.number().int().min(0).optional()
3070
+ context_tokens_before: z17.number().int().min(0).optional(),
3071
+ estimated_tokens_removed: z17.number().int().min(0).optional()
2775
3072
  });
2776
- var postCompactPayloadSchema = z16.object({
3073
+ var postCompactPayloadSchema = z17.object({
2777
3074
  ...commonFields,
2778
- hook_event_name: z16.literal("PostCompact"),
2779
- trigger: z16.string().min(1).optional(),
2780
- compact_trigger: z16.string().min(1).optional(),
3075
+ hook_event_name: z17.literal("PostCompact"),
3076
+ trigger: z17.string().min(1).optional(),
3077
+ compact_trigger: z17.string().min(1).optional(),
2781
3078
  /** Harness-supplied, never upstream; accepted here because one callback carries both. */
2782
- context_tokens_before: z16.number().int().min(0).optional(),
2783
- context_tokens_after: z16.number().int().min(0).optional(),
2784
- dropped_message_count: z16.number().int().min(0).optional(),
3079
+ context_tokens_before: z17.number().int().min(0).optional(),
3080
+ context_tokens_after: z17.number().int().min(0).optional(),
3081
+ dropped_message_count: z17.number().int().min(0).optional(),
2785
3082
  usage: claudeUsageSchema.optional()
2786
3083
  });
2787
- var stopPayloadSchema = z16.object({
3084
+ var stopPayloadSchema = z17.object({
2788
3085
  ...commonFields,
2789
- hook_event_name: z16.literal("Stop"),
3086
+ hook_event_name: z17.literal("Stop"),
2790
3087
  /**
2791
3088
  * Interactive Stop field (Claude Code ≥ 2.1.47). Print / `-p` / Agent SDK
2792
3089
  * result messages use `result` instead; `events.ts` reads both (and camelCase
2793
3090
  * `lastAssistantMessage`) through `extractClaudeAssistantText`.
2794
3091
  */
2795
- last_assistant_message: z16.string().optional(),
3092
+ last_assistant_message: z17.string().optional(),
2796
3093
  /** Print / `-p` JSON result field; accepted so a harness can attach it as-is. */
2797
- result: z16.string().optional(),
3094
+ result: z17.string().optional(),
2798
3095
  /**
2799
3096
  * True when this stop fired because a hook continued the turn.
2800
3097
  *
@@ -2802,22 +3099,44 @@ var stopPayloadSchema = z16.object({
2802
3099
  * stop from a continuation stop, which is what lets `delivery.ts` deduplicate
2803
3100
  * the former without suppressing the latter.
2804
3101
  */
2805
- stop_hook_active: z16.boolean().optional(),
2806
- usage: claudeUsageSchema.optional()
3102
+ stop_hook_active: z17.boolean().optional(),
3103
+ usage: claudeUsageSchema.optional(),
3104
+ /**
3105
+ * The model that answered this turn — harness-supplied, never upstream.
3106
+ *
3107
+ * Claude Code's `Stop` carries no model id; the per-turn model sits only at
3108
+ * `message.model` in the transcript, beside `message.usage`. A wrapping harness
3109
+ * that read it (for instance with `readClaudeTranscriptTurn`) attaches it here
3110
+ * with `usage`, and it becomes the generation's response model. An unusable
3111
+ * value (empty, over 256 characters, not a string) is dropped rather than
3112
+ * failing the whole payload: the turn is still worth reporting without it.
3113
+ */
3114
+ model: z17.string().min(1).max(256).optional().catch(void 0),
3115
+ /**
3116
+ * Harness-supplied, never upstream: whether `usage` covers only part of the
3117
+ * turn. `true` when it is the last model request alone (the tail fallback),
3118
+ * `false` when it sums every request since the previous stop. Exported as
3119
+ * `otelhook.usage.partial`; absent means the attacher did not say.
3120
+ */
3121
+ usage_partial: z17.boolean().optional().catch(void 0)
2807
3122
  });
2808
- var stopFailurePayloadSchema = z16.object({
3123
+ var stopFailurePayloadSchema = z17.object({
2809
3124
  ...commonFields,
2810
- hook_event_name: z16.literal("StopFailure"),
3125
+ hook_event_name: z17.literal("StopFailure"),
2811
3126
  /**
2812
3127
  * Matcher values: rate_limit | overloaded | authentication_failed |
2813
3128
  * oauth_org_not_allowed | billing_error | invalid_request | model_not_found
2814
3129
  * | server_error | max_output_tokens | unknown.
2815
3130
  */
2816
- error_type: z16.string().min(1),
2817
- error_message: z16.string().optional(),
2818
- usage: claudeUsageSchema.optional()
3131
+ error_type: z17.string().min(1),
3132
+ error_message: z17.string().optional(),
3133
+ usage: claudeUsageSchema.optional(),
3134
+ /** Harness-supplied, never upstream: see `stopPayloadSchema.model`. */
3135
+ model: z17.string().min(1).max(256).optional().catch(void 0),
3136
+ /** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */
3137
+ usage_partial: z17.boolean().optional().catch(void 0)
2819
3138
  });
2820
- var claudeHookPayloadSchema = z16.discriminatedUnion("hook_event_name", [
3139
+ var claudeHookPayloadSchema = z17.discriminatedUnion("hook_event_name", [
2821
3140
  sessionStartPayloadSchema,
2822
3141
  sessionEndPayloadSchema,
2823
3142
  userPromptSubmitPayloadSchema,
@@ -2847,15 +3166,15 @@ var CLAUDE_HOOK_EVENT_NAMES = [
2847
3166
  "Stop",
2848
3167
  "StopFailure"
2849
3168
  ];
2850
- var claudeIdentityFieldsSchema = z16.object({
2851
- session_id: z16.string().min(1),
2852
- hook_event_name: z16.string().min(1),
2853
- cwd: z16.string().min(1).optional(),
2854
- prompt_id: z16.string().min(1).optional(),
2855
- agent_id: z16.string().min(1).optional(),
2856
- tool_use_id: z16.string().min(1).optional(),
3169
+ var claudeIdentityFieldsSchema = z17.object({
3170
+ session_id: z17.string().min(1),
3171
+ hook_event_name: z17.string().min(1),
3172
+ cwd: z17.string().min(1).optional(),
3173
+ prompt_id: z17.string().min(1).optional(),
3174
+ agent_id: z17.string().min(1).optional(),
3175
+ tool_use_id: z17.string().min(1).optional(),
2857
3176
  /** Read by `delivery.ts` to tell a once-per-prompt stop from a continuation. */
2858
- stop_hook_active: z16.boolean().optional()
3177
+ stop_hook_active: z17.boolean().optional()
2859
3178
  });
2860
3179
 
2861
3180
  // src/providers/claude/usage.ts
@@ -3347,6 +3666,13 @@ var inferToolKind = (toolName) => {
3347
3666
 
3348
3667
  // src/providers/claude/events.ts
3349
3668
  var UNKNOWN_MODEL = { modelId: "unknown" };
3669
+ var generationModels = (attached, sessionModel) => {
3670
+ const turnModel = attached === void 0 ? void 0 : { modelId: attached };
3671
+ return {
3672
+ request: sessionModel ?? turnModel ?? UNKNOWN_MODEL,
3673
+ response: turnModel ?? sessionModel ?? UNKNOWN_MODEL
3674
+ };
3675
+ };
3350
3676
  var SESSION_END_REASON = Object.freeze({
3351
3677
  completed: "completed",
3352
3678
  aborted: "aborted",
@@ -3413,6 +3739,10 @@ var parseClaudeCode = (input, context) => {
3413
3739
  warnings.push(...normalized.warnings);
3414
3740
  return applyUsage(normalized);
3415
3741
  };
3742
+ const withPartialUsage = (usage, partial) => {
3743
+ const applied = withUsage(usage);
3744
+ return applied.usage === void 0 || partial === void 0 ? applied : { ...applied, usagePartial: partial };
3745
+ };
3416
3746
  switch (payload.hook_event_name) {
3417
3747
  case "SessionStart":
3418
3748
  factory.build({
@@ -3525,11 +3855,12 @@ var parseClaudeCode = (input, context) => {
3525
3855
  payload.prompt_id ?? String(input.sequenceBase)
3526
3856
  ]);
3527
3857
  const assistantText = extractClaudeAssistantText(normalizedPayload);
3528
- factory.build({ type: "generation.start", generationId, model: UNKNOWN_MODEL });
3858
+ const models = generationModels(payload.model, input.sessionModel);
3859
+ factory.build({ type: "generation.start", generationId, model: models.request });
3529
3860
  factory.build({
3530
3861
  type: "generation.end",
3531
3862
  generationId,
3532
- model: UNKNOWN_MODEL,
3863
+ model: models.response,
3533
3864
  outcome: "ok",
3534
3865
  // Always a response fact: a body when Claude sent text, otherwise a
3535
3866
  // zero-length omitted fact so the log mapping can emit metadata_only
@@ -3541,7 +3872,7 @@ var parseClaudeCode = (input, context) => {
3541
3872
  text: assistantText
3542
3873
  })
3543
3874
  ],
3544
- ...withUsage(extractedUsage ?? payload.usage)
3875
+ ...withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial)
3545
3876
  });
3546
3877
  break;
3547
3878
  }
@@ -3552,11 +3883,12 @@ var parseClaudeCode = (input, context) => {
3552
3883
  payload.prompt_id ?? String(input.sequenceBase)
3553
3884
  ]);
3554
3885
  const assistantText = extractClaudeAssistantText(normalizedPayload);
3555
- factory.build({ type: "generation.start", generationId, model: UNKNOWN_MODEL });
3886
+ const models = generationModels(payload.model, input.sessionModel);
3887
+ factory.build({ type: "generation.start", generationId, model: models.request });
3556
3888
  factory.build({
3557
3889
  type: "generation.end",
3558
3890
  generationId,
3559
- model: UNKNOWN_MODEL,
3891
+ model: models.response,
3560
3892
  outcome: mapStopFailureOutcome(payload.error_type),
3561
3893
  stopReason: payload.error_type,
3562
3894
  ...assistantText === void 0 ? {} : {
@@ -3568,7 +3900,7 @@ var parseClaudeCode = (input, context) => {
3568
3900
  })
3569
3901
  ]
3570
3902
  },
3571
- ...withUsage(extractedUsage ?? payload.usage)
3903
+ ...withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial)
3572
3904
  });
3573
3905
  break;
3574
3906
  }
@@ -3595,8 +3927,341 @@ var createClaudeCodeAdapter = (options = {}) => ({
3595
3927
  hookResponse: () => SILENT_HOOK_RESPONSE
3596
3928
  });
3597
3929
 
3930
+ // src/providers/claude/transcript.ts
3931
+ import { createHash as createHash2 } from "crypto";
3932
+ import { open, stat } from "fs/promises";
3933
+ import path from "path";
3934
+ var DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES = 1048576;
3935
+ var DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS = 250;
3936
+ var DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES = 8388608;
3937
+ var DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS = 500;
3938
+ var MIN_TAIL_BYTES = 65536;
3939
+ var MAX_TAIL_BYTES = 16777216;
3940
+ var MAX_RANGE_BYTES = 67108864;
3941
+ var MIN_TIMEOUT_MILLIS = 10;
3942
+ var MAX_TIMEOUT_MILLIS = 5e3;
3943
+ var MAX_MODEL_ID_LENGTH = 256;
3944
+ var MAX_REQUESTS_PER_RANGE = 1e4;
3945
+ var SYNTHETIC_MODEL = "<synthetic>";
3946
+ var TIMED_OUT = /* @__PURE__ */ Symbol("timed-out");
3947
+ var clamp = (value, fallback, min, max) => {
3948
+ if (value === void 0 || !Number.isFinite(value)) {
3949
+ return fallback;
3950
+ }
3951
+ return Math.min(max, Math.max(min, Math.floor(value)));
3952
+ };
3953
+ var asRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
3954
+ var isTranscriptPath = (transcriptPath) => typeof transcriptPath === "string" && transcriptPath.length > 0 && !transcriptPath.includes("\0") && path.isAbsolute(transcriptPath) && path.extname(transcriptPath) === ".jsonl";
3955
+ var assistantRecordOf = (line) => {
3956
+ if (!line.includes('"assistant"')) {
3957
+ return void 0;
3958
+ }
3959
+ let parsed;
3960
+ try {
3961
+ parsed = JSON.parse(line);
3962
+ } catch {
3963
+ return void 0;
3964
+ }
3965
+ const record = asRecord5(parsed);
3966
+ if (record === void 0 || record.type !== "assistant" || record.isSidechain === true) {
3967
+ return void 0;
3968
+ }
3969
+ const message = asRecord5(record.message);
3970
+ if (message === void 0 || message.model === SYNTHETIC_MODEL) {
3971
+ return void 0;
3972
+ }
3973
+ const model = typeof message.model === "string" && message.model.length > 0 && message.model.length <= MAX_MODEL_ID_LENGTH ? message.model : void 0;
3974
+ const usage = coerceClaudeUsage(message.usage);
3975
+ if (model === void 0 && usage === void 0) {
3976
+ return void 0;
3977
+ }
3978
+ const id = typeof message.id === "string" && message.id.length > 0 && message.id.length <= 256 ? message.id : void 0;
3979
+ return {
3980
+ ...id === void 0 ? {} : { id },
3981
+ ...model === void 0 ? {} : { model },
3982
+ ...usage === void 0 ? {} : { usage }
3983
+ };
3984
+ };
3985
+ var cacheCreationOf = (usage) => usage.cache_creation_input_tokens ?? (usage.cache_creation === void 0 ? 0 : (usage.cache_creation.ephemeral_5m_input_tokens ?? 0) + (usage.cache_creation.ephemeral_1h_input_tokens ?? 0));
3986
+ var sumUsage = (usages) => {
3987
+ let input = 0;
3988
+ let output = 0;
3989
+ let cacheRead = 0;
3990
+ let cacheCreation = 0;
3991
+ for (const usage of usages) {
3992
+ input += usage.input_tokens;
3993
+ output += usage.output_tokens;
3994
+ cacheRead += usage.cache_read_input_tokens ?? 0;
3995
+ cacheCreation += cacheCreationOf(usage);
3996
+ }
3997
+ return {
3998
+ input_tokens: input,
3999
+ output_tokens: output,
4000
+ cache_read_input_tokens: cacheRead,
4001
+ cache_creation_input_tokens: cacheCreation
4002
+ };
4003
+ };
4004
+ var withTimeout = async (work, timeoutMillis, onError) => {
4005
+ let timer;
4006
+ const timeout = new Promise((resolve5) => {
4007
+ timer = setTimeout(() => {
4008
+ resolve5(TIMED_OUT);
4009
+ }, timeoutMillis);
4010
+ timer.unref();
4011
+ });
4012
+ try {
4013
+ return await Promise.race([work.catch(() => onError), timeout]);
4014
+ } finally {
4015
+ clearTimeout(timer);
4016
+ }
4017
+ };
4018
+ var withRegularFile = async (transcriptPath, body) => {
4019
+ let info;
4020
+ try {
4021
+ info = await stat(transcriptPath);
4022
+ } catch {
4023
+ return { status: "unavailable", reason: "unreadable" };
4024
+ }
4025
+ if (!info.isFile()) {
4026
+ return { status: "unavailable", reason: "not-a-file" };
4027
+ }
4028
+ let handle;
4029
+ try {
4030
+ handle = await open(transcriptPath, "r");
4031
+ } catch {
4032
+ return { status: "unavailable", reason: "unreadable" };
4033
+ }
4034
+ try {
4035
+ const { size } = await handle.stat();
4036
+ return await body(handle, size);
4037
+ } catch {
4038
+ return { status: "unavailable", reason: "unreadable" };
4039
+ } finally {
4040
+ await handle.close().catch(() => void 0);
4041
+ }
4042
+ };
4043
+ var readBytes = async (handle, start, length) => {
4044
+ const buffer = Buffer.alloc(length);
4045
+ let filled = 0;
4046
+ while (filled < length) {
4047
+ const { bytesRead } = await handle.read(buffer, filled, length - filled, start + filled);
4048
+ if (bytesRead === 0) {
4049
+ break;
4050
+ }
4051
+ filled += bytesRead;
4052
+ }
4053
+ return buffer.subarray(0, filled);
4054
+ };
4055
+ var completeLinesEnd = (bytes, start) => {
4056
+ const lastNewline = bytes.lastIndexOf(10);
4057
+ return lastNewline < 0 ? start : start + lastNewline + 1;
4058
+ };
4059
+ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath, async (handle, size) => {
4060
+ const length = Math.min(size, maxTailBytes);
4061
+ const start = size - length;
4062
+ const bytes = await readBytes(handle, start, length);
4063
+ const endOffset = completeLinesEnd(bytes, start);
4064
+ const lines = bytes.toString("utf8").split("\n");
4065
+ if (start > 0) {
4066
+ lines.shift();
4067
+ }
4068
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
4069
+ const record = assistantRecordOf((lines[index] ?? "").trim());
4070
+ if (record !== void 0) {
4071
+ return {
4072
+ turn: {
4073
+ status: "found",
4074
+ ...record.model === void 0 ? {} : { model: record.model },
4075
+ ...record.usage === void 0 ? {} : { usage: record.usage }
4076
+ },
4077
+ endOffset
4078
+ };
4079
+ }
4080
+ }
4081
+ return { turn: { status: "unavailable", reason: "no-assistant-message" }, endOffset };
4082
+ });
4083
+ var boundedTail = async (transcriptPath, options) => withTimeout(
4084
+ readTail(
4085
+ transcriptPath,
4086
+ clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES)
4087
+ ),
4088
+ clamp(options.timeoutMillis, DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS, MIN_TIMEOUT_MILLIS, MAX_TIMEOUT_MILLIS),
4089
+ { status: "unavailable", reason: "unreadable" }
4090
+ );
4091
+ var readClaudeTranscriptTurn = async (transcriptPath, options = {}) => {
4092
+ if (!isTranscriptPath(transcriptPath)) {
4093
+ return { status: "unavailable", reason: "invalid-path" };
4094
+ }
4095
+ const read = await boundedTail(transcriptPath, options);
4096
+ if (read === TIMED_OUT) {
4097
+ return { status: "unavailable", reason: "timeout" };
4098
+ }
4099
+ return "turn" in read ? read.turn : read;
4100
+ };
4101
+ var readClaudeTranscriptRange = async (transcriptPath, fromOffset, options = {}) => {
4102
+ if (!isTranscriptPath(transcriptPath) || !Number.isSafeInteger(fromOffset) || fromOffset < 0) {
4103
+ return { status: "unavailable", reason: "invalid-path" };
4104
+ }
4105
+ const maxRangeBytes = clamp(options.maxRangeBytes, DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES, MIN_TAIL_BYTES, MAX_RANGE_BYTES);
4106
+ const timeoutMillis = clamp(
4107
+ options.rangeTimeoutMillis,
4108
+ DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS,
4109
+ MIN_TIMEOUT_MILLIS,
4110
+ MAX_TIMEOUT_MILLIS
4111
+ );
4112
+ const work = withRegularFile(transcriptPath, async (handle, size) => {
4113
+ if (size < fromOffset) {
4114
+ return { status: "unavailable", reason: "truncated" };
4115
+ }
4116
+ if (size - fromOffset > maxRangeBytes) {
4117
+ return { status: "unavailable", reason: "over-cap" };
4118
+ }
4119
+ const bytes = await readBytes(handle, fromOffset, size - fromOffset);
4120
+ const endOffset = completeLinesEnd(bytes, fromOffset);
4121
+ const complete = bytes.subarray(0, endOffset - fromOffset).toString("utf8");
4122
+ const requests = /* @__PURE__ */ new Map();
4123
+ let anonymous = 0;
4124
+ let model;
4125
+ for (const line of complete.split("\n")) {
4126
+ const record = assistantRecordOf(line.trim());
4127
+ if (record === void 0) {
4128
+ continue;
4129
+ }
4130
+ if (record.model !== void 0) {
4131
+ model = record.model;
4132
+ }
4133
+ anonymous += record.id === void 0 ? 1 : 0;
4134
+ requests.set(record.id ?? `#${String(anonymous)}`, record);
4135
+ if (requests.size > MAX_REQUESTS_PER_RANGE) {
4136
+ return { status: "unavailable", reason: "over-cap" };
4137
+ }
4138
+ }
4139
+ const usages = [...requests.values()].flatMap((record) => record.usage === void 0 ? [] : [record.usage]);
4140
+ return {
4141
+ status: "found",
4142
+ ...model === void 0 ? {} : { model },
4143
+ ...usages.length === 0 ? {} : { usage: sumUsage(usages) },
4144
+ requestCount: requests.size,
4145
+ endOffset
4146
+ };
4147
+ });
4148
+ const result = await withTimeout(work, timeoutMillis, {
4149
+ status: "unavailable",
4150
+ reason: "unreadable"
4151
+ });
4152
+ return result === TIMED_OUT ? { status: "unavailable", reason: "timeout" } : result;
4153
+ };
4154
+ var STOP_EVENTS = /* @__PURE__ */ new Set(["Stop", "StopFailure"]);
4155
+ var hasUsage = (record) => record.usage !== void 0 || record.token_usage !== void 0 || record.tokenUsage !== void 0;
4156
+ var eventNameOf = (record) => record.hook_event_name ?? record.hookEventName;
4157
+ var transcriptPathOf = (record) => record.transcript_path ?? record.transcriptPath;
4158
+ var attachClaudeTranscriptTurn = async (payload, options = {}) => {
4159
+ const record = asRecord5(payload);
4160
+ if (record === void 0) {
4161
+ return payload;
4162
+ }
4163
+ const eventName = eventNameOf(record);
4164
+ if (typeof eventName !== "string" || !STOP_EVENTS.has(eventName)) {
4165
+ return payload;
4166
+ }
4167
+ const transcriptPath = transcriptPathOf(record);
4168
+ if (typeof transcriptPath !== "string") {
4169
+ return payload;
4170
+ }
4171
+ const needsModel = record.model === void 0;
4172
+ const needsUsage = !hasUsage(record);
4173
+ if (!needsModel && !needsUsage) {
4174
+ return payload;
4175
+ }
4176
+ const turn = await readClaudeTranscriptTurn(transcriptPath, options);
4177
+ if (turn.status !== "found") {
4178
+ return payload;
4179
+ }
4180
+ return {
4181
+ ...record,
4182
+ ...needsModel && turn.model !== void 0 ? { model: turn.model } : {},
4183
+ ...needsUsage && turn.usage !== void 0 ? { usage: turn.usage, usage_partial: true } : {}
4184
+ };
4185
+ };
4186
+ var CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
4187
+ var sourceDigest = (transcriptPath) => createHash2("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
4188
+ var createClaudeTranscriptUsageEnricher = (options = {}) => {
4189
+ const fileSize = async (transcriptPath) => {
4190
+ try {
4191
+ const info = await stat(transcriptPath);
4192
+ return info.isFile() ? info.size : void 0;
4193
+ } catch (thrown) {
4194
+ return thrown?.code === "ENOENT" ? "absent" : void 0;
4195
+ }
4196
+ };
4197
+ const enrich = async (input) => {
4198
+ const unchanged = { payload: input.payload };
4199
+ const record = asRecord5(input.payload);
4200
+ if (record === void 0) {
4201
+ return unchanged;
4202
+ }
4203
+ const eventName = eventNameOf(record);
4204
+ const transcriptPath = transcriptPathOf(record);
4205
+ if (typeof eventName !== "string" || !isTranscriptPath(transcriptPath)) {
4206
+ return unchanged;
4207
+ }
4208
+ const source = sourceDigest(transcriptPath);
4209
+ const cursor = input.cursor?.source === source ? input.cursor : void 0;
4210
+ if (eventName === "SessionStart") {
4211
+ if (cursor !== void 0) {
4212
+ return unchanged;
4213
+ }
4214
+ const size = await fileSize(transcriptPath);
4215
+ if (size === void 0) {
4216
+ return { ...unchanged, notes: ["transcript is not a readable regular file; no cursor recorded"] };
4217
+ }
4218
+ return { payload: input.payload, cursor: { source, offset: size === "absent" ? 0 : size } };
4219
+ }
4220
+ if (!STOP_EVENTS.has(eventName)) {
4221
+ return unchanged;
4222
+ }
4223
+ if (hasUsage(record)) {
4224
+ const size = await fileSize(transcriptPath);
4225
+ return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
4226
+ }
4227
+ const attach = (model, usage, partial) => ({
4228
+ ...record,
4229
+ ...record.model === void 0 && model !== void 0 ? { model } : {},
4230
+ ...usage === void 0 ? {} : { usage, usage_partial: partial }
4231
+ });
4232
+ if (cursor !== void 0) {
4233
+ const range = await readClaudeTranscriptRange(transcriptPath, cursor.offset, options);
4234
+ if (range.status === "found") {
4235
+ return {
4236
+ payload: attach(range.model, range.usage, false),
4237
+ cursor: { source, offset: range.endOffset },
4238
+ notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
4239
+ };
4240
+ }
4241
+ if (range.reason !== "truncated" && range.reason !== "over-cap") {
4242
+ return { ...unchanged, notes: [`transcript range not read (${range.reason}); cursor kept`] };
4243
+ }
4244
+ }
4245
+ const tail = await boundedTail(transcriptPath, options);
4246
+ if (tail === TIMED_OUT || !("turn" in tail)) {
4247
+ return { ...unchanged, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
4248
+ }
4249
+ const why = cursor === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
4250
+ return {
4251
+ payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : input.payload,
4252
+ cursor: { source, offset: tail.endOffset },
4253
+ notes: [`${why}; attached the last request only (usage_partial)`]
4254
+ };
4255
+ };
4256
+ return Object.freeze({
4257
+ id: CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,
4258
+ providerId: CLAUDE_CODE_PROVIDER_ID,
4259
+ enrich
4260
+ });
4261
+ };
4262
+
3598
4263
  // src/providers/cursor/payload.ts
3599
- import { z as z17 } from "zod";
4264
+ import { z as z18 } from "zod";
3600
4265
  var CURSOR_PROVIDER_ID = "cursor";
3601
4266
  var CURSOR_HOOK_EVENT_NAMES = [
3602
4267
  "sessionStart",
@@ -3631,23 +4296,23 @@ var CURSOR_DECISION_EVENTS = Object.freeze({
3631
4296
  subagentStart: "permission",
3632
4297
  beforeSubmitPrompt: "continue"
3633
4298
  });
3634
- var modelParamSchema = z17.object({
3635
- id: z17.string(),
3636
- value: z17.string()
4299
+ var modelParamSchema = z18.object({
4300
+ id: z18.string(),
4301
+ value: z18.string()
3637
4302
  });
3638
- var attachmentSchema = z17.object({
3639
- type: z17.string().optional(),
3640
- file_path: z17.string().optional()
4303
+ var attachmentSchema = z18.object({
4304
+ type: z18.string().optional(),
4305
+ file_path: z18.string().optional()
3641
4306
  });
3642
- var fileEditSchema = z17.object({
3643
- old_string: z17.string().optional(),
3644
- new_string: z17.string().optional()
4307
+ var fileEditSchema = z18.object({
4308
+ old_string: z18.string().optional(),
4309
+ new_string: z18.string().optional()
3645
4310
  });
3646
4311
  var usageFields = {
3647
- input_tokens: z17.number().int().min(0).optional(),
3648
- output_tokens: z17.number().int().min(0).optional(),
3649
- cache_read_tokens: z17.number().int().min(0).optional(),
3650
- cache_write_tokens: z17.number().int().min(0).optional()
4312
+ input_tokens: z18.number().int().min(0).optional(),
4313
+ output_tokens: z18.number().int().min(0).optional(),
4314
+ cache_read_tokens: z18.number().int().min(0).optional(),
4315
+ cache_write_tokens: z18.number().int().min(0).optional()
3651
4316
  };
3652
4317
  var envelopeShape = {
3653
4318
  // Not `.min(1)`: see `cursorSessionId`. A payload naming neither
@@ -3655,136 +4320,136 @@ var envelopeShape = {
3655
4320
  // `recognizeCursorPayload`'s post-parse check — but rejecting it here would
3656
4321
  // fail the whole discriminated union on a field the adapter can source from
3657
4322
  // either name.
3658
- conversation_id: z17.string().optional(),
3659
- generation_id: z17.string().optional(),
3660
- session_id: z17.string().optional(),
3661
- model: z17.string().optional(),
3662
- model_id: z17.string().optional(),
3663
- model_params: z17.array(modelParamSchema).max(64).optional(),
3664
- cursor_version: z17.string().optional(),
3665
- workspace_roots: z17.array(z17.string()).max(64).optional(),
3666
- cwd: z17.string().optional(),
4323
+ conversation_id: z18.string().optional(),
4324
+ generation_id: z18.string().optional(),
4325
+ session_id: z18.string().optional(),
4326
+ model: z18.string().optional(),
4327
+ model_id: z18.string().optional(),
4328
+ model_params: z18.array(modelParamSchema).max(64).optional(),
4329
+ cursor_version: z18.string().optional(),
4330
+ workspace_roots: z18.array(z18.string()).max(64).optional(),
4331
+ cwd: z18.string().optional(),
3667
4332
  /** Never propagated. */
3668
- user_email: z17.string().nullish(),
4333
+ user_email: z18.string().nullish(),
3669
4334
  /** Never propagated. */
3670
- transcript_path: z17.string().nullish()
4335
+ transcript_path: z18.string().nullish()
3671
4336
  };
3672
- var event2 = (name, shape) => z17.object({ ...envelopeShape, hook_event_name: z17.literal(name), ...shape });
4337
+ var event2 = (name, shape) => z18.object({ ...envelopeShape, hook_event_name: z18.literal(name), ...shape });
3673
4338
  var sessionStartPayloadSchema2 = event2("sessionStart", {
3674
- is_background_agent: z17.boolean().optional(),
3675
- composer_mode: z17.string().optional()
4339
+ is_background_agent: z18.boolean().optional(),
4340
+ composer_mode: z18.string().optional()
3676
4341
  });
3677
4342
  var sessionEndPayloadSchema2 = event2("sessionEnd", {
3678
- reason: z17.string().optional(),
3679
- duration_ms: z17.number().min(0).optional(),
3680
- is_background_agent: z17.boolean().optional(),
3681
- final_status: z17.string().optional(),
3682
- error_message: z17.string().optional()
4343
+ reason: z18.string().optional(),
4344
+ duration_ms: z18.number().min(0).optional(),
4345
+ is_background_agent: z18.boolean().optional(),
4346
+ final_status: z18.string().optional(),
4347
+ error_message: z18.string().optional()
3683
4348
  });
3684
4349
  var beforeSubmitPromptPayloadSchema = event2("beforeSubmitPrompt", {
3685
- prompt: z17.string().optional(),
3686
- attachments: z17.array(attachmentSchema).max(256).optional(),
3687
- composer_mode: z17.string().optional()
4350
+ prompt: z18.string().optional(),
4351
+ attachments: z18.array(attachmentSchema).max(256).optional(),
4352
+ composer_mode: z18.string().optional()
3688
4353
  });
3689
4354
  var afterAgentResponsePayloadSchema = event2("afterAgentResponse", {
3690
- text: z17.string().optional(),
4355
+ text: z18.string().optional(),
3691
4356
  ...usageFields
3692
4357
  });
3693
4358
  var afterAgentThoughtPayloadSchema = event2("afterAgentThought", {
3694
- text: z17.string().optional(),
3695
- duration_ms: z17.number().min(0).optional()
4359
+ text: z18.string().optional(),
4360
+ duration_ms: z18.number().min(0).optional()
3696
4361
  });
3697
4362
  var preToolUsePayloadSchema2 = event2("preToolUse", {
3698
- tool_name: z17.string().min(1),
3699
- tool_input: z17.unknown().optional(),
3700
- tool_use_id: z17.string().optional(),
3701
- agent_message: z17.string().optional()
4363
+ tool_name: z18.string().min(1),
4364
+ tool_input: z18.unknown().optional(),
4365
+ tool_use_id: z18.string().optional(),
4366
+ agent_message: z18.string().optional()
3702
4367
  });
3703
4368
  var postToolUsePayloadSchema2 = event2("postToolUse", {
3704
- tool_name: z17.string().min(1),
3705
- tool_input: z17.unknown().optional(),
3706
- tool_output: z17.unknown().optional(),
3707
- tool_use_id: z17.string().optional(),
3708
- duration: z17.number().min(0).optional()
4369
+ tool_name: z18.string().min(1),
4370
+ tool_input: z18.unknown().optional(),
4371
+ tool_output: z18.unknown().optional(),
4372
+ tool_use_id: z18.string().optional(),
4373
+ duration: z18.number().min(0).optional()
3709
4374
  });
3710
4375
  var postToolUseFailurePayloadSchema2 = event2("postToolUseFailure", {
3711
- tool_name: z17.string().min(1),
3712
- tool_input: z17.unknown().optional(),
3713
- tool_use_id: z17.string().optional(),
3714
- error_message: z17.string().optional(),
3715
- failure_type: z17.string().optional(),
3716
- duration: z17.number().min(0).optional(),
3717
- is_interrupt: z17.boolean().optional()
4376
+ tool_name: z18.string().min(1),
4377
+ tool_input: z18.unknown().optional(),
4378
+ tool_use_id: z18.string().optional(),
4379
+ error_message: z18.string().optional(),
4380
+ failure_type: z18.string().optional(),
4381
+ duration: z18.number().min(0).optional(),
4382
+ is_interrupt: z18.boolean().optional()
3718
4383
  });
3719
4384
  var beforeShellExecutionPayloadSchema = event2("beforeShellExecution", {
3720
- command: z17.string(),
3721
- sandbox: z17.boolean().optional()
4385
+ command: z18.string(),
4386
+ sandbox: z18.boolean().optional()
3722
4387
  });
3723
4388
  var afterShellExecutionPayloadSchema = event2("afterShellExecution", {
3724
- command: z17.string(),
3725
- output: z17.string().optional(),
3726
- duration: z17.number().min(0).optional(),
3727
- sandbox: z17.boolean().optional()
4389
+ command: z18.string(),
4390
+ output: z18.string().optional(),
4391
+ duration: z18.number().min(0).optional(),
4392
+ sandbox: z18.boolean().optional()
3728
4393
  });
3729
4394
  var beforeMcpExecutionPayloadSchema = event2("beforeMCPExecution", {
3730
- tool_name: z17.string().min(1),
3731
- tool_input: z17.unknown().optional(),
3732
- url: z17.string().optional(),
3733
- command: z17.string().optional()
4395
+ tool_name: z18.string().min(1),
4396
+ tool_input: z18.unknown().optional(),
4397
+ url: z18.string().optional(),
4398
+ command: z18.string().optional()
3734
4399
  });
3735
4400
  var afterMcpExecutionPayloadSchema = event2("afterMCPExecution", {
3736
- tool_name: z17.string().min(1),
3737
- tool_input: z17.unknown().optional(),
3738
- result_json: z17.string().optional(),
3739
- duration: z17.number().min(0).optional()
4401
+ tool_name: z18.string().min(1),
4402
+ tool_input: z18.unknown().optional(),
4403
+ result_json: z18.string().optional(),
4404
+ duration: z18.number().min(0).optional()
3740
4405
  });
3741
4406
  var beforeReadFilePayloadSchema = event2("beforeReadFile", {
3742
- file_path: z17.string(),
3743
- content: z17.string().optional(),
3744
- attachments: z17.array(attachmentSchema).max(256).optional()
4407
+ file_path: z18.string(),
4408
+ content: z18.string().optional(),
4409
+ attachments: z18.array(attachmentSchema).max(256).optional()
3745
4410
  });
3746
4411
  var afterFileEditPayloadSchema = event2("afterFileEdit", {
3747
- file_path: z17.string(),
3748
- edits: z17.array(fileEditSchema).max(1024).optional()
4412
+ file_path: z18.string(),
4413
+ edits: z18.array(fileEditSchema).max(1024).optional()
3749
4414
  });
3750
4415
  var subagentStartPayloadSchema2 = event2("subagentStart", {
3751
- subagent_id: z17.string().optional(),
3752
- subagent_type: z17.string().optional(),
3753
- task: z17.string().optional(),
3754
- parent_conversation_id: z17.string().optional(),
3755
- tool_call_id: z17.string().optional(),
3756
- subagent_model: z17.string().optional(),
3757
- is_parallel_worker: z17.boolean().optional(),
3758
- git_branch: z17.string().optional()
4416
+ subagent_id: z18.string().optional(),
4417
+ subagent_type: z18.string().optional(),
4418
+ task: z18.string().optional(),
4419
+ parent_conversation_id: z18.string().optional(),
4420
+ tool_call_id: z18.string().optional(),
4421
+ subagent_model: z18.string().optional(),
4422
+ is_parallel_worker: z18.boolean().optional(),
4423
+ git_branch: z18.string().optional()
3759
4424
  });
3760
4425
  var subagentStopPayloadSchema2 = event2("subagentStop", {
3761
- subagent_type: z17.string().optional(),
3762
- status: z17.string().optional(),
3763
- task: z17.string().optional(),
3764
- description: z17.string().optional(),
3765
- summary: z17.string().optional(),
3766
- duration_ms: z17.number().min(0).optional(),
3767
- message_count: z17.number().int().min(0).optional(),
3768
- tool_call_count: z17.number().int().min(0).optional(),
3769
- loop_count: z17.number().int().min(0).optional(),
3770
- modified_files: z17.array(z17.string()).max(1024).optional(),
3771
- agent_transcript_path: z17.string().nullish()
4426
+ subagent_type: z18.string().optional(),
4427
+ status: z18.string().optional(),
4428
+ task: z18.string().optional(),
4429
+ description: z18.string().optional(),
4430
+ summary: z18.string().optional(),
4431
+ duration_ms: z18.number().min(0).optional(),
4432
+ message_count: z18.number().int().min(0).optional(),
4433
+ tool_call_count: z18.number().int().min(0).optional(),
4434
+ loop_count: z18.number().int().min(0).optional(),
4435
+ modified_files: z18.array(z18.string()).max(1024).optional(),
4436
+ agent_transcript_path: z18.string().nullish()
3772
4437
  });
3773
4438
  var preCompactPayloadSchema2 = event2("preCompact", {
3774
- trigger: z17.string().optional(),
3775
- context_usage_percent: z17.number().optional(),
3776
- context_tokens: z17.number().int().min(0).optional(),
3777
- context_window_size: z17.number().int().min(0).optional(),
3778
- message_count: z17.number().int().min(0).optional(),
3779
- messages_to_compact: z17.number().int().min(0).optional(),
3780
- is_first_compaction: z17.boolean().optional()
4439
+ trigger: z18.string().optional(),
4440
+ context_usage_percent: z18.number().optional(),
4441
+ context_tokens: z18.number().int().min(0).optional(),
4442
+ context_window_size: z18.number().int().min(0).optional(),
4443
+ message_count: z18.number().int().min(0).optional(),
4444
+ messages_to_compact: z18.number().int().min(0).optional(),
4445
+ is_first_compaction: z18.boolean().optional()
3781
4446
  });
3782
4447
  var stopPayloadSchema2 = event2("stop", {
3783
- status: z17.string().optional(),
3784
- loop_count: z17.number().int().min(0).optional(),
4448
+ status: z18.string().optional(),
4449
+ loop_count: z18.number().int().min(0).optional(),
3785
4450
  ...usageFields
3786
4451
  });
3787
- var cursorPayloadSchema = z17.discriminatedUnion("hook_event_name", [
4452
+ var cursorPayloadSchema = z18.discriminatedUnion("hook_event_name", [
3788
4453
  sessionStartPayloadSchema2,
3789
4454
  sessionEndPayloadSchema2,
3790
4455
  beforeSubmitPromptPayloadSchema,
@@ -4560,105 +5225,105 @@ var createCursorAdapter = (options = {}) => {
4560
5225
  };
4561
5226
 
4562
5227
  // src/providers/codex/payload.ts
4563
- import { z as z18 } from "zod";
4564
- var permissionModeSchema = z18.enum([
5228
+ import { z as z19 } from "zod";
5229
+ var permissionModeSchema = z19.enum([
4565
5230
  "default",
4566
5231
  "acceptEdits",
4567
5232
  "plan",
4568
5233
  "dontAsk",
4569
5234
  "bypassPermissions"
4570
5235
  ]);
4571
- var codexUsageSchema = z18.object({
4572
- input_tokens: z18.number().int().min(0).optional(),
4573
- cached_input_tokens: z18.number().int().min(0).optional(),
4574
- output_tokens: z18.number().int().min(0).optional(),
4575
- reasoning_output_tokens: z18.number().int().min(0).optional(),
4576
- total_tokens: z18.number().int().min(0).optional()
5236
+ var codexUsageSchema = z19.object({
5237
+ input_tokens: z19.number().int().min(0).optional(),
5238
+ cached_input_tokens: z19.number().int().min(0).optional(),
5239
+ output_tokens: z19.number().int().min(0).optional(),
5240
+ reasoning_output_tokens: z19.number().int().min(0).optional(),
5241
+ total_tokens: z19.number().int().min(0).optional()
4577
5242
  });
4578
5243
  var baseFields = {
4579
- session_id: z18.string().min(1).max(256),
4580
- cwd: z18.string().min(1).max(4096).optional(),
4581
- model: z18.string().min(1).max(256).optional(),
5244
+ session_id: z19.string().min(1).max(256),
5245
+ cwd: z19.string().min(1).max(4096).optional(),
5246
+ model: z19.string().min(1).max(256).optional(),
4582
5247
  permission_mode: permissionModeSchema.optional(),
4583
- transcript_path: z18.string().min(1).max(4096).optional(),
4584
- codex_version: z18.string().min(1).max(64).optional(),
5248
+ transcript_path: z19.string().min(1).max(4096).optional(),
5249
+ codex_version: z19.string().min(1).max(64).optional(),
4585
5250
  /** Not part of the documented protocol; lets tests and replay stay deterministic. */
4586
- occurred_at: z18.number().int().min(0).optional()
5251
+ occurred_at: z19.number().int().min(0).optional()
4587
5252
  };
4588
- var codexSessionStartPayloadSchema = z18.object({
5253
+ var codexSessionStartPayloadSchema = z19.object({
4589
5254
  ...baseFields,
4590
- hook_event_name: z18.literal("SessionStart"),
4591
- source: z18.enum(["startup", "resume", "clear", "compact"]).optional()
5255
+ hook_event_name: z19.literal("SessionStart"),
5256
+ source: z19.enum(["startup", "resume", "clear", "compact"]).optional()
4592
5257
  });
4593
- var codexUserPromptSubmitPayloadSchema = z18.object({
5258
+ var codexUserPromptSubmitPayloadSchema = z19.object({
4594
5259
  ...baseFields,
4595
- hook_event_name: z18.literal("UserPromptSubmit"),
4596
- turn_id: z18.string().min(1).max(256).optional(),
4597
- prompt: z18.string().max(1e6).optional()
5260
+ hook_event_name: z19.literal("UserPromptSubmit"),
5261
+ turn_id: z19.string().min(1).max(256).optional(),
5262
+ prompt: z19.string().max(1e6).optional()
4598
5263
  });
4599
- var codexPreToolUsePayloadSchema = z18.object({
5264
+ var codexPreToolUsePayloadSchema = z19.object({
4600
5265
  ...baseFields,
4601
- hook_event_name: z18.literal("PreToolUse"),
4602
- turn_id: z18.string().min(1).max(256).optional(),
4603
- tool_name: z18.string().min(1).max(256),
4604
- tool_call_id: z18.string().min(1).max(256).optional(),
4605
- tool_input: z18.unknown().optional()
5266
+ hook_event_name: z19.literal("PreToolUse"),
5267
+ turn_id: z19.string().min(1).max(256).optional(),
5268
+ tool_name: z19.string().min(1).max(256),
5269
+ tool_call_id: z19.string().min(1).max(256).optional(),
5270
+ tool_input: z19.unknown().optional()
4606
5271
  });
4607
- var codexPermissionRequestPayloadSchema = z18.object({
5272
+ var codexPermissionRequestPayloadSchema = z19.object({
4608
5273
  ...baseFields,
4609
- hook_event_name: z18.literal("PermissionRequest"),
4610
- turn_id: z18.string().min(1).max(256).optional(),
4611
- tool_name: z18.string().min(1).max(256).optional(),
4612
- tool_call_id: z18.string().min(1).max(256).optional(),
4613
- tool_input: z18.unknown().optional()
5274
+ hook_event_name: z19.literal("PermissionRequest"),
5275
+ turn_id: z19.string().min(1).max(256).optional(),
5276
+ tool_name: z19.string().min(1).max(256).optional(),
5277
+ tool_call_id: z19.string().min(1).max(256).optional(),
5278
+ tool_input: z19.unknown().optional()
4614
5279
  });
4615
- var codexPostToolUsePayloadSchema = z18.object({
5280
+ var codexPostToolUsePayloadSchema = z19.object({
4616
5281
  ...baseFields,
4617
- hook_event_name: z18.literal("PostToolUse"),
4618
- turn_id: z18.string().min(1).max(256).optional(),
4619
- tool_name: z18.string().min(1).max(256),
4620
- tool_call_id: z18.string().min(1).max(256).optional(),
4621
- tool_input: z18.unknown().optional(),
4622
- tool_response: z18.unknown().optional(),
4623
- permission_decision: z18.enum(["allowed", "denied", "deferred"]).optional(),
4624
- duration_ms: z18.number().min(0).optional()
5282
+ hook_event_name: z19.literal("PostToolUse"),
5283
+ turn_id: z19.string().min(1).max(256).optional(),
5284
+ tool_name: z19.string().min(1).max(256),
5285
+ tool_call_id: z19.string().min(1).max(256).optional(),
5286
+ tool_input: z19.unknown().optional(),
5287
+ tool_response: z19.unknown().optional(),
5288
+ permission_decision: z19.enum(["allowed", "denied", "deferred"]).optional(),
5289
+ duration_ms: z19.number().min(0).optional()
4625
5290
  });
4626
- var codexPreCompactPayloadSchema = z18.object({
5291
+ var codexPreCompactPayloadSchema = z19.object({
4627
5292
  ...baseFields,
4628
- hook_event_name: z18.literal("PreCompact"),
4629
- trigger: z18.enum(["auto", "manual"]).optional(),
4630
- context_tokens_before: z18.number().int().min(0).optional()
5293
+ hook_event_name: z19.literal("PreCompact"),
5294
+ trigger: z19.enum(["auto", "manual"]).optional(),
5295
+ context_tokens_before: z19.number().int().min(0).optional()
4631
5296
  });
4632
- var codexPostCompactPayloadSchema = z18.object({
5297
+ var codexPostCompactPayloadSchema = z19.object({
4633
5298
  ...baseFields,
4634
- hook_event_name: z18.literal("PostCompact"),
4635
- trigger: z18.enum(["auto", "manual"]).optional(),
4636
- context_tokens_after: z18.number().int().min(0).optional(),
4637
- dropped_message_count: z18.number().int().min(0).optional(),
5299
+ hook_event_name: z19.literal("PostCompact"),
5300
+ trigger: z19.enum(["auto", "manual"]).optional(),
5301
+ context_tokens_after: z19.number().int().min(0).optional(),
5302
+ dropped_message_count: z19.number().int().min(0).optional(),
4638
5303
  usage: codexUsageSchema.optional()
4639
5304
  });
4640
- var codexSubagentStartPayloadSchema = z18.object({
5305
+ var codexSubagentStartPayloadSchema = z19.object({
4641
5306
  ...baseFields,
4642
- hook_event_name: z18.literal("SubagentStart"),
4643
- turn_id: z18.string().min(1).max(256).optional(),
4644
- subagent_id: z18.string().min(1).max(256),
4645
- subagent_type: z18.string().min(1).max(256).optional()
5307
+ hook_event_name: z19.literal("SubagentStart"),
5308
+ turn_id: z19.string().min(1).max(256).optional(),
5309
+ subagent_id: z19.string().min(1).max(256),
5310
+ subagent_type: z19.string().min(1).max(256).optional()
4646
5311
  });
4647
- var codexSubagentStopPayloadSchema = z18.object({
5312
+ var codexSubagentStopPayloadSchema = z19.object({
4648
5313
  ...baseFields,
4649
- hook_event_name: z18.literal("SubagentStop"),
4650
- turn_id: z18.string().min(1).max(256).optional(),
4651
- subagent_id: z18.string().min(1).max(256),
4652
- status: z18.enum(["completed", "failed", "cancelled"]).optional(),
5314
+ hook_event_name: z19.literal("SubagentStop"),
5315
+ turn_id: z19.string().min(1).max(256).optional(),
5316
+ subagent_id: z19.string().min(1).max(256),
5317
+ status: z19.enum(["completed", "failed", "cancelled"]).optional(),
4653
5318
  usage: codexUsageSchema.optional()
4654
5319
  });
4655
- var codexStopPayloadSchema = z18.object({
5320
+ var codexStopPayloadSchema = z19.object({
4656
5321
  ...baseFields,
4657
- hook_event_name: z18.literal("Stop"),
4658
- turn_id: z18.string().min(1).max(256).optional(),
4659
- stop_reason: z18.string().min(1).max(256).optional(),
5322
+ hook_event_name: z19.literal("Stop"),
5323
+ turn_id: z19.string().min(1).max(256).optional(),
5324
+ stop_reason: z19.string().min(1).max(256).optional(),
4660
5325
  usage: codexUsageSchema.optional(),
4661
- duration_ms: z18.number().min(0).optional()
5326
+ duration_ms: z19.number().min(0).optional()
4662
5327
  });
4663
5328
  var CODEX_HOOK_EVENT_NAMES = [
4664
5329
  "SessionStart",
@@ -4672,7 +5337,7 @@ var CODEX_HOOK_EVENT_NAMES = [
4672
5337
  "SubagentStop",
4673
5338
  "Stop"
4674
5339
  ];
4675
- var codexHookPayloadSchema = z18.discriminatedUnion("hook_event_name", [
5340
+ var codexHookPayloadSchema = z19.discriminatedUnion("hook_event_name", [
4676
5341
  codexSessionStartPayloadSchema,
4677
5342
  codexUserPromptSubmitPayloadSchema,
4678
5343
  codexPreToolUsePayloadSchema,
@@ -4684,9 +5349,9 @@ var codexHookPayloadSchema = z18.discriminatedUnion("hook_event_name", [
4684
5349
  codexSubagentStopPayloadSchema,
4685
5350
  codexStopPayloadSchema
4686
5351
  ]);
4687
- var codexHookEnvelopeSchema = z18.object({
4688
- session_id: z18.string().min(1),
4689
- hook_event_name: z18.enum(CODEX_HOOK_EVENT_NAMES)
5352
+ var codexHookEnvelopeSchema = z19.object({
5353
+ session_id: z19.string().min(1),
5354
+ hook_event_name: z19.enum(CODEX_HOOK_EVENT_NAMES)
4690
5355
  });
4691
5356
 
4692
5357
  // src/providers/codex/delivery.ts
@@ -4749,7 +5414,7 @@ var codexDeliveryIdentity = (input) => {
4749
5414
 
4750
5415
  // src/providers/codex/target.ts
4751
5416
  var PATCH_HEADER = /^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/;
4752
- var asRecord5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
5417
+ var asRecord6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
4753
5418
  var nonEmptyString2 = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
4754
5419
  var commandText = (input) => {
4755
5420
  const command = input?.command ?? input?.cmd;
@@ -4776,7 +5441,7 @@ var patchTextOf = (toolName, input) => {
4776
5441
  if (typeof input === "string") {
4777
5442
  return /^apply[_-]?patch$/i.test(toolName) ? input : void 0;
4778
5443
  }
4779
- const record = asRecord5(input);
5444
+ const record = asRecord6(input);
4780
5445
  if (/^apply[_-]?patch$/i.test(toolName)) {
4781
5446
  return nonEmptyString2(record?.patch) ?? nonEmptyString2(record?.input) ?? commandText(record);
4782
5447
  }
@@ -4784,7 +5449,7 @@ var patchTextOf = (toolName, input) => {
4784
5449
  return command !== void 0 && /^\s*apply_patch\b/.test(command) ? command : void 0;
4785
5450
  };
4786
5451
  var codexTargetHint = (toolName, toolInput, cwd) => {
4787
- const record = asRecord5(toolInput);
5452
+ const record = asRecord6(toolInput);
4788
5453
  const workdir = nonEmptyString2(record?.workdir);
4789
5454
  const base = workdir ?? cwd;
4790
5455
  const patch = patchTextOf(toolName, toolInput);
@@ -4866,7 +5531,7 @@ var CODEX_CAPABILITIES = Object.freeze({
4866
5531
  // compaction callbacks do not. See `./delivery.ts` for which and why.
4867
5532
  deliveryIdentifier: "partial"
4868
5533
  });
4869
- var asRecord6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
5534
+ var asRecord7 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
4870
5535
  var hasExactMarker = (payload) => {
4871
5536
  if (payload.codex_version !== void 0) {
4872
5537
  return true;
@@ -4959,7 +5624,7 @@ var outcomeFromToolResponse = (toolResponse) => {
4959
5624
  if (toolResponse === void 0) {
4960
5625
  return "unknown";
4961
5626
  }
4962
- const record = asRecord6(toolResponse);
5627
+ const record = asRecord7(toolResponse);
4963
5628
  if (record === void 0) {
4964
5629
  return "ok";
4965
5630
  }
@@ -5305,7 +5970,7 @@ var geminiCorrelationSeed = (input) => {
5305
5970
  };
5306
5971
 
5307
5972
  // src/providers/gemini/schema.ts
5308
- import { z as z19 } from "zod";
5973
+ import { z as z20 } from "zod";
5309
5974
  var GEMINI_HOOK_EVENT_NAMES = [
5310
5975
  "SessionStart",
5311
5976
  "SessionEnd",
@@ -5319,113 +5984,113 @@ var GEMINI_HOOK_EVENT_NAMES = [
5319
5984
  "PreCompress",
5320
5985
  "Notification"
5321
5986
  ];
5322
- var baseHookInputSchema = z19.object({
5323
- session_id: z19.string().min(1),
5324
- transcript_path: z19.string().optional(),
5325
- cwd: z19.string().optional(),
5326
- timestamp: z19.string().min(1).optional()
5327
- });
5328
- var llmMessageSchema = z19.object({
5329
- role: z19.enum(["user", "model", "system"]).optional(),
5330
- content: z19.union([z19.string(), z19.array(z19.unknown())]).optional()
5987
+ var baseHookInputSchema = z20.object({
5988
+ session_id: z20.string().min(1),
5989
+ transcript_path: z20.string().optional(),
5990
+ cwd: z20.string().optional(),
5991
+ timestamp: z20.string().min(1).optional()
5992
+ });
5993
+ var llmMessageSchema = z20.object({
5994
+ role: z20.enum(["user", "model", "system"]).optional(),
5995
+ content: z20.union([z20.string(), z20.array(z20.unknown())]).optional()
5331
5996
  }).loose();
5332
- var llmRequestConfigSchema = z19.object({
5333
- temperature: z19.number().optional(),
5334
- maxOutputTokens: z19.number().int().min(0).optional()
5997
+ var llmRequestConfigSchema = z20.object({
5998
+ temperature: z20.number().optional(),
5999
+ maxOutputTokens: z20.number().int().min(0).optional()
5335
6000
  }).loose();
5336
- var geminiLlmRequestSchema = z19.object({
5337
- model: z19.string().min(1).optional(),
5338
- messages: z19.array(llmMessageSchema).optional(),
6001
+ var geminiLlmRequestSchema = z20.object({
6002
+ model: z20.string().min(1).optional(),
6003
+ messages: z20.array(llmMessageSchema).optional(),
5339
6004
  config: llmRequestConfigSchema.optional(),
5340
- toolConfig: z19.unknown().optional()
6005
+ toolConfig: z20.unknown().optional()
5341
6006
  }).loose();
5342
- var geminiUsageMetadataSchema = z19.object({
5343
- promptTokenCount: z19.number().int().min(0).optional(),
5344
- cachedContentTokenCount: z19.number().int().min(0).optional(),
5345
- candidatesTokenCount: z19.number().int().min(0).optional(),
5346
- thoughtsTokenCount: z19.number().int().min(0).optional(),
5347
- totalTokenCount: z19.number().int().min(0).optional()
6007
+ var geminiUsageMetadataSchema = z20.object({
6008
+ promptTokenCount: z20.number().int().min(0).optional(),
6009
+ cachedContentTokenCount: z20.number().int().min(0).optional(),
6010
+ candidatesTokenCount: z20.number().int().min(0).optional(),
6011
+ thoughtsTokenCount: z20.number().int().min(0).optional(),
6012
+ totalTokenCount: z20.number().int().min(0).optional()
5348
6013
  }).loose();
5349
- var geminiCandidateSchema = z19.object({
5350
- content: z19.object({
5351
- role: z19.string().optional(),
5352
- parts: z19.array(z19.unknown()).optional()
6014
+ var geminiCandidateSchema = z20.object({
6015
+ content: z20.object({
6016
+ role: z20.string().optional(),
6017
+ parts: z20.array(z20.unknown()).optional()
5353
6018
  }).loose().optional(),
5354
- finishReason: z19.string().optional(),
5355
- index: z19.number().int().min(0).optional()
6019
+ finishReason: z20.string().optional(),
6020
+ index: z20.number().int().min(0).optional()
5356
6021
  }).loose();
5357
- var geminiLlmResponseSchema = z19.object({
6022
+ var geminiLlmResponseSchema = z20.object({
5358
6023
  /** Whole-response text, set by the translator from `getResponseText`. */
5359
- text: z19.string().optional(),
5360
- candidates: z19.array(geminiCandidateSchema).optional(),
6024
+ text: z20.string().optional(),
6025
+ candidates: z20.array(geminiCandidateSchema).optional(),
5361
6026
  usageMetadata: geminiUsageMetadataSchema.optional()
5362
6027
  }).loose();
5363
- var geminiMcpContextSchema = z19.object({
5364
- server_name: z19.string().optional(),
5365
- tool_name: z19.string().optional()
6028
+ var geminiMcpContextSchema = z20.object({
6029
+ server_name: z20.string().optional(),
6030
+ tool_name: z20.string().optional()
5366
6031
  }).loose();
5367
- var geminiToolResponseSchema = z19.object({
5368
- llmContent: z19.unknown().optional(),
5369
- returnDisplay: z19.unknown().optional(),
5370
- error: z19.unknown().optional()
6032
+ var geminiToolResponseSchema = z20.object({
6033
+ llmContent: z20.unknown().optional(),
6034
+ returnDisplay: z20.unknown().optional(),
6035
+ error: z20.unknown().optional()
5371
6036
  }).loose();
5372
6037
  var sessionStartInputSchema = baseHookInputSchema.extend({
5373
- hook_event_name: z19.literal("SessionStart"),
5374
- source: z19.enum(["startup", "resume", "clear"]).optional()
6038
+ hook_event_name: z20.literal("SessionStart"),
6039
+ source: z20.enum(["startup", "resume", "clear"]).optional()
5375
6040
  });
5376
6041
  var sessionEndInputSchema = baseHookInputSchema.extend({
5377
- hook_event_name: z19.literal("SessionEnd"),
5378
- reason: z19.enum(["exit", "clear", "logout", "prompt_input_exit", "other"]).optional()
6042
+ hook_event_name: z20.literal("SessionEnd"),
6043
+ reason: z20.enum(["exit", "clear", "logout", "prompt_input_exit", "other"]).optional()
5379
6044
  });
5380
6045
  var beforeAgentInputSchema = baseHookInputSchema.extend({
5381
- hook_event_name: z19.literal("BeforeAgent"),
5382
- prompt: z19.string().optional()
6046
+ hook_event_name: z20.literal("BeforeAgent"),
6047
+ prompt: z20.string().optional()
5383
6048
  });
5384
6049
  var afterAgentInputSchema = baseHookInputSchema.extend({
5385
- hook_event_name: z19.literal("AfterAgent"),
5386
- prompt: z19.string().optional(),
5387
- prompt_response: z19.string().optional(),
5388
- stop_hook_active: z19.boolean().optional()
6050
+ hook_event_name: z20.literal("AfterAgent"),
6051
+ prompt: z20.string().optional(),
6052
+ prompt_response: z20.string().optional(),
6053
+ stop_hook_active: z20.boolean().optional()
5389
6054
  });
5390
6055
  var beforeModelInputSchema = baseHookInputSchema.extend({
5391
- hook_event_name: z19.literal("BeforeModel"),
6056
+ hook_event_name: z20.literal("BeforeModel"),
5392
6057
  llm_request: geminiLlmRequestSchema
5393
6058
  });
5394
6059
  var afterModelInputSchema = baseHookInputSchema.extend({
5395
- hook_event_name: z19.literal("AfterModel"),
6060
+ hook_event_name: z20.literal("AfterModel"),
5396
6061
  llm_request: geminiLlmRequestSchema,
5397
6062
  llm_response: geminiLlmResponseSchema
5398
6063
  });
5399
6064
  var beforeToolSelectionInputSchema = baseHookInputSchema.extend({
5400
- hook_event_name: z19.literal("BeforeToolSelection"),
6065
+ hook_event_name: z20.literal("BeforeToolSelection"),
5401
6066
  llm_request: geminiLlmRequestSchema
5402
6067
  });
5403
6068
  var beforeToolInputSchema = baseHookInputSchema.extend({
5404
- hook_event_name: z19.literal("BeforeTool"),
5405
- tool_name: z19.string().min(1),
5406
- tool_input: z19.unknown().optional(),
6069
+ hook_event_name: z20.literal("BeforeTool"),
6070
+ tool_name: z20.string().min(1),
6071
+ tool_input: z20.unknown().optional(),
5407
6072
  mcp_context: geminiMcpContextSchema.optional(),
5408
- original_request_name: z19.string().min(1).optional()
6073
+ original_request_name: z20.string().min(1).optional()
5409
6074
  });
5410
6075
  var afterToolInputSchema = baseHookInputSchema.extend({
5411
- hook_event_name: z19.literal("AfterTool"),
5412
- tool_name: z19.string().min(1),
5413
- tool_input: z19.unknown().optional(),
6076
+ hook_event_name: z20.literal("AfterTool"),
6077
+ tool_name: z20.string().min(1),
6078
+ tool_input: z20.unknown().optional(),
5414
6079
  tool_response: geminiToolResponseSchema.optional(),
5415
6080
  mcp_context: geminiMcpContextSchema.optional(),
5416
- original_request_name: z19.string().min(1).optional()
6081
+ original_request_name: z20.string().min(1).optional()
5417
6082
  });
5418
6083
  var preCompressInputSchema = baseHookInputSchema.extend({
5419
- hook_event_name: z19.literal("PreCompress"),
5420
- trigger: z19.enum(["auto", "manual"]).optional()
6084
+ hook_event_name: z20.literal("PreCompress"),
6085
+ trigger: z20.enum(["auto", "manual"]).optional()
5421
6086
  });
5422
6087
  var notificationInputSchema = baseHookInputSchema.extend({
5423
- hook_event_name: z19.literal("Notification"),
5424
- notification_type: z19.string().optional(),
5425
- message: z19.string().optional(),
5426
- details: z19.unknown().optional()
6088
+ hook_event_name: z20.literal("Notification"),
6089
+ notification_type: z20.string().optional(),
6090
+ message: z20.string().optional(),
6091
+ details: z20.unknown().optional()
5427
6092
  });
5428
- var geminiHookInputSchema = z19.discriminatedUnion("hook_event_name", [
6093
+ var geminiHookInputSchema = z20.discriminatedUnion("hook_event_name", [
5429
6094
  sessionStartInputSchema,
5430
6095
  sessionEndInputSchema,
5431
6096
  beforeAgentInputSchema,
@@ -5870,7 +6535,7 @@ var normalizeUsageOrWarn = (usage, warnings) => {
5870
6535
  };
5871
6536
 
5872
6537
  // src/providers/antigravity/payload.ts
5873
- import { z as z20 } from "zod";
6538
+ import { z as z21 } from "zod";
5874
6539
  var ANTIGRAVITY_HOOK_EVENT_NAMES = [
5875
6540
  "PreInvocation",
5876
6541
  "PostInvocation",
@@ -5878,48 +6543,48 @@ var ANTIGRAVITY_HOOK_EVENT_NAMES = [
5878
6543
  "PostToolUse",
5879
6544
  "Stop"
5880
6545
  ];
5881
- var hookEventNameSchema = z20.enum(ANTIGRAVITY_HOOK_EVENT_NAMES);
5882
- var antigravityWeakShapeSchema = z20.object({ hookEventName: hookEventNameSchema }).passthrough();
6546
+ var hookEventNameSchema = z21.enum(ANTIGRAVITY_HOOK_EVENT_NAMES);
6547
+ var antigravityWeakShapeSchema = z21.object({ hookEventName: hookEventNameSchema }).passthrough();
5883
6548
  var commonFields2 = {
5884
- conversationId: z20.string().min(1),
5885
- workspacePaths: z20.array(z20.string().min(1)).max(64),
5886
- invocationNum: z20.number().int().min(0),
6549
+ conversationId: z21.string().min(1),
6550
+ workspacePaths: z21.array(z21.string().min(1)).max(64),
6551
+ invocationNum: z21.number().int().min(0),
5887
6552
  /** Never disclosed: a real filesystem path. Accepted, never propagated. */
5888
- transcriptPath: z20.string().min(1).optional(),
6553
+ transcriptPath: z21.string().min(1).optional(),
5889
6554
  /** Never disclosed: a real filesystem path. Accepted, never propagated. */
5890
- artifactDirectoryPath: z20.string().min(1).optional()
6555
+ artifactDirectoryPath: z21.string().min(1).optional()
5891
6556
  };
5892
- var preInvocationPayloadSchema = z20.object({
5893
- hookEventName: z20.literal("PreInvocation"),
6557
+ var preInvocationPayloadSchema = z21.object({
6558
+ hookEventName: z21.literal("PreInvocation"),
5894
6559
  ...commonFields2,
5895
- agentVersion: z20.string().min(1).optional()
6560
+ agentVersion: z21.string().min(1).optional()
5896
6561
  });
5897
- var postInvocationPayloadSchema = z20.object({
5898
- hookEventName: z20.literal("PostInvocation"),
6562
+ var postInvocationPayloadSchema = z21.object({
6563
+ hookEventName: z21.literal("PostInvocation"),
5899
6564
  ...commonFields2,
5900
- agentVersion: z20.string().min(1).optional()
6565
+ agentVersion: z21.string().min(1).optional()
5901
6566
  });
5902
- var preToolUsePayloadSchema3 = z20.object({
5903
- hookEventName: z20.literal("PreToolUse"),
6567
+ var preToolUsePayloadSchema3 = z21.object({
6568
+ hookEventName: z21.literal("PreToolUse"),
5904
6569
  ...commonFields2,
5905
- stepIdx: z20.number().int().min(0),
5906
- toolName: z20.string().min(1),
5907
- toolInput: z20.unknown().optional()
6570
+ stepIdx: z21.number().int().min(0),
6571
+ toolName: z21.string().min(1),
6572
+ toolInput: z21.unknown().optional()
5908
6573
  });
5909
- var postToolUsePayloadSchema3 = z20.object({
5910
- hookEventName: z20.literal("PostToolUse"),
6574
+ var postToolUsePayloadSchema3 = z21.object({
6575
+ hookEventName: z21.literal("PostToolUse"),
5911
6576
  ...commonFields2,
5912
- stepIdx: z20.number().int().min(0),
5913
- toolName: z20.string().min(1),
5914
- toolResponse: z20.unknown().optional(),
5915
- isError: z20.boolean().optional()
6577
+ stepIdx: z21.number().int().min(0),
6578
+ toolName: z21.string().min(1),
6579
+ toolResponse: z21.unknown().optional(),
6580
+ isError: z21.boolean().optional()
5916
6581
  });
5917
- var stopPayloadSchema3 = z20.object({
5918
- hookEventName: z20.literal("Stop"),
6582
+ var stopPayloadSchema3 = z21.object({
6583
+ hookEventName: z21.literal("Stop"),
5919
6584
  ...commonFields2,
5920
- fullyIdle: z20.boolean()
6585
+ fullyIdle: z21.boolean()
5921
6586
  });
5922
- var antigravityHookPayloadSchema = z20.discriminatedUnion("hookEventName", [
6587
+ var antigravityHookPayloadSchema = z21.discriminatedUnion("hookEventName", [
5923
6588
  preInvocationPayloadSchema,
5924
6589
  postInvocationPayloadSchema,
5925
6590
  preToolUsePayloadSchema3,
@@ -6233,15 +6898,15 @@ var describeProviderCatalog = (options = {}) => {
6233
6898
  };
6234
6899
 
6235
6900
  // src/runtime/ports.ts
6236
- import { z as z21 } from "zod";
6237
- var appliedDeliverySchema = z21.strictObject({
6238
- callbackId: z21.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
6901
+ import { z as z22 } from "zod";
6902
+ var appliedDeliverySchema = z22.strictObject({
6903
+ callbackId: z22.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
6239
6904
  /** How many of that delivery's observations are folded in, counted from one. */
6240
- applications: z21.number().int().min(1).max(4096)
6905
+ applications: z22.number().int().min(1).max(4096)
6241
6906
  });
6242
- var stateValueSchema = z21.discriminatedUnion("kind", [
6243
- z21.strictObject({
6244
- kind: z21.literal("usage-cumulative"),
6907
+ var stateValueSchema = z22.discriminatedUnion("kind", [
6908
+ z22.strictObject({
6909
+ kind: z22.literal("usage-cumulative"),
6245
6910
  usage: canonicalUsageSchema,
6246
6911
  /**
6247
6912
  * Optional: absent on every record written before this field existed, which
@@ -6250,22 +6915,42 @@ var stateValueSchema = z21.discriminatedUnion("kind", [
6250
6915
  */
6251
6916
  appliedDelivery: appliedDeliverySchema.optional()
6252
6917
  }),
6253
- z21.strictObject({
6254
- kind: z21.literal("sequence"),
6918
+ z22.strictObject({
6919
+ kind: z22.literal("sequence"),
6255
6920
  next: sequenceNumberSchema
6256
6921
  }),
6257
- z21.strictObject({
6258
- kind: z21.literal("attributes"),
6922
+ z22.strictObject({
6923
+ kind: z22.literal("attributes"),
6259
6924
  attributes: attributesSchema
6925
+ }),
6926
+ /**
6927
+ * The model a session last reported, so a later invocation whose payload names
6928
+ * none (Claude Code's `Stop`) can still say which model it was. A model id is
6929
+ * not sensitive (`modelDescriptorSchema`), and the descriptor is the strict,
6930
+ * bounded canonical shape, never a payload fragment.
6931
+ */
6932
+ z22.strictObject({
6933
+ kind: z22.literal("session-model"),
6934
+ model: modelDescriptorSchema
6935
+ }),
6936
+ /**
6937
+ * How far a {@link PayloadEnricher} has read a session's append-only source
6938
+ * (Claude Code's transcript), so the next read starts where the last ended.
6939
+ * `source` is an opaque digest of what was read, never a path.
6940
+ */
6941
+ z22.strictObject({
6942
+ kind: z22.literal("read-cursor"),
6943
+ source: z22.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
6944
+ offset: z22.number().int().min(0).max(Number.MAX_SAFE_INTEGER)
6260
6945
  })
6261
6946
  ]);
6262
- var stateRecordSchema = z21.strictObject({
6947
+ var stateRecordSchema = z22.strictObject({
6263
6948
  /** Incremented on each write; lets callers detect lost updates. */
6264
- revision: z21.number().int().min(0),
6949
+ revision: z22.number().int().min(0),
6265
6950
  updatedAt: epochMillisSchema,
6266
6951
  value: stateValueSchema
6267
6952
  });
6268
- var logLevelSchema = z21.enum(["silent", "error", "warn", "info", "debug"]);
6953
+ var logLevelSchema = z22.enum(["silent", "error", "warn", "info", "debug"]);
6269
6954
  var LOG_LEVEL_RANK = Object.freeze({
6270
6955
  silent: 0,
6271
6956
  error: 1,
@@ -6302,9 +6987,9 @@ var createFixedClock = (options = {}) => {
6302
6987
  };
6303
6988
 
6304
6989
  // src/runtime/ids.ts
6305
- import { createHash as createHash2, randomUUID } from "crypto";
6990
+ import { createHash as createHash3, randomUUID } from "crypto";
6306
6991
  var digest = (namespace, parts) => {
6307
- const hash = createHash2("sha256");
6992
+ const hash = createHash3("sha256");
6308
6993
  hash.update(namespace);
6309
6994
  for (const part of parts) {
6310
6995
  hash.update("\0");
@@ -6537,19 +7222,19 @@ var resolveDeliveryIdentity = (input) => {
6537
7222
  };
6538
7223
 
6539
7224
  // src/runtime/hook.ts
6540
- import { z as z22 } from "zod";
7225
+ import { z as z23 } from "zod";
6541
7226
 
6542
7227
  // src/runtime/target-resolution.ts
6543
- import * as path from "path";
7228
+ import * as path2 from "path";
6544
7229
  var DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS = 50;
6545
7230
  var absolutePathsOf = (hint) => {
6546
- const base = hint.baseDirectory !== void 0 && path.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
7231
+ const base = hint.baseDirectory !== void 0 && path2.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
6547
7232
  const resolved = [];
6548
7233
  for (const candidate of hint.paths) {
6549
- if (path.isAbsolute(candidate)) {
6550
- resolved.push(path.resolve(candidate));
7234
+ if (path2.isAbsolute(candidate)) {
7235
+ resolved.push(path2.resolve(candidate));
6551
7236
  } else if (base !== void 0) {
6552
- resolved.push(path.resolve(base, candidate));
7237
+ resolved.push(path2.resolve(base, candidate));
6553
7238
  } else {
6554
7239
  return void 0;
6555
7240
  }
@@ -6707,7 +7392,7 @@ var withOptionalSessionLock = async (store, sessionId, fn, options) => {
6707
7392
  };
6708
7393
 
6709
7394
  // src/runtime/hook.ts
6710
- var usageScopeSchema = z22.enum(["session", "generation", "subagent"]);
7395
+ var usageScopeSchema = z23.enum(["session", "generation", "subagent"]);
6711
7396
  var classifyDurability = (input) => {
6712
7397
  if (!input.attempted) {
6713
7398
  return "nothing-to-deliver";
@@ -6765,6 +7450,22 @@ var usageScopeOf = (event3) => {
6765
7450
  }
6766
7451
  };
6767
7452
  var sequenceKey = (sessionId) => `sequence:${sessionId}`;
7453
+ var sessionModelKey = (sessionId) => `model:${sessionId}`;
7454
+ var readCursorKey = (enricherId, sessionId) => `cursor:${enricherId}:${sessionId}`;
7455
+ var UNKNOWN_MODEL_ID = "unknown";
7456
+ var latestSessionModel = (events) => {
7457
+ let latest;
7458
+ for (const event3 of events) {
7459
+ if (event3.subagentId !== void 0) {
7460
+ continue;
7461
+ }
7462
+ if ((event3.type === "session.start" || event3.type === "generation.start" || event3.type === "generation.end") && event3.model !== void 0 && event3.model.modelId !== UNKNOWN_MODEL_ID) {
7463
+ latest = event3.model;
7464
+ }
7465
+ }
7466
+ return latest;
7467
+ };
7468
+ var sameModel = (left, right) => left !== void 0 && left.modelId === right.modelId && left.vendor === right.vendor && left.family === right.family;
6768
7469
  var usageKey = (sessionId, scope, scopeKey) => `usage:${sessionId}:${scope}:${scopeKey}`;
6769
7470
  var baselineScopeOf = (scope, scopeKey, sessionId, series) => series === "session-lifetime" && scope === "generation" ? { scope: "session", scopeKey: sessionId } : { scope, scopeKey };
6770
7471
  var createOtelHook = (deps) => {
@@ -6812,6 +7513,66 @@ var createOtelHook = (deps) => {
6812
7513
  return 0;
6813
7514
  }
6814
7515
  };
7516
+ const enrichPayload = async (payload, providerId, sessionId, diagnostics) => {
7517
+ let current = payload;
7518
+ for (const enricher of deps.payloadEnrichers ?? []) {
7519
+ if (enricher.providerId !== providerId) {
7520
+ continue;
7521
+ }
7522
+ const key = readCursorKey(enricher.id, sessionId);
7523
+ let cursor;
7524
+ try {
7525
+ const record = await deps.stateStore.read(key);
7526
+ if (record?.value.kind === "read-cursor") {
7527
+ cursor = { source: record.value.source, offset: record.value.offset };
7528
+ }
7529
+ } catch (thrown) {
7530
+ diagnostics.push(
7531
+ errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
7532
+ );
7533
+ continue;
7534
+ }
7535
+ let result;
7536
+ try {
7537
+ result = await enricher.enrich({ payload: current, sessionId, ...cursor === void 0 ? {} : { cursor } });
7538
+ } catch (thrown) {
7539
+ logger.warn("payload enricher failed; parsing the payload as delivered", {
7540
+ "enricher.id": enricher.id,
7541
+ "error.name": thrown instanceof Error ? thrown.name : typeof thrown
7542
+ });
7543
+ continue;
7544
+ }
7545
+ current = result.payload;
7546
+ if (result.notes !== void 0 && result.notes.length > 0) {
7547
+ logger.debug("payload enricher notes", {
7548
+ "enricher.id": enricher.id,
7549
+ "enricher.notes": result.notes.slice(0, 8).map((note) => note.slice(0, 200))
7550
+ });
7551
+ }
7552
+ const next = result.cursor;
7553
+ if (next !== void 0 && (next.source !== cursor?.source || next.offset !== cursor.offset)) {
7554
+ try {
7555
+ await deps.stateStore.write(key, { kind: "read-cursor", source: next.source, offset: next.offset });
7556
+ } catch (thrown) {
7557
+ diagnostics.push(
7558
+ errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
7559
+ );
7560
+ }
7561
+ }
7562
+ }
7563
+ return current;
7564
+ };
7565
+ const readSessionModel = async (sessionId, diagnostics) => {
7566
+ try {
7567
+ const record = await deps.stateStore.read(sessionModelKey(sessionId));
7568
+ return record?.value.kind === "session-model" ? record.value.model : void 0;
7569
+ } catch (thrown) {
7570
+ diagnostics.push(
7571
+ errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
7572
+ );
7573
+ return void 0;
7574
+ }
7575
+ };
6815
7576
  const deriveUsage = async (events, diagnostics, suppress, series) => {
6816
7577
  const observations = [];
6817
7578
  for (const event3 of events) {
@@ -7132,10 +7893,19 @@ var createOtelHook = (deps) => {
7132
7893
  const identity = resolution.identity;
7133
7894
  const prepare = async () => {
7134
7895
  const sequenceBase = await readSequenceBase(identity.sessionId, diagnostics);
7896
+ const sessionModel = await readSessionModel(identity.sessionId, diagnostics);
7897
+ const payload = suppress ? detectionInput.payload : await enrichPayload(detectionInput.payload, detection.providerId, identity.sessionId, diagnostics);
7135
7898
  let parsed;
7136
7899
  try {
7137
7900
  parsed = adapter.parse(
7138
- { ...detectionInput, detection, identity, sequenceBase },
7901
+ {
7902
+ ...detectionInput,
7903
+ payload,
7904
+ detection,
7905
+ identity,
7906
+ sequenceBase,
7907
+ ...sessionModel === void 0 ? {} : { sessionModel }
7908
+ },
7139
7909
  providerContext
7140
7910
  );
7141
7911
  } catch (thrown) {
@@ -7245,6 +8015,23 @@ var createOtelHook = (deps) => {
7245
8015
  })
7246
8016
  );
7247
8017
  }
8018
+ const reportedModel = latestSessionModel(screened.kept);
8019
+ if (reportedModel !== void 0 && !sameModel(sessionModel, reportedModel)) {
8020
+ try {
8021
+ await deps.stateStore.write(sessionModelKey(identity.sessionId), {
8022
+ kind: "session-model",
8023
+ model: reportedModel
8024
+ });
8025
+ } catch (thrown) {
8026
+ diagnostics.push(
8027
+ errorInfoFromThrown(thrown, {
8028
+ code: "state-store-failure",
8029
+ phase: "state",
8030
+ occurredAt: clock.now()
8031
+ })
8032
+ );
8033
+ }
8034
+ }
7248
8035
  }
7249
8036
  return {
7250
8037
  kind: "ready",
@@ -7463,8 +8250,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
7463
8250
  };
7464
8251
 
7465
8252
  // src/runtime/git-worktree.ts
7466
- import { lstat, open, stat } from "fs/promises";
7467
- import * as path2 from "path";
8253
+ import { lstat, open as open2, stat as stat2 } from "fs/promises";
8254
+ import * as path3 from "path";
7468
8255
  var MAX_WORKTREE_WALK_DEPTH = 128;
7469
8256
  var MAX_GIT_FILE_BYTES = 4096;
7470
8257
  var MAX_CACHE_ENTRIES = 1024;
@@ -7475,7 +8262,7 @@ var INVALID = Object.freeze({ kind: "invalid" });
7475
8262
  var readBounded = async (filePath) => {
7476
8263
  let handle;
7477
8264
  try {
7478
- handle = await open(filePath, "r");
8265
+ handle = await open2(filePath, "r");
7479
8266
  const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
7480
8267
  const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
7481
8268
  return buffer.subarray(0, bytesRead).toString("utf8");
@@ -7496,7 +8283,7 @@ var parseHeadBranch = (head) => {
7496
8283
  return branch;
7497
8284
  };
7498
8285
  var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
7499
- var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path2.resolve(base, target);
8286
+ var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path3.resolve(base, target);
7500
8287
  var parseGitDirFile = (content, worktreeRoot) => {
7501
8288
  const line = firstLine(content);
7502
8289
  return resolveGitPath(
@@ -7516,26 +8303,26 @@ var isMissing = async (filePath) => {
7516
8303
  };
7517
8304
  var isDirectory = async (directory) => {
7518
8305
  try {
7519
- return (await stat(directory)).isDirectory();
8306
+ return (await stat2(directory)).isDirectory();
7520
8307
  } catch {
7521
8308
  return false;
7522
8309
  }
7523
8310
  };
7524
8311
  var repositoryOf = async (worktreeRoot, gitDir) => {
7525
- const commonDirFile = path2.join(gitDir, "commondir");
8312
+ const commonDirFile = path3.join(gitDir, "commondir");
7526
8313
  const content = await readBounded(commonDirFile);
7527
8314
  if (content === void 0) {
7528
8315
  return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
7529
8316
  }
7530
8317
  const commonDir = parseCommonDirFile(content, gitDir);
7531
- const mainRoot = commonDir !== void 0 && path2.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path2.dirname(commonDir) : void 0;
8318
+ const mainRoot = commonDir !== void 0 && path3.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path3.dirname(commonDir) : void 0;
7532
8319
  return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
7533
8320
  };
7534
8321
  var probeDirectory = async (directory) => {
7535
- const dotGit = path2.join(directory, ".git");
8322
+ const dotGit = path3.join(directory, ".git");
7536
8323
  let info;
7537
8324
  try {
7538
- info = await stat(dotGit);
8325
+ info = await stat2(dotGit);
7539
8326
  } catch {
7540
8327
  return ABSENT;
7541
8328
  }
@@ -7549,7 +8336,7 @@ var probeDirectory = async (directory) => {
7549
8336
  if (gitDir === void 0) {
7550
8337
  return INVALID;
7551
8338
  }
7552
- const head = await readBounded(path2.join(gitDir, "HEAD"));
8339
+ const head = await readBounded(path3.join(gitDir, "HEAD"));
7553
8340
  if (head === void 0) {
7554
8341
  return INVALID;
7555
8342
  }
@@ -7579,10 +8366,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
7579
8366
  };
7580
8367
  const locate = async (absolutePath) => {
7581
8368
  try {
7582
- if (!path2.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
8369
+ if (!path3.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
7583
8370
  return void 0;
7584
8371
  }
7585
- let directory = path2.resolve(absolutePath);
8372
+ let directory = path3.resolve(absolutePath);
7586
8373
  for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
7587
8374
  const probe = await cachedProbe(directory);
7588
8375
  if (probe.kind === "worktree") {
@@ -7591,7 +8378,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
7591
8378
  if (probe.kind === "invalid") {
7592
8379
  return void 0;
7593
8380
  }
7594
- const parent = path2.dirname(directory);
8381
+ const parent = path3.dirname(directory);
7595
8382
  if (parent === directory) {
7596
8383
  return void 0;
7597
8384
  }
@@ -7801,7 +8588,7 @@ var createCallbackDeduplicator = (deps) => {
7801
8588
  };
7802
8589
 
7803
8590
  // src/telemetry/semconv.ts
7804
- import { createHash as createHash3 } from "crypto";
8591
+ import { createHash as createHash4 } from "crypto";
7805
8592
  import { SpanKind, SpanStatusCode, TraceFlags } from "@opentelemetry/api";
7806
8593
  import { millisToHrTime } from "@opentelemetry/core";
7807
8594
  import {
@@ -7820,7 +8607,7 @@ import {
7820
8607
  } from "@opentelemetry/semantic-conventions/incubating";
7821
8608
 
7822
8609
  // src/version.ts
7823
- var VERSION = "0.8.0";
8610
+ var VERSION = "0.10.0";
7824
8611
 
7825
8612
  // src/telemetry/export-identity.ts
7826
8613
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -7917,6 +8704,7 @@ var ATTR_OTELHOOK_SPAN_PAIRING = "otelhook.span.pairing";
7917
8704
  var ATTR_OTELHOOK_SPAN_ORPHAN = "otelhook.span.orphan";
7918
8705
  var ATTR_OTELHOOK_OUTCOME = "otelhook.outcome";
7919
8706
  var ATTR_OTELHOOK_RESET_DETECTED = "otelhook.usage.reset_detected";
8707
+ var ATTR_OTELHOOK_USAGE_PARTIAL = "otelhook.usage.partial";
7920
8708
  var ATTR_OTELHOOK_TOOL_KIND = "otelhook.tool.kind";
7921
8709
  var ATTR_OTELHOOK_DELEGATION_DEPTH = "otelhook.delegation_depth";
7922
8710
  var ATTR_OTELHOOK_COMPACTION_TRIGGER = "otelhook.compaction.trigger";
@@ -7924,7 +8712,7 @@ var ATTR_OTELHOOK_AGENT_NAME = "otelhook.agent.name";
7924
8712
  var ATTR_OTELHOOK_AGENT_VERSION = "otelhook.agent.version";
7925
8713
  var ATTR_OTELHOOK_GENERATION_ID = "otelhook.generation.id";
7926
8714
  var FIELD_SEPARATOR = "\0";
7927
- var digestHex = (parts, length) => createHash3("sha256").update(parts.join(FIELD_SEPARATOR)).digest("hex").slice(0, length);
8715
+ var digestHex = (parts, length) => createHash4("sha256").update(parts.join(FIELD_SEPARATOR)).digest("hex").slice(0, length);
7928
8716
  var MAX_RECOVERED_START_ATTRIBUTES = 16;
7929
8717
  var familyOf = (type) => {
7930
8718
  switch (type) {
@@ -8189,7 +8977,8 @@ var buildLifecycleSpan = (plan, resource, scope) => {
8189
8977
  // Codex turn): the key a consumer stores a usage observation under.
8190
8978
  [ATTR_OTELHOOK_GENERATION_ID]: group.ref.scopeKey,
8191
8979
  ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
8192
- ...usageAttributes(end?.usage, false)
8980
+ ...usageAttributes(end?.usage, false),
8981
+ ...end?.usage === void 0 || end.usagePartial === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_PARTIAL]: end.usagePartial }
8193
8982
  };
8194
8983
  status = outcomeStatus(end?.outcome);
8195
8984
  break;
@@ -9042,24 +9831,24 @@ var createBoundedMemoryStateStore = (options) => {
9042
9831
 
9043
9832
  // src/state/filesystem-store.ts
9044
9833
  import { randomBytes as randomBytes2 } from "crypto";
9045
- import { mkdir, open as open2, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
9046
- import * as path3 from "path";
9834
+ import { mkdir, open as open3, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
9835
+ import * as path4 from "path";
9047
9836
 
9048
9837
  // src/state/keys.ts
9049
- import { createHash as createHash4 } from "crypto";
9838
+ import { createHash as createHash5 } from "crypto";
9050
9839
  var SAFE_SEGMENT_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
9051
9840
  var isSafeSegment = (segment) => SAFE_SEGMENT_PATTERN.test(segment);
9052
9841
  var sanitizeSegment = (segment) => {
9053
9842
  if (isSafeSegment(segment)) {
9054
9843
  return segment;
9055
9844
  }
9056
- return `h_${createHash4("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
9845
+ return `h_${createHash5("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
9057
9846
  };
9058
9847
  var namespaceSegments = (namespace) => [
9059
9848
  sanitizeSegment(namespace.providerId),
9060
9849
  sanitizeSegment(namespace.installationId)
9061
9850
  ];
9062
- var keyDigest = (key) => createHash4("sha256").update(key, "utf8").digest("hex");
9851
+ var keyDigest = (key) => createHash5("sha256").update(key, "utf8").digest("hex");
9063
9852
 
9064
9853
  // src/state/filesystem-store.ts
9065
9854
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
@@ -9075,10 +9864,10 @@ var wrapFsError = (thrown, operation) => {
9075
9864
  };
9076
9865
  var createFilesystemStateStore = (options) => {
9077
9866
  const [providerSegment, installationSegment] = namespaceSegments(options);
9078
- const baseDir = path3.join(options.rootDir, providerSegment, installationSegment);
9079
- const recordsDir = path3.join(baseDir, "records");
9080
- const quarantineDir = path3.join(baseDir, "quarantine");
9081
- const locksDir = path3.join(baseDir, "locks");
9867
+ const baseDir = path4.join(options.rootDir, providerSegment, installationSegment);
9868
+ const recordsDir = path4.join(baseDir, "records");
9869
+ const quarantineDir = path4.join(baseDir, "quarantine");
9870
+ const locksDir = path4.join(baseDir, "locks");
9082
9871
  const lockTimeoutMillis = options.lockTimeoutMillis ?? 5e3;
9083
9872
  const lockStaleMillis = options.lockStaleMillis ?? 3e4;
9084
9873
  const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;
@@ -9102,11 +9891,11 @@ var createFilesystemStateStore = (options) => {
9102
9891
  throw wrapFsError(thrown, "ensure-dirs");
9103
9892
  }
9104
9893
  };
9105
- const recordPath = (key) => path3.join(recordsDir, `${keyDigest(key)}.json`);
9106
- const tempPath = (key) => path3.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
9107
- const lockPath = (sessionId) => path3.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
9894
+ const recordPath = (key) => path4.join(recordsDir, `${keyDigest(key)}.json`);
9895
+ const tempPath = (key) => path4.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
9896
+ const lockPath = (sessionId) => path4.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
9108
9897
  const quarantine = async (filePath, key, reason) => {
9109
- const dest = path3.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
9898
+ const dest = path4.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
9110
9899
  try {
9111
9900
  await rename(filePath, dest);
9112
9901
  } catch {
@@ -9170,7 +9959,7 @@ var createFilesystemStateStore = (options) => {
9170
9959
  const startedAt = options.clock.monotonicMillis();
9171
9960
  for (; ; ) {
9172
9961
  try {
9173
- const handle = await open2(filePath, "wx");
9962
+ const handle = await open3(filePath, "wx");
9174
9963
  try {
9175
9964
  await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));
9176
9965
  } finally {
@@ -9238,7 +10027,7 @@ var createFilesystemStateStore = (options) => {
9238
10027
  }
9239
10028
  let raw;
9240
10029
  try {
9241
- raw = await readFile(path3.join(recordsDir, entry), "utf8");
10030
+ raw = await readFile(path4.join(recordsDir, entry), "utf8");
9242
10031
  } catch {
9243
10032
  continue;
9244
10033
  }
@@ -9291,7 +10080,7 @@ var createFilesystemStateStore = (options) => {
9291
10080
  continue;
9292
10081
  }
9293
10082
  scanned += 1;
9294
- const filePath = path3.join(recordsDir, entry);
10083
+ const filePath = path4.join(recordsDir, entry);
9295
10084
  try {
9296
10085
  const raw = await readFile(filePath, "utf8");
9297
10086
  const envelope = JSON.parse(raw);
@@ -9311,7 +10100,7 @@ var createFilesystemStateStore = (options) => {
9311
10100
  lockEntries = [];
9312
10101
  }
9313
10102
  for (const entry of lockEntries) {
9314
- const filePath = path3.join(locksDir, entry);
10103
+ const filePath = path4.join(locksDir, entry);
9315
10104
  try {
9316
10105
  const raw = await readFile(filePath, "utf8");
9317
10106
  const parsed = JSON.parse(raw);
@@ -9329,14 +10118,70 @@ var createFilesystemStateStore = (options) => {
9329
10118
 
9330
10119
  // src/telemetry/spool-queue.ts
9331
10120
  import { randomBytes as randomBytes3 } from "crypto";
9332
- import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, rename as rename2, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
9333
- import * as path4 from "path";
10121
+ import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, rename as rename2, stat as stat3, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
10122
+ import * as path5 from "path";
10123
+ var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
10124
+ total: 0,
10125
+ age: 0,
10126
+ size: 0,
10127
+ count: 0,
10128
+ rejected: 0
10129
+ });
10130
+ var SPOOL_DROPS_FILE = ".drops";
10131
+ var enqueuedAtOf = (fileName) => {
10132
+ const match = /^(\d{16})-/.exec(fileName);
10133
+ return match?.[1] === void 0 ? void 0 : Number(match[1]);
10134
+ };
10135
+ var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
10136
+ var readSpoolDropCounts = async (queueDir) => {
10137
+ try {
10138
+ const parsed = JSON.parse(await readFile2(path5.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
10139
+ if (typeof parsed !== "object" || parsed === null) {
10140
+ return EMPTY_SPOOL_DROP_COUNTS;
10141
+ }
10142
+ const record = parsed;
10143
+ const field = (name) => isCount(record[name]) ? record[name] : 0;
10144
+ return {
10145
+ total: field("total"),
10146
+ age: field("age"),
10147
+ size: field("size"),
10148
+ count: field("count"),
10149
+ rejected: field("rejected"),
10150
+ ...isCount(record.lastDroppedAt) ? { lastDroppedAt: record.lastDroppedAt } : {}
10151
+ };
10152
+ } catch {
10153
+ return EMPTY_SPOOL_DROP_COUNTS;
10154
+ }
10155
+ };
10156
+ var readSpoolQueueStats = async (queueDir) => {
10157
+ let entries;
10158
+ try {
10159
+ entries = await readdir2(queueDir);
10160
+ } catch {
10161
+ return { batches: 0, bytes: 0, dropped: await readSpoolDropCounts(queueDir) };
10162
+ }
10163
+ const files = entries.filter((entry) => entry.endsWith(".json") && !entry.startsWith(".tmp-")).sort();
10164
+ let bytes = 0;
10165
+ for (const file of files) {
10166
+ try {
10167
+ bytes += (await stat3(path5.join(queueDir, file))).size;
10168
+ } catch {
10169
+ }
10170
+ }
10171
+ const oldest = files[0] === void 0 ? void 0 : enqueuedAtOf(files[0]);
10172
+ return {
10173
+ batches: files.length,
10174
+ bytes,
10175
+ ...oldest === void 0 ? {} : { oldestEnqueuedAt: oldest },
10176
+ dropped: await readSpoolDropCounts(queueDir)
10177
+ };
10178
+ };
9334
10179
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
9335
10180
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
9336
10181
  var createSpoolQueue = (options) => {
9337
10182
  const [providerSegment, installationSegment] = namespaceSegments(options);
9338
- const queueDir = path4.join(options.rootDir, providerSegment, installationSegment, options.queueName);
9339
- const corruptDir = path4.join(
10183
+ const queueDir = path5.join(options.rootDir, providerSegment, installationSegment, options.queueName);
10184
+ const corruptDir = path5.join(
9340
10185
  options.rootDir,
9341
10186
  providerSegment,
9342
10187
  installationSegment,
@@ -9371,27 +10216,132 @@ var createSpoolQueue = (options) => {
9371
10216
  }
9372
10217
  return entries.filter((entry) => entry.endsWith(".json") && !entry.startsWith(".tmp-")).sort();
9373
10218
  };
10219
+ const recordDrops = async (reason, dropped) => {
10220
+ if (dropped <= 0) {
10221
+ return;
10222
+ }
10223
+ try {
10224
+ const current = await readSpoolDropCounts(queueDir);
10225
+ const next = {
10226
+ ...current,
10227
+ total: current.total + dropped,
10228
+ [reason]: current[reason] + dropped,
10229
+ lastDroppedAt: options.clock.now()
10230
+ };
10231
+ const tmp = path5.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
10232
+ await writeFile2(tmp, JSON.stringify(next), "utf8");
10233
+ await rename2(tmp, path5.join(queueDir, SPOOL_DROPS_FILE));
10234
+ } catch {
10235
+ }
10236
+ options.logger?.warn("durable spool dropped batches", {
10237
+ "spool.queue": options.queueName,
10238
+ "spool.drop_reason": reason,
10239
+ "spool.dropped": dropped
10240
+ });
10241
+ };
10242
+ const listWithSizes = async () => {
10243
+ const names = await listSorted();
10244
+ const files = [];
10245
+ for (const name of names) {
10246
+ let bytes = 0;
10247
+ if (options.maxBytes !== void 0) {
10248
+ try {
10249
+ bytes = (await stat3(path5.join(queueDir, name))).size;
10250
+ } catch {
10251
+ continue;
10252
+ }
10253
+ }
10254
+ const enqueuedAt = enqueuedAtOf(name);
10255
+ files.push({ name, bytes, ...enqueuedAt === void 0 ? {} : { enqueuedAt } });
10256
+ }
10257
+ return files;
10258
+ };
10259
+ const evict = async (files) => {
10260
+ let removed = 0;
10261
+ for (const file of files) {
10262
+ try {
10263
+ await unlink2(path5.join(queueDir, file.name));
10264
+ removed += 1;
10265
+ } catch {
10266
+ }
10267
+ }
10268
+ return removed;
10269
+ };
10270
+ const isExpired = (file, now) => options.maxAgeMillis !== void 0 && file.enqueuedAt !== void 0 && now - file.enqueuedAt > options.maxAgeMillis;
9374
10271
  const enqueue = async (batch) => {
9375
10272
  await ensureDirs();
9376
- const existing = await listSorted();
9377
- if (existing.length >= options.maxFiles) {
10273
+ const serialized = JSON.stringify(batch);
10274
+ const bytes = Buffer.byteLength(serialized, "utf8");
10275
+ const refuse = async (reason) => {
9378
10276
  options.logger?.warn("durable spool at capacity; batch dropped", {
9379
10277
  "spool.max_files": options.maxFiles,
10278
+ ...options.maxBytes === void 0 ? {} : { "spool.max_bytes": options.maxBytes },
9380
10279
  "spool.queue": options.queueName
9381
10280
  });
10281
+ await recordDrops(reason, 1);
9382
10282
  return { spooled: false, reason: "capacity-exceeded" };
10283
+ };
10284
+ if (options.maxBytes !== void 0 && bytes > options.maxBytes) {
10285
+ return refuse("size");
10286
+ }
10287
+ let queued = await listWithSizes();
10288
+ const now = options.clock.now();
10289
+ const expired = queued.filter((file) => isExpired(file, now));
10290
+ if (expired.length > 0) {
10291
+ await recordDrops("age", await evict(expired));
10292
+ queued = queued.filter((file) => !isExpired(file, now));
10293
+ }
10294
+ const overflow = options.overflow ?? "refuse-new";
10295
+ const totalBytes = () => queued.reduce((sum, file) => sum + file.bytes, 0);
10296
+ if (overflow === "refuse-new") {
10297
+ if (queued.length >= options.maxFiles) {
10298
+ return refuse("count");
10299
+ }
10300
+ if (options.maxBytes !== void 0 && totalBytes() + bytes > options.maxBytes) {
10301
+ return refuse("size");
10302
+ }
10303
+ } else {
10304
+ const overCount = Math.max(0, queued.length + 1 - options.maxFiles);
10305
+ if (overCount > 0) {
10306
+ await recordDrops("count", await evict(queued.slice(0, overCount)));
10307
+ queued = queued.slice(overCount);
10308
+ }
10309
+ if (options.maxBytes !== void 0) {
10310
+ let excess = totalBytes() + bytes - options.maxBytes;
10311
+ let cut = 0;
10312
+ while (excess > 0 && cut < queued.length) {
10313
+ excess -= queued[cut]?.bytes ?? 0;
10314
+ cut += 1;
10315
+ }
10316
+ if (cut > 0) {
10317
+ await recordDrops("size", await evict(queued.slice(0, cut)));
10318
+ queued = queued.slice(cut);
10319
+ }
10320
+ }
9383
10321
  }
9384
- const fileName = `${String(options.clock.now()).padStart(16, "0")}-${randomBytes3(6).toString("hex")}.json`;
9385
- const target = path4.join(queueDir, fileName);
9386
- const tmp = path4.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
9387
- await writeFile2(tmp, JSON.stringify(batch), "utf8");
10322
+ const fileName = `${String(now).padStart(16, "0")}-${randomBytes3(6).toString("hex")}.json`;
10323
+ const target = path5.join(queueDir, fileName);
10324
+ const tmp = path5.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
10325
+ await writeFile2(tmp, serialized, "utf8");
9388
10326
  await rename2(tmp, target);
9389
10327
  return { spooled: true };
9390
10328
  };
9391
10329
  const drain = async (send, drainOptions) => {
9392
10330
  await ensureDirs();
9393
10331
  const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;
9394
- const files = await listSorted();
10332
+ let files = await listSorted();
10333
+ if (options.maxAgeMillis !== void 0) {
10334
+ const now = options.clock.now();
10335
+ const expired = files.map((name) => {
10336
+ const enqueuedAt = enqueuedAtOf(name);
10337
+ return { name, bytes: 0, ...enqueuedAt === void 0 ? {} : { enqueuedAt } };
10338
+ }).filter((file) => isExpired(file, now));
10339
+ if (expired.length > 0) {
10340
+ await recordDrops("age", await evict(expired));
10341
+ const gone = new Set(expired.map((file) => file.name));
10342
+ files = files.filter((name) => !gone.has(name));
10343
+ }
10344
+ }
9395
10345
  let drained = 0;
9396
10346
  let failed = 0;
9397
10347
  let quarantined = 0;
@@ -9401,7 +10351,7 @@ var createSpoolQueue = (options) => {
9401
10351
  if (fileName === void 0) {
9402
10352
  break;
9403
10353
  }
9404
- const filePath = path4.join(queueDir, fileName);
10354
+ const filePath = path5.join(queueDir, fileName);
9405
10355
  const quarantine = async (rejection) => {
9406
10356
  quarantined += 1;
9407
10357
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -9410,7 +10360,7 @@ var createSpoolQueue = (options) => {
9410
10360
  "spool.queue": options.queueName
9411
10361
  });
9412
10362
  try {
9413
- await rename2(filePath, path4.join(corruptDir, fileName));
10363
+ await rename2(filePath, path5.join(corruptDir, fileName));
9414
10364
  } catch {
9415
10365
  await unlink2(filePath).catch(() => void 0);
9416
10366
  }
@@ -9436,6 +10386,12 @@ var createSpoolQueue = (options) => {
9436
10386
  } catch {
9437
10387
  delivered = false;
9438
10388
  }
10389
+ if (delivered === "discard") {
10390
+ if (await unlink2(filePath).then(() => true, () => false)) {
10391
+ await recordDrops("rejected", 1);
10392
+ }
10393
+ continue;
10394
+ }
9439
10395
  if (delivered) {
9440
10396
  await unlink2(filePath).catch(() => void 0);
9441
10397
  drained += 1;
@@ -9453,7 +10409,8 @@ var createSpoolQueue = (options) => {
9453
10409
  size: async () => {
9454
10410
  await ensureDirs();
9455
10411
  return (await listSorted()).length;
9456
- }
10412
+ },
10413
+ stats: () => readSpoolQueueStats(queueDir)
9457
10414
  };
9458
10415
  };
9459
10416
 
@@ -9545,7 +10502,10 @@ var createFileDurableSpool = (options) => createSpoolQueue({
9545
10502
  clock: options.clock,
9546
10503
  ...options.logger === void 0 ? {} : { logger: options.logger },
9547
10504
  maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_SPOOL_FILES,
9548
- queueName: "spool",
10505
+ queueName: options.queueName ?? "spool",
10506
+ ...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
10507
+ ...options.maxAgeMillis === void 0 ? {} : { maxAgeMillis: options.maxAgeMillis },
10508
+ ...options.overflow === void 0 ? {} : { overflow: options.overflow },
9549
10509
  validate: validateSpoolBatch
9550
10510
  });
9551
10511
 
@@ -9586,7 +10546,8 @@ var createHealthTracker = (subsystem, options = {}) => {
9586
10546
  consecutiveFailures,
9587
10547
  ...lastSuccessAt === void 0 ? {} : { lastSuccessAt },
9588
10548
  ...lastFailureAt === void 0 ? {} : { lastFailureAt },
9589
- ...lastErrorCode === void 0 ? {} : { lastErrorCode }
10549
+ ...lastErrorCode === void 0 ? {} : { lastErrorCode },
10550
+ ...options.destination === void 0 ? {} : { destination: options.destination }
9590
10551
  })
9591
10552
  };
9592
10553
  };
@@ -9595,6 +10556,13 @@ var summarizeHealth = (snapshots) => ({
9595
10556
  subsystems: [...snapshots]
9596
10557
  });
9597
10558
 
10559
+ // src/telemetry/export-failure.ts
10560
+ var RETRYABLE_HTTP_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
10561
+ var isPermanentExportFailure = (result) => {
10562
+ const code = result.error?.code;
10563
+ return typeof code === "number" && Number.isInteger(code) && code >= 400 && code < 600 && !RETRYABLE_HTTP_STATUSES.has(code);
10564
+ };
10565
+
9598
10566
  // src/telemetry/exporter-resource.ts
9599
10567
  import { resourceFromAttributes } from "@opentelemetry/resources";
9600
10568
  var resourceFromExporterPolicy = (policy) => resourceFromAttributes({
@@ -9666,8 +10634,11 @@ var deserializeSpan = (serialized, resource, scope) => assembleReadableSpan({
9666
10634
  resource,
9667
10635
  instrumentationScope: scope
9668
10636
  });
9669
- var createDisabledSink = () => {
9670
- const health = createHealthTracker("telemetry-sink");
10637
+ var createDisabledSink = (destination) => {
10638
+ const health = createHealthTracker(
10639
+ "telemetry-sink",
10640
+ destination === void 0 ? {} : { destination }
10641
+ );
9671
10642
  return {
9672
10643
  emit: (events) => {
9673
10644
  health.recordSuccess(events.length);
@@ -9680,22 +10651,27 @@ var createDisabledSink = () => {
9680
10651
  };
9681
10652
  };
9682
10653
  var createOtlpTraceSink = (options) => {
10654
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
9683
10655
  if (!options.exporter.enabled || options.exporter.protocol === "none") {
9684
- return createDisabledSink();
10656
+ return createDisabledSink(options.destination);
9685
10657
  }
9686
10658
  if (options.exporter.endpoint === void 0) {
9687
- options.logger?.warn("otlp sink disabled: no endpoint configured", {});
9688
- return createDisabledSink();
10659
+ options.logger?.warn("otlp sink disabled: no endpoint configured", destinationFields);
10660
+ return createDisabledSink(options.destination);
9689
10661
  }
9690
10662
  if (options.exporter.protocol !== "http/protobuf") {
9691
10663
  options.logger?.warn("otlp sink: protocol not supported by this build, falling back to disabled", {
9692
- "exporter.protocol": options.exporter.protocol
10664
+ "exporter.protocol": options.exporter.protocol,
10665
+ ...destinationFields
9693
10666
  });
9694
- return createDisabledSink();
10667
+ return createDisabledSink(options.destination);
9695
10668
  }
9696
10669
  const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
9697
10670
  const resource = resourceFromExporterPolicy(options.exporter);
9698
- const health = createHealthTracker("telemetry-sink");
10671
+ const health = createHealthTracker(
10672
+ "telemetry-sink",
10673
+ options.destination === void 0 ? {} : { destination: options.destination }
10674
+ );
9699
10675
  const exporter = new OTLPTraceExporter({
9700
10676
  url: options.exporter.endpoint,
9701
10677
  headers: { ...options.headers },
@@ -9717,7 +10693,10 @@ var createOtlpTraceSink = (options) => {
9717
10693
  const batchResource = replayResource(batch.resourceAttributes, options.exporter);
9718
10694
  const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));
9719
10695
  const result = await exportSpans(spans);
9720
- return result.code === ExportResultCode.SUCCESS;
10696
+ if (result.code === ExportResultCode.SUCCESS) {
10697
+ return true;
10698
+ }
10699
+ return isPermanentExportFailure(result) ? "discard" : false;
9721
10700
  };
9722
10701
  const resolveCorrelations = async (events) => {
9723
10702
  if (options.correlate === void 0) {
@@ -9745,6 +10724,9 @@ var createOtlpTraceSink = (options) => {
9745
10724
  let accepted = 0;
9746
10725
  let rejected = 0;
9747
10726
  for (const batch of chunk(spans, options.exporter.maxBatchSize)) {
10727
+ if (batch.length === 0) {
10728
+ continue;
10729
+ }
9748
10730
  let result;
9749
10731
  try {
9750
10732
  result = await exportSpans(batch);
@@ -9757,13 +10739,18 @@ var createOtlpTraceSink = (options) => {
9757
10739
  continue;
9758
10740
  }
9759
10741
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
9760
- if (options.spool !== void 0) {
10742
+ const permanent = isPermanentExportFailure(result);
10743
+ if (options.spool !== void 0 && !permanent) {
9761
10744
  const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
9762
10745
  spooled: false,
9763
10746
  reason: "capacity-exceeded"
9764
10747
  }));
9765
10748
  if (spoolResult.spooled) {
9766
10749
  accepted += batch.length;
10750
+ options.logger?.warn("span batch not delivered; spooled for the next invocation", {
10751
+ "export.batch_size": batch.length,
10752
+ ...destinationFields
10753
+ });
9767
10754
  continue;
9768
10755
  }
9769
10756
  }
@@ -9772,8 +10759,8 @@ var createOtlpTraceSink = (options) => {
9772
10759
  createErrorInfo({
9773
10760
  code: "telemetry-export-failure",
9774
10761
  phase: "export",
9775
- detail: "collector rejected or was unreachable for a span batch",
9776
- details: { "export.batch_size": batch.length }
10762
+ detail: permanent ? "collector refused a span batch with a non-retryable status" : "collector rejected or was unreachable for a span batch",
10763
+ details: { "export.batch_size": batch.length, ...destinationFields }
9777
10764
  })
9778
10765
  );
9779
10766
  }
@@ -10038,7 +11025,8 @@ var eventAttributes = (event3) => {
10038
11025
  ...event3.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event3.model.vendor },
10039
11026
  [ATTR_OTELHOOK_OUTCOME2]: event3.outcome,
10040
11027
  ...event3.stopReason === void 0 ? {} : { [ATTR_OTELHOOK_STOP_REASON]: event3.stopReason },
10041
- ...usageAttributes2(event3.usage)
11028
+ ...usageAttributes2(event3.usage),
11029
+ ...event3.usage === void 0 || event3.usagePartial === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_PARTIAL]: event3.usagePartial }
10042
11030
  };
10043
11031
  case "tool.start":
10044
11032
  return {
@@ -10330,7 +11318,10 @@ var createFileDurableLogSpool = (options) => createSpoolQueue({
10330
11318
  clock: options.clock,
10331
11319
  ...options.logger === void 0 ? {} : { logger: options.logger },
10332
11320
  maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_LOG_SPOOL_FILES,
10333
- queueName: "spool-logs",
11321
+ queueName: options.queueName ?? "spool-logs",
11322
+ ...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
11323
+ ...options.maxAgeMillis === void 0 ? {} : { maxAgeMillis: options.maxAgeMillis },
11324
+ ...options.overflow === void 0 ? {} : { overflow: options.overflow },
10334
11325
  validate: validateLogSpoolBatch
10335
11326
  });
10336
11327
 
@@ -10415,8 +11406,11 @@ var chunk2 = (items, size) => {
10415
11406
  }
10416
11407
  return chunks;
10417
11408
  };
10418
- var createDisabledSink2 = () => {
10419
- const health = createHealthTracker("telemetry-log-sink");
11409
+ var createDisabledSink2 = (destination) => {
11410
+ const health = createHealthTracker(
11411
+ "telemetry-log-sink",
11412
+ destination === void 0 ? {} : { destination }
11413
+ );
10420
11414
  return {
10421
11415
  emit: (events) => {
10422
11416
  health.recordSuccess(events.length);
@@ -10455,19 +11449,24 @@ var DISABLED_DETAIL = Object.freeze({
10455
11449
  "no-endpoint": "otlp log sink disabled: no logs endpoint configured and none could be derived"
10456
11450
  });
10457
11451
  var createOtlpLogSink = (options) => {
11452
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
10458
11453
  const deliverability = describeLogsDeliverability(options.exporter);
10459
11454
  if (deliverability.status === "disabled") {
10460
11455
  if (deliverability.reason !== "logs-disabled") {
10461
11456
  options.logger?.warn(DISABLED_DETAIL[deliverability.reason], {
10462
- "exporter.protocol": options.exporter.protocol
11457
+ "exporter.protocol": options.exporter.protocol,
11458
+ ...destinationFields
10463
11459
  });
10464
11460
  }
10465
- return createDisabledSink2();
11461
+ return createDisabledSink2(options.destination);
10466
11462
  }
10467
11463
  const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
10468
11464
  const resource = resourceFromExporterPolicy(options.exporter);
10469
11465
  const content = options.content ?? NO_LOG_CONTENT;
10470
- const health = createHealthTracker("telemetry-log-sink");
11466
+ const health = createHealthTracker(
11467
+ "telemetry-log-sink",
11468
+ options.destination === void 0 ? {} : { destination: options.destination }
11469
+ );
10471
11470
  const exporter = new OTLPLogExporter({
10472
11471
  url: deliverability.endpoint,
10473
11472
  headers: { ...options.headers },
@@ -10494,7 +11493,10 @@ var createOtlpLogSink = (options) => {
10494
11493
  (record) => deserializeRecord(record, batchResource, batch.instrumentationScope)
10495
11494
  );
10496
11495
  const result = await exportRecords(records);
10497
- return result.code === ExportResultCode2.SUCCESS;
11496
+ if (result.code === ExportResultCode2.SUCCESS) {
11497
+ return true;
11498
+ }
11499
+ return isPermanentExportFailure(result) ? "discard" : false;
10498
11500
  };
10499
11501
  const resolveCorrelations = async (events) => {
10500
11502
  if (options.correlate === void 0) {
@@ -10546,13 +11548,18 @@ var createOtlpLogSink = (options) => {
10546
11548
  continue;
10547
11549
  }
10548
11550
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
10549
- if (options.spool !== void 0) {
11551
+ const permanent = isPermanentExportFailure(result);
11552
+ if (options.spool !== void 0 && !permanent) {
10550
11553
  const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
10551
11554
  spooled: false,
10552
11555
  reason: "capacity-exceeded"
10553
11556
  }));
10554
11557
  if (spoolResult.spooled) {
10555
11558
  accepted += batch.length;
11559
+ options.logger?.warn("log record batch not delivered; spooled for the next invocation", {
11560
+ "export.batch_size": batch.length,
11561
+ ...destinationFields
11562
+ });
10556
11563
  continue;
10557
11564
  }
10558
11565
  }
@@ -10561,8 +11568,12 @@ var createOtlpLogSink = (options) => {
10561
11568
  createErrorInfo({
10562
11569
  code: "telemetry-export-failure",
10563
11570
  phase: "export",
10564
- detail: "collector rejected or was unreachable for a log record batch",
10565
- details: { "export.batch_size": batch.length, "export.signal": "logs" }
11571
+ detail: permanent ? "collector refused a log record batch with a non-retryable status" : "collector rejected or was unreachable for a log record batch",
11572
+ details: {
11573
+ "export.batch_size": batch.length,
11574
+ "export.signal": "logs",
11575
+ ...destinationFields
11576
+ }
10566
11577
  })
10567
11578
  );
10568
11579
  }
@@ -10649,6 +11660,172 @@ var shareCorrelationPerBatch = (correlate) => {
10649
11660
  };
10650
11661
  };
10651
11662
 
11663
+ // src/telemetry/export-destinations.ts
11664
+ var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs" } : { traces: `destinations/${destination}/spool`, logs: `destinations/${destination}/spool-logs` };
11665
+ var exporterPolicyForDestination = (exporter, destination) => {
11666
+ if (destination.source === "exporter") {
11667
+ return exporter;
11668
+ }
11669
+ const { destinations, endpoint, logs, ...shared } = exporter;
11670
+ void destinations;
11671
+ void endpoint;
11672
+ const tracesEndpoint = destination.tracesEndpoint ?? destination.endpoint;
11673
+ const derivedLogs = destination.logsEndpoint ?? (destination.endpoint === void 0 ? void 0 : (() => {
11674
+ const derived = resolveLogsEndpoint({
11675
+ ...exporter,
11676
+ endpoint: destination.endpoint,
11677
+ logs: { enabled: true, includeContent: false, maxBatchSize: logs.maxBatchSize }
11678
+ });
11679
+ return "endpoint" in derived ? derived.endpoint : void 0;
11680
+ })());
11681
+ return {
11682
+ ...shared,
11683
+ protocol: destination.protocol,
11684
+ ...tracesEndpoint === void 0 ? {} : { endpoint: tracesEndpoint },
11685
+ headerNames: Object.keys(destination.headers).sort(),
11686
+ logs: {
11687
+ ...logs,
11688
+ enabled: destination.signals.logs,
11689
+ ...derivedLogs === void 0 ? {} : { endpoint: derivedLogs }
11690
+ }
11691
+ };
11692
+ };
11693
+ var createOptedOutTraceSink = (destination) => {
11694
+ const health = createHealthTracker(
11695
+ "telemetry-sink",
11696
+ destination === void 0 ? {} : { destination }
11697
+ );
11698
+ return {
11699
+ emit: () => Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),
11700
+ flush: () => Promise.resolve(),
11701
+ shutdown: () => Promise.resolve(),
11702
+ health: () => health.snapshot(),
11703
+ drainSpool: () => Promise.resolve({ drained: 0, remaining: 0, failed: 0 })
11704
+ };
11705
+ };
11706
+ var createExportDestinationSinks = (options) => {
11707
+ const labelled = hasConfiguredDestinations(options.exporter);
11708
+ const spoolPolicy = effectiveSpoolPolicy(options.exporter);
11709
+ const destinations = [];
11710
+ const skipped = [];
11711
+ for (const destination of resolveExportDestinations(options.exporter)) {
11712
+ let headers;
11713
+ let logHeaders;
11714
+ if (destination.source === "exporter") {
11715
+ headers = options.defaultHeaders;
11716
+ logHeaders = options.defaultLogHeaders ?? options.defaultHeaders;
11717
+ } else {
11718
+ const resolved = resolveDestinationHeaders(destination.headers, options.headerEnvironment);
11719
+ if (resolved.missingVariables.length > 0) {
11720
+ options.logger?.warn("export destination skipped: a header references an unset environment variable", {
11721
+ "export.destination": destination.name,
11722
+ "config.variables": [...resolved.missingVariables]
11723
+ });
11724
+ skipped.push({
11725
+ name: destination.name,
11726
+ reason: "header-variable-missing",
11727
+ missingVariables: resolved.missingVariables
11728
+ });
11729
+ continue;
11730
+ }
11731
+ headers = resolved.values;
11732
+ logHeaders = resolved.values;
11733
+ }
11734
+ const label = labelled ? destination.name : void 0;
11735
+ const policy = exporterPolicyForDestination(options.exporter, destination);
11736
+ const queues = spoolQueueNamesFor(destination.name);
11737
+ const bounds = {
11738
+ maxSpoolFiles: spoolPolicy.maxBatches,
11739
+ maxBytes: spoolPolicy.maxBytes,
11740
+ maxAgeMillis: spoolPolicy.maxAgeMillis,
11741
+ overflow: "drop-oldest"
11742
+ };
11743
+ const shared = {
11744
+ providerId: options.providerId,
11745
+ installationId: options.installationId,
11746
+ clock: options.clock,
11747
+ ...options.logger === void 0 ? {} : { logger: options.logger }
11748
+ };
11749
+ const spool = options.spoolRootDir === void 0 || !destination.signals.traces ? void 0 : createFileDurableSpool({
11750
+ rootDir: options.spoolRootDir,
11751
+ ...shared,
11752
+ ...bounds,
11753
+ queueName: queues.traces
11754
+ });
11755
+ const logSpool = options.spoolRootDir === void 0 || !destination.signals.logs ? void 0 : createFileDurableLogSpool({
11756
+ rootDir: options.spoolRootDir,
11757
+ ...shared,
11758
+ ...bounds,
11759
+ queueName: queues.logs
11760
+ });
11761
+ const sinkShared = {
11762
+ exporter: policy,
11763
+ ...shared,
11764
+ ...options.correlate === void 0 ? {} : { correlate: options.correlate },
11765
+ ...label === void 0 ? {} : { destination: label }
11766
+ };
11767
+ const traces = destination.signals.traces ? createOtlpTraceSink({
11768
+ ...sinkShared,
11769
+ ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
11770
+ ...spool === void 0 ? {} : { spool }
11771
+ }) : createOptedOutTraceSink(label);
11772
+ const logs = createOtlpLogSink({
11773
+ ...sinkShared,
11774
+ ...logHeaders === void 0 || Object.keys(logHeaders).length === 0 ? {} : { headers: logHeaders },
11775
+ ...logSpool === void 0 ? {} : { spool: logSpool },
11776
+ content: options.logContent
11777
+ });
11778
+ destinations.push({
11779
+ name: destination.name,
11780
+ traces,
11781
+ logs,
11782
+ ...spool === void 0 ? {} : { spool },
11783
+ ...logSpool === void 0 ? {} : { logSpool }
11784
+ });
11785
+ }
11786
+ return { destinations, skipped };
11787
+ };
11788
+ var createDestinationFanout = (destinations) => {
11789
+ const fanouts = destinations.map((destination) => ({
11790
+ name: destination.name,
11791
+ sink: createSignalFanout({ traces: destination.traces, logs: destination.logs })
11792
+ }));
11793
+ const only = fanouts.length === 1 ? fanouts[0] : void 0;
11794
+ if (only !== void 0) {
11795
+ return only.sink;
11796
+ }
11797
+ const emit = async (events) => {
11798
+ const results = await Promise.all(
11799
+ fanouts.map(
11800
+ (fanout) => fanout.sink.emit(events).catch(
11801
+ (thrown) => ({
11802
+ accepted: 0,
11803
+ rejected: events.length,
11804
+ errors: [errorInfoFromThrown(thrown, { code: "telemetry-export-failure", phase: "export" })]
11805
+ })
11806
+ )
11807
+ )
11808
+ );
11809
+ const errors = results.flatMap((result) => result.errors);
11810
+ return {
11811
+ accepted: results.reduce((sum, result) => sum + result.accepted, 0),
11812
+ rejected: results.reduce((sum, result) => sum + result.rejected, 0),
11813
+ errors
11814
+ };
11815
+ };
11816
+ const settleAll = async (run) => {
11817
+ await Promise.all(fanouts.map((fanout) => run(fanout.sink).catch(() => void 0)));
11818
+ };
11819
+ return {
11820
+ emit,
11821
+ // Each destination drains its own spool in its flush; in parallel, so one
11822
+ // unreachable destination's drain cannot use up the others' flush window.
11823
+ flush: () => settleAll((sink) => sink.flush()),
11824
+ shutdown: () => settleAll((sink) => sink.shutdown()),
11825
+ health: () => fanouts.flatMap((fanout) => fanout.sink.health())
11826
+ };
11827
+ };
11828
+
10652
11829
  // src/integration/hook-runtime.ts
10653
11830
  var DEFAULT_FLUSH_TIMEOUT_MILLIS = 2e3;
10654
11831
  var DEFAULT_STATE_LOCK_TIMEOUT_MILLIS = 1e3;
@@ -10711,46 +11888,23 @@ var createHookRuntime = (options) => {
10711
11888
  logger,
10712
11889
  lockTimeoutMillis: stateLockTimeoutMillis
10713
11890
  });
10714
- const spool = options.enableSpool === false ? void 0 : createFileDurableSpool({
10715
- rootDir: options.stateRootDir,
10716
- providerId: options.providerNamespace,
10717
- installationId: options.installationId,
10718
- clock,
10719
- logger
10720
- });
10721
- const logSpool = options.enableSpool === false || !options.config.exporter.logs.enabled ? void 0 : createFileDurableLogSpool({
10722
- rootDir: options.stateRootDir,
10723
- providerId: options.providerNamespace,
10724
- installationId: options.installationId,
10725
- clock,
10726
- logger
10727
- });
10728
11891
  const spanCorrelator = createSpanCorrelator({
10729
11892
  stateStore,
10730
11893
  clock,
10731
11894
  maxStartAgeMillis: lifecycleMaxAge
10732
11895
  });
10733
11896
  const correlate = shareCorrelationPerBatch((events) => spanCorrelator.correlateBatch(events));
10734
- const traceSink = createOtlpTraceSink({
10735
- exporter: options.config.exporter,
10736
- ...options.headers === void 0 ? {} : { headers: options.headers },
10737
- providerId: options.providerNamespace,
10738
- installationId: options.installationId,
10739
- clock,
10740
- logger,
10741
- ...spool === void 0 ? {} : { spool },
10742
- correlate
10743
- });
10744
- const logHeaders = options.logHeaders ?? options.headers;
10745
- const logSink = createOtlpLogSink({
11897
+ const exportDestinations = createExportDestinationSinks({
10746
11898
  exporter: options.config.exporter,
10747
- ...logHeaders === void 0 ? {} : { headers: logHeaders },
11899
+ ...options.headers === void 0 ? {} : { defaultHeaders: options.headers },
11900
+ ...options.logHeaders === void 0 ? {} : { defaultLogHeaders: options.logHeaders },
11901
+ ...options.headerEnvironment === void 0 ? {} : { headerEnvironment: options.headerEnvironment },
10748
11902
  providerId: options.providerNamespace,
10749
11903
  installationId: options.installationId,
10750
11904
  clock,
10751
11905
  logger,
10752
- ...logSpool === void 0 ? {} : { spool: logSpool },
10753
- content: {
11906
+ ...options.enableSpool === false ? {} : { spoolRootDir: options.stateRootDir },
11907
+ logContent: {
10754
11908
  includeContent: options.config.exporter.logs.includeContent,
10755
11909
  // The pre-existing verbatim-content opt-in, passed through rather than
10756
11910
  // re-derived: `raw` disclosure in a log body is governed by the same flag it
@@ -10759,7 +11913,22 @@ var createHookRuntime = (options) => {
10759
11913
  },
10760
11914
  correlate
10761
11915
  });
10762
- const sink = createSignalFanout({ traces: traceSink, logs: logSink });
11916
+ const primary = exportDestinations.destinations[0];
11917
+ const traceSink = primary?.traces ?? createOtlpTraceSink({
11918
+ exporter: { ...options.config.exporter, enabled: false },
11919
+ providerId: options.providerNamespace,
11920
+ installationId: options.installationId,
11921
+ clock
11922
+ });
11923
+ const logSink = primary?.logs ?? createOtlpLogSink({
11924
+ exporter: { ...options.config.exporter, logs: { ...options.config.exporter.logs, enabled: false } },
11925
+ providerId: options.providerNamespace,
11926
+ installationId: options.installationId,
11927
+ clock
11928
+ });
11929
+ const spool = primary?.spool;
11930
+ const logSpool = primary?.logSpool;
11931
+ const sink = createDestinationFanout(exportDestinations.destinations);
10763
11932
  const hookDeps = {
10764
11933
  stateStore,
10765
11934
  config: options.config,
@@ -10769,6 +11938,7 @@ var createHookRuntime = (options) => {
10769
11938
  privacy,
10770
11939
  logger,
10771
11940
  installationId: options.installationId,
11941
+ payloadEnrichers: options.payloadEnrichers ?? (readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : []),
10772
11942
  ...options.worktreeLocator === null ? {} : {
10773
11943
  worktreeLocator: options.worktreeLocator ?? createFilesystemWorktreeLocator({ monotonicMillis: () => clock.monotonicMillis() })
10774
11944
  }
@@ -11028,6 +12198,8 @@ var createHookRuntime = (options) => {
11028
12198
  logSink,
11029
12199
  ...spool === void 0 ? {} : { spool },
11030
12200
  ...logSpool === void 0 ? {} : { logSpool },
12201
+ destinations: exportDestinations.destinations,
12202
+ skippedDestinations: exportDestinations.skipped,
11031
12203
  privacy,
11032
12204
  deduplicator,
11033
12205
  usageAccumulator,
@@ -11900,7 +13072,7 @@ var SUPPORTED_REGISTRATION_PROVIDER_IDS = Object.freeze(
11900
13072
  );
11901
13073
 
11902
13074
  // src/install/scopes.ts
11903
- import * as path5 from "path";
13075
+ import * as path6 from "path";
11904
13076
  var REGISTRATION_SCOPES = Object.freeze([
11905
13077
  "global",
11906
13078
  "project"
@@ -11968,15 +13140,15 @@ var PROVIDERS_WITH_VERIFIED_LOCATION = Object.freeze([
11968
13140
  var findInstallLocation = (providerId, scope) => PROVIDER_INSTALL_LOCATIONS.find(
11969
13141
  (entry) => entry.providerId === providerId && entry.scope === scope
11970
13142
  );
11971
- var resolveInstallPath = (location, roots) => path5.resolve(
13143
+ var resolveInstallPath = (location, roots) => path6.resolve(
11972
13144
  location.scope === "global" ? roots.homeDir : roots.projectDir,
11973
13145
  ...location.segments
11974
13146
  );
11975
13147
 
11976
13148
  // src/install/document.ts
11977
13149
  import { randomBytes as randomBytes4 } from "crypto";
11978
- import { chmod, mkdir as mkdir3, open as open3, readFile as readFile3, rename as rename3, stat as stat2, unlink as unlink3 } from "fs/promises";
11979
- import * as path6 from "path";
13150
+ import { chmod, mkdir as mkdir3, open as open4, readFile as readFile3, rename as rename3, stat as stat4, unlink as unlink3 } from "fs/promises";
13151
+ import * as path7 from "path";
11980
13152
  var DEFAULT_DOCUMENT_FORMAT = Object.freeze({
11981
13153
  indent: " ",
11982
13154
  eol: "\n",
@@ -12047,15 +13219,15 @@ var renameWithRetry = async (from, to) => {
12047
13219
  var NEW_DOCUMENT_MODE = 384;
12048
13220
  var TEMPORARY_DOCUMENT_MODE = 384;
12049
13221
  var writeDocumentAtomically = async (filePath, contents) => {
12050
- const directory = path6.dirname(filePath);
13222
+ const directory = path7.dirname(filePath);
12051
13223
  await mkdir3(directory, { recursive: true });
12052
- const temporary = path6.join(
13224
+ const temporary = path7.join(
12053
13225
  directory,
12054
- `.${path6.basename(filePath)}.${randomBytes4(6).toString("hex")}.tmp`
13226
+ `.${path7.basename(filePath)}.${randomBytes4(6).toString("hex")}.tmp`
12055
13227
  );
12056
13228
  let existingMode;
12057
13229
  try {
12058
- existingMode = (await stat2(filePath)).mode & 4095;
13230
+ existingMode = (await stat4(filePath)).mode & 4095;
12059
13231
  } catch (thrown) {
12060
13232
  if (!isErrnoException3(thrown, "ENOENT")) {
12061
13233
  throw thrown;
@@ -12063,7 +13235,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
12063
13235
  }
12064
13236
  const targetMode = existingMode ?? NEW_DOCUMENT_MODE;
12065
13237
  try {
12066
- const handle = await open3(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
13238
+ const handle = await open4(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
12067
13239
  try {
12068
13240
  await handle.writeFile(contents, "utf8");
12069
13241
  await handle.sync();
@@ -12080,12 +13252,12 @@ var writeDocumentAtomically = async (filePath, contents) => {
12080
13252
 
12081
13253
  // src/install/file-lock.ts
12082
13254
  import { randomBytes as randomBytes5 } from "crypto";
12083
- import { mkdir as mkdir4, open as open4, readFile as readFile4, rename as rename4, stat as stat3, unlink as unlink4 } from "fs/promises";
12084
- import * as path7 from "path";
13255
+ import { mkdir as mkdir4, open as open5, readFile as readFile4, rename as rename4, stat as stat5, unlink as unlink4 } from "fs/promises";
13256
+ import * as path8 from "path";
12085
13257
  var FileLockTimeoutError = class extends Error {
12086
13258
  constructor(lockPath, timeoutMillis) {
12087
13259
  super(
12088
- `timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path7.basename(lockPath)}`
13260
+ `timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path8.basename(lockPath)}`
12089
13261
  );
12090
13262
  this.name = "FileLockTimeoutError";
12091
13263
  }
@@ -12145,7 +13317,7 @@ var isStale = async (lockPath, clock, staleMillis) => {
12145
13317
  } catch {
12146
13318
  }
12147
13319
  try {
12148
- const stats = await stat3(lockPath);
13320
+ const stats = await stat5(lockPath);
12149
13321
  return { stale: clock.now() - stats.mtimeMs > staleMillis };
12150
13322
  } catch (thrown) {
12151
13323
  return { stale: !isErrnoException4(thrown, "ENOENT") };
@@ -12157,12 +13329,12 @@ var withFileLock = async (filePath, options, fn) => {
12157
13329
  const pollIntervalMillis = options.pollIntervalMillis ?? 25;
12158
13330
  const lockPath = lockPathFor(filePath);
12159
13331
  const startedAt = options.clock.monotonicMillis();
12160
- await mkdir4(path7.dirname(filePath), { recursive: true });
13332
+ await mkdir4(path8.dirname(filePath), { recursive: true });
12161
13333
  for (; ; ) {
12162
13334
  const token = randomBytes5(16).toString("hex");
12163
13335
  let acquired = false;
12164
13336
  try {
12165
- const handle = await open4(lockPath, "wx", 384);
13337
+ const handle = await open5(lockPath, "wx", 384);
12166
13338
  try {
12167
13339
  const contents = {
12168
13340
  token,
@@ -12205,7 +13377,7 @@ var withFileLock = async (filePath, options, fn) => {
12205
13377
 
12206
13378
  // src/install/lifecycle.ts
12207
13379
  import { readFile as readFile5 } from "fs/promises";
12208
- import * as path8 from "path";
13380
+ import * as path9 from "path";
12209
13381
  var defaultHookCommand = (providerId) => `otel-hook run --provider ${providerId}`;
12210
13382
  var unsupportedOutcome = (providerId, scope, reason) => ({
12211
13383
  providerId,
@@ -12222,7 +13394,7 @@ var unsupportedOutcome = (providerId, scope, reason) => ({
12222
13394
  var resolveTarget = (providerId, scope, request) => {
12223
13395
  if (request.configFile !== void 0) {
12224
13396
  return {
12225
- configPath: path8.resolve(request.configFile),
13397
+ configPath: path9.resolve(request.configFile),
12226
13398
  evidence: "path supplied by the caller with --settings-file"
12227
13399
  };
12228
13400
  }
@@ -12239,14 +13411,14 @@ var resolveTarget = (providerId, scope, request) => {
12239
13411
  };
12240
13412
  };
12241
13413
  var codexFeatureNote = async (configPath) => {
12242
- const tomlPath = path8.join(path8.dirname(configPath), "config.toml");
13414
+ const tomlPath = path9.join(path9.dirname(configPath), "config.toml");
12243
13415
  let raw;
12244
13416
  try {
12245
13417
  raw = await readFile5(tomlPath, "utf8");
12246
13418
  } catch {
12247
13419
  return void 0;
12248
13420
  }
12249
- return readCodexHooksFeatureFlag(raw) === "disabled" ? `${path8.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed` : void 0;
13421
+ return readCodexHooksFeatureFlag(raw) === "disabled" ? `${path9.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed` : void 0;
12250
13422
  };
12251
13423
  var readState = async (configPath) => {
12252
13424
  const read = await readJsonDocument(configPath);
@@ -12258,12 +13430,12 @@ var readState = async (configPath) => {
12258
13430
  case "unparseable":
12259
13431
  return {
12260
13432
  status: "blocked",
12261
- problem: `${path8.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`
13433
+ problem: `${path9.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`
12262
13434
  };
12263
13435
  case "unreadable":
12264
13436
  return {
12265
13437
  status: "failed",
12266
- problem: `${path8.basename(configPath)} could not be read (${read.detail})`
13438
+ problem: `${path9.basename(configPath)} could not be read (${read.detail})`
12267
13439
  };
12268
13440
  }
12269
13441
  };
@@ -12375,7 +13547,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
12375
13547
  missingEvents: [],
12376
13548
  notes,
12377
13549
  problems: planned.conflicts.map(
12378
- (conflict) => `${path8.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`
13550
+ (conflict) => `${path9.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`
12379
13551
  )
12380
13552
  };
12381
13553
  }
@@ -12386,7 +13558,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
12386
13558
  changed: false,
12387
13559
  registeredEvents: [],
12388
13560
  missingEvents: [],
12389
- notes: [...notes, `${path8.basename(configPath)} does not exist; nothing to remove`],
13561
+ notes: [...notes, `${path9.basename(configPath)} does not exist; nothing to remove`],
12390
13562
  problems: []
12391
13563
  };
12392
13564
  }
@@ -12429,7 +13601,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
12429
13601
  missingEvents: [],
12430
13602
  notes,
12431
13603
  problems: [
12432
- `could not write ${path8.basename(configPath)} (${thrown instanceof Error ? thrown.name : typeof thrown})`
13604
+ `could not write ${path9.basename(configPath)} (${thrown instanceof Error ? thrown.name : typeof thrown})`
12433
13605
  ]
12434
13606
  };
12435
13607
  }
@@ -12456,7 +13628,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
12456
13628
  missingEvents: [],
12457
13629
  notes,
12458
13630
  problems: [
12459
- thrown instanceof Error ? `${path8.basename(configPath)}: ${thrown.message}` : `${path8.basename(configPath)}: the configuration file could not be locked`
13631
+ thrown instanceof Error ? `${path9.basename(configPath)}: ${thrown.message}` : `${path9.basename(configPath)}: the configuration file could not be locked`
12460
13632
  ]
12461
13633
  };
12462
13634
  }
@@ -12549,6 +13721,7 @@ export {
12549
13721
  CLAUDE_HOOK_EVENTS_MODELLED,
12550
13722
  CLAUDE_HOOK_EVENT_NAMES,
12551
13723
  CLAUDE_REGISTRABLE_HOOK_EVENTS,
13724
+ CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,
12552
13725
  CLAUDE_UNREGISTERED_HOOK_EVENTS,
12553
13726
  CODEX_ADAPTER_VERSION,
12554
13727
  CODEX_CAPABILITIES,
@@ -12570,7 +13743,12 @@ export {
12570
13743
  CURSOR_REGISTRABLE_HOOK_EVENTS,
12571
13744
  CURSOR_UNMODELLED_HOOK_EVENT_NAMES,
12572
13745
  CURSOR_UNREGISTERED_HOOK_EVENTS,
13746
+ DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES,
13747
+ DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS,
13748
+ DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES,
13749
+ DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS,
12573
13750
  DEFAULT_CONFIG,
13751
+ DEFAULT_DESTINATION_NAME,
12574
13752
  DEFAULT_DETECTION_POLICY,
12575
13753
  DEFAULT_DIAGNOSTICS_POLICY,
12576
13754
  DEFAULT_DOCUMENT_FORMAT,
@@ -12581,13 +13759,16 @@ export {
12581
13759
  DEFAULT_MANAGED_COMMAND_MARKER,
12582
13760
  DEFAULT_PRIVACY_LIMITS,
12583
13761
  DEFAULT_PRIVACY_POLICY,
13762
+ DEFAULT_PROVIDERS_POLICY,
12584
13763
  DEFAULT_SECRET_KEY_PATTERNS,
12585
13764
  DEFAULT_SECRET_VALUE_PATTERNS,
13765
+ DEFAULT_SPOOL_POLICY,
12586
13766
  DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS,
12587
13767
  DEFAULT_WORKTREE_CACHE_TTL_MILLIS,
12588
13768
  DELIVERY_COMPONENT_PATTERN,
12589
13769
  DELIVERY_GAP_REASON_PATTERN,
12590
13770
  DELIVERY_IDENTIFIER_SUMMARY,
13771
+ DESTINATION_NAME_PATTERN,
12591
13772
  DETECTION_CONFIDENCE_RANK,
12592
13773
  EMPTY_DELTA_USAGE,
12593
13774
  EMPTY_EXTENSIONS,
@@ -12600,6 +13781,7 @@ export {
12600
13781
  GEMINI_ADAPTER_VERSION,
12601
13782
  GEMINI_HOOK_EVENT_NAMES,
12602
13783
  GEMINI_PROVIDER_ID,
13784
+ HEADER_ENV_REFERENCE_PREFIX,
12603
13785
  LOG_LEVEL_RANK,
12604
13786
  LOG_MAPPING_VERSION,
12605
13787
  LOG_SIGNALS,
@@ -12610,6 +13792,8 @@ export {
12610
13792
  MAX_ATTRIBUTE_STRING_LENGTH,
12611
13793
  MAX_DELIVERY_COMPONENTS,
12612
13794
  MAX_DELIVERY_GAPS,
13795
+ MAX_DESTINATION_HEADERS,
13796
+ MAX_EXPORT_DESTINATIONS,
12613
13797
  MAX_EXTENSION_ENTRIES,
12614
13798
  MAX_IDENTIFIER_LENGTH,
12615
13799
  MAX_LOG_BODY_CHARACTERS,
@@ -12654,6 +13838,7 @@ export {
12654
13838
  addUsage,
12655
13839
  appliedDeliverySchema,
12656
13840
  asProviderId,
13841
+ attachClaudeTranscriptTurn,
12657
13842
  attributePrimitiveSchema,
12658
13843
  attributeValueSchema,
12659
13844
  attributesSchema,
@@ -12687,12 +13872,15 @@ export {
12687
13872
  createBoundedMemoryStateStore,
12688
13873
  createCallbackDeduplicator,
12689
13874
  createClaudeCodeAdapter,
13875
+ createClaudeTranscriptUsageEnricher,
12690
13876
  createCodexAdapter,
12691
13877
  createCursorAdapter,
12692
13878
  createDefaultProviderRegistry,
13879
+ createDestinationFanout,
12693
13880
  createDeterministicIdGenerator,
12694
13881
  createErrorInfo,
12695
13882
  createEventFactory,
13883
+ createExportDestinationSinks,
12696
13884
  createFileDurableLogSpool,
12697
13885
  createFileDurableSpool,
12698
13886
  createFilesystemStateStore,
@@ -12726,6 +13914,7 @@ export {
12726
13914
  deriveWorkspaceIdentity,
12727
13915
  describeAdapter,
12728
13916
  describeErrorCode,
13917
+ describeExportDestinations,
12729
13918
  describeLogsDeliverability,
12730
13919
  describeOtlpHeaderNames,
12731
13920
  describeProviderCatalog,
@@ -12737,7 +13926,9 @@ export {
12737
13926
  detectionPolicySchema,
12738
13927
  diagnosticsPolicySchema,
12739
13928
  durationMillisSchema,
13929
+ effectiveSpoolPolicy,
12740
13930
  emptyExtensions,
13931
+ endpointOrigin,
12741
13932
  epochMillisSchema,
12742
13933
  errorInfoFromThrown,
12743
13934
  errorPhaseSchema,
@@ -12745,6 +13936,10 @@ export {
12745
13936
  errorSeveritySchema,
12746
13937
  eventIdSchema,
12747
13938
  eventUsage,
13939
+ exportDestinationSchema,
13940
+ exportDestinationsSchema,
13941
+ exportSignalSchema,
13942
+ exporterPolicyForDestination,
12748
13943
  exporterPolicySchema,
12749
13944
  extensionKeyNamespace,
12750
13945
  extensionsSchema,
@@ -12755,6 +13950,7 @@ export {
12755
13950
  findRegistrationSupport,
12756
13951
  generationEndEventSchema,
12757
13952
  generationStartEventSchema,
13953
+ hasConfiguredDestinations,
12758
13954
  hostDeliveryIdentity,
12759
13955
  identityClaimFieldsSchema,
12760
13956
  identityClaimSchema,
@@ -12765,6 +13961,7 @@ export {
12765
13961
  isExperimentalProvider,
12766
13962
  isLockingStateStore,
12767
13963
  isOtelHookError,
13964
+ isPermanentExportFailure,
12768
13965
  isReservedExtensionNamespace,
12769
13966
  isReservedResourceAttributeKey,
12770
13967
  isSecretResourceAttributeKey,
@@ -12801,6 +13998,7 @@ export {
12801
13998
  parseEnvironmentConfig,
12802
13999
  parseGitDirFile,
12803
14000
  parseHeadBranch,
14001
+ parseHeaderValueReference,
12804
14002
  parseOtlpHeadersValue,
12805
14003
  parseResourceAttributesValue,
12806
14004
  planProviderRegistration,
@@ -12814,8 +14012,11 @@ export {
12814
14012
  providerHookResponseSchema,
12815
14013
  providerIdSchema,
12816
14014
  providerTotalAgreementSchema,
14015
+ providersPolicySchema,
12817
14016
  readAntigravityHookRegistrations,
12818
14017
  readClaudeHookRegistrations,
14018
+ readClaudeTranscriptRange,
14019
+ readClaudeTranscriptTurn,
12819
14020
  readCodexHookRegistrations,
12820
14021
  readCodexHooksFeatureFlag,
12821
14022
  readCursorHookRegistrations,
@@ -12824,6 +14025,7 @@ export {
12824
14025
  readGeminiHookRegistrations,
12825
14026
  readJsonDocument,
12826
14027
  readNestedHookRegistrations,
14028
+ readsClaudeTranscriptUsage,
12827
14029
  removeAntigravityHookRegistration,
12828
14030
  removeClaudeHookRegistration,
12829
14031
  removeCodexHookRegistration,
@@ -12833,7 +14035,9 @@ export {
12833
14035
  renderJsonDocument,
12834
14036
  resolveConfig,
12835
14037
  resolveDeliveryIdentity,
14038
+ resolveDestinationHeaders,
12836
14039
  resolveEventTargets,
14040
+ resolveExportDestinations,
12837
14041
  resolveInstallPath,
12838
14042
  resolveInvocationIdentity,
12839
14043
  resolveLogsEndpoint,
@@ -12853,6 +14057,8 @@ export {
12853
14057
  sourceProvenanceSchema,
12854
14058
  sourceTransportSchema,
12855
14059
  spanScopeRefOf,
14060
+ spoolPolicySchema,
14061
+ spoolQueueNamesFor,
12856
14062
  startOnlySpanAttributes,
12857
14063
  stateRecordSchema,
12858
14064
  stateValueSchema,