@osfactory/otel-hook 0.10.0 → 0.12.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 (51) hide show
  1. package/README.md +108 -4
  2. package/dist/{adapter-B9RwW6TO.d.ts → adapter-DQiPu8xF.d.ts} +2 -2
  3. package/dist/cli.js +1495 -135
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +11 -4
  6. package/dist/config.js +116 -21
  7. package/dist/config.js.map +1 -1
  8. package/dist/{destinations-DWOkVxV1.d.ts → destinations-DvqsPulb.d.ts} +12 -2
  9. package/dist/diagnostics.d.ts +1 -1
  10. package/dist/diagnostics.js.map +1 -1
  11. package/dist/{events-CSD_YiJ2.d.ts → events-fcomX6d5.d.ts} +22 -0
  12. package/dist/{export-destinations-lORbe25J.d.ts → export-destinations-CI7z4n3i.d.ts} +136 -6
  13. package/dist/{filesystem-store-DX3dGIgu.d.ts → filesystem-store-CmnUlj1O.d.ts} +1 -1
  14. package/dist/{hook-BAxXoKsp.d.ts → hook-vM_cgqS2.d.ts} +11 -5
  15. package/dist/index.d.ts +16 -16
  16. package/dist/index.js +1496 -183
  17. package/dist/index.js.map +1 -1
  18. package/dist/install.d.ts +4 -4
  19. package/dist/install.js +9 -1
  20. package/dist/install.js.map +1 -1
  21. package/dist/integration.d.ts +36 -12
  22. package/dist/integration.js +1464 -231
  23. package/dist/integration.js.map +1 -1
  24. package/dist/lifecycle.d.ts +55 -4
  25. package/dist/lifecycle.js +279 -5
  26. package/dist/lifecycle.js.map +1 -1
  27. package/dist/{memory-aJilVG4R.d.ts → memory-DdU1U91y.d.ts} +2 -2
  28. package/dist/{semconv-Dw7gcQcg.d.ts → metric-model-C9lLqqpI.d.ts} +157 -2
  29. package/dist/model.d.ts +1 -1
  30. package/dist/model.js +9 -1
  31. package/dist/model.js.map +1 -1
  32. package/dist/{payload-D7gc0-WQ.d.ts → payload-BT19hiVZ.d.ts} +1 -1
  33. package/dist/{ports-plO5MKrY.d.ts → ports-C3k_5eOQ.d.ts} +57 -2
  34. package/dist/providers.d.ts +10 -10
  35. package/dist/providers.js +10 -1
  36. package/dist/providers.js.map +1 -1
  37. package/dist/{registry-C7XO4DzD.d.ts → registry-gyJqaWmp.d.ts} +2 -2
  38. package/dist/runtime.d.ts +97 -9
  39. package/dist/runtime.js +312 -33
  40. package/dist/runtime.js.map +1 -1
  41. package/dist/{schema-CHb3GU1r.d.ts → schema-SpFM6YQY.d.ts} +87 -1
  42. package/dist/state.d.ts +4 -4
  43. package/dist/state.js +32 -1
  44. package/dist/state.js.map +1 -1
  45. package/dist/telemetry.d.ts +6 -6
  46. package/dist/telemetry.js +929 -31
  47. package/dist/telemetry.js.map +1 -1
  48. package/dist/testing.d.ts +11 -9
  49. package/dist/testing.js +164 -33
  50. package/dist/testing.js.map +1 -1
  51. package/package.json +3 -1
package/dist/cli.js CHANGED
@@ -1,5 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ // src/cli/args.ts
4
+ import { isAbsolute } from "path";
5
+
3
6
  // src/config/resource-attributes.ts
4
7
  import { z as z3 } from "zod";
5
8
 
@@ -332,6 +335,9 @@ var VALUE_FLAGS = /* @__PURE__ */ new Set([
332
335
  "--installation-id",
333
336
  "--flush-timeout-ms",
334
337
  "--logs-endpoint",
338
+ "--metrics-endpoint",
339
+ "--metrics-temporality",
340
+ "--session-context-dir",
335
341
  "--max-input-bytes",
336
342
  "--scope",
337
343
  "--project-dir",
@@ -350,6 +356,9 @@ var BOOLEAN_FLAGS = /* @__PURE__ */ new Set([
350
356
  "--logs",
351
357
  "--no-logs",
352
358
  "--logs-content",
359
+ "--metrics",
360
+ "--no-metrics",
361
+ "--no-metrics-session-id",
353
362
  "--claude-transcript-usage",
354
363
  "--include-experimental",
355
364
  "--no-experimental",
@@ -515,6 +524,24 @@ var parsePolicy = (tokens, errors) => {
515
524
  if (tokens.booleans.has("--logs") && tokens.booleans.has("--no-logs")) {
516
525
  errors.push("flags --logs and --no-logs cannot both be given");
517
526
  }
527
+ const metricsEndpoint = single(tokens, "--metrics-endpoint", errors);
528
+ const metricsEnabled = tokens.booleans.has("--metrics") ? true : tokens.booleans.has("--no-metrics") ? false : void 0;
529
+ if (tokens.booleans.has("--metrics") && tokens.booleans.has("--no-metrics")) {
530
+ errors.push("flags --metrics and --no-metrics cannot both be given");
531
+ }
532
+ const metricsTemporalityRaw = single(tokens, "--metrics-temporality", errors);
533
+ let metricsTemporality;
534
+ if (metricsTemporalityRaw !== void 0) {
535
+ if (metricsTemporalityRaw === "cumulative" || metricsTemporalityRaw === "delta") {
536
+ metricsTemporality = metricsTemporalityRaw;
537
+ } else {
538
+ errors.push("flag --metrics-temporality must be cumulative or delta");
539
+ }
540
+ }
541
+ const sessionContextDir2 = single(tokens, "--session-context-dir", errors);
542
+ if (sessionContextDir2 !== void 0 && !isAbsolute(sessionContextDir2)) {
543
+ errors.push("flag --session-context-dir expects an absolute path");
544
+ }
518
545
  return {
519
546
  ...configFile === void 0 ? {} : { configFile },
520
547
  ...endpoint === void 0 ? {} : { endpoint },
@@ -535,7 +562,12 @@ var parsePolicy = (tokens, errors) => {
535
562
  ...logsEnabled === void 0 ? {} : { logsEnabled },
536
563
  ...logsEndpoint === void 0 ? {} : { logsEndpoint },
537
564
  ...tokens.booleans.has("--logs-content") ? { logsIncludeContent: true } : {},
538
- ...tokens.booleans.has("--claude-transcript-usage") ? { claudeTranscriptUsage: true } : {}
565
+ ...metricsEnabled === void 0 ? {} : { metricsEnabled },
566
+ ...metricsEndpoint === void 0 ? {} : { metricsEndpoint },
567
+ ...metricsTemporality === void 0 ? {} : { metricsTemporality },
568
+ ...tokens.booleans.has("--no-metrics-session-id") ? { metricsIncludeSessionId: false } : {},
569
+ ...tokens.booleans.has("--claude-transcript-usage") ? { claudeTranscriptUsage: true } : {},
570
+ ...sessionContextDir2 === void 0 || !isAbsolute(sessionContextDir2) ? {} : { sessionContextDir: sessionContextDir2 }
539
571
  };
540
572
  };
541
573
  var parseIdentity = (tokens, errors) => {
@@ -590,7 +622,13 @@ var RUN_FLAGS = /* @__PURE__ */ new Set([
590
622
  "--no-logs",
591
623
  "--logs-endpoint",
592
624
  "--logs-content",
625
+ "--metrics",
626
+ "--no-metrics",
627
+ "--metrics-endpoint",
628
+ "--metrics-temporality",
629
+ "--no-metrics-session-id",
593
630
  "--claude-transcript-usage",
631
+ "--session-context-dir",
594
632
  "--max-input-bytes",
595
633
  "--no-export",
596
634
  "--no-spool",
@@ -620,7 +658,13 @@ var DOCTOR_FLAGS = /* @__PURE__ */ new Set([
620
658
  "--no-logs",
621
659
  "--logs-endpoint",
622
660
  "--logs-content",
661
+ "--metrics",
662
+ "--no-metrics",
663
+ "--metrics-endpoint",
664
+ "--metrics-temporality",
665
+ "--no-metrics-session-id",
623
666
  "--claude-transcript-usage",
667
+ "--session-context-dir",
624
668
  "--include-experimental",
625
669
  "--no-experimental"
626
670
  ]);
@@ -865,10 +909,25 @@ Exporter and runtime policy (never identity):
865
909
  --logs-content permit disclosed content text in a log body. Needs
866
910
  --content-mode too: this decides whether the logs
867
911
  pipeline may carry what that one discloses
912
+ --metrics also export hook-derived OTLP metrics (off by
913
+ default): token usage, generation duration,
914
+ sessions, tool calls, provider-reported cost
915
+ --metrics-endpoint <url> OTLP HTTP/protobuf metrics endpoint; derived from
916
+ --endpoint when omitted (/v1/traces -> /v1/metrics)
917
+ --metrics-temporality <t> cumulative (default; running totals kept in the
918
+ state dir) | delta
919
+ --no-metrics-session-id leave session.id off metric points (fewer series)
868
920
  --claude-transcript-usage Claude Code only: at Stop, read the transcript the
869
921
  payload names (bounded) for the turn's model and
870
922
  summed token usage. Off by default; also
871
923
  OTEL_HOOK_CLAUDE_TRANSCRIPT_USAGE=1
924
+ --session-context-dir <dir>
925
+ absolute directory of session context files
926
+ (<dir>/<agent-tool>/<session-id>.json); the
927
+ attributes of the segment in force are put on
928
+ every span, log record and metric point. Overrides
929
+ sessionContext.dir in --config-file. No environment
930
+ variable, by design
872
931
  --max-input-bytes <n> stdin bound (default 1048576)
873
932
  --attr <key=value> opaque consumer attribute for this invocation,
874
933
  carried unchanged (not a resource attribute)
@@ -1170,10 +1229,17 @@ var errorInfoFromThrown = (thrown, input) => {
1170
1229
  var OTLP_ENDPOINT_VARIABLES = Object.freeze({
1171
1230
  generic: "OTEL_EXPORTER_OTLP_ENDPOINT",
1172
1231
  traces: "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
1173
- logs: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT"
1232
+ logs: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
1233
+ metrics: "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"
1174
1234
  });
1175
1235
  var OTLP_TRACES_PATH = "/v1/traces";
1176
1236
  var OTLP_LOGS_PATH = "/v1/logs";
1237
+ var OTLP_METRICS_PATH = "/v1/metrics";
1238
+ var SIGNAL_PATHS = Object.freeze({
1239
+ traces: OTLP_TRACES_PATH,
1240
+ logs: OTLP_LOGS_PATH,
1241
+ metrics: OTLP_METRICS_PATH
1242
+ });
1177
1243
  var withoutTrailingSlashes = (value) => {
1178
1244
  let end = value.length;
1179
1245
  while (end > 0 && value.charCodeAt(end - 1) === 47) {
@@ -1184,9 +1250,20 @@ var withoutTrailingSlashes = (value) => {
1184
1250
  var otlpSignalEndpointFromBase = (base, signal) => {
1185
1251
  const trimmed = withoutTrailingSlashes(base);
1186
1252
  if (trimmed.endsWith(OTLP_TRACES_PATH)) {
1187
- return signal === "traces" ? trimmed : `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${OTLP_LOGS_PATH}`;
1253
+ return signal === "traces" ? trimmed : `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${SIGNAL_PATHS[signal]}`;
1188
1254
  }
1189
- return `${trimmed}${signal === "traces" ? OTLP_TRACES_PATH : OTLP_LOGS_PATH}`;
1255
+ return `${trimmed}${SIGNAL_PATHS[signal]}`;
1256
+ };
1257
+ var siblingSignalEndpoint = (tracesEndpoint, signal) => {
1258
+ const trimmed = withoutTrailingSlashes(tracesEndpoint);
1259
+ const target = SIGNAL_PATHS[signal];
1260
+ if (trimmed.endsWith(target)) {
1261
+ return trimmed;
1262
+ }
1263
+ if (trimmed.endsWith(OTLP_TRACES_PATH)) {
1264
+ return `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${target}`;
1265
+ }
1266
+ return `${trimmed}${target}`;
1190
1267
  };
1191
1268
 
1192
1269
  // src/config/header-value.ts
@@ -1330,6 +1407,12 @@ var ENVIRONMENT_VARIABLES = Object.freeze({
1330
1407
  /** Standard per-signal endpoint; the weaker source of the two. */
1331
1408
  otlpLogsEndpoint: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
1332
1409
  logsIncludeContent: "OTEL_HOOK_LOGS_INCLUDE_CONTENT",
1410
+ metricsEnabled: "OTEL_HOOK_METRICS_ENABLED",
1411
+ metricsEndpoint: "OTEL_HOOK_METRICS_ENDPOINT",
1412
+ /** Standard per-signal endpoint; the weaker source of the two. */
1413
+ otlpMetricsEndpoint: "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT",
1414
+ /** Standard: `cumulative`, `delta`, or `lowmemory` (read as `delta` here). */
1415
+ otlpMetricsTemporality: "OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE",
1333
1416
  serviceName: "OTEL_HOOK_SERVICE_NAME",
1334
1417
  otlpServiceName: "OTEL_SERVICE_NAME",
1335
1418
  serviceNamespace: "OTEL_HOOK_SERVICE_NAMESPACE",
@@ -1492,6 +1575,22 @@ var parseEnvironmentConfig = (env) => {
1492
1575
  ...logsEndpoint === void 0 ? {} : { endpoint: logsEndpoint },
1493
1576
  ...logsIncludeContent === void 0 ? {} : { includeContent: logsIncludeContent }
1494
1577
  };
1578
+ const metricsEnabled = readBoolean(ENVIRONMENT_VARIABLES.metricsEnabled);
1579
+ const metricsEndpoint = readString(ENVIRONMENT_VARIABLES.metricsEndpoint) ?? readString(ENVIRONMENT_VARIABLES.otlpMetricsEndpoint) ?? (hookEndpoint === void 0 && otlpTracesEndpoint !== void 0 && otlpBaseEndpoint !== void 0 ? otlpSignalEndpointFromBase(otlpBaseEndpoint, "metrics") : void 0);
1580
+ const temporalityRaw = readString(ENVIRONMENT_VARIABLES.otlpMetricsTemporality)?.toLowerCase();
1581
+ let metricsTemporality;
1582
+ if (temporalityRaw === "cumulative") {
1583
+ metricsTemporality = "cumulative";
1584
+ } else if (temporalityRaw === "delta" || temporalityRaw === "lowmemory") {
1585
+ metricsTemporality = "delta";
1586
+ } else if (temporalityRaw !== void 0) {
1587
+ warn(ENVIRONMENT_VARIABLES.otlpMetricsTemporality, "expected cumulative, delta, or lowmemory");
1588
+ }
1589
+ const metrics = {
1590
+ ...metricsEnabled === void 0 ? {} : { enabled: metricsEnabled },
1591
+ ...metricsEndpoint === void 0 ? {} : { endpoint: metricsEndpoint },
1592
+ ...metricsTemporality === void 0 ? {} : { temporality: metricsTemporality }
1593
+ };
1495
1594
  const otlpHeaders = resolveOtlpHeaders(env);
1496
1595
  for (const { variable, detail } of otlpHeaders.warnings) {
1497
1596
  warn(variable, detail);
@@ -1506,7 +1605,8 @@ var parseEnvironmentConfig = (env) => {
1506
1605
  ...serviceName === void 0 ? {} : { serviceName },
1507
1606
  ...serviceNamespace === void 0 ? {} : { serviceNamespace },
1508
1607
  ...Object.keys(resourceAttributes).length === 0 ? {} : { resourceAttributes },
1509
- ...Object.keys(logs).length === 0 ? {} : { logs }
1608
+ ...Object.keys(logs).length === 0 ? {} : { logs },
1609
+ ...Object.keys(metrics).length === 0 ? {} : { metrics }
1510
1610
  };
1511
1611
  const limits = {
1512
1612
  ...maxStringLength === void 0 ? {} : { maxStringLength },
@@ -1547,7 +1647,7 @@ var HEADER_ENV_REFERENCE_PREFIX = "env:";
1547
1647
  var HEADER_NAME_PATTERN2 = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
1548
1648
  var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
1549
1649
  var MAX_HEADER_VALUE_LENGTH = 8192;
1550
- var exportSignalSchema = z6.enum(["traces", "logs"]);
1650
+ var exportSignalSchema = z6.enum(["traces", "logs", "metrics"]);
1551
1651
  var headerValueSchema = z6.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
1552
1652
  (value) => !isUnsafeHeaderValue(value),
1553
1653
  "header values may not contain line breaks, control characters, or characters beyond Latin-1"
@@ -1570,6 +1670,8 @@ var exportDestinationSchema = z6.strictObject({
1570
1670
  tracesEndpoint: endpointSchema.optional(),
1571
1671
  /** Per-signal override of the derived logs URL. */
1572
1672
  logsEndpoint: endpointSchema.optional(),
1673
+ /** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */
1674
+ metricsEndpoint: endpointSchema.optional(),
1573
1675
  /** Defaults to `exporter.protocol`. */
1574
1676
  protocol: z6.enum(["http/protobuf", "http/json", "none"]).optional(),
1575
1677
  /**
@@ -1582,15 +1684,17 @@ var exportDestinationSchema = z6.strictObject({
1582
1684
  `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
1583
1685
  ).optional(),
1584
1686
  /**
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.
1687
+ * Which signals this destination receives. Default: traces and logs. The logs
1688
+ * signal is still governed by `exporter.logs.enabled`, which stays the one
1689
+ * opt-in for content-bearing records leaving the host. `metrics` is never on by
1690
+ * default: a destination receives hook-derived metrics only when it lists them.
1588
1691
  */
1589
- signals: z6.array(exportSignalSchema).min(1).max(2).readonly().optional()
1692
+ signals: z6.array(exportSignalSchema).min(1).max(3).readonly().optional()
1590
1693
  }).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"
1694
+ (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
1695
+ "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
1593
1696
  );
1697
+ var DEFAULT_DESTINATION_SIGNALS = Object.freeze(["traces", "logs"]);
1594
1698
  var exportDestinationsSchema = z6.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
1595
1699
  const seen = /* @__PURE__ */ new Set();
1596
1700
  destinations.forEach((destination, index) => {
@@ -1635,7 +1739,8 @@ var legacyDestination = (exporter) => ({
1635
1739
  protocol: exporter.protocol,
1636
1740
  ...exporter.endpoint === void 0 ? {} : { endpoint: exporter.endpoint },
1637
1741
  ...exporter.logs.endpoint === void 0 ? {} : { logsEndpoint: exporter.logs.endpoint },
1638
- signals: { traces: true, logs: exporter.logs.enabled },
1742
+ ...exporter.metrics?.endpoint === void 0 ? {} : { metricsEndpoint: exporter.metrics.endpoint },
1743
+ signals: { traces: true, logs: exporter.logs.enabled, metrics: exporter.metrics?.enabled === true },
1639
1744
  headers: {}
1640
1745
  });
1641
1746
  var hasConfiguredDestinations = (exporter) => exporter.destinations !== void 0 && exporter.destinations.length > 0;
@@ -1644,14 +1749,14 @@ var resolveExportDestinations = (exporter) => {
1644
1749
  return [legacyDestination(exporter)];
1645
1750
  }
1646
1751
  const resolved = [];
1647
- if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0) {
1752
+ if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0 || exporter.metrics?.endpoint !== void 0) {
1648
1753
  resolved.push(legacyDestination(exporter));
1649
1754
  }
1650
1755
  for (const destination of exporter.destinations ?? []) {
1651
1756
  if (destination.enabled === false) {
1652
1757
  continue;
1653
1758
  }
1654
- const signals = destination.signals ?? exportSignalSchema.options;
1759
+ const signals = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;
1655
1760
  resolved.push({
1656
1761
  name: destination.name,
1657
1762
  source: "destinations",
@@ -1659,9 +1764,11 @@ var resolveExportDestinations = (exporter) => {
1659
1764
  ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
1660
1765
  ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
1661
1766
  ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
1767
+ ...destination.metricsEndpoint === void 0 ? {} : { metricsEndpoint: destination.metricsEndpoint },
1662
1768
  signals: {
1663
1769
  traces: signals.includes("traces"),
1664
- logs: exporter.logs.enabled && signals.includes("logs")
1770
+ logs: exporter.logs.enabled && signals.includes("logs"),
1771
+ metrics: signals.includes("metrics")
1665
1772
  },
1666
1773
  headers: { ...destination.headers ?? {} }
1667
1774
  });
@@ -1703,6 +1810,9 @@ var describeExportDestinations = (exporter) => {
1703
1810
  const logsOrigin = endpointOrigin(
1704
1811
  destination.logsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint
1705
1812
  );
1813
+ const metricsOrigin = endpointOrigin(
1814
+ destination.metricsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint
1815
+ );
1706
1816
  const variables = Object.values(destination.headers).map(parseHeaderValueReference).flatMap((reference) => reference.kind === "env" ? [reference.variable] : []);
1707
1817
  return {
1708
1818
  name: destination.name,
@@ -1711,6 +1821,7 @@ var describeExportDestinations = (exporter) => {
1711
1821
  signals: exportSignalSchema.options.filter((signal) => destination.signals[signal]),
1712
1822
  ...tracesOrigin === void 0 || !destination.signals.traces ? {} : { tracesEndpointOrigin: tracesOrigin },
1713
1823
  ...logsOrigin === void 0 || !destination.signals.logs ? {} : { logsEndpointOrigin: logsOrigin },
1824
+ ...metricsOrigin === void 0 || !destination.signals.metrics ? {} : { metricsEndpointOrigin: metricsOrigin },
1714
1825
  headerNames: destination.source === "exporter" ? [...exporter.headerNames].sort() : Object.keys(destination.headers).sort(),
1715
1826
  headerVariables: [...new Set(variables)].sort()
1716
1827
  };
@@ -1725,7 +1836,7 @@ var describeExportDestinations = (exporter) => {
1725
1836
  source: "destinations",
1726
1837
  protocol: destination.protocol ?? exporter.protocol,
1727
1838
  ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
1728
- signals: { traces: false, logs: false },
1839
+ signals: { traces: false, logs: false, metrics: false },
1729
1840
  headers: { ...destination.headers ?? {} }
1730
1841
  },
1731
1842
  false
@@ -1735,6 +1846,7 @@ var describeExportDestinations = (exporter) => {
1735
1846
  };
1736
1847
 
1737
1848
  // src/config/schema.ts
1849
+ import { isAbsolute as isAbsolute2 } from "path";
1738
1850
  import { z as z7 } from "zod";
1739
1851
  var logsPolicySchema = z7.strictObject({
1740
1852
  enabled: z7.boolean(),
@@ -1753,6 +1865,18 @@ var DEFAULT_LOGS_POLICY = Object.freeze({
1753
1865
  includeContent: false,
1754
1866
  maxBatchSize: 128
1755
1867
  });
1868
+ var metricsPolicySchema = z7.strictObject({
1869
+ enabled: z7.boolean(),
1870
+ /** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */
1871
+ endpoint: z7.string().url().max(2048).optional(),
1872
+ temporality: z7.enum(["cumulative", "delta"]),
1873
+ includeSessionId: z7.boolean()
1874
+ });
1875
+ var DEFAULT_METRICS_POLICY = Object.freeze({
1876
+ enabled: false,
1877
+ temporality: "cumulative",
1878
+ includeSessionId: true
1879
+ });
1756
1880
  var exporterPolicySchema = z7.strictObject({
1757
1881
  enabled: z7.boolean(),
1758
1882
  protocol: z7.enum(["http/protobuf", "http/json", "none"]),
@@ -1783,6 +1907,11 @@ var exporterPolicySchema = z7.strictObject({
1783
1907
  * a second top-level section would invite two of each to drift apart.
1784
1908
  */
1785
1909
  logs: logsPolicySchema,
1910
+ /**
1911
+ * Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before
1912
+ * metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.
1913
+ */
1914
+ metrics: metricsPolicySchema.optional(),
1786
1915
  /**
1787
1916
  * Additional OTLP destinations, each sent every batch in parallel.
1788
1917
  *
@@ -1819,20 +1948,27 @@ var providersPolicySchema = z7.strictObject({
1819
1948
  readTranscriptUsage: z7.boolean()
1820
1949
  }).optional()
1821
1950
  });
1951
+ var sessionContextPolicySchema = z7.strictObject({
1952
+ /** Absolute path of the context directory. */
1953
+ dir: z7.string().min(1).max(4096).refine((value) => isAbsolute2(value), { message: "must be an absolute path" })
1954
+ });
1822
1955
  var otelHookConfigSchema = z7.strictObject({
1823
1956
  exporter: exporterPolicySchema,
1824
1957
  privacy: privacyPolicySchema,
1825
1958
  detection: detectionPolicySchema,
1826
1959
  diagnostics: diagnosticsPolicySchema,
1827
1960
  /** Optional so a hand-built configuration from before it existed stays valid. */
1828
- providers: providersPolicySchema.optional()
1961
+ providers: providersPolicySchema.optional(),
1962
+ /** Optional: absent means no session context is read. */
1963
+ sessionContext: sessionContextPolicySchema.optional()
1829
1964
  });
1830
1965
  var otelHookConfigPatchSchema = z7.strictObject({
1831
1966
  // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
1832
1967
  // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
1833
1968
  // without also restating the endpoint and the batch size.
1834
- exporter: exporterPolicySchema.omit({ logs: true, spool: true }).partial().extend({
1969
+ exporter: exporterPolicySchema.omit({ logs: true, metrics: true, spool: true }).partial().extend({
1835
1970
  logs: logsPolicySchema.partial().optional(),
1971
+ metrics: metricsPolicySchema.partial().optional(),
1836
1972
  spool: spoolPolicySchema.partial().optional()
1837
1973
  }).optional(),
1838
1974
  privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
@@ -1840,7 +1976,8 @@ var otelHookConfigPatchSchema = z7.strictObject({
1840
1976
  diagnostics: diagnosticsPolicySchema.partial().optional(),
1841
1977
  providers: z7.strictObject({
1842
1978
  claudeCode: z7.strictObject({ readTranscriptUsage: z7.boolean() }).partial().optional()
1843
- }).partial().optional()
1979
+ }).partial().optional(),
1980
+ sessionContext: sessionContextPolicySchema.partial().optional()
1844
1981
  });
1845
1982
  var DEFAULT_EXPORTER_POLICY = Object.freeze({
1846
1983
  enabled: true,
@@ -1852,7 +1989,8 @@ var DEFAULT_EXPORTER_POLICY = Object.freeze({
1852
1989
  maxRetryAttempts: 2,
1853
1990
  serviceName: "coding-agent",
1854
1991
  resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
1855
- logs: DEFAULT_LOGS_POLICY
1992
+ logs: DEFAULT_LOGS_POLICY,
1993
+ metrics: DEFAULT_METRICS_POLICY
1856
1994
  });
1857
1995
  var DEFAULT_DETECTION_POLICY = Object.freeze({
1858
1996
  minimumConfidence: "strong",
@@ -1874,17 +2012,22 @@ var DEFAULT_CONFIG = Object.freeze({
1874
2012
  providers: DEFAULT_PROVIDERS_POLICY
1875
2013
  });
1876
2014
  var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
2015
+ var sessionContextDir = (config) => config.sessionContext?.dir;
2016
+ var effectiveMetricsPolicy = (exporter) => ({
2017
+ ...DEFAULT_METRICS_POLICY,
2018
+ ...exporter.metrics ?? {}
2019
+ });
1877
2020
 
1878
2021
  // src/config/resolve.ts
1879
2022
  var CONFIG_SOURCE_PRECEDENCE = ["defaults", "file", "environment", "inline-override"];
1880
2023
  var configSourceSchema = z8.enum(CONFIG_SOURCE_PRECEDENCE);
1881
2024
  var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1882
- var mergeLeaf = (target, patch, source, provenance, path14) => {
2025
+ var mergeLeaf = (target, patch, source, provenance, path15) => {
1883
2026
  for (const [key, value] of Object.entries(patch)) {
1884
2027
  if (value === void 0) {
1885
2028
  continue;
1886
2029
  }
1887
- const childPath = path14 === "" ? key : `${path14}.${key}`;
2030
+ const childPath = path15 === "" ? key : `${path15}.${key}`;
1888
2031
  const existing = target[key];
1889
2032
  if (isPlainObject(value) && (isPlainObject(existing) || existing === void 0)) {
1890
2033
  const child = { ...existing ?? {} };
@@ -1898,14 +2041,14 @@ var mergeLeaf = (target, patch, source, provenance, path14) => {
1898
2041
  };
1899
2042
  var initialProvenance = (config) => {
1900
2043
  const provenance = {};
1901
- const walk = (value, path14) => {
2044
+ const walk = (value, path15) => {
1902
2045
  if (isPlainObject(value)) {
1903
2046
  for (const [key, child] of Object.entries(value)) {
1904
- walk(child, path14 === "" ? key : `${path14}.${key}`);
2047
+ walk(child, path15 === "" ? key : `${path15}.${key}`);
1905
2048
  }
1906
2049
  return;
1907
2050
  }
1908
- provenance[path14] = "defaults";
2051
+ provenance[path15] = "defaults";
1909
2052
  };
1910
2053
  walk(config, "");
1911
2054
  return provenance;
@@ -1984,6 +2127,11 @@ var resolveConfig = (layers = []) => {
1984
2127
  "exporter.logs.enabled is true but neither a logs endpoint nor a trace endpoint to derive one from is configured"
1985
2128
  );
1986
2129
  }
2130
+ if (!withDestinations && parsed.data.exporter.metrics?.enabled === true && parsed.data.exporter.metrics.endpoint === void 0 && parsed.data.exporter.endpoint === void 0) {
2131
+ notes.push(
2132
+ "exporter.metrics.enabled is true but neither a metrics endpoint nor a trace endpoint to derive one from is configured"
2133
+ );
2134
+ }
1987
2135
  if (parsed.data.exporter.logs.includeContent && parsed.data.privacy.contentMode === "omit") {
1988
2136
  notes.push(
1989
2137
  "exporter.logs.includeContent is true but privacy.contentMode is omit, so no content is disclosed to describe"
@@ -2015,6 +2163,9 @@ var describeDestinationAttributes = (config) => {
2015
2163
  if (destination.logsEndpointOrigin !== void 0) {
2016
2164
  attributes[`${prefix}.logs_endpoint_origin`] = destination.logsEndpointOrigin;
2017
2165
  }
2166
+ if (destination.metricsEndpointOrigin !== void 0) {
2167
+ attributes[`${prefix}.metrics_endpoint_origin`] = destination.metricsEndpointOrigin;
2168
+ }
2018
2169
  attributes[`${prefix}.header_names`] = [...destination.headerNames];
2019
2170
  attributes[`${prefix}.header_variables`] = [...destination.headerVariables];
2020
2171
  }
@@ -2033,6 +2184,8 @@ var describeResolvedConfig = (config) => {
2033
2184
  };
2034
2185
  const endpointOrigin2 = originOf(config.exporter.endpoint);
2035
2186
  const logsEndpointOrigin = originOf(config.exporter.logs.endpoint);
2187
+ const metrics = effectiveMetricsPolicy(config.exporter);
2188
+ const metricsEndpointOrigin = originOf(metrics.endpoint);
2036
2189
  return {
2037
2190
  "exporter.enabled": config.exporter.enabled,
2038
2191
  "exporter.protocol": config.exporter.protocol,
@@ -2041,6 +2194,10 @@ var describeResolvedConfig = (config) => {
2041
2194
  "exporter.logs_include_content": config.exporter.logs.includeContent,
2042
2195
  "exporter.logs_max_batch_size": config.exporter.logs.maxBatchSize,
2043
2196
  ...logsEndpointOrigin === void 0 ? {} : { "exporter.logs_endpoint_origin": logsEndpointOrigin },
2197
+ "exporter.metrics_enabled": metrics.enabled,
2198
+ "exporter.metrics_temporality": metrics.temporality,
2199
+ "exporter.metrics_include_session_id": metrics.includeSessionId,
2200
+ ...metricsEndpointOrigin === void 0 ? {} : { "exporter.metrics_endpoint_origin": metricsEndpointOrigin },
2044
2201
  "exporter.header_names": [...config.exporter.headerNames],
2045
2202
  // Names only. A resource attribute *name* is already on the wire in every
2046
2203
  // exported resource, so disclosing it here adds nothing; a *value* may hold
@@ -2062,7 +2219,9 @@ var describeResolvedConfig = (config) => {
2062
2219
  "detection.minimum_confidence": config.detection.minimumConfidence,
2063
2220
  "detection.allow_ambiguous_fallback": config.detection.allowAmbiguousFallback,
2064
2221
  "diagnostics.log_level": config.diagnostics.logLevel,
2065
- "diagnostics.emit_error_events": config.diagnostics.emitErrorEvents
2222
+ "diagnostics.emit_error_events": config.diagnostics.emitErrorEvents,
2223
+ // Whether, never where: the directory is a local path.
2224
+ "session_context.enabled": config.sessionContext?.dir !== void 0
2066
2225
  };
2067
2226
  };
2068
2227
 
@@ -2632,7 +2791,15 @@ var baseEventFields = {
2632
2791
  * factory, never by hand.
2633
2792
  */
2634
2793
  subagentId: subagentIdSchema.optional(),
2635
- extensions: extensionsSchema.default(emptyExtensions)
2794
+ extensions: extensionsSchema.default(emptyExtensions),
2795
+ /**
2796
+ * Attributes of the session context segment in force when the event
2797
+ * occurred (`docs/session-context.md`), stamped by the core from a file a
2798
+ * harness wrote. Exported on every record of the event, over the same keys
2799
+ * from the Resource. Absent when no context applies. Set by the core only,
2800
+ * never by an adapter.
2801
+ */
2802
+ contextAttributes: z15.record(z15.string().min(1).max(255), z15.union([z15.string(), z15.number(), z15.boolean()])).optional()
2636
2803
  };
2637
2804
  var event = (shape) => z15.strictObject({ ...baseEventFields, ...shape });
2638
2805
  var sessionStartEventSchema = event({
@@ -2809,6 +2976,29 @@ var stateValueSchema = z16.discriminatedUnion("kind", [
2809
2976
  * (Claude Code's transcript), so the next read starts where the last ended.
2810
2977
  * `source` is an opaque digest of what was read, never a path.
2811
2978
  */
2979
+ /**
2980
+ * Running state of one metric series (issue #69), so a cumulative data point
2981
+ * exported by a later hook process continues the same total. Holds numbers and
2982
+ * a series digest only; the series' attributes are re-supplied by the caller
2983
+ * and never read back from disk.
2984
+ */
2985
+ z16.strictObject({
2986
+ kind: z16.literal("metric-series"),
2987
+ /** Start of the cumulative interval. */
2988
+ startTimeMillis: epochMillisSchema,
2989
+ /** Counters: the running total. */
2990
+ value: z16.number().finite().min(0).optional(),
2991
+ /** Histograms: the running aggregation. */
2992
+ histogram: z16.strictObject({
2993
+ count: z16.number().int().min(0),
2994
+ sum: z16.number().finite().min(0),
2995
+ min: z16.number().finite(),
2996
+ max: z16.number().finite(),
2997
+ bucketCounts: z16.array(z16.number().int().min(0)).max(64)
2998
+ }).optional(),
2999
+ /** Opaque digest of the last delivery folded in; makes a replay a no-op. */
3000
+ appliedDelivery: z16.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional()
3001
+ }),
2812
3002
  z16.strictObject({
2813
3003
  kind: z16.literal("read-cursor"),
2814
3004
  source: z16.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
@@ -2908,6 +3098,12 @@ var policyFlagsToPatch = (policy) => {
2908
3098
  ...policy.logsEndpoint === void 0 ? {} : { endpoint: policy.logsEndpoint },
2909
3099
  ...policy.logsIncludeContent === void 0 ? {} : { includeContent: policy.logsIncludeContent }
2910
3100
  };
3101
+ const metrics = {
3102
+ ...policy.metricsEnabled === void 0 ? {} : { enabled: policy.metricsEnabled },
3103
+ ...policy.metricsEndpoint === void 0 ? {} : { endpoint: policy.metricsEndpoint },
3104
+ ...policy.metricsTemporality === void 0 ? {} : { temporality: policy.metricsTemporality },
3105
+ ...policy.metricsIncludeSessionId === void 0 ? {} : { includeSessionId: policy.metricsIncludeSessionId }
3106
+ };
2911
3107
  const exporter = {
2912
3108
  ...policy.exportDisabled === true ? { enabled: false } : {},
2913
3109
  ...policy.endpoint === void 0 ? {} : { endpoint: policy.endpoint },
@@ -2923,7 +3119,8 @@ var policyFlagsToPatch = (policy) => {
2923
3119
  // value they are exported on every span by design, so there is nothing to
2924
3120
  // keep out of the snapshot. The snapshot still reports names only.
2925
3121
  ...Object.keys(policy.resourceAttributes).length === 0 ? {} : { resourceAttributes: policy.resourceAttributes },
2926
- ...Object.keys(logs).length === 0 ? {} : { logs }
3122
+ ...Object.keys(logs).length === 0 ? {} : { logs },
3123
+ ...Object.keys(metrics).length === 0 ? {} : { metrics }
2927
3124
  };
2928
3125
  const privacy = policy.contentMode === void 0 ? {} : { contentMode: policy.contentMode };
2929
3126
  const diagnostics = policy.logLevel === void 0 ? {} : { logLevel: policy.logLevel };
@@ -2931,7 +3128,8 @@ var policyFlagsToPatch = (policy) => {
2931
3128
  ...Object.keys(exporter).length === 0 ? {} : { exporter },
2932
3129
  ...Object.keys(privacy).length === 0 ? {} : { privacy },
2933
3130
  ...Object.keys(diagnostics).length === 0 ? {} : { diagnostics },
2934
- ...policy.claudeTranscriptUsage === true ? { providers: { claudeCode: { readTranscriptUsage: true } } } : {}
3131
+ ...policy.claudeTranscriptUsage === true ? { providers: { claudeCode: { readTranscriptUsage: true } } } : {},
3132
+ ...policy.sessionContextDir === void 0 ? {} : { sessionContext: { dir: policy.sessionContextDir } }
2935
3133
  };
2936
3134
  };
2937
3135
  var resolveCliExporterHeaders = (policy, io) => {
@@ -3020,7 +3218,7 @@ var createCliLogger = (io, level) => createStderrLogger({
3020
3218
  var readIdentityFile = readJsonFile;
3021
3219
 
3022
3220
  // src/cli/doctor.ts
3023
- import { readdir as readdir3 } from "fs/promises";
3221
+ import { readdir as readdir3, stat as stat2 } from "fs/promises";
3024
3222
  import * as path4 from "path";
3025
3223
 
3026
3224
  // src/diagnostics/health.ts
@@ -3285,11 +3483,11 @@ var createPrivacyService = (policyInput) => {
3285
3483
  };
3286
3484
  const flattenToAttributes = (value, prefix) => {
3287
3485
  const attributes = {};
3288
- const walk = (current, path14) => {
3486
+ const walk = (current, path15) => {
3289
3487
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
3290
3488
  const primitive = toAttributePrimitive(current);
3291
3489
  if (primitive !== void 0) {
3292
- attributes[path14] = primitive;
3490
+ attributes[path15] = primitive;
3293
3491
  }
3294
3492
  return;
3295
3493
  }
@@ -3308,16 +3506,16 @@ var createPrivacyService = (policyInput) => {
3308
3506
  primitives.push(entryPrimitive);
3309
3507
  }
3310
3508
  if (uniform) {
3311
- attributes[path14] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
3509
+ attributes[path15] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
3312
3510
  return;
3313
3511
  }
3314
3512
  for (const [index, entry] of current.entries()) {
3315
- walk(entry, `${path14}.${index}`);
3513
+ walk(entry, `${path15}.${index}`);
3316
3514
  }
3317
3515
  return;
3318
3516
  }
3319
3517
  for (const [key, entry] of Object.entries(current)) {
3320
- walk(entry, path14 === "" ? key : `${path14}.${key}`);
3518
+ walk(entry, path15 === "" ? key : `${path15}.${key}`);
3321
3519
  }
3322
3520
  };
3323
3521
  walk(value, prefix);
@@ -3617,6 +3815,7 @@ var createEventFactory = (input) => {
3617
3815
  const rest = { ...drafted };
3618
3816
  delete rest.target;
3619
3817
  delete rest.subagentId;
3818
+ delete rest.contextAttributes;
3620
3819
  const sanitized = extensions === void 0 ? { extensions: {}, droppedKeys: [] } : context.privacy.sanitizeExtensions(extensions);
3621
3820
  dropped.push(...sanitized.droppedKeys);
3622
3821
  const currentSequence = sequence;
@@ -8348,6 +8547,33 @@ var replayResource = (attributes, policy) => {
8348
8547
  }
8349
8548
  return resourceFromAttributes(safe);
8350
8549
  };
8550
+ var agreedContextAttributes = (events) => {
8551
+ const [first, ...rest] = events;
8552
+ if (first?.contextAttributes === void 0) {
8553
+ return {};
8554
+ }
8555
+ const agreed = { ...first.contextAttributes };
8556
+ for (const event3 of rest) {
8557
+ for (const key of Object.keys(agreed)) {
8558
+ if (event3.contextAttributes?.[key] !== agreed[key]) {
8559
+ delete agreed[key];
8560
+ }
8561
+ }
8562
+ }
8563
+ return agreed;
8564
+ };
8565
+ var resourceWithContext = (resource, context) => {
8566
+ const overrides = {};
8567
+ for (const [key, value] of Object.entries(context)) {
8568
+ if (Object.hasOwn(resource.attributes, key) && !isReservedResourceAttributeKey(key) && resource.attributes[key] !== value) {
8569
+ overrides[key] = value;
8570
+ }
8571
+ }
8572
+ if (Object.keys(overrides).length === 0) {
8573
+ return resource;
8574
+ }
8575
+ return resourceFromAttributes({ ...resource.attributes, ...overrides });
8576
+ };
8351
8577
 
8352
8578
  // src/telemetry/log-records.ts
8353
8579
  import { SeverityNumber, TraceFlags as TraceFlags2 } from "@opentelemetry/api";
@@ -8417,6 +8643,11 @@ var passthroughResourceAttributes = (resource) => {
8417
8643
  }
8418
8644
  return attributes;
8419
8645
  };
8646
+ var contextAttributesOf = (event3) => event3.contextAttributes === void 0 ? {} : { ...event3.contextAttributes };
8647
+ var profileAttributes = (event3, resource) => ({
8648
+ ...passthroughResourceAttributes(resource),
8649
+ ...contextAttributesOf(event3)
8650
+ });
8420
8651
  var resolveExportedSessionId = (eventSessionId, resource) => {
8421
8652
  for (const key of EXTERNAL_SESSION_KEY_ATTRIBUTES) {
8422
8653
  const supplied = resource.attributes[key];
@@ -8437,6 +8668,8 @@ var hexTraceAttributes = (ids) => ({
8437
8668
  var exportIdentityAttributes = (event3, resource, ids) => {
8438
8669
  const { sessionId, providerSessionId } = resolveExportedSessionId(event3.sessionId, resource);
8439
8670
  return {
8671
+ // First, so nothing in the profile layer can replace an identity attribute.
8672
+ ...profileAttributes(event3, resource),
8440
8673
  [ATTR_SESSION_ID]: sessionId,
8441
8674
  [ATTR_OTELHOOK_SESSION_ID]: providerSessionId,
8442
8675
  [ATTR_GEN_AI_CONVERSATION_ID]: providerSessionId,
@@ -8445,7 +8678,6 @@ var exportIdentityAttributes = (event3, resource, ids) => {
8445
8678
  ...event3.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event3.provenance.providerVersion },
8446
8679
  [ATTR_OTELHOOK_WORKSPACE_ID]: event3.workspace.workspaceId,
8447
8680
  ...event3.subagentId === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event3.subagentId },
8448
- ...passthroughResourceAttributes(resource),
8449
8681
  ...hexTraceAttributes(ids)
8450
8682
  };
8451
8683
  };
@@ -8470,7 +8702,7 @@ import {
8470
8702
  } from "@opentelemetry/semantic-conventions/incubating";
8471
8703
 
8472
8704
  // src/version.ts
8473
- var VERSION = "0.10.0";
8705
+ var VERSION = "0.12.0";
8474
8706
 
8475
8707
  // src/telemetry/semconv.ts
8476
8708
  var SCOPE_NAME = "@osfactory/otel-hook";
@@ -8618,12 +8850,12 @@ var pickTarget = (attributes) => {
8618
8850
  }
8619
8851
  return picked;
8620
8852
  };
8621
- var withoutTarget = (attributes, resource) => {
8853
+ var withoutTarget = (attributes, resource, event3) => {
8622
8854
  const rest = { ...attributes };
8623
8855
  for (const key of TARGET_KEYS) {
8624
8856
  delete rest[key];
8625
8857
  }
8626
- return { ...rest, ...pickTarget(passthroughResourceAttributes(resource)) };
8858
+ return { ...rest, ...pickTarget(profileAttributes(event3, resource)) };
8627
8859
  };
8628
8860
  var rankOf = (candidate) => {
8629
8861
  const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];
@@ -8728,7 +8960,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
8728
8960
  name = "session";
8729
8961
  kind = SpanKind.INTERNAL;
8730
8962
  attributes = {
8731
- ...withoutTarget(attributes, resource),
8963
+ ...withoutTarget(attributes, resource, anchor),
8732
8964
  ...strongestTarget([pickTarget(resolved.recovered), start === void 0 ? {} : targetAttributes(start)]),
8733
8965
  ...start?.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName },
8734
8966
  ...start?.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion },
@@ -8770,7 +9002,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
8770
9002
  kind = SpanKind.CLIENT;
8771
9003
  attributes = {
8772
9004
  // Target keys are re-chosen below as one unit, never mixed across edges.
8773
- ...withoutTarget(attributes, resource),
9005
+ ...withoutTarget(attributes, resource, anchor),
8774
9006
  [ATTR_GEN_AI_TOOL_NAME]: toolName,
8775
9007
  [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,
8776
9008
  ...start?.toolKind === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind },
@@ -9500,10 +9732,10 @@ var createOtlpLogSink = (options) => {
9500
9732
  const exportRecords = (records) => new Promise((resolve8) => {
9501
9733
  exporter.export([...records], (result) => resolve8(result));
9502
9734
  });
9503
- const toSpoolBatch = (records) => ({
9735
+ const toSpoolBatch = (records, batchResource) => ({
9504
9736
  providerId: options.providerId,
9505
9737
  installationId: options.installationId,
9506
- resourceAttributes: { ...resource.attributes },
9738
+ resourceAttributes: { ...batchResource.attributes },
9507
9739
  instrumentationScope: {
9508
9740
  name: scope.name,
9509
9741
  ...scope.version === void 0 ? {} : { version: scope.version }
@@ -9538,8 +9770,9 @@ var createOtlpLogSink = (options) => {
9538
9770
  return { accepted: 0, rejected: 0, errors: [] };
9539
9771
  }
9540
9772
  const resolved = await resolveCorrelations(events);
9773
+ const batchResource = resourceWithContext(resource, agreedContextAttributes(events));
9541
9774
  const mapped = canonicalEventsToLogRecords(events, {
9542
- resource,
9775
+ resource: batchResource,
9543
9776
  instrumentationScope: scope,
9544
9777
  content,
9545
9778
  correlations: resolved.correlations,
@@ -9574,7 +9807,7 @@ var createOtlpLogSink = (options) => {
9574
9807
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
9575
9808
  const permanent = isPermanentExportFailure(result);
9576
9809
  if (options.spool !== void 0 && !permanent) {
9577
- const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
9810
+ const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({
9578
9811
  spooled: false,
9579
9812
  reason: "capacity-exceeded"
9580
9813
  }));
@@ -9727,10 +9960,10 @@ var createOtlpTraceSink = (options) => {
9727
9960
  const exportSpans = (spans) => new Promise((resolve8) => {
9728
9961
  exporter.export([...spans], (result) => resolve8(result));
9729
9962
  });
9730
- const toSpoolBatch = (spans) => ({
9963
+ const toSpoolBatch = (spans, batchResource) => ({
9731
9964
  providerId: options.providerId,
9732
9965
  installationId: options.installationId,
9733
- resourceAttributes: { ...resource.attributes },
9966
+ resourceAttributes: { ...batchResource.attributes },
9734
9967
  instrumentationScope: { name: scope.name, ...scope.version === void 0 ? {} : { version: scope.version } },
9735
9968
  spans: spans.map(serializeSpan),
9736
9969
  enqueuedAt: options.clock.now()
@@ -9760,8 +9993,9 @@ var createOtlpTraceSink = (options) => {
9760
9993
  return { accepted: 0, rejected: 0, errors: [] };
9761
9994
  }
9762
9995
  const resolved = await resolveCorrelations(events);
9996
+ const batchResource = resourceWithContext(resource, agreedContextAttributes(events));
9763
9997
  const spans = canonicalEventsToReadableSpans(events, {
9764
- resource,
9998
+ resource: batchResource,
9765
9999
  instrumentationScope: scope,
9766
10000
  correlations: resolved.correlations,
9767
10001
  ...resolved.available === void 0 ? {} : { correlationAvailable: resolved.available }
@@ -9787,7 +10021,7 @@ var createOtlpTraceSink = (options) => {
9787
10021
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
9788
10022
  const permanent = isPermanentExportFailure(result);
9789
10023
  if (options.spool !== void 0 && !permanent) {
9790
- const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
10024
+ const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({
9791
10025
  spooled: false,
9792
10026
  reason: "capacity-exceeded"
9793
10027
  }));
@@ -9849,6 +10083,624 @@ var createOtlpTraceSink = (options) => {
9849
10083
  };
9850
10084
  };
9851
10085
 
10086
+ // src/telemetry/metric-model.ts
10087
+ var TOKEN_USAGE_BUCKETS = Object.freeze([
10088
+ 1,
10089
+ 4,
10090
+ 16,
10091
+ 64,
10092
+ 256,
10093
+ 1024,
10094
+ 4096,
10095
+ 16384,
10096
+ 65536,
10097
+ 262144,
10098
+ 1048576,
10099
+ 4194304,
10100
+ 16777216,
10101
+ 67108864
10102
+ ]);
10103
+ var OPERATION_DURATION_BUCKETS = Object.freeze([
10104
+ 0.01,
10105
+ 0.02,
10106
+ 0.04,
10107
+ 0.08,
10108
+ 0.16,
10109
+ 0.32,
10110
+ 0.64,
10111
+ 1.28,
10112
+ 2.56,
10113
+ 5.12,
10114
+ 10.24,
10115
+ 20.48,
10116
+ 40.96,
10117
+ 81.92
10118
+ ]);
10119
+ var METRIC_TOKEN_USAGE = "gen_ai.client.token.usage";
10120
+ var METRIC_OPERATION_DURATION = "gen_ai.client.operation.duration";
10121
+ var METRIC_SESSIONS = "otelhook.sessions";
10122
+ var METRIC_TOOL_CALLS = "otelhook.tool.calls";
10123
+ var METRIC_COST_USAGE = "otelhook.cost.usage";
10124
+ var METRIC_INSTRUMENTS = Object.freeze({
10125
+ [METRIC_TOKEN_USAGE]: {
10126
+ name: METRIC_TOKEN_USAGE,
10127
+ kind: "histogram",
10128
+ unit: "{token}",
10129
+ description: "Tokens used per generation, by token type (hook-derived)",
10130
+ valueType: "int",
10131
+ boundaries: TOKEN_USAGE_BUCKETS
10132
+ },
10133
+ [METRIC_OPERATION_DURATION]: {
10134
+ name: METRIC_OPERATION_DURATION,
10135
+ kind: "histogram",
10136
+ unit: "s",
10137
+ description: "Generation duration, from its start hook to its end hook (hook-derived)",
10138
+ valueType: "double",
10139
+ boundaries: OPERATION_DURATION_BUCKETS
10140
+ },
10141
+ [METRIC_SESSIONS]: {
10142
+ name: METRIC_SESSIONS,
10143
+ kind: "counter",
10144
+ unit: "{session}",
10145
+ description: "Agent sessions started",
10146
+ valueType: "int"
10147
+ },
10148
+ [METRIC_TOOL_CALLS]: {
10149
+ name: METRIC_TOOL_CALLS,
10150
+ kind: "counter",
10151
+ unit: "{call}",
10152
+ description: "Completed tool calls, by tool name and outcome",
10153
+ valueType: "int"
10154
+ },
10155
+ [METRIC_COST_USAGE]: {
10156
+ name: METRIC_COST_USAGE,
10157
+ kind: "counter",
10158
+ unit: "USD",
10159
+ description: "Cost reported by the provider; never estimated",
10160
+ valueType: "double"
10161
+ }
10162
+ });
10163
+ var isMetricInstrumentName = (value) => typeof value === "string" && Object.hasOwn(METRIC_INSTRUMENTS, value);
10164
+ var ATTR_GEN_AI_TOKEN_TYPE = "gen_ai.token.type";
10165
+ var ATTR_GEN_AI_PROVIDER_NAME = "gen_ai.provider.name";
10166
+ var ATTR_GEN_AI_OPERATION_NAME3 = "gen_ai.operation.name";
10167
+ var ATTR_GEN_AI_REQUEST_MODEL3 = "gen_ai.request.model";
10168
+ var ATTR_GEN_AI_RESPONSE_MODEL3 = "gen_ai.response.model";
10169
+ var ATTR_GEN_AI_TOOL_NAME3 = "gen_ai.tool.name";
10170
+ var ATTR_ERROR_TYPE3 = "error.type";
10171
+ var ATTR_SESSION_ID2 = "session.id";
10172
+ var ATTR_OTELHOOK_PROVIDER_ID2 = "otelhook.provider.id";
10173
+ var ATTR_OTELHOOK_OUTCOME3 = "otelhook.outcome";
10174
+ var ATTR_OTELHOOK_SESSION_KIND2 = "otelhook.session.kind";
10175
+ var commonAttributes = (event3, resource, includeSessionId) => ({
10176
+ // Session context first, so the metric's own attributes always win; and never
10177
+ // anything account-shaped, whatever the context says.
10178
+ ...event3.contextAttributes === void 0 ? {} : withoutAccountIdentity(event3.contextAttributes),
10179
+ [ATTR_OTELHOOK_PROVIDER_ID2]: event3.provenance.providerId,
10180
+ ...includeSessionId ? { [ATTR_SESSION_ID2]: resolveExportedSessionId(event3.sessionId, resource).sessionId } : {}
10181
+ });
10182
+ var generationAttributes = (end, requestModel) => ({
10183
+ [ATTR_GEN_AI_OPERATION_NAME3]: "chat",
10184
+ ...end.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_PROVIDER_NAME]: end.model.vendor },
10185
+ [ATTR_GEN_AI_REQUEST_MODEL3]: requestModel ?? end.model.modelId,
10186
+ [ATTR_GEN_AI_RESPONSE_MODEL3]: end.model.modelId
10187
+ });
10188
+ var TOKEN_FIELDS = [
10189
+ ["input", (usage) => usage.inputTokens],
10190
+ ["output", (usage) => usage.outputTokens],
10191
+ ["cache_read", (usage) => usage.cachedInputTokens],
10192
+ ["cache_creation", (usage) => usage.cacheCreationInputTokens]
10193
+ ];
10194
+ var isFailedOutcome = (outcome) => outcome !== "ok" && outcome !== "unknown" && outcome !== "cancelled";
10195
+ var deriveMetricObservations = (input) => {
10196
+ const includeSessionId = input.includeSessionId ?? true;
10197
+ const observations = [];
10198
+ const byId = /* @__PURE__ */ new Map();
10199
+ const startsInBatch = /* @__PURE__ */ new Map();
10200
+ for (const event3 of input.events) {
10201
+ byId.set(event3.eventId, event3);
10202
+ if (event3.type === "generation.start") {
10203
+ startsInBatch.set(event3.generationId, {
10204
+ startMillis: event3.occurredAt,
10205
+ requestModel: event3.model.modelId
10206
+ });
10207
+ }
10208
+ }
10209
+ const requestModelOf = (generationId) => startsInBatch.get(generationId)?.requestModel ?? input.generationStarts?.(generationId)?.requestModel;
10210
+ let lastPromptInBatch;
10211
+ for (const event3 of input.events) {
10212
+ if (event3.type === "prompt.submitted") {
10213
+ lastPromptInBatch ??= /* @__PURE__ */ new Map();
10214
+ lastPromptInBatch.set(event3.sessionId, Math.max(lastPromptInBatch.get(event3.sessionId) ?? 0, event3.occurredAt));
10215
+ }
10216
+ }
10217
+ const measuredDurationOf = (end) => {
10218
+ if (end.durationMillis !== void 0) {
10219
+ return end.durationMillis;
10220
+ }
10221
+ const recovered = startsInBatch.has(end.generationId) ? void 0 : input.generationStarts?.(end.generationId);
10222
+ if (recovered !== void 0) {
10223
+ return end.occurredAt - recovered.startMillis;
10224
+ }
10225
+ const turn = lastPromptInBatch?.get(end.sessionId) ?? input.turnStart?.(end.sessionId);
10226
+ return turn === void 0 || turn > end.occurredAt ? void 0 : end.occurredAt - turn;
10227
+ };
10228
+ const push = (event3, instrument, value, attributes) => {
10229
+ if (!Number.isFinite(value) || value < 0) {
10230
+ return;
10231
+ }
10232
+ observations.push({
10233
+ instrument,
10234
+ value,
10235
+ attributes: { ...commonAttributes(event3, input.resource, includeSessionId), ...attributes },
10236
+ timeMillis: event3.occurredAt,
10237
+ sessionId: event3.sessionId
10238
+ });
10239
+ };
10240
+ for (const event3 of input.events) {
10241
+ switch (event3.type) {
10242
+ case "session.start":
10243
+ push(event3, METRIC_SESSIONS, 1, { [ATTR_OTELHOOK_SESSION_KIND2]: event3.sessionKind });
10244
+ break;
10245
+ case "tool.end":
10246
+ push(event3, METRIC_TOOL_CALLS, 1, {
10247
+ [ATTR_GEN_AI_TOOL_NAME3]: event3.toolName,
10248
+ [ATTR_OTELHOOK_OUTCOME3]: event3.outcome
10249
+ });
10250
+ break;
10251
+ case "generation.end": {
10252
+ const attributes = generationAttributes(event3, requestModelOf(event3.generationId));
10253
+ const durationMillis = measuredDurationOf(event3);
10254
+ if (durationMillis !== void 0 && durationMillis >= 0) {
10255
+ push(event3, METRIC_OPERATION_DURATION, durationMillis / 1e3, {
10256
+ ...attributes,
10257
+ ...isFailedOutcome(event3.outcome) ? { [ATTR_ERROR_TYPE3]: event3.outcome } : {}
10258
+ });
10259
+ }
10260
+ if (event3.cost !== void 0 && event3.cost.source === "provider-reported" && event3.cost.currency === "USD") {
10261
+ push(event3, METRIC_COST_USAGE, event3.cost.amount, attributes);
10262
+ }
10263
+ break;
10264
+ }
10265
+ default:
10266
+ break;
10267
+ }
10268
+ }
10269
+ for (const observation of input.usage) {
10270
+ if (observation.scope !== "generation") {
10271
+ continue;
10272
+ }
10273
+ const event3 = byId.get(observation.eventId);
10274
+ if (event3?.type !== "generation.end") {
10275
+ continue;
10276
+ }
10277
+ const attributes = generationAttributes(event3, requestModelOf(event3.generationId));
10278
+ for (const [tokenType, read] of TOKEN_FIELDS) {
10279
+ const value = read(observation.delta);
10280
+ if (value === 0 && (tokenType === "cache_read" || tokenType === "cache_creation")) {
10281
+ continue;
10282
+ }
10283
+ push(event3, METRIC_TOKEN_USAGE, value, { ...attributes, [ATTR_GEN_AI_TOKEN_TYPE]: tokenType });
10284
+ }
10285
+ }
10286
+ return observations;
10287
+ };
10288
+ var emptyHistogram = (boundaries) => ({
10289
+ count: 0,
10290
+ sum: 0,
10291
+ min: Number.POSITIVE_INFINITY,
10292
+ max: Number.NEGATIVE_INFINITY,
10293
+ bucketCounts: new Array(boundaries.length + 1).fill(0)
10294
+ });
10295
+ var bucketIndex = (boundaries, value) => {
10296
+ for (let index = 0; index < boundaries.length; index += 1) {
10297
+ const bound = boundaries[index];
10298
+ if (bound !== void 0 && value <= bound) {
10299
+ return index;
10300
+ }
10301
+ }
10302
+ return boundaries.length;
10303
+ };
10304
+ var recordIntoHistogram = (state, boundaries, value) => {
10305
+ const bucketCounts = [...state.bucketCounts];
10306
+ const index = bucketIndex(boundaries, value);
10307
+ bucketCounts[index] = (bucketCounts[index] ?? 0) + 1;
10308
+ return {
10309
+ count: state.count + 1,
10310
+ sum: state.sum + value,
10311
+ min: Math.min(state.min, value),
10312
+ max: Math.max(state.max, value),
10313
+ bucketCounts
10314
+ };
10315
+ };
10316
+ var seriesIdentity = (instrument, attributes) => JSON.stringify([
10317
+ instrument,
10318
+ Object.entries(attributes).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
10319
+ ]);
10320
+ var aggregateDeltaPoints = (observations, nowMillis) => {
10321
+ const series = /* @__PURE__ */ new Map();
10322
+ for (const observation of observations) {
10323
+ const instrument = METRIC_INSTRUMENTS[observation.instrument];
10324
+ const key = seriesIdentity(observation.instrument, observation.attributes);
10325
+ const existing = series.get(key) ?? {
10326
+ observation,
10327
+ start: observation.timeMillis,
10328
+ value: 0,
10329
+ ...instrument.boundaries === void 0 ? {} : { histogram: emptyHistogram(instrument.boundaries) }
10330
+ };
10331
+ existing.start = Math.min(existing.start, observation.timeMillis);
10332
+ if (existing.histogram !== void 0 && instrument.boundaries !== void 0) {
10333
+ existing.histogram = recordIntoHistogram(existing.histogram, instrument.boundaries, observation.value);
10334
+ } else {
10335
+ existing.value += observation.value;
10336
+ }
10337
+ series.set(key, existing);
10338
+ }
10339
+ return [...series.values()].map((entry) => ({
10340
+ instrument: entry.observation.instrument,
10341
+ temporality: "delta",
10342
+ attributes: entry.observation.attributes,
10343
+ startTimeMillis: Math.min(entry.start, nowMillis),
10344
+ timeMillis: Math.max(nowMillis, entry.start),
10345
+ ...entry.histogram === void 0 ? { value: entry.value } : { histogram: entry.histogram }
10346
+ }));
10347
+ };
10348
+ var FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES = Object.freeze([
10349
+ "user.",
10350
+ "enduser.",
10351
+ "organization."
10352
+ ]);
10353
+ var withoutAccountIdentity = (attributes) => Object.fromEntries(
10354
+ Object.entries(attributes).filter(
10355
+ ([key]) => !FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES.some((prefix) => key.startsWith(prefix))
10356
+ )
10357
+ );
10358
+
10359
+ // src/telemetry/durable-metric-spool.ts
10360
+ var MAX_SPOOLED_METRIC_POINTS_PER_BATCH = 4096;
10361
+ var MAX_STRING_LENGTH = 8192;
10362
+ var MAX_ATTRIBUTES_PER_POINT = 64;
10363
+ var MAX_BUCKETS = 64;
10364
+ var isPlainObject5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10365
+ var isFiniteNonNegative3 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
10366
+ var isBoundedString3 = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_STRING_LENGTH;
10367
+ var isPrimitiveAttribute2 = (value) => typeof value === "string" && value.length <= MAX_STRING_LENGTH || typeof value === "number" && Number.isFinite(value) || typeof value === "boolean";
10368
+ var isReplayablePoint = (value) => {
10369
+ if (!isPlainObject5(value) || !isMetricInstrumentName(value.instrument)) {
10370
+ return false;
10371
+ }
10372
+ if (value.temporality !== "cumulative" && value.temporality !== "delta") {
10373
+ return false;
10374
+ }
10375
+ if (!isFiniteNonNegative3(value.startTimeMillis) || !isFiniteNonNegative3(value.timeMillis)) {
10376
+ return false;
10377
+ }
10378
+ if (!isPlainObject5(value.attributes)) {
10379
+ return false;
10380
+ }
10381
+ const entries = Object.entries(value.attributes);
10382
+ if (entries.length > MAX_ATTRIBUTES_PER_POINT || !entries.every(([, item]) => isPrimitiveAttribute2(item))) {
10383
+ return false;
10384
+ }
10385
+ const instrument = METRIC_INSTRUMENTS[value.instrument];
10386
+ if (instrument.kind === "counter") {
10387
+ return isFiniteNonNegative3(value.value) && value.histogram === void 0;
10388
+ }
10389
+ const histogram = value.histogram;
10390
+ if (!isPlainObject5(histogram) || value.value !== void 0) {
10391
+ return false;
10392
+ }
10393
+ const buckets = histogram.bucketCounts;
10394
+ 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));
10395
+ };
10396
+ var validateMetricSpoolBatch = (value, identity) => {
10397
+ if (!isPlainObject5(value)) {
10398
+ return { rejection: "not-an-object" };
10399
+ }
10400
+ if (value.providerId !== identity.providerId || value.installationId !== identity.installationId) {
10401
+ return { rejection: "identity-mismatch" };
10402
+ }
10403
+ if (!isPlainObject5(value.resourceAttributes)) {
10404
+ return { rejection: "resource-attributes-invalid" };
10405
+ }
10406
+ if (!isPlainObject5(value.instrumentationScope) || !isBoundedString3(value.instrumentationScope.name)) {
10407
+ return { rejection: "instrumentation-scope-invalid" };
10408
+ }
10409
+ if (value.instrumentationScope.version !== void 0 && typeof value.instrumentationScope.version !== "string") {
10410
+ return { rejection: "instrumentation-scope-invalid" };
10411
+ }
10412
+ if (!Array.isArray(value.points) || value.points.length === 0 || value.points.length > MAX_SPOOLED_METRIC_POINTS_PER_BATCH) {
10413
+ return { rejection: "points-invalid" };
10414
+ }
10415
+ if (!value.points.every(isReplayablePoint)) {
10416
+ return { rejection: "point-field-invalid" };
10417
+ }
10418
+ if (!isFiniteNonNegative3(value.enqueuedAt)) {
10419
+ return { rejection: "not-an-object" };
10420
+ }
10421
+ return { batch: value };
10422
+ };
10423
+ var DEFAULT_MAX_METRIC_SPOOL_FILES = 500;
10424
+ var createFileDurableMetricSpool = (options) => createSpoolQueue({
10425
+ rootDir: options.rootDir,
10426
+ providerId: options.providerId,
10427
+ installationId: options.installationId,
10428
+ clock: options.clock,
10429
+ ...options.logger === void 0 ? {} : { logger: options.logger },
10430
+ maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_METRIC_SPOOL_FILES,
10431
+ queueName: options.queueName ?? "spool-metrics",
10432
+ ...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
10433
+ ...options.maxAgeMillis === void 0 ? {} : { maxAgeMillis: options.maxAgeMillis },
10434
+ ...options.overflow === void 0 ? {} : { overflow: options.overflow },
10435
+ validate: validateMetricSpoolBatch
10436
+ });
10437
+
10438
+ // src/telemetry/otlp-metric-sink.ts
10439
+ import { ValueType } from "@opentelemetry/api";
10440
+ import { ExportResultCode as ExportResultCode3, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
10441
+ import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
10442
+ import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
10443
+ import {
10444
+ AggregationTemporality,
10445
+ DataPointType
10446
+ } from "@opentelemetry/sdk-metrics";
10447
+ var resolveMetricsEndpoint = (exporter) => {
10448
+ const stated = exporter.metrics?.endpoint;
10449
+ if (stated !== void 0) {
10450
+ return { endpoint: stated, derived: false };
10451
+ }
10452
+ if (exporter.endpoint === void 0) {
10453
+ return { unresolvable: "no-endpoint" };
10454
+ }
10455
+ return { endpoint: siblingSignalEndpoint(exporter.endpoint, "metrics"), derived: true };
10456
+ };
10457
+ var describeMetricsDeliverability = (exporter) => {
10458
+ if (exporter.metrics?.enabled !== true) {
10459
+ return { status: "disabled", reason: "metrics-disabled" };
10460
+ }
10461
+ if (!exporter.enabled) {
10462
+ return { status: "disabled", reason: "exporter-disabled" };
10463
+ }
10464
+ if (exporter.protocol === "none") {
10465
+ return { status: "disabled", reason: "protocol-none" };
10466
+ }
10467
+ if (exporter.protocol !== "http/protobuf") {
10468
+ return { status: "disabled", reason: "protocol-unsupported" };
10469
+ }
10470
+ const resolved = resolveMetricsEndpoint(exporter);
10471
+ if ("unresolvable" in resolved) {
10472
+ return { status: "disabled", reason: "no-endpoint" };
10473
+ }
10474
+ return { status: "configured", endpoint: resolved.endpoint, derivedEndpoint: resolved.derived };
10475
+ };
10476
+ var DISABLED_DETAIL2 = Object.freeze({
10477
+ "exporter-disabled": "otlp metric sink disabled: the exporter is disabled",
10478
+ "protocol-none": "otlp metric sink disabled: protocol is none",
10479
+ "protocol-unsupported": "otlp metric sink disabled: protocol not supported by this build",
10480
+ "no-endpoint": "otlp metric sink disabled: no metrics endpoint configured and none could be derived"
10481
+ });
10482
+ var createDisabledMetricSink = (destination) => {
10483
+ const health = createHealthTracker(
10484
+ "telemetry-metric-sink",
10485
+ destination === void 0 ? {} : { destination }
10486
+ );
10487
+ return {
10488
+ enabled: false,
10489
+ exportPoints: () => Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),
10490
+ flush: () => Promise.resolve(),
10491
+ shutdown: () => Promise.resolve(),
10492
+ health: () => health.snapshot(),
10493
+ drainSpool: () => Promise.resolve({ drained: 0, remaining: 0, failed: 0 })
10494
+ };
10495
+ };
10496
+ var createDisabledOtlpMetricSink = createDisabledMetricSink;
10497
+ var toMetricData = (points) => {
10498
+ const byInstrument = /* @__PURE__ */ new Map();
10499
+ for (const point of points) {
10500
+ const key = `${point.instrument}|${point.temporality}`;
10501
+ const group = byInstrument.get(key) ?? [];
10502
+ group.push(point);
10503
+ byInstrument.set(key, group);
10504
+ }
10505
+ const metrics = [];
10506
+ for (const group of byInstrument.values()) {
10507
+ const first = group[0];
10508
+ if (first === void 0) {
10509
+ continue;
10510
+ }
10511
+ const instrument = METRIC_INSTRUMENTS[first.instrument];
10512
+ const descriptor = {
10513
+ name: instrument.name,
10514
+ description: instrument.description,
10515
+ unit: instrument.unit,
10516
+ valueType: instrument.valueType === "int" ? ValueType.INT : ValueType.DOUBLE
10517
+ };
10518
+ const aggregationTemporality = first.temporality === "cumulative" ? AggregationTemporality.CUMULATIVE : AggregationTemporality.DELTA;
10519
+ const times = (point) => ({
10520
+ startTime: millisToHrTime4(point.startTimeMillis),
10521
+ endTime: millisToHrTime4(point.timeMillis)
10522
+ });
10523
+ if (instrument.kind === "counter") {
10524
+ metrics.push({
10525
+ descriptor,
10526
+ aggregationTemporality,
10527
+ dataPointType: DataPointType.SUM,
10528
+ isMonotonic: true,
10529
+ dataPoints: group.map((point) => ({
10530
+ ...times(point),
10531
+ attributes: { ...point.attributes },
10532
+ value: point.value ?? 0
10533
+ }))
10534
+ });
10535
+ continue;
10536
+ }
10537
+ metrics.push({
10538
+ descriptor,
10539
+ aggregationTemporality,
10540
+ dataPointType: DataPointType.HISTOGRAM,
10541
+ dataPoints: group.map((point) => {
10542
+ const histogram = point.histogram;
10543
+ return {
10544
+ ...times(point),
10545
+ attributes: { ...point.attributes },
10546
+ value: {
10547
+ buckets: {
10548
+ boundaries: [...instrument.boundaries ?? []],
10549
+ counts: [...histogram?.bucketCounts ?? []]
10550
+ },
10551
+ count: histogram?.count ?? 0,
10552
+ sum: histogram?.sum ?? 0,
10553
+ ...histogram === void 0 || histogram.count === 0 ? {} : { min: histogram.min, max: histogram.max }
10554
+ }
10555
+ };
10556
+ })
10557
+ });
10558
+ }
10559
+ return metrics;
10560
+ };
10561
+ var createOtlpMetricSink = (options) => {
10562
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
10563
+ const deliverability = describeMetricsDeliverability(options.exporter);
10564
+ if (deliverability.status === "disabled") {
10565
+ if (deliverability.reason !== "metrics-disabled") {
10566
+ options.logger?.warn(DISABLED_DETAIL2[deliverability.reason], {
10567
+ "exporter.protocol": options.exporter.protocol,
10568
+ ...destinationFields
10569
+ });
10570
+ }
10571
+ return createDisabledMetricSink(options.destination);
10572
+ }
10573
+ const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
10574
+ const resource = resourceFromAttributes2(
10575
+ withoutAccountIdentity(resourceFromExporterPolicy(options.exporter).attributes)
10576
+ );
10577
+ const health = createHealthTracker(
10578
+ "telemetry-metric-sink",
10579
+ options.destination === void 0 ? {} : { destination: options.destination }
10580
+ );
10581
+ const exporter = new OTLPMetricExporter({
10582
+ url: deliverability.endpoint,
10583
+ headers: { ...options.headers },
10584
+ timeoutMillis: options.exporter.timeoutMillis
10585
+ });
10586
+ let shutdownCompleted = false;
10587
+ const exportResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve8) => {
10588
+ const payload = {
10589
+ resource: batchResource,
10590
+ scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }]
10591
+ };
10592
+ try {
10593
+ exporter.export(payload, (result) => resolve8(result));
10594
+ } catch (thrown) {
10595
+ resolve8({
10596
+ code: ExportResultCode3.FAILED,
10597
+ error: thrown instanceof Error ? thrown : new Error("export threw")
10598
+ });
10599
+ }
10600
+ });
10601
+ const toSpoolBatch = (points, batchResource) => ({
10602
+ providerId: options.providerId,
10603
+ installationId: options.installationId,
10604
+ resourceAttributes: { ...batchResource.attributes },
10605
+ instrumentationScope: {
10606
+ name: scope.name,
10607
+ ...scope.version === void 0 ? {} : { version: scope.version }
10608
+ },
10609
+ points: points.map((point) => ({ ...point })),
10610
+ enqueuedAt: options.clock.now()
10611
+ });
10612
+ const sendSerializedBatch = async (batch) => {
10613
+ const batchResource = resourceFromAttributes2(
10614
+ withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes)
10615
+ );
10616
+ const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);
10617
+ if (result.code === ExportResultCode3.SUCCESS) {
10618
+ return true;
10619
+ }
10620
+ return isPermanentExportFailure(result) ? "discard" : false;
10621
+ };
10622
+ const exportPoints = async (points, context) => {
10623
+ if (points.length === 0) {
10624
+ return { accepted: 0, rejected: 0, errors: [] };
10625
+ }
10626
+ const batchResource = context === void 0 ? resource : resourceWithContext(resource, context);
10627
+ const result = await exportResourceMetrics(points, batchResource, scope);
10628
+ if (result.code === ExportResultCode3.SUCCESS) {
10629
+ health.recordSuccess(points.length, options.clock.now());
10630
+ return { accepted: points.length, rejected: 0, errors: [] };
10631
+ }
10632
+ health.recordFailure("telemetry-export-failure", points.length, options.clock.now());
10633
+ const permanent = isPermanentExportFailure(result);
10634
+ if (options.spool !== void 0 && !permanent) {
10635
+ const spooled = await options.spool.enqueue(toSpoolBatch(points, batchResource)).catch(() => ({
10636
+ spooled: false,
10637
+ reason: "capacity-exceeded"
10638
+ }));
10639
+ if (spooled.spooled) {
10640
+ options.logger?.warn("metric batch not delivered; spooled for the next invocation", {
10641
+ "export.batch_size": points.length,
10642
+ ...destinationFields
10643
+ });
10644
+ return { accepted: points.length, rejected: 0, errors: [] };
10645
+ }
10646
+ }
10647
+ return {
10648
+ accepted: 0,
10649
+ rejected: points.length,
10650
+ errors: [
10651
+ createErrorInfo({
10652
+ code: "telemetry-export-failure",
10653
+ phase: "export",
10654
+ detail: permanent ? "collector refused a metric batch with a non-retryable status" : "collector rejected or was unreachable for a metric batch",
10655
+ details: {
10656
+ "export.batch_size": points.length,
10657
+ "export.signal": "metrics",
10658
+ ...destinationFields
10659
+ }
10660
+ })
10661
+ ]
10662
+ };
10663
+ };
10664
+ const drainSpool = async (maxBatches) => {
10665
+ if (options.spool === void 0) {
10666
+ return { drained: 0, remaining: 0, failed: 0 };
10667
+ }
10668
+ const result = await options.spool.drain(sendSerializedBatch, {
10669
+ ...maxBatches === void 0 ? {} : { maxBatches }
10670
+ });
10671
+ if (result.drained > 0) {
10672
+ health.recordSuccess(result.drained, options.clock.now());
10673
+ }
10674
+ return result;
10675
+ };
10676
+ const flush = async () => {
10677
+ try {
10678
+ await exporter.forceFlush();
10679
+ } catch {
10680
+ }
10681
+ await drainSpool().catch(() => void 0);
10682
+ };
10683
+ const shutdown = async () => {
10684
+ if (shutdownCompleted) {
10685
+ return;
10686
+ }
10687
+ shutdownCompleted = true;
10688
+ await flush();
10689
+ try {
10690
+ await exporter.shutdown();
10691
+ } catch {
10692
+ }
10693
+ };
10694
+ return {
10695
+ enabled: true,
10696
+ exportPoints,
10697
+ flush,
10698
+ shutdown,
10699
+ health: () => health.snapshot(),
10700
+ drainSpool
10701
+ };
10702
+ };
10703
+
9852
10704
  // src/telemetry/signal-fanout.ts
9853
10705
  var createSignalFanout = (options) => {
9854
10706
  const emit = async (events) => {
@@ -9892,7 +10744,11 @@ var shareCorrelationPerBatch = (correlate) => {
9892
10744
  };
9893
10745
 
9894
10746
  // 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` };
10747
+ var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs", metrics: "spool-metrics" } : {
10748
+ traces: `destinations/${destination}/spool`,
10749
+ logs: `destinations/${destination}/spool-logs`,
10750
+ metrics: `destinations/${destination}/spool-metrics`
10751
+ };
9896
10752
  var exporterPolicyForDestination = (exporter, destination) => {
9897
10753
  if (destination.source === "exporter") {
9898
10754
  return exporter;
@@ -9909,8 +10765,10 @@ var exporterPolicyForDestination = (exporter, destination) => {
9909
10765
  });
9910
10766
  return "endpoint" in derived ? derived.endpoint : void 0;
9911
10767
  })());
10768
+ const { metrics: sharedMetrics, ...rest } = shared;
10769
+ const derivedMetrics = destination.metricsEndpoint ?? (destination.endpoint === void 0 ? void 0 : siblingSignalEndpoint(destination.endpoint, "metrics"));
9912
10770
  return {
9913
- ...shared,
10771
+ ...rest,
9914
10772
  protocol: destination.protocol,
9915
10773
  ...tracesEndpoint === void 0 ? {} : { endpoint: tracesEndpoint },
9916
10774
  headerNames: Object.keys(destination.headers).sort(),
@@ -9918,6 +10776,11 @@ var exporterPolicyForDestination = (exporter, destination) => {
9918
10776
  ...logs,
9919
10777
  enabled: destination.signals.logs,
9920
10778
  ...derivedLogs === void 0 ? {} : { endpoint: derivedLogs }
10779
+ },
10780
+ metrics: {
10781
+ ...effectiveMetricsPolicy({ ...exporter, metrics: sharedMetrics }),
10782
+ enabled: destination.signals.metrics,
10783
+ ...derivedMetrics === void 0 ? {} : { endpoint: derivedMetrics }
9921
10784
  }
9922
10785
  };
9923
10786
  };
@@ -9989,6 +10852,12 @@ var createExportDestinationSinks = (options) => {
9989
10852
  ...bounds,
9990
10853
  queueName: queues.logs
9991
10854
  });
10855
+ const metricSpool = options.spoolRootDir === void 0 || !destination.signals.metrics ? void 0 : createFileDurableMetricSpool({
10856
+ rootDir: options.spoolRootDir,
10857
+ ...shared,
10858
+ ...bounds,
10859
+ queueName: queues.metrics
10860
+ });
9992
10861
  const sinkShared = {
9993
10862
  exporter: policy,
9994
10863
  ...shared,
@@ -10006,12 +10875,21 @@ var createExportDestinationSinks = (options) => {
10006
10875
  ...logSpool === void 0 ? {} : { spool: logSpool },
10007
10876
  content: options.logContent
10008
10877
  });
10878
+ const metrics = destination.signals.metrics ? createOtlpMetricSink({
10879
+ exporter: policy,
10880
+ ...shared,
10881
+ ...label === void 0 ? {} : { destination: label },
10882
+ ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
10883
+ ...metricSpool === void 0 ? {} : { spool: metricSpool }
10884
+ }) : createDisabledOtlpMetricSink(label);
10009
10885
  destinations.push({
10010
10886
  name: destination.name,
10011
10887
  traces,
10012
10888
  logs,
10889
+ metrics,
10013
10890
  ...spool === void 0 ? {} : { spool },
10014
- ...logSpool === void 0 ? {} : { logSpool }
10891
+ ...logSpool === void 0 ? {} : { logSpool },
10892
+ ...metricSpool === void 0 ? {} : { metricSpool }
10015
10893
  });
10016
10894
  }
10017
10895
  return { destinations, skipped };
@@ -10170,6 +11048,20 @@ var collectDoctorReport = async (command, io) => {
10170
11048
  ok: resolved.config.privacy.contentMode === "omit" || resolved.config.privacy.allowRawContent,
10171
11049
  detail: `content mode is "${privacy.policy.contentMode}"${privacy.policyNotes.length === 0 ? "" : `; ${privacy.policyNotes.join("; ")}`}`
10172
11050
  });
11051
+ const contextDir = resolved.config.sessionContext?.dir;
11052
+ let contextDirExists = false;
11053
+ if (contextDir !== void 0) {
11054
+ try {
11055
+ contextDirExists = (await stat2(contextDir)).isDirectory();
11056
+ } catch {
11057
+ contextDirExists = false;
11058
+ }
11059
+ }
11060
+ checks.push({
11061
+ name: "session-context",
11062
+ ok: true,
11063
+ detail: contextDir === void 0 ? "off (sessionContext.dir is not set)" : `reading ${path4.join(contextDir, "<agent-tool>", "<session-id>.json")}${contextDirExists ? "" : " (directory does not exist yet; nothing is stamped until it does)"}`
11064
+ });
10173
11065
  const providers = describeProviderCatalog({
10174
11066
  includeExperimental: command.policy.includeExperimental ?? true
10175
11067
  });
@@ -10216,6 +11108,9 @@ var describeDestinationLine = (destination) => {
10216
11108
  if (destination.logsEndpointOrigin !== void 0) {
10217
11109
  parts.push(`logs -> ${destination.logsEndpointOrigin}`);
10218
11110
  }
11111
+ if (destination.metricsEndpointOrigin !== void 0) {
11112
+ parts.push(`metrics -> ${destination.metricsEndpointOrigin}`);
11113
+ }
10219
11114
  if (destination.headerNames.length > 0) {
10220
11115
  parts.push(`headers ${destination.headerNames.join(", ")}`);
10221
11116
  }
@@ -10279,7 +11174,7 @@ var describeDoctorDestinations = async (exporter, environment, spool) => {
10279
11174
  const headers = configured.get(description.name)?.headers ?? {};
10280
11175
  const missingVariables = resolveDestinationHeaders(headers, environment).missingVariables;
10281
11176
  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;
11177
+ 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
11178
  let detail = "resolves";
10284
11179
  let ok = true;
10285
11180
  if (!description.enabled) {
@@ -10297,7 +11192,8 @@ var describeDoctorDestinations = async (exporter, environment, spool) => {
10297
11192
  const queues = spoolQueueNamesFor(description.name);
10298
11193
  const spoolStats = spool === void 0 || !resolvedNames.has(description.name) ? void 0 : {
10299
11194
  ...description.signals.includes("traces") ? { traces: await inspectQueue(spool, queues.traces) } : {},
10300
- ...description.signals.includes("logs") ? { logs: await inspectQueue(spool, queues.logs) } : {}
11195
+ ...description.signals.includes("logs") ? { logs: await inspectQueue(spool, queues.logs) } : {},
11196
+ ...description.signals.includes("metrics") ? { metrics: await inspectQueue(spool, queues.metrics) } : {}
10301
11197
  };
10302
11198
  return {
10303
11199
  ...description,
@@ -10351,12 +11247,12 @@ var runDoctorCommand = async (command, io) => {
10351
11247
  };
10352
11248
 
10353
11249
  // src/providers/antigravity/registration.ts
10354
- var isPlainObject5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
11250
+ var isPlainObject6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10355
11251
  var mergeAntigravityHookRegistration = (input) => {
10356
11252
  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);
11253
+ const base = isPlainObject6(input.existing) ? input.existing : {};
11254
+ const existingHooks = isPlainObject6(base.hooks) ? base.hooks : {};
11255
+ let changed = !isPlainObject6(input.existing) || !isPlainObject6(base.hooks);
10360
11256
  const nextHooks = { ...existingHooks };
10361
11257
  const identifies = input.identifies ?? ((entry) => entry.command === input.command);
10362
11258
  const desired = {
@@ -10365,7 +11261,7 @@ var mergeAntigravityHookRegistration = (input) => {
10365
11261
  };
10366
11262
  for (const event3 of events) {
10367
11263
  const currentList = Array.isArray(existingHooks[event3]) ? [...existingHooks[event3]] : [];
10368
- const managedIndex = currentList.findIndex((entry) => isPlainObject5(entry) && identifies(entry));
11264
+ const managedIndex = currentList.findIndex((entry) => isPlainObject6(entry) && identifies(entry));
10369
11265
  if (managedIndex === -1) {
10370
11266
  changed = true;
10371
11267
  nextHooks[event3] = [...currentList, desired];
@@ -10374,7 +11270,7 @@ var mergeAntigravityHookRegistration = (input) => {
10374
11270
  const managed = currentList[managedIndex];
10375
11271
  const updated = { ...managed, ...desired };
10376
11272
  const next = currentList.filter(
10377
- (entry, index) => index === managedIndex || !(isPlainObject5(entry) && identifies(entry))
11273
+ (entry, index) => index === managedIndex || !(isPlainObject6(entry) && identifies(entry))
10378
11274
  );
10379
11275
  next[next.indexOf(managed)] = updated;
10380
11276
  const rewritten = Object.entries(desired).some(([key, value]) => managed[key] !== value);
@@ -10389,8 +11285,8 @@ var mergeAntigravityHookRegistration = (input) => {
10389
11285
  };
10390
11286
  };
10391
11287
  var removeAntigravityHookRegistration = (input) => {
10392
- const base = isPlainObject5(input.existing) ? { ...input.existing } : {};
10393
- if (!isPlainObject5(base.hooks)) {
11288
+ const base = isPlainObject6(input.existing) ? { ...input.existing } : {};
11289
+ if (!isPlainObject6(base.hooks)) {
10394
11290
  return { config: base, changed: false };
10395
11291
  }
10396
11292
  const nextHooks = { ...base.hooks };
@@ -10402,7 +11298,7 @@ var removeAntigravityHookRegistration = (input) => {
10402
11298
  continue;
10403
11299
  }
10404
11300
  const kept = currentList.filter(
10405
- (entry) => !(isPlainObject5(entry) && input.identifies(entry))
11301
+ (entry) => !(isPlainObject6(entry) && input.identifies(entry))
10406
11302
  );
10407
11303
  if (kept.length === currentList.length) {
10408
11304
  continue;
@@ -10427,7 +11323,7 @@ var removeAntigravityHookRegistration = (input) => {
10427
11323
  };
10428
11324
  var readAntigravityHookRegistrations = (existing, identifies) => {
10429
11325
  const found = /* @__PURE__ */ new Map();
10430
- if (!isPlainObject5(existing) || !isPlainObject5(existing.hooks)) {
11326
+ if (!isPlainObject6(existing) || !isPlainObject6(existing.hooks)) {
10431
11327
  return found;
10432
11328
  }
10433
11329
  for (const [event3, list] of Object.entries(existing.hooks)) {
@@ -10435,7 +11331,7 @@ var readAntigravityHookRegistrations = (existing, identifies) => {
10435
11331
  continue;
10436
11332
  }
10437
11333
  const commands = list.filter(
10438
- (entry) => isPlainObject5(entry) && typeof entry.command === "string" && identifies(entry)
11334
+ (entry) => isPlainObject6(entry) && typeof entry.command === "string" && identifies(entry)
10439
11335
  ).map((entry) => entry.command);
10440
11336
  if (commands.length > 0) {
10441
11337
  found.set(event3, commands);
@@ -10445,10 +11341,10 @@ var readAntigravityHookRegistrations = (existing, identifies) => {
10445
11341
  };
10446
11342
 
10447
11343
  // src/providers/hook-document.ts
10448
- var isPlainObject6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
11344
+ var isPlainObject7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10449
11345
  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;
11346
+ var isManaged = (value, identifies) => isPlainObject7(value) && identifies(value);
11347
+ var cloneGroup = (value) => isPlainObject7(value) && Array.isArray(value.hooks) ? { ...value, hooks: [...value.hooks] } : void 0;
10452
11348
  var matchesDesired = (existing, desired) => {
10453
11349
  for (const [key, value] of Object.entries(desired)) {
10454
11350
  if (existing[key] !== value) {
@@ -10476,7 +11372,7 @@ var readHooksObject = (base, conflicts) => {
10476
11372
  if (raw === void 0) {
10477
11373
  return {};
10478
11374
  }
10479
- if (!isPlainObject6(raw)) {
11375
+ if (!isPlainObject7(raw)) {
10480
11376
  conflicts.push({
10481
11377
  location: "hooks",
10482
11378
  detail: `expected an object keyed by hook event name, found ${Array.isArray(raw) ? "an array" : raw === null ? "null" : typeof raw}`
@@ -10485,7 +11381,7 @@ var readHooksObject = (base, conflicts) => {
10485
11381
  }
10486
11382
  return { ...raw };
10487
11383
  };
10488
- var pruneEventList = (list) => list.filter((group) => !(isPlainObject6(group) && Array.isArray(group.hooks) && group.hooks.length === 0));
11384
+ var pruneEventList = (list) => list.filter((group) => !(isPlainObject7(group) && Array.isArray(group.hooks) && group.hooks.length === 0));
10489
11385
  var finalize = (base, hooks) => {
10490
11386
  const next = { ...base };
10491
11387
  if (Object.keys(hooks).length === 0) {
@@ -10496,7 +11392,7 @@ var finalize = (base, hooks) => {
10496
11392
  return next;
10497
11393
  };
10498
11394
  var mergeNestedHookRegistration = (input) => {
10499
- const base = isPlainObject6(input.existing) ? { ...input.existing } : {};
11395
+ const base = isPlainObject7(input.existing) ? { ...input.existing } : {};
10500
11396
  const conflicts = [];
10501
11397
  const hooks = readHooksObject(base, conflicts);
10502
11398
  if (hooks === void 0) {
@@ -10512,7 +11408,7 @@ var mergeNestedHookRegistration = (input) => {
10512
11408
  }
10513
11409
  const groups = list.map((group) => cloneGroup(group) ?? group);
10514
11410
  const usableGroups = groups.filter(
10515
- (group) => isPlainObject6(group) && Array.isArray(group.hooks)
11411
+ (group) => isPlainObject7(group) && Array.isArray(group.hooks)
10516
11412
  );
10517
11413
  let ownHandler;
10518
11414
  let ownGroup;
@@ -10577,7 +11473,7 @@ var mergeNestedHookRegistration = (input) => {
10577
11473
  return { document: finalize(base, hooks), changed, changes, conflicts };
10578
11474
  };
10579
11475
  var removeNestedHookRegistrations = (input) => {
10580
- const base = isPlainObject6(input.existing) ? { ...input.existing } : {};
11476
+ const base = isPlainObject7(input.existing) ? { ...input.existing } : {};
10581
11477
  const conflicts = [];
10582
11478
  const hooks = readHooksObject(base, conflicts);
10583
11479
  if (hooks === void 0) {
@@ -10630,7 +11526,7 @@ var removeNestedHookRegistrations = (input) => {
10630
11526
  };
10631
11527
  var readNestedHookRegistrations = (existing, identifies) => {
10632
11528
  const found = /* @__PURE__ */ new Map();
10633
- if (!isPlainObject6(existing) || !isPlainObject6(existing.hooks)) {
11529
+ if (!isPlainObject7(existing) || !isPlainObject7(existing.hooks)) {
10634
11530
  return found;
10635
11531
  }
10636
11532
  for (const [event3, list] of Object.entries(existing.hooks)) {
@@ -10639,7 +11535,7 @@ var readNestedHookRegistrations = (existing, identifies) => {
10639
11535
  }
10640
11536
  const commands = [];
10641
11537
  for (const group of list) {
10642
- if (!isPlainObject6(group) || !Array.isArray(group.hooks)) {
11538
+ if (!isPlainObject7(group) || !Array.isArray(group.hooks)) {
10643
11539
  continue;
10644
11540
  }
10645
11541
  for (const handler of group.hooks) {
@@ -10776,7 +11672,7 @@ var CURSOR_UNREGISTERED_HOOK_EVENTS = Object.freeze({
10776
11672
  workspaceOpen: "an app-lifecycle hook that carries no conversation_id, so it has no session to attribute telemetry to"
10777
11673
  });
10778
11674
  var CURSOR_HOOKS_DOCUMENT_VERSION = 1;
10779
- var isPlainObject7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
11675
+ var isPlainObject8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10780
11676
  var buildEntry3 = (input) => ({
10781
11677
  type: "command",
10782
11678
  command: input.command,
@@ -10785,8 +11681,8 @@ var buildEntry3 = (input) => ({
10785
11681
  });
10786
11682
  var mergeCursorHookRegistration = (input) => {
10787
11683
  const events = input.events ?? CURSOR_REGISTRABLE_HOOK_EVENTS;
10788
- const base = isPlainObject7(input.existing) ? { ...input.existing } : {};
10789
- const existingHooks = isPlainObject7(base.hooks) ? base.hooks : {};
11684
+ const base = isPlainObject8(input.existing) ? { ...input.existing } : {};
11685
+ const existingHooks = isPlainObject8(base.hooks) ? base.hooks : {};
10790
11686
  const nextHooks = { ...existingHooks };
10791
11687
  const desired = buildEntry3(input);
10792
11688
  let changed = false;
@@ -10797,7 +11693,7 @@ var mergeCursorHookRegistration = (input) => {
10797
11693
  for (const event3 of events) {
10798
11694
  const currentList = Array.isArray(existingHooks[event3]) ? [...existingHooks[event3]] : [];
10799
11695
  const managed = currentList.filter(
10800
- (entry) => isPlainObject7(entry) && input.identifies(entry)
11696
+ (entry) => isPlainObject8(entry) && input.identifies(entry)
10801
11697
  );
10802
11698
  const [ours] = managed;
10803
11699
  if (ours === void 0) {
@@ -10806,7 +11702,7 @@ var mergeCursorHookRegistration = (input) => {
10806
11702
  continue;
10807
11703
  }
10808
11704
  const rewritten = { ...ours, ...desired };
10809
- const next = currentList.filter((entry) => entry === ours || !(isPlainObject7(entry) && input.identifies(entry))).map((entry) => entry === ours ? rewritten : entry);
11705
+ const next = currentList.filter((entry) => entry === ours || !(isPlainObject8(entry) && input.identifies(entry))).map((entry) => entry === ours ? rewritten : entry);
10810
11706
  const entryChanged = Object.entries(desired).some(([key, value]) => ours[key] !== value);
10811
11707
  if (entryChanged || managed.length > 1) {
10812
11708
  changed = true;
@@ -10816,8 +11712,8 @@ var mergeCursorHookRegistration = (input) => {
10816
11712
  return { config: { ...base, hooks: nextHooks }, changed };
10817
11713
  };
10818
11714
  var removeCursorHookRegistration = (input) => {
10819
- const base = isPlainObject7(input.existing) ? { ...input.existing } : {};
10820
- if (!isPlainObject7(base.hooks)) {
11715
+ const base = isPlainObject8(input.existing) ? { ...input.existing } : {};
11716
+ if (!isPlainObject8(base.hooks)) {
10821
11717
  return { config: base, changed: false };
10822
11718
  }
10823
11719
  const nextHooks = { ...base.hooks };
@@ -10829,7 +11725,7 @@ var removeCursorHookRegistration = (input) => {
10829
11725
  continue;
10830
11726
  }
10831
11727
  const kept = currentList.filter(
10832
- (entry) => !(isPlainObject7(entry) && input.identifies(entry))
11728
+ (entry) => !(isPlainObject8(entry) && input.identifies(entry))
10833
11729
  );
10834
11730
  if (kept.length === currentList.length) {
10835
11731
  continue;
@@ -10857,7 +11753,7 @@ var removeCursorHookRegistration = (input) => {
10857
11753
  };
10858
11754
  var readCursorHookRegistrations = (existing, identifies) => {
10859
11755
  const found = /* @__PURE__ */ new Map();
10860
- if (!isPlainObject7(existing) || !isPlainObject7(existing.hooks)) {
11756
+ if (!isPlainObject8(existing) || !isPlainObject8(existing.hooks)) {
10861
11757
  return found;
10862
11758
  }
10863
11759
  for (const [event3, list] of Object.entries(existing.hooks)) {
@@ -10865,7 +11761,7 @@ var readCursorHookRegistrations = (existing, identifies) => {
10865
11761
  continue;
10866
11762
  }
10867
11763
  const commands = list.filter(
10868
- (entry) => isPlainObject7(entry) && typeof entry.command === "string" && identifies(entry)
11764
+ (entry) => isPlainObject8(entry) && typeof entry.command === "string" && identifies(entry)
10869
11765
  ).map((entry) => entry.command);
10870
11766
  if (commands.length > 0) {
10871
11767
  found.set(event3, commands);
@@ -10965,7 +11861,7 @@ var managedHookPredicate = (marker) => {
10965
11861
  }
10966
11862
  return (handler) => handler.name === MANAGED_HOOK_NAME || typeof handler.command === "string" && handler.command.includes(marker);
10967
11863
  };
10968
- var isPlainObject8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
11864
+ var isPlainObject9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10969
11865
  var adaptFlatResult = (read, existing, events, identifies, result, removal) => {
10970
11866
  const before = read(existing, identifies);
10971
11867
  const after = read(result.config, identifies);
@@ -10989,10 +11885,10 @@ var adaptFlatResult = (read, existing, events, identifies, result, removal) => {
10989
11885
  return { document: result.config, changed: result.changed, changes, conflicts: [] };
10990
11886
  };
10991
11887
  var flatHookConflicts = (existing) => {
10992
- if (!isPlainObject8(existing) || existing.hooks === void 0) {
11888
+ if (!isPlainObject9(existing) || existing.hooks === void 0) {
10993
11889
  return [];
10994
11890
  }
10995
- if (!isPlainObject8(existing.hooks)) {
11891
+ if (!isPlainObject9(existing.hooks)) {
10996
11892
  return [
10997
11893
  {
10998
11894
  location: "hooks",
@@ -11012,7 +11908,7 @@ var flatHookConflicts = (existing) => {
11012
11908
  return conflicts;
11013
11909
  };
11014
11910
  var asAntigravityEvents = (events) => events;
11015
- var documentEventNames = (existing) => isPlainObject8(existing) && isPlainObject8(existing.hooks) ? Object.keys(existing.hooks) : [];
11911
+ var documentEventNames = (existing) => isPlainObject9(existing) && isPlainObject9(existing.hooks) ? Object.keys(existing.hooks) : [];
11016
11912
  var PLANNERS = Object.freeze([
11017
11913
  Object.freeze({
11018
11914
  providerId: ANTIGRAVITY_PROVIDER_ID,
@@ -11021,7 +11917,7 @@ var PLANNERS = Object.freeze([
11021
11917
  const conflicts = flatHookConflicts(input.existing);
11022
11918
  if (conflicts.length > 0) {
11023
11919
  return {
11024
- document: isPlainObject8(input.existing) ? input.existing : {},
11920
+ document: isPlainObject9(input.existing) ? input.existing : {},
11025
11921
  changed: false,
11026
11922
  changes: [],
11027
11923
  conflicts
@@ -11047,7 +11943,7 @@ var PLANNERS = Object.freeze([
11047
11943
  const conflicts = flatHookConflicts(input.existing);
11048
11944
  if (conflicts.length > 0) {
11049
11945
  return {
11050
- document: isPlainObject8(input.existing) ? input.existing : {},
11946
+ document: isPlainObject9(input.existing) ? input.existing : {},
11051
11947
  changed: false,
11052
11948
  changes: [],
11053
11949
  conflicts
@@ -11090,7 +11986,7 @@ var PLANNERS = Object.freeze([
11090
11986
  const conflicts = flatHookConflicts(input.existing);
11091
11987
  if (conflicts.length > 0) {
11092
11988
  return {
11093
- document: isPlainObject8(input.existing) ? input.existing : {},
11989
+ document: isPlainObject9(input.existing) ? input.existing : {},
11094
11990
  changed: false,
11095
11991
  changes: [],
11096
11992
  conflicts
@@ -11117,7 +12013,7 @@ var PLANNERS = Object.freeze([
11117
12013
  const conflicts = flatHookConflicts(input.existing);
11118
12014
  if (conflicts.length > 0) {
11119
12015
  return {
11120
- document: isPlainObject8(input.existing) ? input.existing : {},
12016
+ document: isPlainObject9(input.existing) ? input.existing : {},
11121
12017
  changed: false,
11122
12018
  changes: [],
11123
12019
  conflicts
@@ -11282,7 +12178,7 @@ var resolveInstallPath = (location, roots) => path5.resolve(
11282
12178
 
11283
12179
  // src/install/document.ts
11284
12180
  import { randomBytes as randomBytes3 } from "crypto";
11285
- import { chmod, mkdir as mkdir3, open as open2, readFile as readFile4, rename as rename3, stat as stat2, unlink as unlink3 } from "fs/promises";
12181
+ import { chmod, mkdir as mkdir3, open as open2, readFile as readFile4, rename as rename3, stat as stat3, unlink as unlink3 } from "fs/promises";
11286
12182
  import * as path6 from "path";
11287
12183
  var DEFAULT_DOCUMENT_FORMAT = Object.freeze({
11288
12184
  indent: " ",
@@ -11362,7 +12258,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
11362
12258
  );
11363
12259
  let existingMode;
11364
12260
  try {
11365
- existingMode = (await stat2(filePath)).mode & 4095;
12261
+ existingMode = (await stat3(filePath)).mode & 4095;
11366
12262
  } catch (thrown) {
11367
12263
  if (!isErrnoException3(thrown, "ENOENT")) {
11368
12264
  throw thrown;
@@ -11387,7 +12283,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
11387
12283
 
11388
12284
  // src/install/file-lock.ts
11389
12285
  import { randomBytes as randomBytes4 } from "crypto";
11390
- import { mkdir as mkdir4, open as open3, readFile as readFile5, rename as rename4, stat as stat3, unlink as unlink4 } from "fs/promises";
12286
+ import { mkdir as mkdir4, open as open3, readFile as readFile5, rename as rename4, stat as stat4, unlink as unlink4 } from "fs/promises";
11391
12287
  import * as path7 from "path";
11392
12288
  var FileLockTimeoutError = class extends Error {
11393
12289
  constructor(lockPath, timeoutMillis) {
@@ -11452,7 +12348,7 @@ var isStale = async (lockPath, clock, staleMillis) => {
11452
12348
  } catch {
11453
12349
  }
11454
12350
  try {
11455
- const stats = await stat3(lockPath);
12351
+ const stats = await stat4(lockPath);
11456
12352
  return { stale: clock.now() - stats.mtimeMs > staleMillis };
11457
12353
  } catch (thrown) {
11458
12354
  return { stale: !isErrnoException4(thrown, "ENOENT") };
@@ -11942,7 +12838,7 @@ var runRegistrationCommand = async (command, io) => {
11942
12838
  };
11943
12839
 
11944
12840
  // src/cli/run.ts
11945
- import * as path13 from "path";
12841
+ import * as path14 from "path";
11946
12842
 
11947
12843
  // src/lifecycle/dedup.ts
11948
12844
  import { randomBytes as randomBytes5 } from "crypto";
@@ -11970,6 +12866,8 @@ var rollupUsageKey = (sessionId, scope, scopeKey) => `${rollupScanPrefix(session
11970
12866
  var rollupEpochKey = (sessionId, scope, scopeKey) => `${rollupEpochScanPrefix(sessionId)}${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;
11971
12867
  var rollupScanPrefix = (sessionId) => sessionId === void 0 ? `${LIFECYCLE_PREFIX}:usage:` : `${LIFECYCLE_PREFIX}:usage:${encodeSegment(sessionId)}:`;
11972
12868
  var rollupEpochScanPrefix = (sessionId) => sessionId === void 0 ? `${LIFECYCLE_PREFIX}:epoch:` : `${LIFECYCLE_PREFIX}:epoch:${encodeSegment(sessionId)}:`;
12869
+ var metricSeriesKey = (sessionScope2, seriesDigest) => `${metricSeriesScanPrefix(sessionScope2)}${encodeSegment(seriesDigest)}`;
12870
+ var metricSeriesScanPrefix = (sessionScope2) => sessionScope2 === void 0 ? `${LIFECYCLE_PREFIX}:metric:v1:` : `${LIFECYCLE_PREFIX}:metric:v1:${encodeSegment(sessionScope2)}:`;
11973
12871
 
11974
12872
  // src/lifecycle/dedup.ts
11975
12873
  var DEFAULT_STALE_CLAIM_MILLIS = 6e4;
@@ -12139,6 +13037,150 @@ var createCallbackDeduplicator = (deps) => {
12139
13037
  return { checkAndMark, claim, commit, release, cleanup };
12140
13038
  };
12141
13039
 
13040
+ // src/lifecycle/metric-series.ts
13041
+ import { createHash as createHash4 } from "crypto";
13042
+ var TURN_START_SEGMENT = "turn-start";
13043
+ var SHARED_SCOPE = "all";
13044
+ var SHARED_LOCK = "otelhook.metrics.shared";
13045
+ var sessionScope = (sessionId) => `s=${sessionId}`;
13046
+ var digest = (identity) => createHash4("sha256").update(identity).digest("base64url").slice(0, 43);
13047
+ var toStoredHistogram = (histogram) => ({
13048
+ count: histogram.count,
13049
+ sum: histogram.sum,
13050
+ // An empty histogram has infinite min/max, which JSON cannot hold. A stored
13051
+ // histogram always has at least one value, so these are finite in practice.
13052
+ min: Number.isFinite(histogram.min) ? histogram.min : 0,
13053
+ max: Number.isFinite(histogram.max) ? histogram.max : 0,
13054
+ bucketCounts: [...histogram.bucketCounts]
13055
+ });
13056
+ var createMetricSeriesStore = (deps) => {
13057
+ const { stateStore, clock } = deps;
13058
+ const readSeries = async (key) => {
13059
+ const record = await stateStore.read(key);
13060
+ if (record?.value.kind !== "metric-series") {
13061
+ return void 0;
13062
+ }
13063
+ return record.value;
13064
+ };
13065
+ const recordGroup = async (scope, observations, deliveryToken) => {
13066
+ const bySeries = /* @__PURE__ */ new Map();
13067
+ for (const observation of observations) {
13068
+ const identity = seriesIdentity(observation.instrument, observation.attributes);
13069
+ const group = bySeries.get(identity) ?? [];
13070
+ group.push(observation);
13071
+ bySeries.set(identity, group);
13072
+ }
13073
+ const now = clock.now();
13074
+ const points = [];
13075
+ for (const [identity, group] of bySeries) {
13076
+ const first = group[0];
13077
+ if (first === void 0) {
13078
+ continue;
13079
+ }
13080
+ const instrument = METRIC_INSTRUMENTS[first.instrument];
13081
+ const key = metricSeriesKey(scope, digest(identity));
13082
+ const existing = await readSeries(key);
13083
+ const boundaries = instrument.boundaries;
13084
+ const compatible = existing !== void 0 && (boundaries === void 0 ? existing.value !== void 0 : existing.histogram?.bucketCounts.length === boundaries.length + 1);
13085
+ const base = compatible ? existing : void 0;
13086
+ const replay = deliveryToken !== void 0 && base?.appliedDelivery === deliveryToken;
13087
+ const earliest = Math.min(...group.map((observation) => observation.timeMillis));
13088
+ const startTimeMillis = base?.startTimeMillis ?? Math.min(earliest, now);
13089
+ let value = base?.value ?? 0;
13090
+ let histogram = boundaries === void 0 ? void 0 : base?.histogram === void 0 ? emptyHistogram(boundaries) : base.histogram;
13091
+ if (!replay) {
13092
+ for (const observation of group) {
13093
+ if (histogram !== void 0 && boundaries !== void 0) {
13094
+ histogram = recordIntoHistogram(histogram, boundaries, observation.value);
13095
+ } else {
13096
+ value += observation.value;
13097
+ }
13098
+ }
13099
+ await stateStore.write(key, {
13100
+ kind: "metric-series",
13101
+ startTimeMillis,
13102
+ ...histogram === void 0 ? { value } : { histogram: toStoredHistogram(histogram) },
13103
+ ...deliveryToken === void 0 ? {} : { appliedDelivery: deliveryToken }
13104
+ });
13105
+ }
13106
+ points.push({
13107
+ instrument: first.instrument,
13108
+ temporality: "cumulative",
13109
+ attributes: first.attributes,
13110
+ startTimeMillis,
13111
+ timeMillis: Math.max(now, startTimeMillis),
13112
+ ...histogram === void 0 ? { value } : { histogram }
13113
+ });
13114
+ }
13115
+ return points;
13116
+ };
13117
+ const recordCumulative = async (observations, options) => {
13118
+ if (observations.length === 0) {
13119
+ return [];
13120
+ }
13121
+ if (options?.perSession === false) {
13122
+ return withOptionalSessionLock(
13123
+ stateStore,
13124
+ SHARED_LOCK,
13125
+ () => recordGroup(SHARED_SCOPE, observations, options.deliveryToken)
13126
+ );
13127
+ }
13128
+ const bySession = /* @__PURE__ */ new Map();
13129
+ for (const observation of observations) {
13130
+ const group = bySession.get(observation.sessionId) ?? [];
13131
+ group.push(observation);
13132
+ bySession.set(observation.sessionId, group);
13133
+ }
13134
+ const points = [];
13135
+ for (const [sessionId, group] of bySession) {
13136
+ points.push(
13137
+ ...await withOptionalSessionLock(
13138
+ stateStore,
13139
+ sessionId,
13140
+ () => recordGroup(sessionScope(sessionId), group, options?.deliveryToken)
13141
+ )
13142
+ );
13143
+ }
13144
+ return points;
13145
+ };
13146
+ const cleanup = async (maxAgeMillis, options) => {
13147
+ const cap = options?.maxEntries ?? 1e3;
13148
+ const now = clock.now();
13149
+ let removed = 0;
13150
+ let scanned = 0;
13151
+ const prefix = metricSeriesScanPrefix(
13152
+ options?.sessionId === void 0 ? void 0 : sessionScope(options.sessionId)
13153
+ );
13154
+ for (const key of await stateStore.keys(prefix)) {
13155
+ if (scanned >= cap) {
13156
+ break;
13157
+ }
13158
+ scanned += 1;
13159
+ const record = await stateStore.read(key);
13160
+ if (record !== void 0 && now - record.updatedAt > maxAgeMillis) {
13161
+ await stateStore.delete(key);
13162
+ removed += 1;
13163
+ }
13164
+ }
13165
+ return { removed, scanned };
13166
+ };
13167
+ const turnKey = (sessionId) => metricSeriesKey(sessionScope(sessionId), TURN_START_SEGMENT);
13168
+ const recordTurnStart = (sessionId, startMillis) => withOptionalSessionLock(stateStore, sessionId, async () => {
13169
+ const existing = await stateStore.read(turnKey(sessionId));
13170
+ const previous = existing?.value.kind === "attributes" && typeof existing.value.attributes.startMillis === "number" ? existing.value.attributes.startMillis : void 0;
13171
+ if (previous !== void 0 && previous >= startMillis) {
13172
+ return;
13173
+ }
13174
+ await stateStore.write(turnKey(sessionId), { kind: "attributes", attributes: { startMillis } });
13175
+ });
13176
+ const readTurnStart = async (sessionId) => {
13177
+ const record = await stateStore.read(turnKey(sessionId));
13178
+ const value = record?.value.kind === "attributes" ? record.value.attributes.startMillis : void 0;
13179
+ return typeof value === "number" ? value : void 0;
13180
+ };
13181
+ return { recordCumulative, recordTurnStart, readTurnStart, cleanup };
13182
+ };
13183
+
12142
13184
  // src/lifecycle/janitor.ts
12143
13185
  var DEFAULT_MAX_AGE_MILLIS = 24 * 60 * 60 * 1e3;
12144
13186
  var DEFAULT_MAX_ENTRIES_PER_COMPONENT = 1e3;
@@ -12149,7 +13191,7 @@ var createLifecycleJanitor = (options) => {
12149
13191
  const usageMaxAge = options.usageMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
12150
13192
  const runOnce = async (sessionId) => {
12151
13193
  const scope = { maxEntries, ...sessionId === void 0 ? {} : { sessionId } };
12152
- const [span, dedup, usage] = await Promise.all([
13194
+ const [span, dedup, usage, metrics] = await Promise.all([
12153
13195
  options.spanCorrelator?.cleanup(spanMaxAge, scope),
12154
13196
  // Deduplication is deliberately swept across every scope rather than the
12155
13197
  // ending session's: a delivery scope is a host-chosen namespace or a
@@ -12160,12 +13202,14 @@ var createLifecycleJanitor = (options) => {
12160
13202
  maxEntries,
12161
13203
  ...options.dedupStaleClaimMillis === void 0 ? {} : { staleClaimMillis: options.dedupStaleClaimMillis }
12162
13204
  }),
12163
- options.usageAccumulator?.cleanup(usageMaxAge, scope)
13205
+ options.usageAccumulator?.cleanup(usageMaxAge, scope),
13206
+ options.metricSeries?.cleanup(usageMaxAge, scope)
12164
13207
  ]);
12165
13208
  return {
12166
13209
  ...span === void 0 ? {} : { span },
12167
13210
  ...dedup === void 0 ? {} : { dedup },
12168
- ...usage === void 0 ? {} : { usage }
13211
+ ...usage === void 0 ? {} : { usage },
13212
+ ...metrics === void 0 ? {} : { metrics }
12169
13213
  };
12170
13214
  };
12171
13215
  return { runOnce };
@@ -12679,8 +13723,8 @@ var createUsageAccumulator = (deps) => {
12679
13723
  };
12680
13724
 
12681
13725
  // src/providers/claude/transcript.ts
12682
- import { createHash as createHash4 } from "crypto";
12683
- import { open as open4, stat as stat4 } from "fs/promises";
13726
+ import { createHash as createHash5 } from "crypto";
13727
+ import { open as open4, stat as stat5 } from "fs/promises";
12684
13728
  import path10 from "path";
12685
13729
  var DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES = 1048576;
12686
13730
  var DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS = 250;
@@ -12769,7 +13813,7 @@ var withTimeout = async (work, timeoutMillis, onError) => {
12769
13813
  var withRegularFile = async (transcriptPath, body) => {
12770
13814
  let info;
12771
13815
  try {
12772
- info = await stat4(transcriptPath);
13816
+ info = await stat5(transcriptPath);
12773
13817
  } catch {
12774
13818
  return { status: "unavailable", reason: "unreadable" };
12775
13819
  }
@@ -12897,11 +13941,11 @@ var hasUsage = (record) => record.usage !== void 0 || record.token_usage !== voi
12897
13941
  var eventNameOf = (record) => record.hook_event_name ?? record.hookEventName;
12898
13942
  var transcriptPathOf = (record) => record.transcript_path ?? record.transcriptPath;
12899
13943
  var CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
12900
- var sourceDigest = (transcriptPath) => createHash4("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
13944
+ var sourceDigest = (transcriptPath) => createHash5("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
12901
13945
  var createClaudeTranscriptUsageEnricher = (options = {}) => {
12902
13946
  const fileSize = async (transcriptPath) => {
12903
13947
  try {
12904
- const info = await stat4(transcriptPath);
13948
+ const info = await stat5(transcriptPath);
12905
13949
  return info.isFile() ? info.size : void 0;
12906
13950
  } catch (thrown) {
12907
13951
  return thrown?.code === "ENOENT" ? "absent" : void 0;
@@ -12974,7 +14018,7 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
12974
14018
  };
12975
14019
 
12976
14020
  // src/runtime/hook.ts
12977
- import { z as z23 } from "zod";
14021
+ import { z as z24 } from "zod";
12978
14022
 
12979
14023
  // src/runtime/delivery.ts
12980
14024
  var PROVIDER_SCOPE_PREFIX = "provider-session";
@@ -13006,9 +14050,9 @@ var resolveDeliveryIdentity = (input) => {
13006
14050
  };
13007
14051
 
13008
14052
  // src/runtime/ids.ts
13009
- import { createHash as createHash5, randomUUID } from "crypto";
13010
- var digest = (namespace, parts) => {
13011
- const hash = createHash5("sha256");
14053
+ import { createHash as createHash6, randomUUID } from "crypto";
14054
+ var digest2 = (namespace, parts) => {
14055
+ const hash = createHash6("sha256");
13012
14056
  hash.update(namespace);
13013
14057
  for (const part of parts) {
13014
14058
  hash.update("\0");
@@ -13023,7 +14067,7 @@ var createDeterministicIdGenerator = (options = {}) => {
13023
14067
  return {
13024
14068
  newInvocationId: (seed) => invocationIdSchema.parse(
13025
14069
  `inv_${truncate(
13026
- digest(`${namespace}/invocation`, [
14070
+ digest2(`${namespace}/invocation`, [
13027
14071
  seed.providerId,
13028
14072
  seed.sessionId,
13029
14073
  seed.sourceEventName,
@@ -13034,7 +14078,7 @@ var createDeterministicIdGenerator = (options = {}) => {
13034
14078
  ),
13035
14079
  newEventId: (seed) => eventIdSchema.parse(
13036
14080
  `evt_${truncate(
13037
- digest(`${namespace}/event`, [
14081
+ digest2(`${namespace}/event`, [
13038
14082
  seed.invocationId,
13039
14083
  seed.sequence,
13040
14084
  seed.eventType,
@@ -13042,7 +14086,7 @@ var createDeterministicIdGenerator = (options = {}) => {
13042
14086
  ])
13043
14087
  )}`
13044
14088
  ),
13045
- newOpaqueId: (parts) => truncate(digest(`${namespace}/opaque`, parts))
14089
+ newOpaqueId: (parts) => truncate(digest2(`${namespace}/opaque`, parts))
13046
14090
  };
13047
14091
  };
13048
14092
 
@@ -13134,8 +14178,200 @@ var resolveEventTargets = async (input) => {
13134
14178
  return { events, resolved: settled.size, timedOut: finished === "timeout" };
13135
14179
  };
13136
14180
 
14181
+ // src/runtime/session-context.ts
14182
+ import { open as open5 } from "fs/promises";
14183
+ import * as path12 from "path";
14184
+ import { z as z23 } from "zod";
14185
+ var SESSION_CONTEXT_FILE_VERSION = 1;
14186
+ var DEFAULT_SESSION_CONTEXT_MAX_BYTES = 256 * 1024;
14187
+ var DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS = 100;
14188
+ var MAX_SESSION_CONTEXT_SEGMENTS = 1024;
14189
+ var SESSION_CONTEXT_AGENT_TOOLS = Object.freeze({
14190
+ "claude-code": "claude_code",
14191
+ codex: "codex",
14192
+ cursor: "cursor",
14193
+ "gemini-cli": "gemini_cli",
14194
+ antigravity: "antigravity"
14195
+ });
14196
+ var sessionContextAgentTool = (providerId) => Object.hasOwn(SESSION_CONTEXT_AGENT_TOOLS, providerId) ? SESSION_CONTEXT_AGENT_TOOLS[providerId] : void 0;
14197
+ var SESSION_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
14198
+ var isSessionContextFileName = (sessionId) => SESSION_FILE_NAME_PATTERN.test(sessionId) && !sessionId.includes("..");
14199
+ var sessionContextFilePath = (dir, providerId, sessionId) => {
14200
+ const tool = sessionContextAgentTool(providerId);
14201
+ if (tool === void 0 || !isSessionContextFileName(sessionId) || !path12.isAbsolute(dir)) {
14202
+ return void 0;
14203
+ }
14204
+ return path12.join(dir, tool, `${sessionId}.json`);
14205
+ };
14206
+ var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([
14207
+ "session.id",
14208
+ "trace_id",
14209
+ "span_id",
14210
+ "parent_span_id",
14211
+ "gen_ai.conversation.id",
14212
+ "factory.local"
14213
+ ]);
14214
+ var RESERVED_CONTEXT_PREFIXES = Object.freeze(["factory.local.", "otelhook."]);
14215
+ var isReservedSessionContextKey = (key) => RESERVED_CONTEXT_KEYS.has(key) || RESERVED_CONTEXT_PREFIXES.some((prefix) => key.startsWith(prefix));
14216
+ var sanitizeSessionContextAttributes = (attributes) => {
14217
+ const kept = {};
14218
+ let count = 0;
14219
+ for (const [key, value] of Object.entries(attributes)) {
14220
+ if (count >= MAX_RESOURCE_ATTRIBUTES) {
14221
+ break;
14222
+ }
14223
+ if (checkResourceAttributeKey(key) !== void 0 || isReservedSessionContextKey(key)) {
14224
+ continue;
14225
+ }
14226
+ if (typeof value === "string") {
14227
+ if (value.length > MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) {
14228
+ continue;
14229
+ }
14230
+ } else if (typeof value === "number") {
14231
+ if (!Number.isFinite(value)) {
14232
+ continue;
14233
+ }
14234
+ } else if (typeof value !== "boolean") {
14235
+ continue;
14236
+ }
14237
+ kept[key] = value;
14238
+ count += 1;
14239
+ }
14240
+ return kept;
14241
+ };
14242
+ var ISO_INSTANT_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}:\d{2})$/;
14243
+ var isoInstantSchema = z23.string().max(64).regex(ISO_INSTANT_PATTERN).transform((value, ctx) => {
14244
+ const millis = Date.parse(value);
14245
+ if (!Number.isFinite(millis)) {
14246
+ ctx.issues.push({ code: "custom", input: value, message: "not a valid instant" });
14247
+ return z23.NEVER;
14248
+ }
14249
+ return millis;
14250
+ });
14251
+ var segmentSchema = z23.object({
14252
+ from: isoInstantSchema,
14253
+ to: isoInstantSchema.nullable(),
14254
+ reason: z23.string().max(256).optional(),
14255
+ attributes: z23.record(z23.string(), z23.unknown())
14256
+ });
14257
+ var sessionContextFileSchema = z23.object({
14258
+ version: z23.literal(SESSION_CONTEXT_FILE_VERSION),
14259
+ agentTool: z23.string().max(64).optional(),
14260
+ sessionId: z23.string().max(256).optional(),
14261
+ segments: z23.array(segmentSchema).max(MAX_SESSION_CONTEXT_SEGMENTS)
14262
+ });
14263
+ var parseSessionContextFile = (value, expected) => {
14264
+ const parsed = sessionContextFileSchema.safeParse(value);
14265
+ if (!parsed.success) {
14266
+ return void 0;
14267
+ }
14268
+ const file = parsed.data;
14269
+ if (expected?.agentTool !== void 0 && file.agentTool !== void 0 && file.agentTool !== expected.agentTool || expected?.sessionId !== void 0 && file.sessionId !== void 0 && file.sessionId !== expected.sessionId) {
14270
+ return void 0;
14271
+ }
14272
+ return file.segments.map((segment) => ({
14273
+ from: segment.from,
14274
+ to: segment.to,
14275
+ attributes: sanitizeSessionContextAttributes(segment.attributes)
14276
+ }));
14277
+ };
14278
+ var segmentInForce = (segments, at) => {
14279
+ let best;
14280
+ for (const segment of segments) {
14281
+ if (segment.from <= at && (segment.to === null || at < segment.to)) {
14282
+ if (best === void 0 || segment.from >= best.from) {
14283
+ best = segment;
14284
+ }
14285
+ }
14286
+ }
14287
+ return best;
14288
+ };
14289
+ var stampSessionContext = (events, segments) => events.map((event3) => {
14290
+ const { contextAttributes: _discarded, ...rest } = event3;
14291
+ const segment = segments === void 0 ? void 0 : segmentInForce(segments, event3.occurredAt);
14292
+ if (segment === void 0 || Object.keys(segment.attributes).length === 0) {
14293
+ return _discarded === void 0 ? event3 : rest;
14294
+ }
14295
+ return { ...rest, contextAttributes: { ...segment.attributes } };
14296
+ });
14297
+ var readBounded = async (file, maxBytes) => {
14298
+ let handle;
14299
+ try {
14300
+ handle = await open5(file, "r");
14301
+ } catch {
14302
+ return void 0;
14303
+ }
14304
+ try {
14305
+ const stats = await handle.stat();
14306
+ if (!stats.isFile() || stats.size > maxBytes) {
14307
+ return void 0;
14308
+ }
14309
+ const buffer = Buffer.alloc(maxBytes + 1);
14310
+ let length = 0;
14311
+ while (length < buffer.length) {
14312
+ const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
14313
+ if (bytesRead === 0) {
14314
+ break;
14315
+ }
14316
+ length += bytesRead;
14317
+ }
14318
+ if (length > maxBytes) {
14319
+ return void 0;
14320
+ }
14321
+ return buffer.subarray(0, length).toString("utf8");
14322
+ } catch {
14323
+ return void 0;
14324
+ } finally {
14325
+ await handle.close().catch(() => void 0);
14326
+ }
14327
+ };
14328
+ var createDirectorySessionContextReader = (options) => {
14329
+ const maxBytes = options.maxBytes ?? DEFAULT_SESSION_CONTEXT_MAX_BYTES;
14330
+ const budgetMillis = options.budgetMillis ?? DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS;
14331
+ const readOnce = async (providerId, sessionId) => {
14332
+ const file = sessionContextFilePath(options.dir, providerId, sessionId);
14333
+ if (file === void 0) {
14334
+ return void 0;
14335
+ }
14336
+ const text = await readBounded(file, maxBytes);
14337
+ if (text === void 0) {
14338
+ return void 0;
14339
+ }
14340
+ let decoded;
14341
+ try {
14342
+ decoded = JSON.parse(text);
14343
+ } catch {
14344
+ return void 0;
14345
+ }
14346
+ const agentTool = sessionContextAgentTool(providerId);
14347
+ return parseSessionContextFile(decoded, {
14348
+ ...agentTool === void 0 ? {} : { agentTool },
14349
+ sessionId
14350
+ });
14351
+ };
14352
+ return {
14353
+ read: async (request) => {
14354
+ let timer;
14355
+ const timeout = new Promise((resolve8) => {
14356
+ timer = setTimeout(() => resolve8(void 0), budgetMillis);
14357
+ timer.unref?.();
14358
+ });
14359
+ try {
14360
+ return await Promise.race([
14361
+ readOnce(request.providerId, request.sessionId).catch(() => void 0),
14362
+ timeout
14363
+ ]);
14364
+ } finally {
14365
+ if (timer !== void 0) {
14366
+ clearTimeout(timer);
14367
+ }
14368
+ }
14369
+ }
14370
+ };
14371
+ };
14372
+
13137
14373
  // src/runtime/hook.ts
13138
- var usageScopeSchema = z23.enum(["session", "generation", "subagent"]);
14374
+ var usageScopeSchema = z24.enum(["session", "generation", "subagent"]);
13139
14375
  var classifyDurability = (input) => {
13140
14376
  if (!input.attempted) {
13141
14377
  return "nothing-to-deliver";
@@ -13844,6 +15080,10 @@ var createOtelHook = (deps) => {
13844
15080
  });
13845
15081
  }
13846
15082
  }
15083
+ batch = stampSessionContext(
15084
+ batch,
15085
+ !suppress && batch.length > 0 && deps.sessionContext !== void 0 ? await readSessionContext(deps.sessionContext, detection.providerId, identity.sessionId) : void 0
15086
+ );
13847
15087
  let emitted = 0;
13848
15088
  let exportRejected = 0;
13849
15089
  if (!suppress && batch.length > 0) {
@@ -13959,6 +15199,13 @@ var createOtelHook = (deps) => {
13959
15199
  };
13960
15200
  return { resolveDelivery, ingest, flush, shutdown, config };
13961
15201
  };
15202
+ var readSessionContext = async (reader, providerId, sessionId) => {
15203
+ try {
15204
+ return await reader.read({ providerId, sessionId });
15205
+ } catch {
15206
+ return void 0;
15207
+ }
15208
+ };
13962
15209
  var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
13963
15210
  const events = [];
13964
15211
  for (const [index, info] of diagnostics.slice(0, MAX_ERROR_EVENTS).entries()) {
@@ -13993,8 +15240,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
13993
15240
  };
13994
15241
 
13995
15242
  // src/runtime/git-worktree.ts
13996
- import { lstat, open as open5, stat as stat5 } from "fs/promises";
13997
- import * as path12 from "path";
15243
+ import { lstat, open as open6, stat as stat6 } from "fs/promises";
15244
+ import * as path13 from "path";
13998
15245
  var MAX_WORKTREE_WALK_DEPTH = 128;
13999
15246
  var MAX_GIT_FILE_BYTES = 4096;
14000
15247
  var MAX_CACHE_ENTRIES = 1024;
@@ -14002,10 +15249,10 @@ var DEFAULT_WORKTREE_CACHE_TTL_MILLIS = 5e3;
14002
15249
  var MAX_BRANCH_NAME_LENGTH = 255;
14003
15250
  var ABSENT = Object.freeze({ kind: "absent" });
14004
15251
  var INVALID = Object.freeze({ kind: "invalid" });
14005
- var readBounded = async (filePath) => {
15252
+ var readBounded2 = async (filePath) => {
14006
15253
  let handle;
14007
15254
  try {
14008
- handle = await open5(filePath, "r");
15255
+ handle = await open6(filePath, "r");
14009
15256
  const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
14010
15257
  const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
14011
15258
  return buffer.subarray(0, bytesRead).toString("utf8");
@@ -14026,7 +15273,7 @@ var parseHeadBranch = (head) => {
14026
15273
  return branch;
14027
15274
  };
14028
15275
  var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
14029
- var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path12.resolve(base, target);
15276
+ var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path13.resolve(base, target);
14030
15277
  var parseGitDirFile = (content, worktreeRoot) => {
14031
15278
  const line = firstLine(content);
14032
15279
  return resolveGitPath(
@@ -14046,26 +15293,26 @@ var isMissing = async (filePath) => {
14046
15293
  };
14047
15294
  var isDirectory = async (directory) => {
14048
15295
  try {
14049
- return (await stat5(directory)).isDirectory();
15296
+ return (await stat6(directory)).isDirectory();
14050
15297
  } catch {
14051
15298
  return false;
14052
15299
  }
14053
15300
  };
14054
15301
  var repositoryOf = async (worktreeRoot, gitDir) => {
14055
- const commonDirFile = path12.join(gitDir, "commondir");
14056
- const content = await readBounded(commonDirFile);
15302
+ const commonDirFile = path13.join(gitDir, "commondir");
15303
+ const content = await readBounded2(commonDirFile);
14057
15304
  if (content === void 0) {
14058
15305
  return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
14059
15306
  }
14060
15307
  const commonDir = parseCommonDirFile(content, gitDir);
14061
- const mainRoot = commonDir !== void 0 && path12.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path12.dirname(commonDir) : void 0;
15308
+ const mainRoot = commonDir !== void 0 && path13.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path13.dirname(commonDir) : void 0;
14062
15309
  return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
14063
15310
  };
14064
15311
  var probeDirectory = async (directory) => {
14065
- const dotGit = path12.join(directory, ".git");
15312
+ const dotGit = path13.join(directory, ".git");
14066
15313
  let info;
14067
15314
  try {
14068
- info = await stat5(dotGit);
15315
+ info = await stat6(dotGit);
14069
15316
  } catch {
14070
15317
  return ABSENT;
14071
15318
  }
@@ -14073,13 +15320,13 @@ var probeDirectory = async (directory) => {
14073
15320
  if (info.isDirectory()) {
14074
15321
  gitDir = dotGit;
14075
15322
  } else if (info.isFile()) {
14076
- const content = await readBounded(dotGit);
15323
+ const content = await readBounded2(dotGit);
14077
15324
  gitDir = content === void 0 ? void 0 : parseGitDirFile(content, directory);
14078
15325
  }
14079
15326
  if (gitDir === void 0) {
14080
15327
  return INVALID;
14081
15328
  }
14082
- const head = await readBounded(path12.join(gitDir, "HEAD"));
15329
+ const head = await readBounded2(path13.join(gitDir, "HEAD"));
14083
15330
  if (head === void 0) {
14084
15331
  return INVALID;
14085
15332
  }
@@ -14109,10 +15356,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
14109
15356
  };
14110
15357
  const locate = async (absolutePath) => {
14111
15358
  try {
14112
- if (!path12.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
15359
+ if (!path13.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
14113
15360
  return void 0;
14114
15361
  }
14115
- let directory = path12.resolve(absolutePath);
15362
+ let directory = path13.resolve(absolutePath);
14116
15363
  for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
14117
15364
  const probe = await cachedProbe(directory);
14118
15365
  if (probe.kind === "worktree") {
@@ -14121,7 +15368,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
14121
15368
  if (probe.kind === "invalid") {
14122
15369
  return void 0;
14123
15370
  }
14124
- const parent = path12.dirname(directory);
15371
+ const parent = path13.dirname(directory);
14125
15372
  if (parent === directory) {
14126
15373
  return void 0;
14127
15374
  }
@@ -14248,6 +15495,16 @@ var createHookRuntime = (options) => {
14248
15495
  logger,
14249
15496
  installationId: options.installationId,
14250
15497
  payloadEnrichers: options.payloadEnrichers ?? (readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : []),
15498
+ ...(() => {
15499
+ if (options.sessionContextReader === null) {
15500
+ return {};
15501
+ }
15502
+ if (options.sessionContextReader !== void 0) {
15503
+ return { sessionContext: options.sessionContextReader };
15504
+ }
15505
+ const dir = sessionContextDir(options.config);
15506
+ return dir === void 0 ? {} : { sessionContext: createDirectorySessionContextReader({ dir }) };
15507
+ })(),
14251
15508
  ...options.worktreeLocator === null ? {} : {
14252
15509
  worktreeLocator: options.worktreeLocator ?? createFilesystemWorktreeLocator({ monotonicMillis: () => clock.monotonicMillis() })
14253
15510
  }
@@ -14255,6 +15512,12 @@ var createHookRuntime = (options) => {
14255
15512
  const hook = createOtelHook({ ...hookDeps, sink });
14256
15513
  const deduplicator = createCallbackDeduplicator({ stateStore, clock });
14257
15514
  const usageAccumulator = createUsageAccumulator({ stateStore, clock });
15515
+ const metricSeries = createMetricSeriesStore({ stateStore, clock });
15516
+ const metricsPolicy = effectiveMetricsPolicy(options.config.exporter);
15517
+ const metricDestinations = exportDestinations.destinations.filter(
15518
+ (destination) => destination.metrics.enabled
15519
+ );
15520
+ const metricResource = resourceFromExporterPolicy(options.config.exporter);
14258
15521
  const deliveryRetentionMillis = options.deliveryRetentionMillis ?? lifecycleMaxAge;
14259
15522
  if (deliveryRetentionMillis < staleClaimMillis) {
14260
15523
  logger.warn("delivery retention is shorter than the stale-claim window", {
@@ -14266,6 +15529,7 @@ var createHookRuntime = (options) => {
14266
15529
  spanCorrelator,
14267
15530
  deduplicator,
14268
15531
  usageAccumulator,
15532
+ metricSeries,
14269
15533
  spanMaxAgeMillis: lifecycleMaxAge,
14270
15534
  dedupMaxAgeMillis: deliveryRetentionMillis,
14271
15535
  // The *effective* window, not the requested one: a sweep that considered a
@@ -14276,6 +15540,87 @@ var createHookRuntime = (options) => {
14276
15540
  });
14277
15541
  const deliveryLock = createAsyncLock();
14278
15542
  const stateDiagnostic = (thrown) => errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() });
15543
+ const generationStartsFor = async (events) => {
15544
+ const needed = events.some(
15545
+ (event3) => event3.type === "generation.end" && event3.durationMillis === void 0 && !events.some(
15546
+ (other) => other.type === "generation.start" && other.generationId === event3.generationId
15547
+ )
15548
+ );
15549
+ if (!needed) {
15550
+ return void 0;
15551
+ }
15552
+ try {
15553
+ const starts = /* @__PURE__ */ new Map();
15554
+ for (const correlation of await correlate(events)) {
15555
+ if (correlation.ref.family !== "generation" || correlation.startMillis === void 0) {
15556
+ continue;
15557
+ }
15558
+ const requestModel = correlation.attributes?.["gen_ai.request.model"];
15559
+ starts.set(correlation.ref.scopeKey, {
15560
+ startMillis: correlation.startMillis,
15561
+ ...typeof requestModel === "string" ? { requestModel } : {}
15562
+ });
15563
+ }
15564
+ return (generationId) => starts.get(generationId);
15565
+ } catch {
15566
+ return void 0;
15567
+ }
15568
+ };
15569
+ const recordMetrics = async (ingest, deliveryToken, diagnostics) => {
15570
+ if (metricDestinations.length === 0 || ingest.events.length === 0) {
15571
+ return void 0;
15572
+ }
15573
+ try {
15574
+ for (const event3 of ingest.events) {
15575
+ if (event3.type === "prompt.submitted") {
15576
+ await metricSeries.recordTurnStart(event3.sessionId, event3.occurredAt);
15577
+ }
15578
+ }
15579
+ const generationStarts = await generationStartsFor(ingest.events);
15580
+ const turnStarts = /* @__PURE__ */ new Map();
15581
+ for (const event3 of ingest.events) {
15582
+ if (event3.type === "generation.end" && !turnStarts.has(event3.sessionId)) {
15583
+ turnStarts.set(event3.sessionId, await metricSeries.readTurnStart(event3.sessionId));
15584
+ }
15585
+ }
15586
+ const observations = deriveMetricObservations({
15587
+ events: ingest.events,
15588
+ usage: ingest.usageObservations,
15589
+ resource: metricResource,
15590
+ includeSessionId: metricsPolicy.includeSessionId,
15591
+ ...generationStarts === void 0 ? {} : { generationStarts },
15592
+ turnStart: (sessionId) => turnStarts.get(sessionId)
15593
+ });
15594
+ if (observations.length === 0) {
15595
+ return void 0;
15596
+ }
15597
+ const points = metricsPolicy.temporality === "delta" ? aggregateDeltaPoints(observations, clock.now()) : await metricSeries.recordCumulative(observations, {
15598
+ perSession: metricsPolicy.includeSessionId,
15599
+ ...deliveryToken === void 0 ? {} : { deliveryToken }
15600
+ });
15601
+ const context = agreedContextAttributes(ingest.events);
15602
+ const results = await Promise.all(
15603
+ metricDestinations.map(async (destination) => {
15604
+ const result = await destination.metrics.exportPoints(points, context).catch(
15605
+ (thrown) => ({
15606
+ accepted: 0,
15607
+ rejected: points.length,
15608
+ errors: [
15609
+ errorInfoFromThrown(thrown, { code: "telemetry-export-failure", phase: "export" })
15610
+ ]
15611
+ })
15612
+ );
15613
+ diagnostics.push(...result.errors);
15614
+ return { name: destination.name, accepted: result.accepted, rejected: result.rejected };
15615
+ })
15616
+ );
15617
+ return { points: points.length, destinations: results };
15618
+ } catch (thrown) {
15619
+ diagnostics.push(stateDiagnostic(thrown));
15620
+ logger.warn("hook-derived metrics could not be recorded for this callback", {});
15621
+ return void 0;
15622
+ }
15623
+ };
14279
15624
  const rollupDeliveryToken = (identity) => {
14280
15625
  const token = ids.newOpaqueId(["usage-delivery", identity.scope, identity.callbackId]).replace(/[^A-Za-z0-9_-]/g, "").slice(0, 128);
14281
15626
  return token.length === 0 ? void 0 : token;
@@ -14396,6 +15741,11 @@ var createHookRuntime = (options) => {
14396
15741
  identity === void 0 ? void 0 : rollupDeliveryToken(identity)
14397
15742
  );
14398
15743
  }
15744
+ const metrics = !duplicateDelivery && ingest.identity !== void 0 && isCommittable(ingest.durability) ? await recordMetrics(
15745
+ ingest,
15746
+ identity === void 0 ? void 0 : rollupDeliveryToken(identity),
15747
+ diagnostics
15748
+ ) : void 0;
14399
15749
  if (owned && identity !== void 0) {
14400
15750
  try {
14401
15751
  if (isCommittable(ingest.durability)) {
@@ -14462,6 +15812,7 @@ var createHookRuntime = (options) => {
14462
15812
  duplicateDelivery,
14463
15813
  delivery,
14464
15814
  usageRollups,
15815
+ ...metrics === void 0 ? {} : { metrics },
14465
15816
  ...cleanup === void 0 ? {} : { cleanup },
14466
15817
  diagnostics
14467
15818
  };
@@ -14478,12 +15829,20 @@ var createHookRuntime = (options) => {
14478
15829
  () => runProcess(input, identified.identity, report, diagnostics)
14479
15830
  );
14480
15831
  };
14481
- const snapshots = () => sink.health();
15832
+ const snapshots = () => [
15833
+ ...sink.health(),
15834
+ ...metricDestinations.map((destination) => destination.metrics.health())
15835
+ ];
14482
15836
  let shutdownReport;
14483
15837
  const shutdown = () => {
14484
15838
  shutdownReport ??= (async () => {
14485
15839
  const raced = await Promise.race([
14486
- hook.shutdown().then(() => "completed"),
15840
+ Promise.all([
15841
+ hook.shutdown(),
15842
+ // Metric sinks are not behind the hook's sink: they replay their own
15843
+ // spools here, inside the same bounded window.
15844
+ ...metricDestinations.map((destination) => destination.metrics.shutdown().catch(() => void 0))
15845
+ ]).then(() => "completed"),
14487
15846
  delay3(flushTimeoutMillis)
14488
15847
  ]);
14489
15848
  if (raced === "timeout") {
@@ -14513,6 +15872,7 @@ var createHookRuntime = (options) => {
14513
15872
  deduplicator,
14514
15873
  usageAccumulator,
14515
15874
  spanCorrelator,
15875
+ metricSeries,
14516
15876
  janitor,
14517
15877
  process: process_,
14518
15878
  shutdown,
@@ -14810,13 +16170,13 @@ var runHookCommand = async (command, io) => {
14810
16170
  }
14811
16171
  const identityClaims = [];
14812
16172
  if (command.identity.identityFile !== void 0) {
14813
- const read = await readIdentityFile(path13.resolve(command.identity.identityFile));
16173
+ const read = await readIdentityFile(path14.resolve(command.identity.identityFile));
14814
16174
  if ("error" in read) {
14815
16175
  logDiagnostics(logger, [read.error]);
14816
16176
  } else {
14817
16177
  const fromFile = claimFromIdentityFile(
14818
16178
  read.value,
14819
- path13.basename(command.identity.identityFile)
16179
+ path14.basename(command.identity.identityFile)
14820
16180
  );
14821
16181
  logDiagnostics(logger, fromFile.errors);
14822
16182
  identityClaims.push(...fromFile.claims);