@osfactory/otel-hook 0.10.0 → 0.11.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 (43) hide show
  1. package/README.md +82 -3
  2. package/dist/{adapter-B9RwW6TO.d.ts → adapter-DiLknaTF.d.ts} +1 -1
  3. package/dist/cli.js +1131 -77
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +11 -4
  6. package/dist/config.js +100 -18
  7. package/dist/config.js.map +1 -1
  8. package/dist/{destinations-DWOkVxV1.d.ts → destinations-BIl3gGzx.d.ts} +12 -2
  9. package/dist/diagnostics.d.ts +1 -1
  10. package/dist/diagnostics.js.map +1 -1
  11. package/dist/{export-destinations-lORbe25J.d.ts → export-destinations-QWKGGEjk.d.ts} +130 -5
  12. package/dist/{filesystem-store-DX3dGIgu.d.ts → filesystem-store-D3SCNmbX.d.ts} +1 -1
  13. package/dist/{hook-BAxXoKsp.d.ts → hook-BOecWGSz.d.ts} +4 -4
  14. package/dist/index.d.ts +14 -14
  15. package/dist/index.js +1114 -90
  16. package/dist/index.js.map +1 -1
  17. package/dist/install.d.ts +3 -3
  18. package/dist/integration.d.ts +29 -11
  19. package/dist/integration.js +1117 -154
  20. package/dist/integration.js.map +1 -1
  21. package/dist/lifecycle.d.ts +54 -3
  22. package/dist/lifecycle.js +270 -4
  23. package/dist/lifecycle.js.map +1 -1
  24. package/dist/{memory-aJilVG4R.d.ts → memory-Cs51jyRk.d.ts} +1 -1
  25. package/dist/{semconv-Dw7gcQcg.d.ts → metric-model-DDnWxL9d.d.ts} +154 -2
  26. package/dist/{payload-D7gc0-WQ.d.ts → payload-ChtrEX6A.d.ts} +1 -1
  27. package/dist/{ports-plO5MKrY.d.ts → ports-CeqLq31i.d.ts} +24 -0
  28. package/dist/providers.d.ts +8 -8
  29. package/dist/{registry-C7XO4DzD.d.ts → registry-CcJNF3WY.d.ts} +2 -2
  30. package/dist/runtime.d.ts +7 -7
  31. package/dist/runtime.js +55 -9
  32. package/dist/runtime.js.map +1 -1
  33. package/dist/{schema-CHb3GU1r.d.ts → schema-DMnoU1V_.d.ts} +64 -1
  34. package/dist/state.d.ts +3 -3
  35. package/dist/state.js +23 -0
  36. package/dist/state.js.map +1 -1
  37. package/dist/telemetry.d.ts +5 -5
  38. package/dist/telemetry.js +860 -17
  39. package/dist/telemetry.js.map +1 -1
  40. package/dist/testing.d.ts +8 -8
  41. package/dist/testing.js +55 -9
  42. package/dist/testing.js.map +1 -1
  43. package/package.json +3 -1
package/dist/cli.js CHANGED
@@ -332,6 +332,8 @@ var VALUE_FLAGS = /* @__PURE__ */ new Set([
332
332
  "--installation-id",
333
333
  "--flush-timeout-ms",
334
334
  "--logs-endpoint",
335
+ "--metrics-endpoint",
336
+ "--metrics-temporality",
335
337
  "--max-input-bytes",
336
338
  "--scope",
337
339
  "--project-dir",
@@ -350,6 +352,9 @@ var BOOLEAN_FLAGS = /* @__PURE__ */ new Set([
350
352
  "--logs",
351
353
  "--no-logs",
352
354
  "--logs-content",
355
+ "--metrics",
356
+ "--no-metrics",
357
+ "--no-metrics-session-id",
353
358
  "--claude-transcript-usage",
354
359
  "--include-experimental",
355
360
  "--no-experimental",
@@ -515,6 +520,20 @@ var parsePolicy = (tokens, errors) => {
515
520
  if (tokens.booleans.has("--logs") && tokens.booleans.has("--no-logs")) {
516
521
  errors.push("flags --logs and --no-logs cannot both be given");
517
522
  }
523
+ const metricsEndpoint = single(tokens, "--metrics-endpoint", errors);
524
+ const metricsEnabled = tokens.booleans.has("--metrics") ? true : tokens.booleans.has("--no-metrics") ? false : void 0;
525
+ if (tokens.booleans.has("--metrics") && tokens.booleans.has("--no-metrics")) {
526
+ errors.push("flags --metrics and --no-metrics cannot both be given");
527
+ }
528
+ const metricsTemporalityRaw = single(tokens, "--metrics-temporality", errors);
529
+ let metricsTemporality;
530
+ if (metricsTemporalityRaw !== void 0) {
531
+ if (metricsTemporalityRaw === "cumulative" || metricsTemporalityRaw === "delta") {
532
+ metricsTemporality = metricsTemporalityRaw;
533
+ } else {
534
+ errors.push("flag --metrics-temporality must be cumulative or delta");
535
+ }
536
+ }
518
537
  return {
519
538
  ...configFile === void 0 ? {} : { configFile },
520
539
  ...endpoint === void 0 ? {} : { endpoint },
@@ -535,6 +554,10 @@ var parsePolicy = (tokens, errors) => {
535
554
  ...logsEnabled === void 0 ? {} : { logsEnabled },
536
555
  ...logsEndpoint === void 0 ? {} : { logsEndpoint },
537
556
  ...tokens.booleans.has("--logs-content") ? { logsIncludeContent: true } : {},
557
+ ...metricsEnabled === void 0 ? {} : { metricsEnabled },
558
+ ...metricsEndpoint === void 0 ? {} : { metricsEndpoint },
559
+ ...metricsTemporality === void 0 ? {} : { metricsTemporality },
560
+ ...tokens.booleans.has("--no-metrics-session-id") ? { metricsIncludeSessionId: false } : {},
538
561
  ...tokens.booleans.has("--claude-transcript-usage") ? { claudeTranscriptUsage: true } : {}
539
562
  };
540
563
  };
@@ -590,6 +613,11 @@ var RUN_FLAGS = /* @__PURE__ */ new Set([
590
613
  "--no-logs",
591
614
  "--logs-endpoint",
592
615
  "--logs-content",
616
+ "--metrics",
617
+ "--no-metrics",
618
+ "--metrics-endpoint",
619
+ "--metrics-temporality",
620
+ "--no-metrics-session-id",
593
621
  "--claude-transcript-usage",
594
622
  "--max-input-bytes",
595
623
  "--no-export",
@@ -620,6 +648,11 @@ var DOCTOR_FLAGS = /* @__PURE__ */ new Set([
620
648
  "--no-logs",
621
649
  "--logs-endpoint",
622
650
  "--logs-content",
651
+ "--metrics",
652
+ "--no-metrics",
653
+ "--metrics-endpoint",
654
+ "--metrics-temporality",
655
+ "--no-metrics-session-id",
623
656
  "--claude-transcript-usage",
624
657
  "--include-experimental",
625
658
  "--no-experimental"
@@ -865,6 +898,14 @@ Exporter and runtime policy (never identity):
865
898
  --logs-content permit disclosed content text in a log body. Needs
866
899
  --content-mode too: this decides whether the logs
867
900
  pipeline may carry what that one discloses
901
+ --metrics also export hook-derived OTLP metrics (off by
902
+ default): token usage, generation duration,
903
+ sessions, tool calls, provider-reported cost
904
+ --metrics-endpoint <url> OTLP HTTP/protobuf metrics endpoint; derived from
905
+ --endpoint when omitted (/v1/traces -> /v1/metrics)
906
+ --metrics-temporality <t> cumulative (default; running totals kept in the
907
+ state dir) | delta
908
+ --no-metrics-session-id leave session.id off metric points (fewer series)
868
909
  --claude-transcript-usage Claude Code only: at Stop, read the transcript the
869
910
  payload names (bounded) for the turn's model and
870
911
  summed token usage. Off by default; also
@@ -1170,10 +1211,17 @@ var errorInfoFromThrown = (thrown, input) => {
1170
1211
  var OTLP_ENDPOINT_VARIABLES = Object.freeze({
1171
1212
  generic: "OTEL_EXPORTER_OTLP_ENDPOINT",
1172
1213
  traces: "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
1173
- logs: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT"
1214
+ logs: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
1215
+ metrics: "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"
1174
1216
  });
1175
1217
  var OTLP_TRACES_PATH = "/v1/traces";
1176
1218
  var OTLP_LOGS_PATH = "/v1/logs";
1219
+ var OTLP_METRICS_PATH = "/v1/metrics";
1220
+ var SIGNAL_PATHS = Object.freeze({
1221
+ traces: OTLP_TRACES_PATH,
1222
+ logs: OTLP_LOGS_PATH,
1223
+ metrics: OTLP_METRICS_PATH
1224
+ });
1177
1225
  var withoutTrailingSlashes = (value) => {
1178
1226
  let end = value.length;
1179
1227
  while (end > 0 && value.charCodeAt(end - 1) === 47) {
@@ -1184,9 +1232,20 @@ var withoutTrailingSlashes = (value) => {
1184
1232
  var otlpSignalEndpointFromBase = (base, signal) => {
1185
1233
  const trimmed = withoutTrailingSlashes(base);
1186
1234
  if (trimmed.endsWith(OTLP_TRACES_PATH)) {
1187
- return signal === "traces" ? trimmed : `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${OTLP_LOGS_PATH}`;
1235
+ return signal === "traces" ? trimmed : `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${SIGNAL_PATHS[signal]}`;
1188
1236
  }
1189
- return `${trimmed}${signal === "traces" ? OTLP_TRACES_PATH : OTLP_LOGS_PATH}`;
1237
+ return `${trimmed}${SIGNAL_PATHS[signal]}`;
1238
+ };
1239
+ var siblingSignalEndpoint = (tracesEndpoint, signal) => {
1240
+ const trimmed = withoutTrailingSlashes(tracesEndpoint);
1241
+ const target = SIGNAL_PATHS[signal];
1242
+ if (trimmed.endsWith(target)) {
1243
+ return trimmed;
1244
+ }
1245
+ if (trimmed.endsWith(OTLP_TRACES_PATH)) {
1246
+ return `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${target}`;
1247
+ }
1248
+ return `${trimmed}${target}`;
1190
1249
  };
1191
1250
 
1192
1251
  // src/config/header-value.ts
@@ -1330,6 +1389,12 @@ var ENVIRONMENT_VARIABLES = Object.freeze({
1330
1389
  /** Standard per-signal endpoint; the weaker source of the two. */
1331
1390
  otlpLogsEndpoint: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
1332
1391
  logsIncludeContent: "OTEL_HOOK_LOGS_INCLUDE_CONTENT",
1392
+ metricsEnabled: "OTEL_HOOK_METRICS_ENABLED",
1393
+ metricsEndpoint: "OTEL_HOOK_METRICS_ENDPOINT",
1394
+ /** Standard per-signal endpoint; the weaker source of the two. */
1395
+ otlpMetricsEndpoint: "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT",
1396
+ /** Standard: `cumulative`, `delta`, or `lowmemory` (read as `delta` here). */
1397
+ otlpMetricsTemporality: "OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE",
1333
1398
  serviceName: "OTEL_HOOK_SERVICE_NAME",
1334
1399
  otlpServiceName: "OTEL_SERVICE_NAME",
1335
1400
  serviceNamespace: "OTEL_HOOK_SERVICE_NAMESPACE",
@@ -1492,6 +1557,22 @@ var parseEnvironmentConfig = (env) => {
1492
1557
  ...logsEndpoint === void 0 ? {} : { endpoint: logsEndpoint },
1493
1558
  ...logsIncludeContent === void 0 ? {} : { includeContent: logsIncludeContent }
1494
1559
  };
1560
+ const metricsEnabled = readBoolean(ENVIRONMENT_VARIABLES.metricsEnabled);
1561
+ const metricsEndpoint = readString(ENVIRONMENT_VARIABLES.metricsEndpoint) ?? readString(ENVIRONMENT_VARIABLES.otlpMetricsEndpoint) ?? (hookEndpoint === void 0 && otlpTracesEndpoint !== void 0 && otlpBaseEndpoint !== void 0 ? otlpSignalEndpointFromBase(otlpBaseEndpoint, "metrics") : void 0);
1562
+ const temporalityRaw = readString(ENVIRONMENT_VARIABLES.otlpMetricsTemporality)?.toLowerCase();
1563
+ let metricsTemporality;
1564
+ if (temporalityRaw === "cumulative") {
1565
+ metricsTemporality = "cumulative";
1566
+ } else if (temporalityRaw === "delta" || temporalityRaw === "lowmemory") {
1567
+ metricsTemporality = "delta";
1568
+ } else if (temporalityRaw !== void 0) {
1569
+ warn(ENVIRONMENT_VARIABLES.otlpMetricsTemporality, "expected cumulative, delta, or lowmemory");
1570
+ }
1571
+ const metrics = {
1572
+ ...metricsEnabled === void 0 ? {} : { enabled: metricsEnabled },
1573
+ ...metricsEndpoint === void 0 ? {} : { endpoint: metricsEndpoint },
1574
+ ...metricsTemporality === void 0 ? {} : { temporality: metricsTemporality }
1575
+ };
1495
1576
  const otlpHeaders = resolveOtlpHeaders(env);
1496
1577
  for (const { variable, detail } of otlpHeaders.warnings) {
1497
1578
  warn(variable, detail);
@@ -1506,7 +1587,8 @@ var parseEnvironmentConfig = (env) => {
1506
1587
  ...serviceName === void 0 ? {} : { serviceName },
1507
1588
  ...serviceNamespace === void 0 ? {} : { serviceNamespace },
1508
1589
  ...Object.keys(resourceAttributes).length === 0 ? {} : { resourceAttributes },
1509
- ...Object.keys(logs).length === 0 ? {} : { logs }
1590
+ ...Object.keys(logs).length === 0 ? {} : { logs },
1591
+ ...Object.keys(metrics).length === 0 ? {} : { metrics }
1510
1592
  };
1511
1593
  const limits = {
1512
1594
  ...maxStringLength === void 0 ? {} : { maxStringLength },
@@ -1547,7 +1629,7 @@ var HEADER_ENV_REFERENCE_PREFIX = "env:";
1547
1629
  var HEADER_NAME_PATTERN2 = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
1548
1630
  var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
1549
1631
  var MAX_HEADER_VALUE_LENGTH = 8192;
1550
- var exportSignalSchema = z6.enum(["traces", "logs"]);
1632
+ var exportSignalSchema = z6.enum(["traces", "logs", "metrics"]);
1551
1633
  var headerValueSchema = z6.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
1552
1634
  (value) => !isUnsafeHeaderValue(value),
1553
1635
  "header values may not contain line breaks, control characters, or characters beyond Latin-1"
@@ -1570,6 +1652,8 @@ var exportDestinationSchema = z6.strictObject({
1570
1652
  tracesEndpoint: endpointSchema.optional(),
1571
1653
  /** Per-signal override of the derived logs URL. */
1572
1654
  logsEndpoint: endpointSchema.optional(),
1655
+ /** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */
1656
+ metricsEndpoint: endpointSchema.optional(),
1573
1657
  /** Defaults to `exporter.protocol`. */
1574
1658
  protocol: z6.enum(["http/protobuf", "http/json", "none"]).optional(),
1575
1659
  /**
@@ -1582,15 +1666,17 @@ var exportDestinationSchema = z6.strictObject({
1582
1666
  `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
1583
1667
  ).optional(),
1584
1668
  /**
1585
- * Which signals this destination receives. Default: both. The logs signal is
1586
- * still governed by `exporter.logs.enabled`, which stays the one opt-in for a
1587
- * second stream leaving the host.
1669
+ * Which signals this destination receives. Default: traces and logs. The logs
1670
+ * signal is still governed by `exporter.logs.enabled`, which stays the one
1671
+ * opt-in for content-bearing records leaving the host. `metrics` is never on by
1672
+ * default: a destination receives hook-derived metrics only when it lists them.
1588
1673
  */
1589
- signals: z6.array(exportSignalSchema).min(1).max(2).readonly().optional()
1674
+ signals: z6.array(exportSignalSchema).min(1).max(3).readonly().optional()
1590
1675
  }).refine(
1591
- (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0,
1592
- "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint"
1676
+ (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
1677
+ "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
1593
1678
  );
1679
+ var DEFAULT_DESTINATION_SIGNALS = Object.freeze(["traces", "logs"]);
1594
1680
  var exportDestinationsSchema = z6.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
1595
1681
  const seen = /* @__PURE__ */ new Set();
1596
1682
  destinations.forEach((destination, index) => {
@@ -1635,7 +1721,8 @@ var legacyDestination = (exporter) => ({
1635
1721
  protocol: exporter.protocol,
1636
1722
  ...exporter.endpoint === void 0 ? {} : { endpoint: exporter.endpoint },
1637
1723
  ...exporter.logs.endpoint === void 0 ? {} : { logsEndpoint: exporter.logs.endpoint },
1638
- signals: { traces: true, logs: exporter.logs.enabled },
1724
+ ...exporter.metrics?.endpoint === void 0 ? {} : { metricsEndpoint: exporter.metrics.endpoint },
1725
+ signals: { traces: true, logs: exporter.logs.enabled, metrics: exporter.metrics?.enabled === true },
1639
1726
  headers: {}
1640
1727
  });
1641
1728
  var hasConfiguredDestinations = (exporter) => exporter.destinations !== void 0 && exporter.destinations.length > 0;
@@ -1644,14 +1731,14 @@ var resolveExportDestinations = (exporter) => {
1644
1731
  return [legacyDestination(exporter)];
1645
1732
  }
1646
1733
  const resolved = [];
1647
- if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0) {
1734
+ if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0 || exporter.metrics?.endpoint !== void 0) {
1648
1735
  resolved.push(legacyDestination(exporter));
1649
1736
  }
1650
1737
  for (const destination of exporter.destinations ?? []) {
1651
1738
  if (destination.enabled === false) {
1652
1739
  continue;
1653
1740
  }
1654
- const signals = destination.signals ?? exportSignalSchema.options;
1741
+ const signals = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;
1655
1742
  resolved.push({
1656
1743
  name: destination.name,
1657
1744
  source: "destinations",
@@ -1659,9 +1746,11 @@ var resolveExportDestinations = (exporter) => {
1659
1746
  ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
1660
1747
  ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
1661
1748
  ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
1749
+ ...destination.metricsEndpoint === void 0 ? {} : { metricsEndpoint: destination.metricsEndpoint },
1662
1750
  signals: {
1663
1751
  traces: signals.includes("traces"),
1664
- logs: exporter.logs.enabled && signals.includes("logs")
1752
+ logs: exporter.logs.enabled && signals.includes("logs"),
1753
+ metrics: signals.includes("metrics")
1665
1754
  },
1666
1755
  headers: { ...destination.headers ?? {} }
1667
1756
  });
@@ -1703,6 +1792,9 @@ var describeExportDestinations = (exporter) => {
1703
1792
  const logsOrigin = endpointOrigin(
1704
1793
  destination.logsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint
1705
1794
  );
1795
+ const metricsOrigin = endpointOrigin(
1796
+ destination.metricsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint
1797
+ );
1706
1798
  const variables = Object.values(destination.headers).map(parseHeaderValueReference).flatMap((reference) => reference.kind === "env" ? [reference.variable] : []);
1707
1799
  return {
1708
1800
  name: destination.name,
@@ -1711,6 +1803,7 @@ var describeExportDestinations = (exporter) => {
1711
1803
  signals: exportSignalSchema.options.filter((signal) => destination.signals[signal]),
1712
1804
  ...tracesOrigin === void 0 || !destination.signals.traces ? {} : { tracesEndpointOrigin: tracesOrigin },
1713
1805
  ...logsOrigin === void 0 || !destination.signals.logs ? {} : { logsEndpointOrigin: logsOrigin },
1806
+ ...metricsOrigin === void 0 || !destination.signals.metrics ? {} : { metricsEndpointOrigin: metricsOrigin },
1714
1807
  headerNames: destination.source === "exporter" ? [...exporter.headerNames].sort() : Object.keys(destination.headers).sort(),
1715
1808
  headerVariables: [...new Set(variables)].sort()
1716
1809
  };
@@ -1725,7 +1818,7 @@ var describeExportDestinations = (exporter) => {
1725
1818
  source: "destinations",
1726
1819
  protocol: destination.protocol ?? exporter.protocol,
1727
1820
  ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
1728
- signals: { traces: false, logs: false },
1821
+ signals: { traces: false, logs: false, metrics: false },
1729
1822
  headers: { ...destination.headers ?? {} }
1730
1823
  },
1731
1824
  false
@@ -1753,6 +1846,18 @@ var DEFAULT_LOGS_POLICY = Object.freeze({
1753
1846
  includeContent: false,
1754
1847
  maxBatchSize: 128
1755
1848
  });
1849
+ var metricsPolicySchema = z7.strictObject({
1850
+ enabled: z7.boolean(),
1851
+ /** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */
1852
+ endpoint: z7.string().url().max(2048).optional(),
1853
+ temporality: z7.enum(["cumulative", "delta"]),
1854
+ includeSessionId: z7.boolean()
1855
+ });
1856
+ var DEFAULT_METRICS_POLICY = Object.freeze({
1857
+ enabled: false,
1858
+ temporality: "cumulative",
1859
+ includeSessionId: true
1860
+ });
1756
1861
  var exporterPolicySchema = z7.strictObject({
1757
1862
  enabled: z7.boolean(),
1758
1863
  protocol: z7.enum(["http/protobuf", "http/json", "none"]),
@@ -1783,6 +1888,11 @@ var exporterPolicySchema = z7.strictObject({
1783
1888
  * a second top-level section would invite two of each to drift apart.
1784
1889
  */
1785
1890
  logs: logsPolicySchema,
1891
+ /**
1892
+ * Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before
1893
+ * metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.
1894
+ */
1895
+ metrics: metricsPolicySchema.optional(),
1786
1896
  /**
1787
1897
  * Additional OTLP destinations, each sent every batch in parallel.
1788
1898
  *
@@ -1831,8 +1941,9 @@ var otelHookConfigPatchSchema = z7.strictObject({
1831
1941
  // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
1832
1942
  // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
1833
1943
  // without also restating the endpoint and the batch size.
1834
- exporter: exporterPolicySchema.omit({ logs: true, spool: true }).partial().extend({
1944
+ exporter: exporterPolicySchema.omit({ logs: true, metrics: true, spool: true }).partial().extend({
1835
1945
  logs: logsPolicySchema.partial().optional(),
1946
+ metrics: metricsPolicySchema.partial().optional(),
1836
1947
  spool: spoolPolicySchema.partial().optional()
1837
1948
  }).optional(),
1838
1949
  privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
@@ -1852,7 +1963,8 @@ var DEFAULT_EXPORTER_POLICY = Object.freeze({
1852
1963
  maxRetryAttempts: 2,
1853
1964
  serviceName: "coding-agent",
1854
1965
  resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
1855
- logs: DEFAULT_LOGS_POLICY
1966
+ logs: DEFAULT_LOGS_POLICY,
1967
+ metrics: DEFAULT_METRICS_POLICY
1856
1968
  });
1857
1969
  var DEFAULT_DETECTION_POLICY = Object.freeze({
1858
1970
  minimumConfidence: "strong",
@@ -1874,6 +1986,10 @@ var DEFAULT_CONFIG = Object.freeze({
1874
1986
  providers: DEFAULT_PROVIDERS_POLICY
1875
1987
  });
1876
1988
  var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
1989
+ var effectiveMetricsPolicy = (exporter) => ({
1990
+ ...DEFAULT_METRICS_POLICY,
1991
+ ...exporter.metrics ?? {}
1992
+ });
1877
1993
 
1878
1994
  // src/config/resolve.ts
1879
1995
  var CONFIG_SOURCE_PRECEDENCE = ["defaults", "file", "environment", "inline-override"];
@@ -1984,6 +2100,11 @@ var resolveConfig = (layers = []) => {
1984
2100
  "exporter.logs.enabled is true but neither a logs endpoint nor a trace endpoint to derive one from is configured"
1985
2101
  );
1986
2102
  }
2103
+ if (!withDestinations && parsed.data.exporter.metrics?.enabled === true && parsed.data.exporter.metrics.endpoint === void 0 && parsed.data.exporter.endpoint === void 0) {
2104
+ notes.push(
2105
+ "exporter.metrics.enabled is true but neither a metrics endpoint nor a trace endpoint to derive one from is configured"
2106
+ );
2107
+ }
1987
2108
  if (parsed.data.exporter.logs.includeContent && parsed.data.privacy.contentMode === "omit") {
1988
2109
  notes.push(
1989
2110
  "exporter.logs.includeContent is true but privacy.contentMode is omit, so no content is disclosed to describe"
@@ -2015,6 +2136,9 @@ var describeDestinationAttributes = (config) => {
2015
2136
  if (destination.logsEndpointOrigin !== void 0) {
2016
2137
  attributes[`${prefix}.logs_endpoint_origin`] = destination.logsEndpointOrigin;
2017
2138
  }
2139
+ if (destination.metricsEndpointOrigin !== void 0) {
2140
+ attributes[`${prefix}.metrics_endpoint_origin`] = destination.metricsEndpointOrigin;
2141
+ }
2018
2142
  attributes[`${prefix}.header_names`] = [...destination.headerNames];
2019
2143
  attributes[`${prefix}.header_variables`] = [...destination.headerVariables];
2020
2144
  }
@@ -2033,6 +2157,8 @@ var describeResolvedConfig = (config) => {
2033
2157
  };
2034
2158
  const endpointOrigin2 = originOf(config.exporter.endpoint);
2035
2159
  const logsEndpointOrigin = originOf(config.exporter.logs.endpoint);
2160
+ const metrics = effectiveMetricsPolicy(config.exporter);
2161
+ const metricsEndpointOrigin = originOf(metrics.endpoint);
2036
2162
  return {
2037
2163
  "exporter.enabled": config.exporter.enabled,
2038
2164
  "exporter.protocol": config.exporter.protocol,
@@ -2041,6 +2167,10 @@ var describeResolvedConfig = (config) => {
2041
2167
  "exporter.logs_include_content": config.exporter.logs.includeContent,
2042
2168
  "exporter.logs_max_batch_size": config.exporter.logs.maxBatchSize,
2043
2169
  ...logsEndpointOrigin === void 0 ? {} : { "exporter.logs_endpoint_origin": logsEndpointOrigin },
2170
+ "exporter.metrics_enabled": metrics.enabled,
2171
+ "exporter.metrics_temporality": metrics.temporality,
2172
+ "exporter.metrics_include_session_id": metrics.includeSessionId,
2173
+ ...metricsEndpointOrigin === void 0 ? {} : { "exporter.metrics_endpoint_origin": metricsEndpointOrigin },
2044
2174
  "exporter.header_names": [...config.exporter.headerNames],
2045
2175
  // Names only. A resource attribute *name* is already on the wire in every
2046
2176
  // exported resource, so disclosing it here adds nothing; a *value* may hold
@@ -2809,6 +2939,29 @@ var stateValueSchema = z16.discriminatedUnion("kind", [
2809
2939
  * (Claude Code's transcript), so the next read starts where the last ended.
2810
2940
  * `source` is an opaque digest of what was read, never a path.
2811
2941
  */
2942
+ /**
2943
+ * Running state of one metric series (issue #69), so a cumulative data point
2944
+ * exported by a later hook process continues the same total. Holds numbers and
2945
+ * a series digest only; the series' attributes are re-supplied by the caller
2946
+ * and never read back from disk.
2947
+ */
2948
+ z16.strictObject({
2949
+ kind: z16.literal("metric-series"),
2950
+ /** Start of the cumulative interval. */
2951
+ startTimeMillis: epochMillisSchema,
2952
+ /** Counters: the running total. */
2953
+ value: z16.number().finite().min(0).optional(),
2954
+ /** Histograms: the running aggregation. */
2955
+ histogram: z16.strictObject({
2956
+ count: z16.number().int().min(0),
2957
+ sum: z16.number().finite().min(0),
2958
+ min: z16.number().finite(),
2959
+ max: z16.number().finite(),
2960
+ bucketCounts: z16.array(z16.number().int().min(0)).max(64)
2961
+ }).optional(),
2962
+ /** Opaque digest of the last delivery folded in; makes a replay a no-op. */
2963
+ appliedDelivery: z16.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional()
2964
+ }),
2812
2965
  z16.strictObject({
2813
2966
  kind: z16.literal("read-cursor"),
2814
2967
  source: z16.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
@@ -2908,6 +3061,12 @@ var policyFlagsToPatch = (policy) => {
2908
3061
  ...policy.logsEndpoint === void 0 ? {} : { endpoint: policy.logsEndpoint },
2909
3062
  ...policy.logsIncludeContent === void 0 ? {} : { includeContent: policy.logsIncludeContent }
2910
3063
  };
3064
+ const metrics = {
3065
+ ...policy.metricsEnabled === void 0 ? {} : { enabled: policy.metricsEnabled },
3066
+ ...policy.metricsEndpoint === void 0 ? {} : { endpoint: policy.metricsEndpoint },
3067
+ ...policy.metricsTemporality === void 0 ? {} : { temporality: policy.metricsTemporality },
3068
+ ...policy.metricsIncludeSessionId === void 0 ? {} : { includeSessionId: policy.metricsIncludeSessionId }
3069
+ };
2911
3070
  const exporter = {
2912
3071
  ...policy.exportDisabled === true ? { enabled: false } : {},
2913
3072
  ...policy.endpoint === void 0 ? {} : { endpoint: policy.endpoint },
@@ -2923,7 +3082,8 @@ var policyFlagsToPatch = (policy) => {
2923
3082
  // value they are exported on every span by design, so there is nothing to
2924
3083
  // keep out of the snapshot. The snapshot still reports names only.
2925
3084
  ...Object.keys(policy.resourceAttributes).length === 0 ? {} : { resourceAttributes: policy.resourceAttributes },
2926
- ...Object.keys(logs).length === 0 ? {} : { logs }
3085
+ ...Object.keys(logs).length === 0 ? {} : { logs },
3086
+ ...Object.keys(metrics).length === 0 ? {} : { metrics }
2927
3087
  };
2928
3088
  const privacy = policy.contentMode === void 0 ? {} : { contentMode: policy.contentMode };
2929
3089
  const diagnostics = policy.logLevel === void 0 ? {} : { logLevel: policy.logLevel };
@@ -8470,7 +8630,7 @@ import {
8470
8630
  } from "@opentelemetry/semantic-conventions/incubating";
8471
8631
 
8472
8632
  // src/version.ts
8473
- var VERSION = "0.10.0";
8633
+ var VERSION = "0.11.0";
8474
8634
 
8475
8635
  // src/telemetry/semconv.ts
8476
8636
  var SCOPE_NAME = "@osfactory/otel-hook";
@@ -9849,6 +10009,620 @@ var createOtlpTraceSink = (options) => {
9849
10009
  };
9850
10010
  };
9851
10011
 
10012
+ // src/telemetry/metric-model.ts
10013
+ var TOKEN_USAGE_BUCKETS = Object.freeze([
10014
+ 1,
10015
+ 4,
10016
+ 16,
10017
+ 64,
10018
+ 256,
10019
+ 1024,
10020
+ 4096,
10021
+ 16384,
10022
+ 65536,
10023
+ 262144,
10024
+ 1048576,
10025
+ 4194304,
10026
+ 16777216,
10027
+ 67108864
10028
+ ]);
10029
+ var OPERATION_DURATION_BUCKETS = Object.freeze([
10030
+ 0.01,
10031
+ 0.02,
10032
+ 0.04,
10033
+ 0.08,
10034
+ 0.16,
10035
+ 0.32,
10036
+ 0.64,
10037
+ 1.28,
10038
+ 2.56,
10039
+ 5.12,
10040
+ 10.24,
10041
+ 20.48,
10042
+ 40.96,
10043
+ 81.92
10044
+ ]);
10045
+ var METRIC_TOKEN_USAGE = "gen_ai.client.token.usage";
10046
+ var METRIC_OPERATION_DURATION = "gen_ai.client.operation.duration";
10047
+ var METRIC_SESSIONS = "otelhook.sessions";
10048
+ var METRIC_TOOL_CALLS = "otelhook.tool.calls";
10049
+ var METRIC_COST_USAGE = "otelhook.cost.usage";
10050
+ var METRIC_INSTRUMENTS = Object.freeze({
10051
+ [METRIC_TOKEN_USAGE]: {
10052
+ name: METRIC_TOKEN_USAGE,
10053
+ kind: "histogram",
10054
+ unit: "{token}",
10055
+ description: "Tokens used per generation, by token type (hook-derived)",
10056
+ valueType: "int",
10057
+ boundaries: TOKEN_USAGE_BUCKETS
10058
+ },
10059
+ [METRIC_OPERATION_DURATION]: {
10060
+ name: METRIC_OPERATION_DURATION,
10061
+ kind: "histogram",
10062
+ unit: "s",
10063
+ description: "Generation duration, from its start hook to its end hook (hook-derived)",
10064
+ valueType: "double",
10065
+ boundaries: OPERATION_DURATION_BUCKETS
10066
+ },
10067
+ [METRIC_SESSIONS]: {
10068
+ name: METRIC_SESSIONS,
10069
+ kind: "counter",
10070
+ unit: "{session}",
10071
+ description: "Agent sessions started",
10072
+ valueType: "int"
10073
+ },
10074
+ [METRIC_TOOL_CALLS]: {
10075
+ name: METRIC_TOOL_CALLS,
10076
+ kind: "counter",
10077
+ unit: "{call}",
10078
+ description: "Completed tool calls, by tool name and outcome",
10079
+ valueType: "int"
10080
+ },
10081
+ [METRIC_COST_USAGE]: {
10082
+ name: METRIC_COST_USAGE,
10083
+ kind: "counter",
10084
+ unit: "USD",
10085
+ description: "Cost reported by the provider; never estimated",
10086
+ valueType: "double"
10087
+ }
10088
+ });
10089
+ var isMetricInstrumentName = (value) => typeof value === "string" && Object.hasOwn(METRIC_INSTRUMENTS, value);
10090
+ var ATTR_GEN_AI_TOKEN_TYPE = "gen_ai.token.type";
10091
+ var ATTR_GEN_AI_PROVIDER_NAME = "gen_ai.provider.name";
10092
+ var ATTR_GEN_AI_OPERATION_NAME3 = "gen_ai.operation.name";
10093
+ var ATTR_GEN_AI_REQUEST_MODEL3 = "gen_ai.request.model";
10094
+ var ATTR_GEN_AI_RESPONSE_MODEL3 = "gen_ai.response.model";
10095
+ var ATTR_GEN_AI_TOOL_NAME3 = "gen_ai.tool.name";
10096
+ var ATTR_ERROR_TYPE3 = "error.type";
10097
+ var ATTR_SESSION_ID2 = "session.id";
10098
+ var ATTR_OTELHOOK_PROVIDER_ID2 = "otelhook.provider.id";
10099
+ var ATTR_OTELHOOK_OUTCOME3 = "otelhook.outcome";
10100
+ var ATTR_OTELHOOK_SESSION_KIND2 = "otelhook.session.kind";
10101
+ var commonAttributes = (event3, resource, includeSessionId) => ({
10102
+ [ATTR_OTELHOOK_PROVIDER_ID2]: event3.provenance.providerId,
10103
+ ...includeSessionId ? { [ATTR_SESSION_ID2]: resolveExportedSessionId(event3.sessionId, resource).sessionId } : {}
10104
+ });
10105
+ var generationAttributes = (end, requestModel) => ({
10106
+ [ATTR_GEN_AI_OPERATION_NAME3]: "chat",
10107
+ ...end.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_PROVIDER_NAME]: end.model.vendor },
10108
+ [ATTR_GEN_AI_REQUEST_MODEL3]: requestModel ?? end.model.modelId,
10109
+ [ATTR_GEN_AI_RESPONSE_MODEL3]: end.model.modelId
10110
+ });
10111
+ var TOKEN_FIELDS = [
10112
+ ["input", (usage) => usage.inputTokens],
10113
+ ["output", (usage) => usage.outputTokens],
10114
+ ["cache_read", (usage) => usage.cachedInputTokens],
10115
+ ["cache_creation", (usage) => usage.cacheCreationInputTokens]
10116
+ ];
10117
+ var isFailedOutcome = (outcome) => outcome !== "ok" && outcome !== "unknown" && outcome !== "cancelled";
10118
+ var deriveMetricObservations = (input) => {
10119
+ const includeSessionId = input.includeSessionId ?? true;
10120
+ const observations = [];
10121
+ const byId = /* @__PURE__ */ new Map();
10122
+ const startsInBatch = /* @__PURE__ */ new Map();
10123
+ for (const event3 of input.events) {
10124
+ byId.set(event3.eventId, event3);
10125
+ if (event3.type === "generation.start") {
10126
+ startsInBatch.set(event3.generationId, {
10127
+ startMillis: event3.occurredAt,
10128
+ requestModel: event3.model.modelId
10129
+ });
10130
+ }
10131
+ }
10132
+ const requestModelOf = (generationId) => startsInBatch.get(generationId)?.requestModel ?? input.generationStarts?.(generationId)?.requestModel;
10133
+ let lastPromptInBatch;
10134
+ for (const event3 of input.events) {
10135
+ if (event3.type === "prompt.submitted") {
10136
+ lastPromptInBatch ??= /* @__PURE__ */ new Map();
10137
+ lastPromptInBatch.set(event3.sessionId, Math.max(lastPromptInBatch.get(event3.sessionId) ?? 0, event3.occurredAt));
10138
+ }
10139
+ }
10140
+ const measuredDurationOf = (end) => {
10141
+ if (end.durationMillis !== void 0) {
10142
+ return end.durationMillis;
10143
+ }
10144
+ const recovered = startsInBatch.has(end.generationId) ? void 0 : input.generationStarts?.(end.generationId);
10145
+ if (recovered !== void 0) {
10146
+ return end.occurredAt - recovered.startMillis;
10147
+ }
10148
+ const turn = lastPromptInBatch?.get(end.sessionId) ?? input.turnStart?.(end.sessionId);
10149
+ return turn === void 0 || turn > end.occurredAt ? void 0 : end.occurredAt - turn;
10150
+ };
10151
+ const push = (event3, instrument, value, attributes) => {
10152
+ if (!Number.isFinite(value) || value < 0) {
10153
+ return;
10154
+ }
10155
+ observations.push({
10156
+ instrument,
10157
+ value,
10158
+ attributes: { ...commonAttributes(event3, input.resource, includeSessionId), ...attributes },
10159
+ timeMillis: event3.occurredAt,
10160
+ sessionId: event3.sessionId
10161
+ });
10162
+ };
10163
+ for (const event3 of input.events) {
10164
+ switch (event3.type) {
10165
+ case "session.start":
10166
+ push(event3, METRIC_SESSIONS, 1, { [ATTR_OTELHOOK_SESSION_KIND2]: event3.sessionKind });
10167
+ break;
10168
+ case "tool.end":
10169
+ push(event3, METRIC_TOOL_CALLS, 1, {
10170
+ [ATTR_GEN_AI_TOOL_NAME3]: event3.toolName,
10171
+ [ATTR_OTELHOOK_OUTCOME3]: event3.outcome
10172
+ });
10173
+ break;
10174
+ case "generation.end": {
10175
+ const attributes = generationAttributes(event3, requestModelOf(event3.generationId));
10176
+ const durationMillis = measuredDurationOf(event3);
10177
+ if (durationMillis !== void 0 && durationMillis >= 0) {
10178
+ push(event3, METRIC_OPERATION_DURATION, durationMillis / 1e3, {
10179
+ ...attributes,
10180
+ ...isFailedOutcome(event3.outcome) ? { [ATTR_ERROR_TYPE3]: event3.outcome } : {}
10181
+ });
10182
+ }
10183
+ if (event3.cost !== void 0 && event3.cost.source === "provider-reported" && event3.cost.currency === "USD") {
10184
+ push(event3, METRIC_COST_USAGE, event3.cost.amount, attributes);
10185
+ }
10186
+ break;
10187
+ }
10188
+ default:
10189
+ break;
10190
+ }
10191
+ }
10192
+ for (const observation of input.usage) {
10193
+ if (observation.scope !== "generation") {
10194
+ continue;
10195
+ }
10196
+ const event3 = byId.get(observation.eventId);
10197
+ if (event3?.type !== "generation.end") {
10198
+ continue;
10199
+ }
10200
+ const attributes = generationAttributes(event3, requestModelOf(event3.generationId));
10201
+ for (const [tokenType, read] of TOKEN_FIELDS) {
10202
+ const value = read(observation.delta);
10203
+ if (value === 0 && (tokenType === "cache_read" || tokenType === "cache_creation")) {
10204
+ continue;
10205
+ }
10206
+ push(event3, METRIC_TOKEN_USAGE, value, { ...attributes, [ATTR_GEN_AI_TOKEN_TYPE]: tokenType });
10207
+ }
10208
+ }
10209
+ return observations;
10210
+ };
10211
+ var emptyHistogram = (boundaries) => ({
10212
+ count: 0,
10213
+ sum: 0,
10214
+ min: Number.POSITIVE_INFINITY,
10215
+ max: Number.NEGATIVE_INFINITY,
10216
+ bucketCounts: new Array(boundaries.length + 1).fill(0)
10217
+ });
10218
+ var bucketIndex = (boundaries, value) => {
10219
+ for (let index = 0; index < boundaries.length; index += 1) {
10220
+ const bound = boundaries[index];
10221
+ if (bound !== void 0 && value <= bound) {
10222
+ return index;
10223
+ }
10224
+ }
10225
+ return boundaries.length;
10226
+ };
10227
+ var recordIntoHistogram = (state, boundaries, value) => {
10228
+ const bucketCounts = [...state.bucketCounts];
10229
+ const index = bucketIndex(boundaries, value);
10230
+ bucketCounts[index] = (bucketCounts[index] ?? 0) + 1;
10231
+ return {
10232
+ count: state.count + 1,
10233
+ sum: state.sum + value,
10234
+ min: Math.min(state.min, value),
10235
+ max: Math.max(state.max, value),
10236
+ bucketCounts
10237
+ };
10238
+ };
10239
+ var seriesIdentity = (instrument, attributes) => JSON.stringify([
10240
+ instrument,
10241
+ Object.entries(attributes).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
10242
+ ]);
10243
+ var aggregateDeltaPoints = (observations, nowMillis) => {
10244
+ const series = /* @__PURE__ */ new Map();
10245
+ for (const observation of observations) {
10246
+ const instrument = METRIC_INSTRUMENTS[observation.instrument];
10247
+ const key = seriesIdentity(observation.instrument, observation.attributes);
10248
+ const existing = series.get(key) ?? {
10249
+ observation,
10250
+ start: observation.timeMillis,
10251
+ value: 0,
10252
+ ...instrument.boundaries === void 0 ? {} : { histogram: emptyHistogram(instrument.boundaries) }
10253
+ };
10254
+ existing.start = Math.min(existing.start, observation.timeMillis);
10255
+ if (existing.histogram !== void 0 && instrument.boundaries !== void 0) {
10256
+ existing.histogram = recordIntoHistogram(existing.histogram, instrument.boundaries, observation.value);
10257
+ } else {
10258
+ existing.value += observation.value;
10259
+ }
10260
+ series.set(key, existing);
10261
+ }
10262
+ return [...series.values()].map((entry) => ({
10263
+ instrument: entry.observation.instrument,
10264
+ temporality: "delta",
10265
+ attributes: entry.observation.attributes,
10266
+ startTimeMillis: Math.min(entry.start, nowMillis),
10267
+ timeMillis: Math.max(nowMillis, entry.start),
10268
+ ...entry.histogram === void 0 ? { value: entry.value } : { histogram: entry.histogram }
10269
+ }));
10270
+ };
10271
+ var FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES = Object.freeze([
10272
+ "user.",
10273
+ "enduser.",
10274
+ "organization."
10275
+ ]);
10276
+ var withoutAccountIdentity = (attributes) => Object.fromEntries(
10277
+ Object.entries(attributes).filter(
10278
+ ([key]) => !FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES.some((prefix) => key.startsWith(prefix))
10279
+ )
10280
+ );
10281
+
10282
+ // src/telemetry/durable-metric-spool.ts
10283
+ var MAX_SPOOLED_METRIC_POINTS_PER_BATCH = 4096;
10284
+ var MAX_STRING_LENGTH = 8192;
10285
+ var MAX_ATTRIBUTES_PER_POINT = 64;
10286
+ var MAX_BUCKETS = 64;
10287
+ var isPlainObject5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10288
+ var isFiniteNonNegative3 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
10289
+ var isBoundedString3 = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_STRING_LENGTH;
10290
+ var isPrimitiveAttribute2 = (value) => typeof value === "string" && value.length <= MAX_STRING_LENGTH || typeof value === "number" && Number.isFinite(value) || typeof value === "boolean";
10291
+ var isReplayablePoint = (value) => {
10292
+ if (!isPlainObject5(value) || !isMetricInstrumentName(value.instrument)) {
10293
+ return false;
10294
+ }
10295
+ if (value.temporality !== "cumulative" && value.temporality !== "delta") {
10296
+ return false;
10297
+ }
10298
+ if (!isFiniteNonNegative3(value.startTimeMillis) || !isFiniteNonNegative3(value.timeMillis)) {
10299
+ return false;
10300
+ }
10301
+ if (!isPlainObject5(value.attributes)) {
10302
+ return false;
10303
+ }
10304
+ const entries = Object.entries(value.attributes);
10305
+ if (entries.length > MAX_ATTRIBUTES_PER_POINT || !entries.every(([, item]) => isPrimitiveAttribute2(item))) {
10306
+ return false;
10307
+ }
10308
+ const instrument = METRIC_INSTRUMENTS[value.instrument];
10309
+ if (instrument.kind === "counter") {
10310
+ return isFiniteNonNegative3(value.value) && value.histogram === void 0;
10311
+ }
10312
+ const histogram = value.histogram;
10313
+ if (!isPlainObject5(histogram) || value.value !== void 0) {
10314
+ return false;
10315
+ }
10316
+ const buckets = histogram.bucketCounts;
10317
+ return isFiniteNonNegative3(histogram.count) && Number.isInteger(histogram.count) && isFiniteNonNegative3(histogram.sum) && typeof histogram.min === "number" && typeof histogram.max === "number" && Array.isArray(buckets) && buckets.length <= MAX_BUCKETS && buckets.length === (instrument.boundaries?.length ?? 0) + 1 && buckets.every((count) => isFiniteNonNegative3(count) && Number.isInteger(count));
10318
+ };
10319
+ var validateMetricSpoolBatch = (value, identity) => {
10320
+ if (!isPlainObject5(value)) {
10321
+ return { rejection: "not-an-object" };
10322
+ }
10323
+ if (value.providerId !== identity.providerId || value.installationId !== identity.installationId) {
10324
+ return { rejection: "identity-mismatch" };
10325
+ }
10326
+ if (!isPlainObject5(value.resourceAttributes)) {
10327
+ return { rejection: "resource-attributes-invalid" };
10328
+ }
10329
+ if (!isPlainObject5(value.instrumentationScope) || !isBoundedString3(value.instrumentationScope.name)) {
10330
+ return { rejection: "instrumentation-scope-invalid" };
10331
+ }
10332
+ if (value.instrumentationScope.version !== void 0 && typeof value.instrumentationScope.version !== "string") {
10333
+ return { rejection: "instrumentation-scope-invalid" };
10334
+ }
10335
+ if (!Array.isArray(value.points) || value.points.length === 0 || value.points.length > MAX_SPOOLED_METRIC_POINTS_PER_BATCH) {
10336
+ return { rejection: "points-invalid" };
10337
+ }
10338
+ if (!value.points.every(isReplayablePoint)) {
10339
+ return { rejection: "point-field-invalid" };
10340
+ }
10341
+ if (!isFiniteNonNegative3(value.enqueuedAt)) {
10342
+ return { rejection: "not-an-object" };
10343
+ }
10344
+ return { batch: value };
10345
+ };
10346
+ var DEFAULT_MAX_METRIC_SPOOL_FILES = 500;
10347
+ var createFileDurableMetricSpool = (options) => createSpoolQueue({
10348
+ rootDir: options.rootDir,
10349
+ providerId: options.providerId,
10350
+ installationId: options.installationId,
10351
+ clock: options.clock,
10352
+ ...options.logger === void 0 ? {} : { logger: options.logger },
10353
+ maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_METRIC_SPOOL_FILES,
10354
+ queueName: options.queueName ?? "spool-metrics",
10355
+ ...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
10356
+ ...options.maxAgeMillis === void 0 ? {} : { maxAgeMillis: options.maxAgeMillis },
10357
+ ...options.overflow === void 0 ? {} : { overflow: options.overflow },
10358
+ validate: validateMetricSpoolBatch
10359
+ });
10360
+
10361
+ // src/telemetry/otlp-metric-sink.ts
10362
+ import { ValueType } from "@opentelemetry/api";
10363
+ import { ExportResultCode as ExportResultCode3, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
10364
+ import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
10365
+ import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
10366
+ import {
10367
+ AggregationTemporality,
10368
+ DataPointType
10369
+ } from "@opentelemetry/sdk-metrics";
10370
+ var resolveMetricsEndpoint = (exporter) => {
10371
+ const stated = exporter.metrics?.endpoint;
10372
+ if (stated !== void 0) {
10373
+ return { endpoint: stated, derived: false };
10374
+ }
10375
+ if (exporter.endpoint === void 0) {
10376
+ return { unresolvable: "no-endpoint" };
10377
+ }
10378
+ return { endpoint: siblingSignalEndpoint(exporter.endpoint, "metrics"), derived: true };
10379
+ };
10380
+ var describeMetricsDeliverability = (exporter) => {
10381
+ if (exporter.metrics?.enabled !== true) {
10382
+ return { status: "disabled", reason: "metrics-disabled" };
10383
+ }
10384
+ if (!exporter.enabled) {
10385
+ return { status: "disabled", reason: "exporter-disabled" };
10386
+ }
10387
+ if (exporter.protocol === "none") {
10388
+ return { status: "disabled", reason: "protocol-none" };
10389
+ }
10390
+ if (exporter.protocol !== "http/protobuf") {
10391
+ return { status: "disabled", reason: "protocol-unsupported" };
10392
+ }
10393
+ const resolved = resolveMetricsEndpoint(exporter);
10394
+ if ("unresolvable" in resolved) {
10395
+ return { status: "disabled", reason: "no-endpoint" };
10396
+ }
10397
+ return { status: "configured", endpoint: resolved.endpoint, derivedEndpoint: resolved.derived };
10398
+ };
10399
+ var DISABLED_DETAIL2 = Object.freeze({
10400
+ "exporter-disabled": "otlp metric sink disabled: the exporter is disabled",
10401
+ "protocol-none": "otlp metric sink disabled: protocol is none",
10402
+ "protocol-unsupported": "otlp metric sink disabled: protocol not supported by this build",
10403
+ "no-endpoint": "otlp metric sink disabled: no metrics endpoint configured and none could be derived"
10404
+ });
10405
+ var createDisabledMetricSink = (destination) => {
10406
+ const health = createHealthTracker(
10407
+ "telemetry-metric-sink",
10408
+ destination === void 0 ? {} : { destination }
10409
+ );
10410
+ return {
10411
+ enabled: false,
10412
+ exportPoints: () => Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),
10413
+ flush: () => Promise.resolve(),
10414
+ shutdown: () => Promise.resolve(),
10415
+ health: () => health.snapshot(),
10416
+ drainSpool: () => Promise.resolve({ drained: 0, remaining: 0, failed: 0 })
10417
+ };
10418
+ };
10419
+ var createDisabledOtlpMetricSink = createDisabledMetricSink;
10420
+ var toMetricData = (points) => {
10421
+ const byInstrument = /* @__PURE__ */ new Map();
10422
+ for (const point of points) {
10423
+ const key = `${point.instrument}|${point.temporality}`;
10424
+ const group = byInstrument.get(key) ?? [];
10425
+ group.push(point);
10426
+ byInstrument.set(key, group);
10427
+ }
10428
+ const metrics = [];
10429
+ for (const group of byInstrument.values()) {
10430
+ const first = group[0];
10431
+ if (first === void 0) {
10432
+ continue;
10433
+ }
10434
+ const instrument = METRIC_INSTRUMENTS[first.instrument];
10435
+ const descriptor = {
10436
+ name: instrument.name,
10437
+ description: instrument.description,
10438
+ unit: instrument.unit,
10439
+ valueType: instrument.valueType === "int" ? ValueType.INT : ValueType.DOUBLE
10440
+ };
10441
+ const aggregationTemporality = first.temporality === "cumulative" ? AggregationTemporality.CUMULATIVE : AggregationTemporality.DELTA;
10442
+ const times = (point) => ({
10443
+ startTime: millisToHrTime4(point.startTimeMillis),
10444
+ endTime: millisToHrTime4(point.timeMillis)
10445
+ });
10446
+ if (instrument.kind === "counter") {
10447
+ metrics.push({
10448
+ descriptor,
10449
+ aggregationTemporality,
10450
+ dataPointType: DataPointType.SUM,
10451
+ isMonotonic: true,
10452
+ dataPoints: group.map((point) => ({
10453
+ ...times(point),
10454
+ attributes: { ...point.attributes },
10455
+ value: point.value ?? 0
10456
+ }))
10457
+ });
10458
+ continue;
10459
+ }
10460
+ metrics.push({
10461
+ descriptor,
10462
+ aggregationTemporality,
10463
+ dataPointType: DataPointType.HISTOGRAM,
10464
+ dataPoints: group.map((point) => {
10465
+ const histogram = point.histogram;
10466
+ return {
10467
+ ...times(point),
10468
+ attributes: { ...point.attributes },
10469
+ value: {
10470
+ buckets: {
10471
+ boundaries: [...instrument.boundaries ?? []],
10472
+ counts: [...histogram?.bucketCounts ?? []]
10473
+ },
10474
+ count: histogram?.count ?? 0,
10475
+ sum: histogram?.sum ?? 0,
10476
+ ...histogram === void 0 || histogram.count === 0 ? {} : { min: histogram.min, max: histogram.max }
10477
+ }
10478
+ };
10479
+ })
10480
+ });
10481
+ }
10482
+ return metrics;
10483
+ };
10484
+ var createOtlpMetricSink = (options) => {
10485
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
10486
+ const deliverability = describeMetricsDeliverability(options.exporter);
10487
+ if (deliverability.status === "disabled") {
10488
+ if (deliverability.reason !== "metrics-disabled") {
10489
+ options.logger?.warn(DISABLED_DETAIL2[deliverability.reason], {
10490
+ "exporter.protocol": options.exporter.protocol,
10491
+ ...destinationFields
10492
+ });
10493
+ }
10494
+ return createDisabledMetricSink(options.destination);
10495
+ }
10496
+ const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
10497
+ const resource = resourceFromAttributes2(
10498
+ withoutAccountIdentity(resourceFromExporterPolicy(options.exporter).attributes)
10499
+ );
10500
+ const health = createHealthTracker(
10501
+ "telemetry-metric-sink",
10502
+ options.destination === void 0 ? {} : { destination: options.destination }
10503
+ );
10504
+ const exporter = new OTLPMetricExporter({
10505
+ url: deliverability.endpoint,
10506
+ headers: { ...options.headers },
10507
+ timeoutMillis: options.exporter.timeoutMillis
10508
+ });
10509
+ let shutdownCompleted = false;
10510
+ const exportResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve8) => {
10511
+ const payload = {
10512
+ resource: batchResource,
10513
+ scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }]
10514
+ };
10515
+ try {
10516
+ exporter.export(payload, (result) => resolve8(result));
10517
+ } catch (thrown) {
10518
+ resolve8({
10519
+ code: ExportResultCode3.FAILED,
10520
+ error: thrown instanceof Error ? thrown : new Error("export threw")
10521
+ });
10522
+ }
10523
+ });
10524
+ const toSpoolBatch = (points) => ({
10525
+ providerId: options.providerId,
10526
+ installationId: options.installationId,
10527
+ resourceAttributes: { ...resource.attributes },
10528
+ instrumentationScope: {
10529
+ name: scope.name,
10530
+ ...scope.version === void 0 ? {} : { version: scope.version }
10531
+ },
10532
+ points: points.map((point) => ({ ...point })),
10533
+ enqueuedAt: options.clock.now()
10534
+ });
10535
+ const sendSerializedBatch = async (batch) => {
10536
+ const batchResource = resourceFromAttributes2(
10537
+ withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes)
10538
+ );
10539
+ const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);
10540
+ if (result.code === ExportResultCode3.SUCCESS) {
10541
+ return true;
10542
+ }
10543
+ return isPermanentExportFailure(result) ? "discard" : false;
10544
+ };
10545
+ const exportPoints = async (points) => {
10546
+ if (points.length === 0) {
10547
+ return { accepted: 0, rejected: 0, errors: [] };
10548
+ }
10549
+ const result = await exportResourceMetrics(points, resource, scope);
10550
+ if (result.code === ExportResultCode3.SUCCESS) {
10551
+ health.recordSuccess(points.length, options.clock.now());
10552
+ return { accepted: points.length, rejected: 0, errors: [] };
10553
+ }
10554
+ health.recordFailure("telemetry-export-failure", points.length, options.clock.now());
10555
+ const permanent = isPermanentExportFailure(result);
10556
+ if (options.spool !== void 0 && !permanent) {
10557
+ const spooled = await options.spool.enqueue(toSpoolBatch(points)).catch(() => ({
10558
+ spooled: false,
10559
+ reason: "capacity-exceeded"
10560
+ }));
10561
+ if (spooled.spooled) {
10562
+ options.logger?.warn("metric batch not delivered; spooled for the next invocation", {
10563
+ "export.batch_size": points.length,
10564
+ ...destinationFields
10565
+ });
10566
+ return { accepted: points.length, rejected: 0, errors: [] };
10567
+ }
10568
+ }
10569
+ return {
10570
+ accepted: 0,
10571
+ rejected: points.length,
10572
+ errors: [
10573
+ createErrorInfo({
10574
+ code: "telemetry-export-failure",
10575
+ phase: "export",
10576
+ detail: permanent ? "collector refused a metric batch with a non-retryable status" : "collector rejected or was unreachable for a metric batch",
10577
+ details: {
10578
+ "export.batch_size": points.length,
10579
+ "export.signal": "metrics",
10580
+ ...destinationFields
10581
+ }
10582
+ })
10583
+ ]
10584
+ };
10585
+ };
10586
+ const drainSpool = async (maxBatches) => {
10587
+ if (options.spool === void 0) {
10588
+ return { drained: 0, remaining: 0, failed: 0 };
10589
+ }
10590
+ const result = await options.spool.drain(sendSerializedBatch, {
10591
+ ...maxBatches === void 0 ? {} : { maxBatches }
10592
+ });
10593
+ if (result.drained > 0) {
10594
+ health.recordSuccess(result.drained, options.clock.now());
10595
+ }
10596
+ return result;
10597
+ };
10598
+ const flush = async () => {
10599
+ try {
10600
+ await exporter.forceFlush();
10601
+ } catch {
10602
+ }
10603
+ await drainSpool().catch(() => void 0);
10604
+ };
10605
+ const shutdown = async () => {
10606
+ if (shutdownCompleted) {
10607
+ return;
10608
+ }
10609
+ shutdownCompleted = true;
10610
+ await flush();
10611
+ try {
10612
+ await exporter.shutdown();
10613
+ } catch {
10614
+ }
10615
+ };
10616
+ return {
10617
+ enabled: true,
10618
+ exportPoints,
10619
+ flush,
10620
+ shutdown,
10621
+ health: () => health.snapshot(),
10622
+ drainSpool
10623
+ };
10624
+ };
10625
+
9852
10626
  // src/telemetry/signal-fanout.ts
9853
10627
  var createSignalFanout = (options) => {
9854
10628
  const emit = async (events) => {
@@ -9892,7 +10666,11 @@ var shareCorrelationPerBatch = (correlate) => {
9892
10666
  };
9893
10667
 
9894
10668
  // src/telemetry/export-destinations.ts
9895
- var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs" } : { traces: `destinations/${destination}/spool`, logs: `destinations/${destination}/spool-logs` };
10669
+ var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs", metrics: "spool-metrics" } : {
10670
+ traces: `destinations/${destination}/spool`,
10671
+ logs: `destinations/${destination}/spool-logs`,
10672
+ metrics: `destinations/${destination}/spool-metrics`
10673
+ };
9896
10674
  var exporterPolicyForDestination = (exporter, destination) => {
9897
10675
  if (destination.source === "exporter") {
9898
10676
  return exporter;
@@ -9909,8 +10687,10 @@ var exporterPolicyForDestination = (exporter, destination) => {
9909
10687
  });
9910
10688
  return "endpoint" in derived ? derived.endpoint : void 0;
9911
10689
  })());
10690
+ const { metrics: sharedMetrics, ...rest } = shared;
10691
+ const derivedMetrics = destination.metricsEndpoint ?? (destination.endpoint === void 0 ? void 0 : siblingSignalEndpoint(destination.endpoint, "metrics"));
9912
10692
  return {
9913
- ...shared,
10693
+ ...rest,
9914
10694
  protocol: destination.protocol,
9915
10695
  ...tracesEndpoint === void 0 ? {} : { endpoint: tracesEndpoint },
9916
10696
  headerNames: Object.keys(destination.headers).sort(),
@@ -9918,6 +10698,11 @@ var exporterPolicyForDestination = (exporter, destination) => {
9918
10698
  ...logs,
9919
10699
  enabled: destination.signals.logs,
9920
10700
  ...derivedLogs === void 0 ? {} : { endpoint: derivedLogs }
10701
+ },
10702
+ metrics: {
10703
+ ...effectiveMetricsPolicy({ ...exporter, metrics: sharedMetrics }),
10704
+ enabled: destination.signals.metrics,
10705
+ ...derivedMetrics === void 0 ? {} : { endpoint: derivedMetrics }
9921
10706
  }
9922
10707
  };
9923
10708
  };
@@ -9989,6 +10774,12 @@ var createExportDestinationSinks = (options) => {
9989
10774
  ...bounds,
9990
10775
  queueName: queues.logs
9991
10776
  });
10777
+ const metricSpool = options.spoolRootDir === void 0 || !destination.signals.metrics ? void 0 : createFileDurableMetricSpool({
10778
+ rootDir: options.spoolRootDir,
10779
+ ...shared,
10780
+ ...bounds,
10781
+ queueName: queues.metrics
10782
+ });
9992
10783
  const sinkShared = {
9993
10784
  exporter: policy,
9994
10785
  ...shared,
@@ -10006,12 +10797,21 @@ var createExportDestinationSinks = (options) => {
10006
10797
  ...logSpool === void 0 ? {} : { spool: logSpool },
10007
10798
  content: options.logContent
10008
10799
  });
10800
+ const metrics = destination.signals.metrics ? createOtlpMetricSink({
10801
+ exporter: policy,
10802
+ ...shared,
10803
+ ...label === void 0 ? {} : { destination: label },
10804
+ ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
10805
+ ...metricSpool === void 0 ? {} : { spool: metricSpool }
10806
+ }) : createDisabledOtlpMetricSink(label);
10009
10807
  destinations.push({
10010
10808
  name: destination.name,
10011
10809
  traces,
10012
10810
  logs,
10811
+ metrics,
10013
10812
  ...spool === void 0 ? {} : { spool },
10014
- ...logSpool === void 0 ? {} : { logSpool }
10813
+ ...logSpool === void 0 ? {} : { logSpool },
10814
+ ...metricSpool === void 0 ? {} : { metricSpool }
10015
10815
  });
10016
10816
  }
10017
10817
  return { destinations, skipped };
@@ -10216,6 +11016,9 @@ var describeDestinationLine = (destination) => {
10216
11016
  if (destination.logsEndpointOrigin !== void 0) {
10217
11017
  parts.push(`logs -> ${destination.logsEndpointOrigin}`);
10218
11018
  }
11019
+ if (destination.metricsEndpointOrigin !== void 0) {
11020
+ parts.push(`metrics -> ${destination.metricsEndpointOrigin}`);
11021
+ }
10219
11022
  if (destination.headerNames.length > 0) {
10220
11023
  parts.push(`headers ${destination.headerNames.join(", ")}`);
10221
11024
  }
@@ -10279,7 +11082,7 @@ var describeDoctorDestinations = async (exporter, environment, spool) => {
10279
11082
  const headers = configured.get(description.name)?.headers ?? {};
10280
11083
  const missingVariables = resolveDestinationHeaders(headers, environment).missingVariables;
10281
11084
  const sends = description.signals.length > 0;
10282
- const reachable = description.signals.includes("traces") && description.tracesEndpointOrigin !== void 0 || description.signals.includes("logs") && description.logsEndpointOrigin !== void 0;
11085
+ const reachable = description.signals.includes("traces") && description.tracesEndpointOrigin !== void 0 || description.signals.includes("logs") && description.logsEndpointOrigin !== void 0 || description.signals.includes("metrics") && description.metricsEndpointOrigin !== void 0;
10283
11086
  let detail = "resolves";
10284
11087
  let ok = true;
10285
11088
  if (!description.enabled) {
@@ -10297,7 +11100,8 @@ var describeDoctorDestinations = async (exporter, environment, spool) => {
10297
11100
  const queues = spoolQueueNamesFor(description.name);
10298
11101
  const spoolStats = spool === void 0 || !resolvedNames.has(description.name) ? void 0 : {
10299
11102
  ...description.signals.includes("traces") ? { traces: await inspectQueue(spool, queues.traces) } : {},
10300
- ...description.signals.includes("logs") ? { logs: await inspectQueue(spool, queues.logs) } : {}
11103
+ ...description.signals.includes("logs") ? { logs: await inspectQueue(spool, queues.logs) } : {},
11104
+ ...description.signals.includes("metrics") ? { metrics: await inspectQueue(spool, queues.metrics) } : {}
10301
11105
  };
10302
11106
  return {
10303
11107
  ...description,
@@ -10351,12 +11155,12 @@ var runDoctorCommand = async (command, io) => {
10351
11155
  };
10352
11156
 
10353
11157
  // src/providers/antigravity/registration.ts
10354
- var isPlainObject5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
11158
+ var isPlainObject6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10355
11159
  var mergeAntigravityHookRegistration = (input) => {
10356
11160
  const events = input.events ?? ANTIGRAVITY_HOOK_EVENT_NAMES;
10357
- const base = isPlainObject5(input.existing) ? input.existing : {};
10358
- const existingHooks = isPlainObject5(base.hooks) ? base.hooks : {};
10359
- let changed = !isPlainObject5(input.existing) || !isPlainObject5(base.hooks);
11161
+ const base = isPlainObject6(input.existing) ? input.existing : {};
11162
+ const existingHooks = isPlainObject6(base.hooks) ? base.hooks : {};
11163
+ let changed = !isPlainObject6(input.existing) || !isPlainObject6(base.hooks);
10360
11164
  const nextHooks = { ...existingHooks };
10361
11165
  const identifies = input.identifies ?? ((entry) => entry.command === input.command);
10362
11166
  const desired = {
@@ -10365,7 +11169,7 @@ var mergeAntigravityHookRegistration = (input) => {
10365
11169
  };
10366
11170
  for (const event3 of events) {
10367
11171
  const currentList = Array.isArray(existingHooks[event3]) ? [...existingHooks[event3]] : [];
10368
- const managedIndex = currentList.findIndex((entry) => isPlainObject5(entry) && identifies(entry));
11172
+ const managedIndex = currentList.findIndex((entry) => isPlainObject6(entry) && identifies(entry));
10369
11173
  if (managedIndex === -1) {
10370
11174
  changed = true;
10371
11175
  nextHooks[event3] = [...currentList, desired];
@@ -10374,7 +11178,7 @@ var mergeAntigravityHookRegistration = (input) => {
10374
11178
  const managed = currentList[managedIndex];
10375
11179
  const updated = { ...managed, ...desired };
10376
11180
  const next = currentList.filter(
10377
- (entry, index) => index === managedIndex || !(isPlainObject5(entry) && identifies(entry))
11181
+ (entry, index) => index === managedIndex || !(isPlainObject6(entry) && identifies(entry))
10378
11182
  );
10379
11183
  next[next.indexOf(managed)] = updated;
10380
11184
  const rewritten = Object.entries(desired).some(([key, value]) => managed[key] !== value);
@@ -10389,8 +11193,8 @@ var mergeAntigravityHookRegistration = (input) => {
10389
11193
  };
10390
11194
  };
10391
11195
  var removeAntigravityHookRegistration = (input) => {
10392
- const base = isPlainObject5(input.existing) ? { ...input.existing } : {};
10393
- if (!isPlainObject5(base.hooks)) {
11196
+ const base = isPlainObject6(input.existing) ? { ...input.existing } : {};
11197
+ if (!isPlainObject6(base.hooks)) {
10394
11198
  return { config: base, changed: false };
10395
11199
  }
10396
11200
  const nextHooks = { ...base.hooks };
@@ -10402,7 +11206,7 @@ var removeAntigravityHookRegistration = (input) => {
10402
11206
  continue;
10403
11207
  }
10404
11208
  const kept = currentList.filter(
10405
- (entry) => !(isPlainObject5(entry) && input.identifies(entry))
11209
+ (entry) => !(isPlainObject6(entry) && input.identifies(entry))
10406
11210
  );
10407
11211
  if (kept.length === currentList.length) {
10408
11212
  continue;
@@ -10427,7 +11231,7 @@ var removeAntigravityHookRegistration = (input) => {
10427
11231
  };
10428
11232
  var readAntigravityHookRegistrations = (existing, identifies) => {
10429
11233
  const found = /* @__PURE__ */ new Map();
10430
- if (!isPlainObject5(existing) || !isPlainObject5(existing.hooks)) {
11234
+ if (!isPlainObject6(existing) || !isPlainObject6(existing.hooks)) {
10431
11235
  return found;
10432
11236
  }
10433
11237
  for (const [event3, list] of Object.entries(existing.hooks)) {
@@ -10435,7 +11239,7 @@ var readAntigravityHookRegistrations = (existing, identifies) => {
10435
11239
  continue;
10436
11240
  }
10437
11241
  const commands = list.filter(
10438
- (entry) => isPlainObject5(entry) && typeof entry.command === "string" && identifies(entry)
11242
+ (entry) => isPlainObject6(entry) && typeof entry.command === "string" && identifies(entry)
10439
11243
  ).map((entry) => entry.command);
10440
11244
  if (commands.length > 0) {
10441
11245
  found.set(event3, commands);
@@ -10445,10 +11249,10 @@ var readAntigravityHookRegistrations = (existing, identifies) => {
10445
11249
  };
10446
11250
 
10447
11251
  // src/providers/hook-document.ts
10448
- var isPlainObject6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
11252
+ var isPlainObject7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10449
11253
  var normalizeMatcher = (value) => typeof value === "string" && value !== "" && value !== "*" ? value : void 0;
10450
- var isManaged = (value, identifies) => isPlainObject6(value) && identifies(value);
10451
- var cloneGroup = (value) => isPlainObject6(value) && Array.isArray(value.hooks) ? { ...value, hooks: [...value.hooks] } : void 0;
11254
+ var isManaged = (value, identifies) => isPlainObject7(value) && identifies(value);
11255
+ var cloneGroup = (value) => isPlainObject7(value) && Array.isArray(value.hooks) ? { ...value, hooks: [...value.hooks] } : void 0;
10452
11256
  var matchesDesired = (existing, desired) => {
10453
11257
  for (const [key, value] of Object.entries(desired)) {
10454
11258
  if (existing[key] !== value) {
@@ -10476,7 +11280,7 @@ var readHooksObject = (base, conflicts) => {
10476
11280
  if (raw === void 0) {
10477
11281
  return {};
10478
11282
  }
10479
- if (!isPlainObject6(raw)) {
11283
+ if (!isPlainObject7(raw)) {
10480
11284
  conflicts.push({
10481
11285
  location: "hooks",
10482
11286
  detail: `expected an object keyed by hook event name, found ${Array.isArray(raw) ? "an array" : raw === null ? "null" : typeof raw}`
@@ -10485,7 +11289,7 @@ var readHooksObject = (base, conflicts) => {
10485
11289
  }
10486
11290
  return { ...raw };
10487
11291
  };
10488
- var pruneEventList = (list) => list.filter((group) => !(isPlainObject6(group) && Array.isArray(group.hooks) && group.hooks.length === 0));
11292
+ var pruneEventList = (list) => list.filter((group) => !(isPlainObject7(group) && Array.isArray(group.hooks) && group.hooks.length === 0));
10489
11293
  var finalize = (base, hooks) => {
10490
11294
  const next = { ...base };
10491
11295
  if (Object.keys(hooks).length === 0) {
@@ -10496,7 +11300,7 @@ var finalize = (base, hooks) => {
10496
11300
  return next;
10497
11301
  };
10498
11302
  var mergeNestedHookRegistration = (input) => {
10499
- const base = isPlainObject6(input.existing) ? { ...input.existing } : {};
11303
+ const base = isPlainObject7(input.existing) ? { ...input.existing } : {};
10500
11304
  const conflicts = [];
10501
11305
  const hooks = readHooksObject(base, conflicts);
10502
11306
  if (hooks === void 0) {
@@ -10512,7 +11316,7 @@ var mergeNestedHookRegistration = (input) => {
10512
11316
  }
10513
11317
  const groups = list.map((group) => cloneGroup(group) ?? group);
10514
11318
  const usableGroups = groups.filter(
10515
- (group) => isPlainObject6(group) && Array.isArray(group.hooks)
11319
+ (group) => isPlainObject7(group) && Array.isArray(group.hooks)
10516
11320
  );
10517
11321
  let ownHandler;
10518
11322
  let ownGroup;
@@ -10577,7 +11381,7 @@ var mergeNestedHookRegistration = (input) => {
10577
11381
  return { document: finalize(base, hooks), changed, changes, conflicts };
10578
11382
  };
10579
11383
  var removeNestedHookRegistrations = (input) => {
10580
- const base = isPlainObject6(input.existing) ? { ...input.existing } : {};
11384
+ const base = isPlainObject7(input.existing) ? { ...input.existing } : {};
10581
11385
  const conflicts = [];
10582
11386
  const hooks = readHooksObject(base, conflicts);
10583
11387
  if (hooks === void 0) {
@@ -10630,7 +11434,7 @@ var removeNestedHookRegistrations = (input) => {
10630
11434
  };
10631
11435
  var readNestedHookRegistrations = (existing, identifies) => {
10632
11436
  const found = /* @__PURE__ */ new Map();
10633
- if (!isPlainObject6(existing) || !isPlainObject6(existing.hooks)) {
11437
+ if (!isPlainObject7(existing) || !isPlainObject7(existing.hooks)) {
10634
11438
  return found;
10635
11439
  }
10636
11440
  for (const [event3, list] of Object.entries(existing.hooks)) {
@@ -10639,7 +11443,7 @@ var readNestedHookRegistrations = (existing, identifies) => {
10639
11443
  }
10640
11444
  const commands = [];
10641
11445
  for (const group of list) {
10642
- if (!isPlainObject6(group) || !Array.isArray(group.hooks)) {
11446
+ if (!isPlainObject7(group) || !Array.isArray(group.hooks)) {
10643
11447
  continue;
10644
11448
  }
10645
11449
  for (const handler of group.hooks) {
@@ -10776,7 +11580,7 @@ var CURSOR_UNREGISTERED_HOOK_EVENTS = Object.freeze({
10776
11580
  workspaceOpen: "an app-lifecycle hook that carries no conversation_id, so it has no session to attribute telemetry to"
10777
11581
  });
10778
11582
  var CURSOR_HOOKS_DOCUMENT_VERSION = 1;
10779
- var isPlainObject7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
11583
+ var isPlainObject8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10780
11584
  var buildEntry3 = (input) => ({
10781
11585
  type: "command",
10782
11586
  command: input.command,
@@ -10785,8 +11589,8 @@ var buildEntry3 = (input) => ({
10785
11589
  });
10786
11590
  var mergeCursorHookRegistration = (input) => {
10787
11591
  const events = input.events ?? CURSOR_REGISTRABLE_HOOK_EVENTS;
10788
- const base = isPlainObject7(input.existing) ? { ...input.existing } : {};
10789
- const existingHooks = isPlainObject7(base.hooks) ? base.hooks : {};
11592
+ const base = isPlainObject8(input.existing) ? { ...input.existing } : {};
11593
+ const existingHooks = isPlainObject8(base.hooks) ? base.hooks : {};
10790
11594
  const nextHooks = { ...existingHooks };
10791
11595
  const desired = buildEntry3(input);
10792
11596
  let changed = false;
@@ -10797,7 +11601,7 @@ var mergeCursorHookRegistration = (input) => {
10797
11601
  for (const event3 of events) {
10798
11602
  const currentList = Array.isArray(existingHooks[event3]) ? [...existingHooks[event3]] : [];
10799
11603
  const managed = currentList.filter(
10800
- (entry) => isPlainObject7(entry) && input.identifies(entry)
11604
+ (entry) => isPlainObject8(entry) && input.identifies(entry)
10801
11605
  );
10802
11606
  const [ours] = managed;
10803
11607
  if (ours === void 0) {
@@ -10806,7 +11610,7 @@ var mergeCursorHookRegistration = (input) => {
10806
11610
  continue;
10807
11611
  }
10808
11612
  const rewritten = { ...ours, ...desired };
10809
- const next = currentList.filter((entry) => entry === ours || !(isPlainObject7(entry) && input.identifies(entry))).map((entry) => entry === ours ? rewritten : entry);
11613
+ const next = currentList.filter((entry) => entry === ours || !(isPlainObject8(entry) && input.identifies(entry))).map((entry) => entry === ours ? rewritten : entry);
10810
11614
  const entryChanged = Object.entries(desired).some(([key, value]) => ours[key] !== value);
10811
11615
  if (entryChanged || managed.length > 1) {
10812
11616
  changed = true;
@@ -10816,8 +11620,8 @@ var mergeCursorHookRegistration = (input) => {
10816
11620
  return { config: { ...base, hooks: nextHooks }, changed };
10817
11621
  };
10818
11622
  var removeCursorHookRegistration = (input) => {
10819
- const base = isPlainObject7(input.existing) ? { ...input.existing } : {};
10820
- if (!isPlainObject7(base.hooks)) {
11623
+ const base = isPlainObject8(input.existing) ? { ...input.existing } : {};
11624
+ if (!isPlainObject8(base.hooks)) {
10821
11625
  return { config: base, changed: false };
10822
11626
  }
10823
11627
  const nextHooks = { ...base.hooks };
@@ -10829,7 +11633,7 @@ var removeCursorHookRegistration = (input) => {
10829
11633
  continue;
10830
11634
  }
10831
11635
  const kept = currentList.filter(
10832
- (entry) => !(isPlainObject7(entry) && input.identifies(entry))
11636
+ (entry) => !(isPlainObject8(entry) && input.identifies(entry))
10833
11637
  );
10834
11638
  if (kept.length === currentList.length) {
10835
11639
  continue;
@@ -10857,7 +11661,7 @@ var removeCursorHookRegistration = (input) => {
10857
11661
  };
10858
11662
  var readCursorHookRegistrations = (existing, identifies) => {
10859
11663
  const found = /* @__PURE__ */ new Map();
10860
- if (!isPlainObject7(existing) || !isPlainObject7(existing.hooks)) {
11664
+ if (!isPlainObject8(existing) || !isPlainObject8(existing.hooks)) {
10861
11665
  return found;
10862
11666
  }
10863
11667
  for (const [event3, list] of Object.entries(existing.hooks)) {
@@ -10865,7 +11669,7 @@ var readCursorHookRegistrations = (existing, identifies) => {
10865
11669
  continue;
10866
11670
  }
10867
11671
  const commands = list.filter(
10868
- (entry) => isPlainObject7(entry) && typeof entry.command === "string" && identifies(entry)
11672
+ (entry) => isPlainObject8(entry) && typeof entry.command === "string" && identifies(entry)
10869
11673
  ).map((entry) => entry.command);
10870
11674
  if (commands.length > 0) {
10871
11675
  found.set(event3, commands);
@@ -10965,7 +11769,7 @@ var managedHookPredicate = (marker) => {
10965
11769
  }
10966
11770
  return (handler) => handler.name === MANAGED_HOOK_NAME || typeof handler.command === "string" && handler.command.includes(marker);
10967
11771
  };
10968
- var isPlainObject8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
11772
+ var isPlainObject9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10969
11773
  var adaptFlatResult = (read, existing, events, identifies, result, removal) => {
10970
11774
  const before = read(existing, identifies);
10971
11775
  const after = read(result.config, identifies);
@@ -10989,10 +11793,10 @@ var adaptFlatResult = (read, existing, events, identifies, result, removal) => {
10989
11793
  return { document: result.config, changed: result.changed, changes, conflicts: [] };
10990
11794
  };
10991
11795
  var flatHookConflicts = (existing) => {
10992
- if (!isPlainObject8(existing) || existing.hooks === void 0) {
11796
+ if (!isPlainObject9(existing) || existing.hooks === void 0) {
10993
11797
  return [];
10994
11798
  }
10995
- if (!isPlainObject8(existing.hooks)) {
11799
+ if (!isPlainObject9(existing.hooks)) {
10996
11800
  return [
10997
11801
  {
10998
11802
  location: "hooks",
@@ -11012,7 +11816,7 @@ var flatHookConflicts = (existing) => {
11012
11816
  return conflicts;
11013
11817
  };
11014
11818
  var asAntigravityEvents = (events) => events;
11015
- var documentEventNames = (existing) => isPlainObject8(existing) && isPlainObject8(existing.hooks) ? Object.keys(existing.hooks) : [];
11819
+ var documentEventNames = (existing) => isPlainObject9(existing) && isPlainObject9(existing.hooks) ? Object.keys(existing.hooks) : [];
11016
11820
  var PLANNERS = Object.freeze([
11017
11821
  Object.freeze({
11018
11822
  providerId: ANTIGRAVITY_PROVIDER_ID,
@@ -11021,7 +11825,7 @@ var PLANNERS = Object.freeze([
11021
11825
  const conflicts = flatHookConflicts(input.existing);
11022
11826
  if (conflicts.length > 0) {
11023
11827
  return {
11024
- document: isPlainObject8(input.existing) ? input.existing : {},
11828
+ document: isPlainObject9(input.existing) ? input.existing : {},
11025
11829
  changed: false,
11026
11830
  changes: [],
11027
11831
  conflicts
@@ -11047,7 +11851,7 @@ var PLANNERS = Object.freeze([
11047
11851
  const conflicts = flatHookConflicts(input.existing);
11048
11852
  if (conflicts.length > 0) {
11049
11853
  return {
11050
- document: isPlainObject8(input.existing) ? input.existing : {},
11854
+ document: isPlainObject9(input.existing) ? input.existing : {},
11051
11855
  changed: false,
11052
11856
  changes: [],
11053
11857
  conflicts
@@ -11090,7 +11894,7 @@ var PLANNERS = Object.freeze([
11090
11894
  const conflicts = flatHookConflicts(input.existing);
11091
11895
  if (conflicts.length > 0) {
11092
11896
  return {
11093
- document: isPlainObject8(input.existing) ? input.existing : {},
11897
+ document: isPlainObject9(input.existing) ? input.existing : {},
11094
11898
  changed: false,
11095
11899
  changes: [],
11096
11900
  conflicts
@@ -11117,7 +11921,7 @@ var PLANNERS = Object.freeze([
11117
11921
  const conflicts = flatHookConflicts(input.existing);
11118
11922
  if (conflicts.length > 0) {
11119
11923
  return {
11120
- document: isPlainObject8(input.existing) ? input.existing : {},
11924
+ document: isPlainObject9(input.existing) ? input.existing : {},
11121
11925
  changed: false,
11122
11926
  changes: [],
11123
11927
  conflicts
@@ -11970,6 +12774,8 @@ var rollupUsageKey = (sessionId, scope, scopeKey) => `${rollupScanPrefix(session
11970
12774
  var rollupEpochKey = (sessionId, scope, scopeKey) => `${rollupEpochScanPrefix(sessionId)}${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;
11971
12775
  var rollupScanPrefix = (sessionId) => sessionId === void 0 ? `${LIFECYCLE_PREFIX}:usage:` : `${LIFECYCLE_PREFIX}:usage:${encodeSegment(sessionId)}:`;
11972
12776
  var rollupEpochScanPrefix = (sessionId) => sessionId === void 0 ? `${LIFECYCLE_PREFIX}:epoch:` : `${LIFECYCLE_PREFIX}:epoch:${encodeSegment(sessionId)}:`;
12777
+ var metricSeriesKey = (sessionScope2, seriesDigest) => `${metricSeriesScanPrefix(sessionScope2)}${encodeSegment(seriesDigest)}`;
12778
+ var metricSeriesScanPrefix = (sessionScope2) => sessionScope2 === void 0 ? `${LIFECYCLE_PREFIX}:metric:v1:` : `${LIFECYCLE_PREFIX}:metric:v1:${encodeSegment(sessionScope2)}:`;
11973
12779
 
11974
12780
  // src/lifecycle/dedup.ts
11975
12781
  var DEFAULT_STALE_CLAIM_MILLIS = 6e4;
@@ -12139,6 +12945,150 @@ var createCallbackDeduplicator = (deps) => {
12139
12945
  return { checkAndMark, claim, commit, release, cleanup };
12140
12946
  };
12141
12947
 
12948
+ // src/lifecycle/metric-series.ts
12949
+ import { createHash as createHash4 } from "crypto";
12950
+ var TURN_START_SEGMENT = "turn-start";
12951
+ var SHARED_SCOPE = "all";
12952
+ var SHARED_LOCK = "otelhook.metrics.shared";
12953
+ var sessionScope = (sessionId) => `s=${sessionId}`;
12954
+ var digest = (identity) => createHash4("sha256").update(identity).digest("base64url").slice(0, 43);
12955
+ var toStoredHistogram = (histogram) => ({
12956
+ count: histogram.count,
12957
+ sum: histogram.sum,
12958
+ // An empty histogram has infinite min/max, which JSON cannot hold. A stored
12959
+ // histogram always has at least one value, so these are finite in practice.
12960
+ min: Number.isFinite(histogram.min) ? histogram.min : 0,
12961
+ max: Number.isFinite(histogram.max) ? histogram.max : 0,
12962
+ bucketCounts: [...histogram.bucketCounts]
12963
+ });
12964
+ var createMetricSeriesStore = (deps) => {
12965
+ const { stateStore, clock } = deps;
12966
+ const readSeries = async (key) => {
12967
+ const record = await stateStore.read(key);
12968
+ if (record?.value.kind !== "metric-series") {
12969
+ return void 0;
12970
+ }
12971
+ return record.value;
12972
+ };
12973
+ const recordGroup = async (scope, observations, deliveryToken) => {
12974
+ const bySeries = /* @__PURE__ */ new Map();
12975
+ for (const observation of observations) {
12976
+ const identity = seriesIdentity(observation.instrument, observation.attributes);
12977
+ const group = bySeries.get(identity) ?? [];
12978
+ group.push(observation);
12979
+ bySeries.set(identity, group);
12980
+ }
12981
+ const now = clock.now();
12982
+ const points = [];
12983
+ for (const [identity, group] of bySeries) {
12984
+ const first = group[0];
12985
+ if (first === void 0) {
12986
+ continue;
12987
+ }
12988
+ const instrument = METRIC_INSTRUMENTS[first.instrument];
12989
+ const key = metricSeriesKey(scope, digest(identity));
12990
+ const existing = await readSeries(key);
12991
+ const boundaries = instrument.boundaries;
12992
+ const compatible = existing !== void 0 && (boundaries === void 0 ? existing.value !== void 0 : existing.histogram?.bucketCounts.length === boundaries.length + 1);
12993
+ const base = compatible ? existing : void 0;
12994
+ const replay = deliveryToken !== void 0 && base?.appliedDelivery === deliveryToken;
12995
+ const earliest = Math.min(...group.map((observation) => observation.timeMillis));
12996
+ const startTimeMillis = base?.startTimeMillis ?? Math.min(earliest, now);
12997
+ let value = base?.value ?? 0;
12998
+ let histogram = boundaries === void 0 ? void 0 : base?.histogram === void 0 ? emptyHistogram(boundaries) : base.histogram;
12999
+ if (!replay) {
13000
+ for (const observation of group) {
13001
+ if (histogram !== void 0 && boundaries !== void 0) {
13002
+ histogram = recordIntoHistogram(histogram, boundaries, observation.value);
13003
+ } else {
13004
+ value += observation.value;
13005
+ }
13006
+ }
13007
+ await stateStore.write(key, {
13008
+ kind: "metric-series",
13009
+ startTimeMillis,
13010
+ ...histogram === void 0 ? { value } : { histogram: toStoredHistogram(histogram) },
13011
+ ...deliveryToken === void 0 ? {} : { appliedDelivery: deliveryToken }
13012
+ });
13013
+ }
13014
+ points.push({
13015
+ instrument: first.instrument,
13016
+ temporality: "cumulative",
13017
+ attributes: first.attributes,
13018
+ startTimeMillis,
13019
+ timeMillis: Math.max(now, startTimeMillis),
13020
+ ...histogram === void 0 ? { value } : { histogram }
13021
+ });
13022
+ }
13023
+ return points;
13024
+ };
13025
+ const recordCumulative = async (observations, options) => {
13026
+ if (observations.length === 0) {
13027
+ return [];
13028
+ }
13029
+ if (options?.perSession === false) {
13030
+ return withOptionalSessionLock(
13031
+ stateStore,
13032
+ SHARED_LOCK,
13033
+ () => recordGroup(SHARED_SCOPE, observations, options.deliveryToken)
13034
+ );
13035
+ }
13036
+ const bySession = /* @__PURE__ */ new Map();
13037
+ for (const observation of observations) {
13038
+ const group = bySession.get(observation.sessionId) ?? [];
13039
+ group.push(observation);
13040
+ bySession.set(observation.sessionId, group);
13041
+ }
13042
+ const points = [];
13043
+ for (const [sessionId, group] of bySession) {
13044
+ points.push(
13045
+ ...await withOptionalSessionLock(
13046
+ stateStore,
13047
+ sessionId,
13048
+ () => recordGroup(sessionScope(sessionId), group, options?.deliveryToken)
13049
+ )
13050
+ );
13051
+ }
13052
+ return points;
13053
+ };
13054
+ const cleanup = async (maxAgeMillis, options) => {
13055
+ const cap = options?.maxEntries ?? 1e3;
13056
+ const now = clock.now();
13057
+ let removed = 0;
13058
+ let scanned = 0;
13059
+ const prefix = metricSeriesScanPrefix(
13060
+ options?.sessionId === void 0 ? void 0 : sessionScope(options.sessionId)
13061
+ );
13062
+ for (const key of await stateStore.keys(prefix)) {
13063
+ if (scanned >= cap) {
13064
+ break;
13065
+ }
13066
+ scanned += 1;
13067
+ const record = await stateStore.read(key);
13068
+ if (record !== void 0 && now - record.updatedAt > maxAgeMillis) {
13069
+ await stateStore.delete(key);
13070
+ removed += 1;
13071
+ }
13072
+ }
13073
+ return { removed, scanned };
13074
+ };
13075
+ const turnKey = (sessionId) => metricSeriesKey(sessionScope(sessionId), TURN_START_SEGMENT);
13076
+ const recordTurnStart = (sessionId, startMillis) => withOptionalSessionLock(stateStore, sessionId, async () => {
13077
+ const existing = await stateStore.read(turnKey(sessionId));
13078
+ const previous = existing?.value.kind === "attributes" && typeof existing.value.attributes.startMillis === "number" ? existing.value.attributes.startMillis : void 0;
13079
+ if (previous !== void 0 && previous >= startMillis) {
13080
+ return;
13081
+ }
13082
+ await stateStore.write(turnKey(sessionId), { kind: "attributes", attributes: { startMillis } });
13083
+ });
13084
+ const readTurnStart = async (sessionId) => {
13085
+ const record = await stateStore.read(turnKey(sessionId));
13086
+ const value = record?.value.kind === "attributes" ? record.value.attributes.startMillis : void 0;
13087
+ return typeof value === "number" ? value : void 0;
13088
+ };
13089
+ return { recordCumulative, recordTurnStart, readTurnStart, cleanup };
13090
+ };
13091
+
12142
13092
  // src/lifecycle/janitor.ts
12143
13093
  var DEFAULT_MAX_AGE_MILLIS = 24 * 60 * 60 * 1e3;
12144
13094
  var DEFAULT_MAX_ENTRIES_PER_COMPONENT = 1e3;
@@ -12149,7 +13099,7 @@ var createLifecycleJanitor = (options) => {
12149
13099
  const usageMaxAge = options.usageMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
12150
13100
  const runOnce = async (sessionId) => {
12151
13101
  const scope = { maxEntries, ...sessionId === void 0 ? {} : { sessionId } };
12152
- const [span, dedup, usage] = await Promise.all([
13102
+ const [span, dedup, usage, metrics] = await Promise.all([
12153
13103
  options.spanCorrelator?.cleanup(spanMaxAge, scope),
12154
13104
  // Deduplication is deliberately swept across every scope rather than the
12155
13105
  // ending session's: a delivery scope is a host-chosen namespace or a
@@ -12160,12 +13110,14 @@ var createLifecycleJanitor = (options) => {
12160
13110
  maxEntries,
12161
13111
  ...options.dedupStaleClaimMillis === void 0 ? {} : { staleClaimMillis: options.dedupStaleClaimMillis }
12162
13112
  }),
12163
- options.usageAccumulator?.cleanup(usageMaxAge, scope)
13113
+ options.usageAccumulator?.cleanup(usageMaxAge, scope),
13114
+ options.metricSeries?.cleanup(usageMaxAge, scope)
12164
13115
  ]);
12165
13116
  return {
12166
13117
  ...span === void 0 ? {} : { span },
12167
13118
  ...dedup === void 0 ? {} : { dedup },
12168
- ...usage === void 0 ? {} : { usage }
13119
+ ...usage === void 0 ? {} : { usage },
13120
+ ...metrics === void 0 ? {} : { metrics }
12169
13121
  };
12170
13122
  };
12171
13123
  return { runOnce };
@@ -12679,7 +13631,7 @@ var createUsageAccumulator = (deps) => {
12679
13631
  };
12680
13632
 
12681
13633
  // src/providers/claude/transcript.ts
12682
- import { createHash as createHash4 } from "crypto";
13634
+ import { createHash as createHash5 } from "crypto";
12683
13635
  import { open as open4, stat as stat4 } from "fs/promises";
12684
13636
  import path10 from "path";
12685
13637
  var DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES = 1048576;
@@ -12897,7 +13849,7 @@ var hasUsage = (record) => record.usage !== void 0 || record.token_usage !== voi
12897
13849
  var eventNameOf = (record) => record.hook_event_name ?? record.hookEventName;
12898
13850
  var transcriptPathOf = (record) => record.transcript_path ?? record.transcriptPath;
12899
13851
  var CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
12900
- var sourceDigest = (transcriptPath) => createHash4("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
13852
+ var sourceDigest = (transcriptPath) => createHash5("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
12901
13853
  var createClaudeTranscriptUsageEnricher = (options = {}) => {
12902
13854
  const fileSize = async (transcriptPath) => {
12903
13855
  try {
@@ -13006,9 +13958,9 @@ var resolveDeliveryIdentity = (input) => {
13006
13958
  };
13007
13959
 
13008
13960
  // src/runtime/ids.ts
13009
- import { createHash as createHash5, randomUUID } from "crypto";
13010
- var digest = (namespace, parts) => {
13011
- const hash = createHash5("sha256");
13961
+ import { createHash as createHash6, randomUUID } from "crypto";
13962
+ var digest2 = (namespace, parts) => {
13963
+ const hash = createHash6("sha256");
13012
13964
  hash.update(namespace);
13013
13965
  for (const part of parts) {
13014
13966
  hash.update("\0");
@@ -13023,7 +13975,7 @@ var createDeterministicIdGenerator = (options = {}) => {
13023
13975
  return {
13024
13976
  newInvocationId: (seed) => invocationIdSchema.parse(
13025
13977
  `inv_${truncate(
13026
- digest(`${namespace}/invocation`, [
13978
+ digest2(`${namespace}/invocation`, [
13027
13979
  seed.providerId,
13028
13980
  seed.sessionId,
13029
13981
  seed.sourceEventName,
@@ -13034,7 +13986,7 @@ var createDeterministicIdGenerator = (options = {}) => {
13034
13986
  ),
13035
13987
  newEventId: (seed) => eventIdSchema.parse(
13036
13988
  `evt_${truncate(
13037
- digest(`${namespace}/event`, [
13989
+ digest2(`${namespace}/event`, [
13038
13990
  seed.invocationId,
13039
13991
  seed.sequence,
13040
13992
  seed.eventType,
@@ -13042,7 +13994,7 @@ var createDeterministicIdGenerator = (options = {}) => {
13042
13994
  ])
13043
13995
  )}`
13044
13996
  ),
13045
- newOpaqueId: (parts) => truncate(digest(`${namespace}/opaque`, parts))
13997
+ newOpaqueId: (parts) => truncate(digest2(`${namespace}/opaque`, parts))
13046
13998
  };
13047
13999
  };
13048
14000
 
@@ -14255,6 +15207,12 @@ var createHookRuntime = (options) => {
14255
15207
  const hook = createOtelHook({ ...hookDeps, sink });
14256
15208
  const deduplicator = createCallbackDeduplicator({ stateStore, clock });
14257
15209
  const usageAccumulator = createUsageAccumulator({ stateStore, clock });
15210
+ const metricSeries = createMetricSeriesStore({ stateStore, clock });
15211
+ const metricsPolicy = effectiveMetricsPolicy(options.config.exporter);
15212
+ const metricDestinations = exportDestinations.destinations.filter(
15213
+ (destination) => destination.metrics.enabled
15214
+ );
15215
+ const metricResource = resourceFromExporterPolicy(options.config.exporter);
14258
15216
  const deliveryRetentionMillis = options.deliveryRetentionMillis ?? lifecycleMaxAge;
14259
15217
  if (deliveryRetentionMillis < staleClaimMillis) {
14260
15218
  logger.warn("delivery retention is shorter than the stale-claim window", {
@@ -14266,6 +15224,7 @@ var createHookRuntime = (options) => {
14266
15224
  spanCorrelator,
14267
15225
  deduplicator,
14268
15226
  usageAccumulator,
15227
+ metricSeries,
14269
15228
  spanMaxAgeMillis: lifecycleMaxAge,
14270
15229
  dedupMaxAgeMillis: deliveryRetentionMillis,
14271
15230
  // The *effective* window, not the requested one: a sweep that considered a
@@ -14276,6 +15235,86 @@ var createHookRuntime = (options) => {
14276
15235
  });
14277
15236
  const deliveryLock = createAsyncLock();
14278
15237
  const stateDiagnostic = (thrown) => errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() });
15238
+ const generationStartsFor = async (events) => {
15239
+ const needed = events.some(
15240
+ (event3) => event3.type === "generation.end" && event3.durationMillis === void 0 && !events.some(
15241
+ (other) => other.type === "generation.start" && other.generationId === event3.generationId
15242
+ )
15243
+ );
15244
+ if (!needed) {
15245
+ return void 0;
15246
+ }
15247
+ try {
15248
+ const starts = /* @__PURE__ */ new Map();
15249
+ for (const correlation of await correlate(events)) {
15250
+ if (correlation.ref.family !== "generation" || correlation.startMillis === void 0) {
15251
+ continue;
15252
+ }
15253
+ const requestModel = correlation.attributes?.["gen_ai.request.model"];
15254
+ starts.set(correlation.ref.scopeKey, {
15255
+ startMillis: correlation.startMillis,
15256
+ ...typeof requestModel === "string" ? { requestModel } : {}
15257
+ });
15258
+ }
15259
+ return (generationId) => starts.get(generationId);
15260
+ } catch {
15261
+ return void 0;
15262
+ }
15263
+ };
15264
+ const recordMetrics = async (ingest, deliveryToken, diagnostics) => {
15265
+ if (metricDestinations.length === 0 || ingest.events.length === 0) {
15266
+ return void 0;
15267
+ }
15268
+ try {
15269
+ for (const event3 of ingest.events) {
15270
+ if (event3.type === "prompt.submitted") {
15271
+ await metricSeries.recordTurnStart(event3.sessionId, event3.occurredAt);
15272
+ }
15273
+ }
15274
+ const generationStarts = await generationStartsFor(ingest.events);
15275
+ const turnStarts = /* @__PURE__ */ new Map();
15276
+ for (const event3 of ingest.events) {
15277
+ if (event3.type === "generation.end" && !turnStarts.has(event3.sessionId)) {
15278
+ turnStarts.set(event3.sessionId, await metricSeries.readTurnStart(event3.sessionId));
15279
+ }
15280
+ }
15281
+ const observations = deriveMetricObservations({
15282
+ events: ingest.events,
15283
+ usage: ingest.usageObservations,
15284
+ resource: metricResource,
15285
+ includeSessionId: metricsPolicy.includeSessionId,
15286
+ ...generationStarts === void 0 ? {} : { generationStarts },
15287
+ turnStart: (sessionId) => turnStarts.get(sessionId)
15288
+ });
15289
+ if (observations.length === 0) {
15290
+ return void 0;
15291
+ }
15292
+ const points = metricsPolicy.temporality === "delta" ? aggregateDeltaPoints(observations, clock.now()) : await metricSeries.recordCumulative(observations, {
15293
+ perSession: metricsPolicy.includeSessionId,
15294
+ ...deliveryToken === void 0 ? {} : { deliveryToken }
15295
+ });
15296
+ const results = await Promise.all(
15297
+ metricDestinations.map(async (destination) => {
15298
+ const result = await destination.metrics.exportPoints(points).catch(
15299
+ (thrown) => ({
15300
+ accepted: 0,
15301
+ rejected: points.length,
15302
+ errors: [
15303
+ errorInfoFromThrown(thrown, { code: "telemetry-export-failure", phase: "export" })
15304
+ ]
15305
+ })
15306
+ );
15307
+ diagnostics.push(...result.errors);
15308
+ return { name: destination.name, accepted: result.accepted, rejected: result.rejected };
15309
+ })
15310
+ );
15311
+ return { points: points.length, destinations: results };
15312
+ } catch (thrown) {
15313
+ diagnostics.push(stateDiagnostic(thrown));
15314
+ logger.warn("hook-derived metrics could not be recorded for this callback", {});
15315
+ return void 0;
15316
+ }
15317
+ };
14279
15318
  const rollupDeliveryToken = (identity) => {
14280
15319
  const token = ids.newOpaqueId(["usage-delivery", identity.scope, identity.callbackId]).replace(/[^A-Za-z0-9_-]/g, "").slice(0, 128);
14281
15320
  return token.length === 0 ? void 0 : token;
@@ -14396,6 +15435,11 @@ var createHookRuntime = (options) => {
14396
15435
  identity === void 0 ? void 0 : rollupDeliveryToken(identity)
14397
15436
  );
14398
15437
  }
15438
+ const metrics = !duplicateDelivery && ingest.identity !== void 0 && isCommittable(ingest.durability) ? await recordMetrics(
15439
+ ingest,
15440
+ identity === void 0 ? void 0 : rollupDeliveryToken(identity),
15441
+ diagnostics
15442
+ ) : void 0;
14399
15443
  if (owned && identity !== void 0) {
14400
15444
  try {
14401
15445
  if (isCommittable(ingest.durability)) {
@@ -14462,6 +15506,7 @@ var createHookRuntime = (options) => {
14462
15506
  duplicateDelivery,
14463
15507
  delivery,
14464
15508
  usageRollups,
15509
+ ...metrics === void 0 ? {} : { metrics },
14465
15510
  ...cleanup === void 0 ? {} : { cleanup },
14466
15511
  diagnostics
14467
15512
  };
@@ -14478,12 +15523,20 @@ var createHookRuntime = (options) => {
14478
15523
  () => runProcess(input, identified.identity, report, diagnostics)
14479
15524
  );
14480
15525
  };
14481
- const snapshots = () => sink.health();
15526
+ const snapshots = () => [
15527
+ ...sink.health(),
15528
+ ...metricDestinations.map((destination) => destination.metrics.health())
15529
+ ];
14482
15530
  let shutdownReport;
14483
15531
  const shutdown = () => {
14484
15532
  shutdownReport ??= (async () => {
14485
15533
  const raced = await Promise.race([
14486
- hook.shutdown().then(() => "completed"),
15534
+ Promise.all([
15535
+ hook.shutdown(),
15536
+ // Metric sinks are not behind the hook's sink: they replay their own
15537
+ // spools here, inside the same bounded window.
15538
+ ...metricDestinations.map((destination) => destination.metrics.shutdown().catch(() => void 0))
15539
+ ]).then(() => "completed"),
14487
15540
  delay3(flushTimeoutMillis)
14488
15541
  ]);
14489
15542
  if (raced === "timeout") {
@@ -14513,6 +15566,7 @@ var createHookRuntime = (options) => {
14513
15566
  deduplicator,
14514
15567
  usageAccumulator,
14515
15568
  spanCorrelator,
15569
+ metricSeries,
14516
15570
  janitor,
14517
15571
  process: process_,
14518
15572
  shutdown,