@osfactory/otel-hook 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +82 -3
  2. package/dist/{adapter-B9RwW6TO.d.ts → adapter-DiLknaTF.d.ts} +1 -1
  3. package/dist/cli.js +1131 -77
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +11 -4
  6. package/dist/config.js +100 -18
  7. package/dist/config.js.map +1 -1
  8. package/dist/{destinations-DWOkVxV1.d.ts → destinations-BIl3gGzx.d.ts} +12 -2
  9. package/dist/diagnostics.d.ts +1 -1
  10. package/dist/diagnostics.js.map +1 -1
  11. package/dist/{export-destinations-lORbe25J.d.ts → export-destinations-QWKGGEjk.d.ts} +130 -5
  12. package/dist/{filesystem-store-DX3dGIgu.d.ts → filesystem-store-D3SCNmbX.d.ts} +1 -1
  13. package/dist/{hook-BAxXoKsp.d.ts → hook-BOecWGSz.d.ts} +4 -4
  14. package/dist/index.d.ts +14 -14
  15. package/dist/index.js +1114 -90
  16. package/dist/index.js.map +1 -1
  17. package/dist/install.d.ts +3 -3
  18. package/dist/integration.d.ts +29 -11
  19. package/dist/integration.js +1117 -154
  20. package/dist/integration.js.map +1 -1
  21. package/dist/lifecycle.d.ts +54 -3
  22. package/dist/lifecycle.js +270 -4
  23. package/dist/lifecycle.js.map +1 -1
  24. package/dist/{memory-aJilVG4R.d.ts → memory-Cs51jyRk.d.ts} +1 -1
  25. package/dist/{semconv-Dw7gcQcg.d.ts → metric-model-DDnWxL9d.d.ts} +154 -2
  26. package/dist/{payload-D7gc0-WQ.d.ts → payload-ChtrEX6A.d.ts} +1 -1
  27. package/dist/{ports-plO5MKrY.d.ts → ports-CeqLq31i.d.ts} +24 -0
  28. package/dist/providers.d.ts +8 -8
  29. package/dist/{registry-C7XO4DzD.d.ts → registry-CcJNF3WY.d.ts} +2 -2
  30. package/dist/runtime.d.ts +7 -7
  31. package/dist/runtime.js +55 -9
  32. package/dist/runtime.js.map +1 -1
  33. package/dist/{schema-CHb3GU1r.d.ts → schema-DMnoU1V_.d.ts} +64 -1
  34. package/dist/state.d.ts +3 -3
  35. package/dist/state.js +23 -0
  36. package/dist/state.js.map +1 -1
  37. package/dist/telemetry.d.ts +5 -5
  38. package/dist/telemetry.js +860 -17
  39. package/dist/telemetry.js.map +1 -1
  40. package/dist/testing.d.ts +8 -8
  41. package/dist/testing.js +55 -9
  42. package/dist/testing.js.map +1 -1
  43. package/package.json +3 -1
package/dist/index.js CHANGED
@@ -1820,7 +1820,7 @@ var HEADER_ENV_REFERENCE_PREFIX = "env:";
1820
1820
  var HEADER_NAME_PATTERN2 = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
1821
1821
  var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
1822
1822
  var MAX_HEADER_VALUE_LENGTH = 8192;
1823
- var exportSignalSchema = z13.enum(["traces", "logs"]);
1823
+ var exportSignalSchema = z13.enum(["traces", "logs", "metrics"]);
1824
1824
  var headerValueSchema = z13.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
1825
1825
  (value) => !isUnsafeHeaderValue(value),
1826
1826
  "header values may not contain line breaks, control characters, or characters beyond Latin-1"
@@ -1843,6 +1843,8 @@ var exportDestinationSchema = z13.strictObject({
1843
1843
  tracesEndpoint: endpointSchema.optional(),
1844
1844
  /** Per-signal override of the derived logs URL. */
1845
1845
  logsEndpoint: endpointSchema.optional(),
1846
+ /** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */
1847
+ metricsEndpoint: endpointSchema.optional(),
1846
1848
  /** Defaults to `exporter.protocol`. */
1847
1849
  protocol: z13.enum(["http/protobuf", "http/json", "none"]).optional(),
1848
1850
  /**
@@ -1855,15 +1857,17 @@ var exportDestinationSchema = z13.strictObject({
1855
1857
  `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
1856
1858
  ).optional(),
1857
1859
  /**
1858
- * Which signals this destination receives. Default: both. The logs signal is
1859
- * still governed by `exporter.logs.enabled`, which stays the one opt-in for a
1860
- * second stream leaving the host.
1860
+ * Which signals this destination receives. Default: traces and logs. The logs
1861
+ * signal is still governed by `exporter.logs.enabled`, which stays the one
1862
+ * opt-in for content-bearing records leaving the host. `metrics` is never on by
1863
+ * default: a destination receives hook-derived metrics only when it lists them.
1861
1864
  */
1862
- signals: z13.array(exportSignalSchema).min(1).max(2).readonly().optional()
1865
+ signals: z13.array(exportSignalSchema).min(1).max(3).readonly().optional()
1863
1866
  }).refine(
1864
- (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0,
1865
- "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint"
1867
+ (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
1868
+ "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
1866
1869
  );
1870
+ var DEFAULT_DESTINATION_SIGNALS = Object.freeze(["traces", "logs"]);
1867
1871
  var exportDestinationsSchema = z13.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
1868
1872
  const seen = /* @__PURE__ */ new Set();
1869
1873
  destinations.forEach((destination, index) => {
@@ -1908,7 +1912,8 @@ var legacyDestination = (exporter) => ({
1908
1912
  protocol: exporter.protocol,
1909
1913
  ...exporter.endpoint === void 0 ? {} : { endpoint: exporter.endpoint },
1910
1914
  ...exporter.logs.endpoint === void 0 ? {} : { logsEndpoint: exporter.logs.endpoint },
1911
- signals: { traces: true, logs: exporter.logs.enabled },
1915
+ ...exporter.metrics?.endpoint === void 0 ? {} : { metricsEndpoint: exporter.metrics.endpoint },
1916
+ signals: { traces: true, logs: exporter.logs.enabled, metrics: exporter.metrics?.enabled === true },
1912
1917
  headers: {}
1913
1918
  });
1914
1919
  var hasConfiguredDestinations = (exporter) => exporter.destinations !== void 0 && exporter.destinations.length > 0;
@@ -1917,14 +1922,14 @@ var resolveExportDestinations = (exporter) => {
1917
1922
  return [legacyDestination(exporter)];
1918
1923
  }
1919
1924
  const resolved = [];
1920
- if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0) {
1925
+ if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0 || exporter.metrics?.endpoint !== void 0) {
1921
1926
  resolved.push(legacyDestination(exporter));
1922
1927
  }
1923
1928
  for (const destination of exporter.destinations ?? []) {
1924
1929
  if (destination.enabled === false) {
1925
1930
  continue;
1926
1931
  }
1927
- const signals = destination.signals ?? exportSignalSchema.options;
1932
+ const signals = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;
1928
1933
  resolved.push({
1929
1934
  name: destination.name,
1930
1935
  source: "destinations",
@@ -1932,9 +1937,11 @@ var resolveExportDestinations = (exporter) => {
1932
1937
  ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
1933
1938
  ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
1934
1939
  ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
1940
+ ...destination.metricsEndpoint === void 0 ? {} : { metricsEndpoint: destination.metricsEndpoint },
1935
1941
  signals: {
1936
1942
  traces: signals.includes("traces"),
1937
- logs: exporter.logs.enabled && signals.includes("logs")
1943
+ logs: exporter.logs.enabled && signals.includes("logs"),
1944
+ metrics: signals.includes("metrics")
1938
1945
  },
1939
1946
  headers: { ...destination.headers ?? {} }
1940
1947
  });
@@ -1976,6 +1983,9 @@ var describeExportDestinations = (exporter) => {
1976
1983
  const logsOrigin = endpointOrigin(
1977
1984
  destination.logsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint
1978
1985
  );
1986
+ const metricsOrigin = endpointOrigin(
1987
+ destination.metricsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint
1988
+ );
1979
1989
  const variables = Object.values(destination.headers).map(parseHeaderValueReference).flatMap((reference) => reference.kind === "env" ? [reference.variable] : []);
1980
1990
  return {
1981
1991
  name: destination.name,
@@ -1984,6 +1994,7 @@ var describeExportDestinations = (exporter) => {
1984
1994
  signals: exportSignalSchema.options.filter((signal) => destination.signals[signal]),
1985
1995
  ...tracesOrigin === void 0 || !destination.signals.traces ? {} : { tracesEndpointOrigin: tracesOrigin },
1986
1996
  ...logsOrigin === void 0 || !destination.signals.logs ? {} : { logsEndpointOrigin: logsOrigin },
1997
+ ...metricsOrigin === void 0 || !destination.signals.metrics ? {} : { metricsEndpointOrigin: metricsOrigin },
1987
1998
  headerNames: destination.source === "exporter" ? [...exporter.headerNames].sort() : Object.keys(destination.headers).sort(),
1988
1999
  headerVariables: [...new Set(variables)].sort()
1989
2000
  };
@@ -1998,7 +2009,7 @@ var describeExportDestinations = (exporter) => {
1998
2009
  source: "destinations",
1999
2010
  protocol: destination.protocol ?? exporter.protocol,
2000
2011
  ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
2001
- signals: { traces: false, logs: false },
2012
+ signals: { traces: false, logs: false, metrics: false },
2002
2013
  headers: { ...destination.headers ?? {} }
2003
2014
  },
2004
2015
  false
@@ -2025,6 +2036,18 @@ var DEFAULT_LOGS_POLICY = Object.freeze({
2025
2036
  includeContent: false,
2026
2037
  maxBatchSize: 128
2027
2038
  });
2039
+ var metricsPolicySchema = z14.strictObject({
2040
+ enabled: z14.boolean(),
2041
+ /** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */
2042
+ endpoint: z14.string().url().max(2048).optional(),
2043
+ temporality: z14.enum(["cumulative", "delta"]),
2044
+ includeSessionId: z14.boolean()
2045
+ });
2046
+ var DEFAULT_METRICS_POLICY = Object.freeze({
2047
+ enabled: false,
2048
+ temporality: "cumulative",
2049
+ includeSessionId: true
2050
+ });
2028
2051
  var exporterPolicySchema = z14.strictObject({
2029
2052
  enabled: z14.boolean(),
2030
2053
  protocol: z14.enum(["http/protobuf", "http/json", "none"]),
@@ -2055,6 +2078,11 @@ var exporterPolicySchema = z14.strictObject({
2055
2078
  * a second top-level section would invite two of each to drift apart.
2056
2079
  */
2057
2080
  logs: logsPolicySchema,
2081
+ /**
2082
+ * Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before
2083
+ * metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.
2084
+ */
2085
+ metrics: metricsPolicySchema.optional(),
2058
2086
  /**
2059
2087
  * Additional OTLP destinations, each sent every batch in parallel.
2060
2088
  *
@@ -2103,8 +2131,9 @@ var otelHookConfigPatchSchema = z14.strictObject({
2103
2131
  // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
2104
2132
  // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
2105
2133
  // without also restating the endpoint and the batch size.
2106
- exporter: exporterPolicySchema.omit({ logs: true, spool: true }).partial().extend({
2134
+ exporter: exporterPolicySchema.omit({ logs: true, metrics: true, spool: true }).partial().extend({
2107
2135
  logs: logsPolicySchema.partial().optional(),
2136
+ metrics: metricsPolicySchema.partial().optional(),
2108
2137
  spool: spoolPolicySchema.partial().optional()
2109
2138
  }).optional(),
2110
2139
  privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
@@ -2124,7 +2153,8 @@ var DEFAULT_EXPORTER_POLICY = Object.freeze({
2124
2153
  maxRetryAttempts: 2,
2125
2154
  serviceName: "coding-agent",
2126
2155
  resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
2127
- logs: DEFAULT_LOGS_POLICY
2156
+ logs: DEFAULT_LOGS_POLICY,
2157
+ metrics: DEFAULT_METRICS_POLICY
2128
2158
  });
2129
2159
  var DEFAULT_DETECTION_POLICY = Object.freeze({
2130
2160
  minimumConfidence: "strong",
@@ -2146,6 +2176,10 @@ var DEFAULT_CONFIG = Object.freeze({
2146
2176
  providers: DEFAULT_PROVIDERS_POLICY
2147
2177
  });
2148
2178
  var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
2179
+ var effectiveMetricsPolicy = (exporter) => ({
2180
+ ...DEFAULT_METRICS_POLICY,
2181
+ ...exporter.metrics ?? {}
2182
+ });
2149
2183
 
2150
2184
  // src/config/resolve.ts
2151
2185
  import { z as z15 } from "zod";
@@ -2257,6 +2291,11 @@ var resolveConfig = (layers = []) => {
2257
2291
  "exporter.logs.enabled is true but neither a logs endpoint nor a trace endpoint to derive one from is configured"
2258
2292
  );
2259
2293
  }
2294
+ if (!withDestinations && parsed.data.exporter.metrics?.enabled === true && parsed.data.exporter.metrics.endpoint === void 0 && parsed.data.exporter.endpoint === void 0) {
2295
+ notes.push(
2296
+ "exporter.metrics.enabled is true but neither a metrics endpoint nor a trace endpoint to derive one from is configured"
2297
+ );
2298
+ }
2260
2299
  if (parsed.data.exporter.logs.includeContent && parsed.data.privacy.contentMode === "omit") {
2261
2300
  notes.push(
2262
2301
  "exporter.logs.includeContent is true but privacy.contentMode is omit, so no content is disclosed to describe"
@@ -2288,6 +2327,9 @@ var describeDestinationAttributes = (config) => {
2288
2327
  if (destination.logsEndpointOrigin !== void 0) {
2289
2328
  attributes[`${prefix}.logs_endpoint_origin`] = destination.logsEndpointOrigin;
2290
2329
  }
2330
+ if (destination.metricsEndpointOrigin !== void 0) {
2331
+ attributes[`${prefix}.metrics_endpoint_origin`] = destination.metricsEndpointOrigin;
2332
+ }
2291
2333
  attributes[`${prefix}.header_names`] = [...destination.headerNames];
2292
2334
  attributes[`${prefix}.header_variables`] = [...destination.headerVariables];
2293
2335
  }
@@ -2306,6 +2348,8 @@ var describeResolvedConfig = (config) => {
2306
2348
  };
2307
2349
  const endpointOrigin2 = originOf(config.exporter.endpoint);
2308
2350
  const logsEndpointOrigin = originOf(config.exporter.logs.endpoint);
2351
+ const metrics = effectiveMetricsPolicy(config.exporter);
2352
+ const metricsEndpointOrigin = originOf(metrics.endpoint);
2309
2353
  return {
2310
2354
  "exporter.enabled": config.exporter.enabled,
2311
2355
  "exporter.protocol": config.exporter.protocol,
@@ -2314,6 +2358,10 @@ var describeResolvedConfig = (config) => {
2314
2358
  "exporter.logs_include_content": config.exporter.logs.includeContent,
2315
2359
  "exporter.logs_max_batch_size": config.exporter.logs.maxBatchSize,
2316
2360
  ...logsEndpointOrigin === void 0 ? {} : { "exporter.logs_endpoint_origin": logsEndpointOrigin },
2361
+ "exporter.metrics_enabled": metrics.enabled,
2362
+ "exporter.metrics_temporality": metrics.temporality,
2363
+ "exporter.metrics_include_session_id": metrics.includeSessionId,
2364
+ ...metricsEndpointOrigin === void 0 ? {} : { "exporter.metrics_endpoint_origin": metricsEndpointOrigin },
2317
2365
  "exporter.header_names": [...config.exporter.headerNames],
2318
2366
  // Names only. A resource attribute *name* is already on the wire in every
2319
2367
  // exported resource, so disclosing it here adds nothing; a *value* may hold
@@ -2343,10 +2391,17 @@ var describeResolvedConfig = (config) => {
2343
2391
  var OTLP_ENDPOINT_VARIABLES = Object.freeze({
2344
2392
  generic: "OTEL_EXPORTER_OTLP_ENDPOINT",
2345
2393
  traces: "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
2346
- logs: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT"
2394
+ logs: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
2395
+ metrics: "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"
2347
2396
  });
2348
2397
  var OTLP_TRACES_PATH = "/v1/traces";
2349
2398
  var OTLP_LOGS_PATH = "/v1/logs";
2399
+ var OTLP_METRICS_PATH = "/v1/metrics";
2400
+ var SIGNAL_PATHS = Object.freeze({
2401
+ traces: OTLP_TRACES_PATH,
2402
+ logs: OTLP_LOGS_PATH,
2403
+ metrics: OTLP_METRICS_PATH
2404
+ });
2350
2405
  var withoutTrailingSlashes = (value) => {
2351
2406
  let end = value.length;
2352
2407
  while (end > 0 && value.charCodeAt(end - 1) === 47) {
@@ -2357,9 +2412,20 @@ var withoutTrailingSlashes = (value) => {
2357
2412
  var otlpSignalEndpointFromBase = (base, signal) => {
2358
2413
  const trimmed = withoutTrailingSlashes(base);
2359
2414
  if (trimmed.endsWith(OTLP_TRACES_PATH)) {
2360
- return signal === "traces" ? trimmed : `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${OTLP_LOGS_PATH}`;
2415
+ return signal === "traces" ? trimmed : `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${SIGNAL_PATHS[signal]}`;
2416
+ }
2417
+ return `${trimmed}${SIGNAL_PATHS[signal]}`;
2418
+ };
2419
+ var siblingSignalEndpoint = (tracesEndpoint, signal) => {
2420
+ const trimmed = withoutTrailingSlashes(tracesEndpoint);
2421
+ const target = SIGNAL_PATHS[signal];
2422
+ if (trimmed.endsWith(target)) {
2423
+ return trimmed;
2424
+ }
2425
+ if (trimmed.endsWith(OTLP_TRACES_PATH)) {
2426
+ return `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${target}`;
2361
2427
  }
2362
- return `${trimmed}${signal === "traces" ? OTLP_TRACES_PATH : OTLP_LOGS_PATH}`;
2428
+ return `${trimmed}${target}`;
2363
2429
  };
2364
2430
 
2365
2431
  // src/config/environment.ts
@@ -2380,6 +2446,12 @@ var ENVIRONMENT_VARIABLES = Object.freeze({
2380
2446
  /** Standard per-signal endpoint; the weaker source of the two. */
2381
2447
  otlpLogsEndpoint: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
2382
2448
  logsIncludeContent: "OTEL_HOOK_LOGS_INCLUDE_CONTENT",
2449
+ metricsEnabled: "OTEL_HOOK_METRICS_ENABLED",
2450
+ metricsEndpoint: "OTEL_HOOK_METRICS_ENDPOINT",
2451
+ /** Standard per-signal endpoint; the weaker source of the two. */
2452
+ otlpMetricsEndpoint: "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT",
2453
+ /** Standard: `cumulative`, `delta`, or `lowmemory` (read as `delta` here). */
2454
+ otlpMetricsTemporality: "OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE",
2383
2455
  serviceName: "OTEL_HOOK_SERVICE_NAME",
2384
2456
  otlpServiceName: "OTEL_SERVICE_NAME",
2385
2457
  serviceNamespace: "OTEL_HOOK_SERVICE_NAMESPACE",
@@ -2542,6 +2614,22 @@ var parseEnvironmentConfig = (env) => {
2542
2614
  ...logsEndpoint === void 0 ? {} : { endpoint: logsEndpoint },
2543
2615
  ...logsIncludeContent === void 0 ? {} : { includeContent: logsIncludeContent }
2544
2616
  };
2617
+ const metricsEnabled = readBoolean(ENVIRONMENT_VARIABLES.metricsEnabled);
2618
+ const metricsEndpoint = readString(ENVIRONMENT_VARIABLES.metricsEndpoint) ?? readString(ENVIRONMENT_VARIABLES.otlpMetricsEndpoint) ?? (hookEndpoint === void 0 && otlpTracesEndpoint !== void 0 && otlpBaseEndpoint !== void 0 ? otlpSignalEndpointFromBase(otlpBaseEndpoint, "metrics") : void 0);
2619
+ const temporalityRaw = readString(ENVIRONMENT_VARIABLES.otlpMetricsTemporality)?.toLowerCase();
2620
+ let metricsTemporality;
2621
+ if (temporalityRaw === "cumulative") {
2622
+ metricsTemporality = "cumulative";
2623
+ } else if (temporalityRaw === "delta" || temporalityRaw === "lowmemory") {
2624
+ metricsTemporality = "delta";
2625
+ } else if (temporalityRaw !== void 0) {
2626
+ warn(ENVIRONMENT_VARIABLES.otlpMetricsTemporality, "expected cumulative, delta, or lowmemory");
2627
+ }
2628
+ const metrics = {
2629
+ ...metricsEnabled === void 0 ? {} : { enabled: metricsEnabled },
2630
+ ...metricsEndpoint === void 0 ? {} : { endpoint: metricsEndpoint },
2631
+ ...metricsTemporality === void 0 ? {} : { temporality: metricsTemporality }
2632
+ };
2545
2633
  const otlpHeaders = resolveOtlpHeaders(env);
2546
2634
  for (const { variable, detail } of otlpHeaders.warnings) {
2547
2635
  warn(variable, detail);
@@ -2556,7 +2644,8 @@ var parseEnvironmentConfig = (env) => {
2556
2644
  ...serviceName === void 0 ? {} : { serviceName },
2557
2645
  ...serviceNamespace === void 0 ? {} : { serviceNamespace },
2558
2646
  ...Object.keys(resourceAttributes).length === 0 ? {} : { resourceAttributes },
2559
- ...Object.keys(logs).length === 0 ? {} : { logs }
2647
+ ...Object.keys(logs).length === 0 ? {} : { logs },
2648
+ ...Object.keys(metrics).length === 0 ? {} : { metrics }
2560
2649
  };
2561
2650
  const limits = {
2562
2651
  ...maxStringLength === void 0 ? {} : { maxStringLength },
@@ -6938,6 +7027,29 @@ var stateValueSchema = z22.discriminatedUnion("kind", [
6938
7027
  * (Claude Code's transcript), so the next read starts where the last ended.
6939
7028
  * `source` is an opaque digest of what was read, never a path.
6940
7029
  */
7030
+ /**
7031
+ * Running state of one metric series (issue #69), so a cumulative data point
7032
+ * exported by a later hook process continues the same total. Holds numbers and
7033
+ * a series digest only; the series' attributes are re-supplied by the caller
7034
+ * and never read back from disk.
7035
+ */
7036
+ z22.strictObject({
7037
+ kind: z22.literal("metric-series"),
7038
+ /** Start of the cumulative interval. */
7039
+ startTimeMillis: epochMillisSchema,
7040
+ /** Counters: the running total. */
7041
+ value: z22.number().finite().min(0).optional(),
7042
+ /** Histograms: the running aggregation. */
7043
+ histogram: z22.strictObject({
7044
+ count: z22.number().int().min(0),
7045
+ sum: z22.number().finite().min(0),
7046
+ min: z22.number().finite(),
7047
+ max: z22.number().finite(),
7048
+ bucketCounts: z22.array(z22.number().int().min(0)).max(64)
7049
+ }).optional(),
7050
+ /** Opaque digest of the last delivery folded in; makes a replay a no-op. */
7051
+ appliedDelivery: z22.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional()
7052
+ }),
6941
7053
  z22.strictObject({
6942
7054
  kind: z22.literal("read-cursor"),
6943
7055
  source: z22.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
@@ -8418,6 +8530,8 @@ var rollupUsageKey = (sessionId, scope, scopeKey) => `${rollupScanPrefix(session
8418
8530
  var rollupEpochKey = (sessionId, scope, scopeKey) => `${rollupEpochScanPrefix(sessionId)}${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;
8419
8531
  var rollupScanPrefix = (sessionId) => sessionId === void 0 ? `${LIFECYCLE_PREFIX}:usage:` : `${LIFECYCLE_PREFIX}:usage:${encodeSegment(sessionId)}:`;
8420
8532
  var rollupEpochScanPrefix = (sessionId) => sessionId === void 0 ? `${LIFECYCLE_PREFIX}:epoch:` : `${LIFECYCLE_PREFIX}:epoch:${encodeSegment(sessionId)}:`;
8533
+ var metricSeriesKey = (sessionScope2, seriesDigest) => `${metricSeriesScanPrefix(sessionScope2)}${encodeSegment(seriesDigest)}`;
8534
+ var metricSeriesScanPrefix = (sessionScope2) => sessionScope2 === void 0 ? `${LIFECYCLE_PREFIX}:metric:v1:` : `${LIFECYCLE_PREFIX}:metric:v1:${encodeSegment(sessionScope2)}:`;
8421
8535
 
8422
8536
  // src/lifecycle/dedup.ts
8423
8537
  var DEFAULT_STALE_CLAIM_MILLIS = 6e4;
@@ -8607,7 +8721,7 @@ import {
8607
8721
  } from "@opentelemetry/semantic-conventions/incubating";
8608
8722
 
8609
8723
  // src/version.ts
8610
- var VERSION = "0.10.0";
8724
+ var VERSION = "0.11.0";
8611
8725
 
8612
8726
  // src/telemetry/export-identity.ts
8613
8727
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -9729,6 +9843,422 @@ var createUsageAccumulator = (deps) => {
9729
9843
  return { accumulateDelta, recordReset, read, cleanup };
9730
9844
  };
9731
9845
 
9846
+ // src/lifecycle/metric-series.ts
9847
+ import { createHash as createHash5 } from "crypto";
9848
+
9849
+ // src/telemetry/metric-model.ts
9850
+ var TOKEN_USAGE_BUCKETS = Object.freeze([
9851
+ 1,
9852
+ 4,
9853
+ 16,
9854
+ 64,
9855
+ 256,
9856
+ 1024,
9857
+ 4096,
9858
+ 16384,
9859
+ 65536,
9860
+ 262144,
9861
+ 1048576,
9862
+ 4194304,
9863
+ 16777216,
9864
+ 67108864
9865
+ ]);
9866
+ var OPERATION_DURATION_BUCKETS = Object.freeze([
9867
+ 0.01,
9868
+ 0.02,
9869
+ 0.04,
9870
+ 0.08,
9871
+ 0.16,
9872
+ 0.32,
9873
+ 0.64,
9874
+ 1.28,
9875
+ 2.56,
9876
+ 5.12,
9877
+ 10.24,
9878
+ 20.48,
9879
+ 40.96,
9880
+ 81.92
9881
+ ]);
9882
+ var METRIC_TOKEN_USAGE = "gen_ai.client.token.usage";
9883
+ var METRIC_OPERATION_DURATION = "gen_ai.client.operation.duration";
9884
+ var METRIC_SESSIONS = "otelhook.sessions";
9885
+ var METRIC_TOOL_CALLS = "otelhook.tool.calls";
9886
+ var METRIC_COST_USAGE = "otelhook.cost.usage";
9887
+ var METRIC_INSTRUMENTS = Object.freeze({
9888
+ [METRIC_TOKEN_USAGE]: {
9889
+ name: METRIC_TOKEN_USAGE,
9890
+ kind: "histogram",
9891
+ unit: "{token}",
9892
+ description: "Tokens used per generation, by token type (hook-derived)",
9893
+ valueType: "int",
9894
+ boundaries: TOKEN_USAGE_BUCKETS
9895
+ },
9896
+ [METRIC_OPERATION_DURATION]: {
9897
+ name: METRIC_OPERATION_DURATION,
9898
+ kind: "histogram",
9899
+ unit: "s",
9900
+ description: "Generation duration, from its start hook to its end hook (hook-derived)",
9901
+ valueType: "double",
9902
+ boundaries: OPERATION_DURATION_BUCKETS
9903
+ },
9904
+ [METRIC_SESSIONS]: {
9905
+ name: METRIC_SESSIONS,
9906
+ kind: "counter",
9907
+ unit: "{session}",
9908
+ description: "Agent sessions started",
9909
+ valueType: "int"
9910
+ },
9911
+ [METRIC_TOOL_CALLS]: {
9912
+ name: METRIC_TOOL_CALLS,
9913
+ kind: "counter",
9914
+ unit: "{call}",
9915
+ description: "Completed tool calls, by tool name and outcome",
9916
+ valueType: "int"
9917
+ },
9918
+ [METRIC_COST_USAGE]: {
9919
+ name: METRIC_COST_USAGE,
9920
+ kind: "counter",
9921
+ unit: "USD",
9922
+ description: "Cost reported by the provider; never estimated",
9923
+ valueType: "double"
9924
+ }
9925
+ });
9926
+ var isMetricInstrumentName = (value) => typeof value === "string" && Object.hasOwn(METRIC_INSTRUMENTS, value);
9927
+ var ATTR_GEN_AI_TOKEN_TYPE = "gen_ai.token.type";
9928
+ var ATTR_GEN_AI_PROVIDER_NAME = "gen_ai.provider.name";
9929
+ var ATTR_GEN_AI_OPERATION_NAME2 = "gen_ai.operation.name";
9930
+ var ATTR_GEN_AI_REQUEST_MODEL2 = "gen_ai.request.model";
9931
+ var ATTR_GEN_AI_RESPONSE_MODEL2 = "gen_ai.response.model";
9932
+ var ATTR_GEN_AI_TOOL_NAME2 = "gen_ai.tool.name";
9933
+ var ATTR_ERROR_TYPE2 = "error.type";
9934
+ var ATTR_SESSION_ID2 = "session.id";
9935
+ var ATTR_OTELHOOK_PROVIDER_ID2 = "otelhook.provider.id";
9936
+ var ATTR_OTELHOOK_OUTCOME2 = "otelhook.outcome";
9937
+ var ATTR_OTELHOOK_SESSION_KIND = "otelhook.session.kind";
9938
+ var commonAttributes = (event3, resource, includeSessionId) => ({
9939
+ [ATTR_OTELHOOK_PROVIDER_ID2]: event3.provenance.providerId,
9940
+ ...includeSessionId ? { [ATTR_SESSION_ID2]: resolveExportedSessionId(event3.sessionId, resource).sessionId } : {}
9941
+ });
9942
+ var generationAttributes = (end, requestModel) => ({
9943
+ [ATTR_GEN_AI_OPERATION_NAME2]: "chat",
9944
+ ...end.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_PROVIDER_NAME]: end.model.vendor },
9945
+ [ATTR_GEN_AI_REQUEST_MODEL2]: requestModel ?? end.model.modelId,
9946
+ [ATTR_GEN_AI_RESPONSE_MODEL2]: end.model.modelId
9947
+ });
9948
+ var TOKEN_FIELDS = [
9949
+ ["input", (usage) => usage.inputTokens],
9950
+ ["output", (usage) => usage.outputTokens],
9951
+ ["cache_read", (usage) => usage.cachedInputTokens],
9952
+ ["cache_creation", (usage) => usage.cacheCreationInputTokens]
9953
+ ];
9954
+ var isFailedOutcome = (outcome) => outcome !== "ok" && outcome !== "unknown" && outcome !== "cancelled";
9955
+ var deriveMetricObservations = (input) => {
9956
+ const includeSessionId = input.includeSessionId ?? true;
9957
+ const observations = [];
9958
+ const byId = /* @__PURE__ */ new Map();
9959
+ const startsInBatch = /* @__PURE__ */ new Map();
9960
+ for (const event3 of input.events) {
9961
+ byId.set(event3.eventId, event3);
9962
+ if (event3.type === "generation.start") {
9963
+ startsInBatch.set(event3.generationId, {
9964
+ startMillis: event3.occurredAt,
9965
+ requestModel: event3.model.modelId
9966
+ });
9967
+ }
9968
+ }
9969
+ const requestModelOf = (generationId) => startsInBatch.get(generationId)?.requestModel ?? input.generationStarts?.(generationId)?.requestModel;
9970
+ let lastPromptInBatch;
9971
+ for (const event3 of input.events) {
9972
+ if (event3.type === "prompt.submitted") {
9973
+ lastPromptInBatch ??= /* @__PURE__ */ new Map();
9974
+ lastPromptInBatch.set(event3.sessionId, Math.max(lastPromptInBatch.get(event3.sessionId) ?? 0, event3.occurredAt));
9975
+ }
9976
+ }
9977
+ const measuredDurationOf = (end) => {
9978
+ if (end.durationMillis !== void 0) {
9979
+ return end.durationMillis;
9980
+ }
9981
+ const recovered = startsInBatch.has(end.generationId) ? void 0 : input.generationStarts?.(end.generationId);
9982
+ if (recovered !== void 0) {
9983
+ return end.occurredAt - recovered.startMillis;
9984
+ }
9985
+ const turn = lastPromptInBatch?.get(end.sessionId) ?? input.turnStart?.(end.sessionId);
9986
+ return turn === void 0 || turn > end.occurredAt ? void 0 : end.occurredAt - turn;
9987
+ };
9988
+ const push = (event3, instrument, value, attributes) => {
9989
+ if (!Number.isFinite(value) || value < 0) {
9990
+ return;
9991
+ }
9992
+ observations.push({
9993
+ instrument,
9994
+ value,
9995
+ attributes: { ...commonAttributes(event3, input.resource, includeSessionId), ...attributes },
9996
+ timeMillis: event3.occurredAt,
9997
+ sessionId: event3.sessionId
9998
+ });
9999
+ };
10000
+ for (const event3 of input.events) {
10001
+ switch (event3.type) {
10002
+ case "session.start":
10003
+ push(event3, METRIC_SESSIONS, 1, { [ATTR_OTELHOOK_SESSION_KIND]: event3.sessionKind });
10004
+ break;
10005
+ case "tool.end":
10006
+ push(event3, METRIC_TOOL_CALLS, 1, {
10007
+ [ATTR_GEN_AI_TOOL_NAME2]: event3.toolName,
10008
+ [ATTR_OTELHOOK_OUTCOME2]: event3.outcome
10009
+ });
10010
+ break;
10011
+ case "generation.end": {
10012
+ const attributes = generationAttributes(event3, requestModelOf(event3.generationId));
10013
+ const durationMillis = measuredDurationOf(event3);
10014
+ if (durationMillis !== void 0 && durationMillis >= 0) {
10015
+ push(event3, METRIC_OPERATION_DURATION, durationMillis / 1e3, {
10016
+ ...attributes,
10017
+ ...isFailedOutcome(event3.outcome) ? { [ATTR_ERROR_TYPE2]: event3.outcome } : {}
10018
+ });
10019
+ }
10020
+ if (event3.cost !== void 0 && event3.cost.source === "provider-reported" && event3.cost.currency === "USD") {
10021
+ push(event3, METRIC_COST_USAGE, event3.cost.amount, attributes);
10022
+ }
10023
+ break;
10024
+ }
10025
+ default:
10026
+ break;
10027
+ }
10028
+ }
10029
+ for (const observation of input.usage) {
10030
+ if (observation.scope !== "generation") {
10031
+ continue;
10032
+ }
10033
+ const event3 = byId.get(observation.eventId);
10034
+ if (event3?.type !== "generation.end") {
10035
+ continue;
10036
+ }
10037
+ const attributes = generationAttributes(event3, requestModelOf(event3.generationId));
10038
+ for (const [tokenType, read] of TOKEN_FIELDS) {
10039
+ const value = read(observation.delta);
10040
+ if (value === 0 && (tokenType === "cache_read" || tokenType === "cache_creation")) {
10041
+ continue;
10042
+ }
10043
+ push(event3, METRIC_TOKEN_USAGE, value, { ...attributes, [ATTR_GEN_AI_TOKEN_TYPE]: tokenType });
10044
+ }
10045
+ }
10046
+ return observations;
10047
+ };
10048
+ var emptyHistogram = (boundaries) => ({
10049
+ count: 0,
10050
+ sum: 0,
10051
+ min: Number.POSITIVE_INFINITY,
10052
+ max: Number.NEGATIVE_INFINITY,
10053
+ bucketCounts: new Array(boundaries.length + 1).fill(0)
10054
+ });
10055
+ var bucketIndex = (boundaries, value) => {
10056
+ for (let index = 0; index < boundaries.length; index += 1) {
10057
+ const bound = boundaries[index];
10058
+ if (bound !== void 0 && value <= bound) {
10059
+ return index;
10060
+ }
10061
+ }
10062
+ return boundaries.length;
10063
+ };
10064
+ var recordIntoHistogram = (state, boundaries, value) => {
10065
+ const bucketCounts = [...state.bucketCounts];
10066
+ const index = bucketIndex(boundaries, value);
10067
+ bucketCounts[index] = (bucketCounts[index] ?? 0) + 1;
10068
+ return {
10069
+ count: state.count + 1,
10070
+ sum: state.sum + value,
10071
+ min: Math.min(state.min, value),
10072
+ max: Math.max(state.max, value),
10073
+ bucketCounts
10074
+ };
10075
+ };
10076
+ var seriesIdentity = (instrument, attributes) => JSON.stringify([
10077
+ instrument,
10078
+ Object.entries(attributes).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
10079
+ ]);
10080
+ var aggregateDeltaPoints = (observations, nowMillis) => {
10081
+ const series = /* @__PURE__ */ new Map();
10082
+ for (const observation of observations) {
10083
+ const instrument = METRIC_INSTRUMENTS[observation.instrument];
10084
+ const key = seriesIdentity(observation.instrument, observation.attributes);
10085
+ const existing = series.get(key) ?? {
10086
+ observation,
10087
+ start: observation.timeMillis,
10088
+ value: 0,
10089
+ ...instrument.boundaries === void 0 ? {} : { histogram: emptyHistogram(instrument.boundaries) }
10090
+ };
10091
+ existing.start = Math.min(existing.start, observation.timeMillis);
10092
+ if (existing.histogram !== void 0 && instrument.boundaries !== void 0) {
10093
+ existing.histogram = recordIntoHistogram(existing.histogram, instrument.boundaries, observation.value);
10094
+ } else {
10095
+ existing.value += observation.value;
10096
+ }
10097
+ series.set(key, existing);
10098
+ }
10099
+ return [...series.values()].map((entry) => ({
10100
+ instrument: entry.observation.instrument,
10101
+ temporality: "delta",
10102
+ attributes: entry.observation.attributes,
10103
+ startTimeMillis: Math.min(entry.start, nowMillis),
10104
+ timeMillis: Math.max(nowMillis, entry.start),
10105
+ ...entry.histogram === void 0 ? { value: entry.value } : { histogram: entry.histogram }
10106
+ }));
10107
+ };
10108
+ var FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES = Object.freeze([
10109
+ "user.",
10110
+ "enduser.",
10111
+ "organization."
10112
+ ]);
10113
+ var withoutAccountIdentity = (attributes) => Object.fromEntries(
10114
+ Object.entries(attributes).filter(
10115
+ ([key]) => !FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES.some((prefix) => key.startsWith(prefix))
10116
+ )
10117
+ );
10118
+
10119
+ // src/lifecycle/metric-series.ts
10120
+ var TURN_START_SEGMENT = "turn-start";
10121
+ var SHARED_SCOPE = "all";
10122
+ var SHARED_LOCK = "otelhook.metrics.shared";
10123
+ var sessionScope = (sessionId) => `s=${sessionId}`;
10124
+ var digest2 = (identity) => createHash5("sha256").update(identity).digest("base64url").slice(0, 43);
10125
+ var toStoredHistogram = (histogram) => ({
10126
+ count: histogram.count,
10127
+ sum: histogram.sum,
10128
+ // An empty histogram has infinite min/max, which JSON cannot hold. A stored
10129
+ // histogram always has at least one value, so these are finite in practice.
10130
+ min: Number.isFinite(histogram.min) ? histogram.min : 0,
10131
+ max: Number.isFinite(histogram.max) ? histogram.max : 0,
10132
+ bucketCounts: [...histogram.bucketCounts]
10133
+ });
10134
+ var createMetricSeriesStore = (deps) => {
10135
+ const { stateStore, clock } = deps;
10136
+ const readSeries = async (key) => {
10137
+ const record = await stateStore.read(key);
10138
+ if (record?.value.kind !== "metric-series") {
10139
+ return void 0;
10140
+ }
10141
+ return record.value;
10142
+ };
10143
+ const recordGroup = async (scope, observations, deliveryToken) => {
10144
+ const bySeries = /* @__PURE__ */ new Map();
10145
+ for (const observation of observations) {
10146
+ const identity = seriesIdentity(observation.instrument, observation.attributes);
10147
+ const group = bySeries.get(identity) ?? [];
10148
+ group.push(observation);
10149
+ bySeries.set(identity, group);
10150
+ }
10151
+ const now = clock.now();
10152
+ const points = [];
10153
+ for (const [identity, group] of bySeries) {
10154
+ const first = group[0];
10155
+ if (first === void 0) {
10156
+ continue;
10157
+ }
10158
+ const instrument = METRIC_INSTRUMENTS[first.instrument];
10159
+ const key = metricSeriesKey(scope, digest2(identity));
10160
+ const existing = await readSeries(key);
10161
+ const boundaries = instrument.boundaries;
10162
+ const compatible = existing !== void 0 && (boundaries === void 0 ? existing.value !== void 0 : existing.histogram?.bucketCounts.length === boundaries.length + 1);
10163
+ const base = compatible ? existing : void 0;
10164
+ const replay = deliveryToken !== void 0 && base?.appliedDelivery === deliveryToken;
10165
+ const earliest = Math.min(...group.map((observation) => observation.timeMillis));
10166
+ const startTimeMillis = base?.startTimeMillis ?? Math.min(earliest, now);
10167
+ let value = base?.value ?? 0;
10168
+ let histogram = boundaries === void 0 ? void 0 : base?.histogram === void 0 ? emptyHistogram(boundaries) : base.histogram;
10169
+ if (!replay) {
10170
+ for (const observation of group) {
10171
+ if (histogram !== void 0 && boundaries !== void 0) {
10172
+ histogram = recordIntoHistogram(histogram, boundaries, observation.value);
10173
+ } else {
10174
+ value += observation.value;
10175
+ }
10176
+ }
10177
+ await stateStore.write(key, {
10178
+ kind: "metric-series",
10179
+ startTimeMillis,
10180
+ ...histogram === void 0 ? { value } : { histogram: toStoredHistogram(histogram) },
10181
+ ...deliveryToken === void 0 ? {} : { appliedDelivery: deliveryToken }
10182
+ });
10183
+ }
10184
+ points.push({
10185
+ instrument: first.instrument,
10186
+ temporality: "cumulative",
10187
+ attributes: first.attributes,
10188
+ startTimeMillis,
10189
+ timeMillis: Math.max(now, startTimeMillis),
10190
+ ...histogram === void 0 ? { value } : { histogram }
10191
+ });
10192
+ }
10193
+ return points;
10194
+ };
10195
+ const recordCumulative = async (observations, options) => {
10196
+ if (observations.length === 0) {
10197
+ return [];
10198
+ }
10199
+ if (options?.perSession === false) {
10200
+ return withOptionalSessionLock(
10201
+ stateStore,
10202
+ SHARED_LOCK,
10203
+ () => recordGroup(SHARED_SCOPE, observations, options.deliveryToken)
10204
+ );
10205
+ }
10206
+ const bySession = /* @__PURE__ */ new Map();
10207
+ for (const observation of observations) {
10208
+ const group = bySession.get(observation.sessionId) ?? [];
10209
+ group.push(observation);
10210
+ bySession.set(observation.sessionId, group);
10211
+ }
10212
+ const points = [];
10213
+ for (const [sessionId, group] of bySession) {
10214
+ points.push(
10215
+ ...await withOptionalSessionLock(
10216
+ stateStore,
10217
+ sessionId,
10218
+ () => recordGroup(sessionScope(sessionId), group, options?.deliveryToken)
10219
+ )
10220
+ );
10221
+ }
10222
+ return points;
10223
+ };
10224
+ const cleanup = async (maxAgeMillis, options) => {
10225
+ const cap = options?.maxEntries ?? 1e3;
10226
+ const now = clock.now();
10227
+ let removed = 0;
10228
+ let scanned = 0;
10229
+ const prefix = metricSeriesScanPrefix(
10230
+ options?.sessionId === void 0 ? void 0 : sessionScope(options.sessionId)
10231
+ );
10232
+ for (const key of await stateStore.keys(prefix)) {
10233
+ if (scanned >= cap) {
10234
+ break;
10235
+ }
10236
+ scanned += 1;
10237
+ const record = await stateStore.read(key);
10238
+ if (record !== void 0 && now - record.updatedAt > maxAgeMillis) {
10239
+ await stateStore.delete(key);
10240
+ removed += 1;
10241
+ }
10242
+ }
10243
+ return { removed, scanned };
10244
+ };
10245
+ const turnKey = (sessionId) => metricSeriesKey(sessionScope(sessionId), TURN_START_SEGMENT);
10246
+ const recordTurnStart = (sessionId, startMillis) => withOptionalSessionLock(stateStore, sessionId, async () => {
10247
+ const existing = await stateStore.read(turnKey(sessionId));
10248
+ const previous = existing?.value.kind === "attributes" && typeof existing.value.attributes.startMillis === "number" ? existing.value.attributes.startMillis : void 0;
10249
+ if (previous !== void 0 && previous >= startMillis) {
10250
+ return;
10251
+ }
10252
+ await stateStore.write(turnKey(sessionId), { kind: "attributes", attributes: { startMillis } });
10253
+ });
10254
+ const readTurnStart = async (sessionId) => {
10255
+ const record = await stateStore.read(turnKey(sessionId));
10256
+ const value = record?.value.kind === "attributes" ? record.value.attributes.startMillis : void 0;
10257
+ return typeof value === "number" ? value : void 0;
10258
+ };
10259
+ return { recordCumulative, recordTurnStart, readTurnStart, cleanup };
10260
+ };
10261
+
9732
10262
  // src/lifecycle/janitor.ts
9733
10263
  var DEFAULT_MAX_AGE_MILLIS = 24 * 60 * 60 * 1e3;
9734
10264
  var DEFAULT_MAX_ENTRIES_PER_COMPONENT = 1e3;
@@ -9739,7 +10269,7 @@ var createLifecycleJanitor = (options) => {
9739
10269
  const usageMaxAge = options.usageMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
9740
10270
  const runOnce = async (sessionId) => {
9741
10271
  const scope = { maxEntries, ...sessionId === void 0 ? {} : { sessionId } };
9742
- const [span, dedup, usage] = await Promise.all([
10272
+ const [span, dedup, usage, metrics] = await Promise.all([
9743
10273
  options.spanCorrelator?.cleanup(spanMaxAge, scope),
9744
10274
  // Deduplication is deliberately swept across every scope rather than the
9745
10275
  // ending session's: a delivery scope is a host-chosen namespace or a
@@ -9750,12 +10280,14 @@ var createLifecycleJanitor = (options) => {
9750
10280
  maxEntries,
9751
10281
  ...options.dedupStaleClaimMillis === void 0 ? {} : { staleClaimMillis: options.dedupStaleClaimMillis }
9752
10282
  }),
9753
- options.usageAccumulator?.cleanup(usageMaxAge, scope)
10283
+ options.usageAccumulator?.cleanup(usageMaxAge, scope),
10284
+ options.metricSeries?.cleanup(usageMaxAge, scope)
9754
10285
  ]);
9755
10286
  return {
9756
10287
  ...span === void 0 ? {} : { span },
9757
10288
  ...dedup === void 0 ? {} : { dedup },
9758
- ...usage === void 0 ? {} : { usage }
10289
+ ...usage === void 0 ? {} : { usage },
10290
+ ...metrics === void 0 ? {} : { metrics }
9759
10291
  };
9760
10292
  };
9761
10293
  return { runOnce };
@@ -9835,20 +10367,20 @@ import { mkdir, open as open3, readFile, readdir, rename, unlink, writeFile } fr
9835
10367
  import * as path4 from "path";
9836
10368
 
9837
10369
  // src/state/keys.ts
9838
- import { createHash as createHash5 } from "crypto";
10370
+ import { createHash as createHash6 } from "crypto";
9839
10371
  var SAFE_SEGMENT_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
9840
10372
  var isSafeSegment = (segment) => SAFE_SEGMENT_PATTERN.test(segment);
9841
10373
  var sanitizeSegment = (segment) => {
9842
10374
  if (isSafeSegment(segment)) {
9843
10375
  return segment;
9844
10376
  }
9845
- return `h_${createHash5("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
10377
+ return `h_${createHash6("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
9846
10378
  };
9847
10379
  var namespaceSegments = (namespace) => [
9848
10380
  sanitizeSegment(namespace.providerId),
9849
10381
  sanitizeSegment(namespace.installationId)
9850
10382
  ];
9851
- var keyDigest = (key) => createHash5("sha256").update(key, "utf8").digest("hex");
10383
+ var keyDigest = (key) => createHash6("sha256").update(key, "utf8").digest("hex");
9852
10384
 
9853
10385
  // src/state/filesystem-store.ts
9854
10386
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
@@ -10807,13 +11339,13 @@ var createOtlpTraceSink = (options) => {
10807
11339
  import { SeverityNumber, TraceFlags as TraceFlags2 } from "@opentelemetry/api";
10808
11340
  import { millisToHrTime as millisToHrTime2 } from "@opentelemetry/core";
10809
11341
  import {
10810
- ATTR_ERROR_TYPE as ATTR_ERROR_TYPE2,
10811
- ATTR_GEN_AI_OPERATION_NAME as ATTR_GEN_AI_OPERATION_NAME2,
10812
- ATTR_GEN_AI_REQUEST_MODEL as ATTR_GEN_AI_REQUEST_MODEL2,
10813
- ATTR_GEN_AI_RESPONSE_MODEL as ATTR_GEN_AI_RESPONSE_MODEL2,
11342
+ ATTR_ERROR_TYPE as ATTR_ERROR_TYPE3,
11343
+ ATTR_GEN_AI_OPERATION_NAME as ATTR_GEN_AI_OPERATION_NAME3,
11344
+ ATTR_GEN_AI_REQUEST_MODEL as ATTR_GEN_AI_REQUEST_MODEL3,
11345
+ ATTR_GEN_AI_RESPONSE_MODEL as ATTR_GEN_AI_RESPONSE_MODEL3,
10814
11346
  ATTR_GEN_AI_SYSTEM as ATTR_GEN_AI_SYSTEM2,
10815
11347
  ATTR_GEN_AI_TOOL_CALL_ID as ATTR_GEN_AI_TOOL_CALL_ID2,
10816
- ATTR_GEN_AI_TOOL_NAME as ATTR_GEN_AI_TOOL_NAME2,
11348
+ ATTR_GEN_AI_TOOL_NAME as ATTR_GEN_AI_TOOL_NAME3,
10817
11349
  ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS as ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS2,
10818
11350
  ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS as ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS2,
10819
11351
  ATTR_GEN_AI_USAGE_INPUT_TOKENS as ATTR_GEN_AI_USAGE_INPUT_TOKENS2,
@@ -10842,14 +11374,14 @@ var ATTR_OTELHOOK_EVENT_ID = "otelhook.event.id";
10842
11374
  var ATTR_OTELHOOK_EVENT_SEQUENCE = "otelhook.event.sequence";
10843
11375
  var ATTR_OTELHOOK_LOG_SIGNAL = "otelhook.log.signal";
10844
11376
  var ATTR_OTELHOOK_LOG_MAPPING_VERSION = "otelhook.log.mapping_version";
10845
- var ATTR_OTELHOOK_OUTCOME2 = "otelhook.outcome";
11377
+ var ATTR_OTELHOOK_OUTCOME3 = "otelhook.outcome";
10846
11378
  var ATTR_OTELHOOK_TOOL_KIND2 = "otelhook.tool.kind";
10847
11379
  var ATTR_OTELHOOK_TOOL_PERMISSION = "otelhook.tool.permission_decision";
10848
11380
  var ATTR_OTELHOOK_DELEGATION_DEPTH2 = "otelhook.delegation_depth";
10849
11381
  var ATTR_OTELHOOK_SUBAGENT_TYPE = "otelhook.subagent.type";
10850
11382
  var ATTR_OTELHOOK_AGENT_NAME2 = "otelhook.agent.name";
10851
11383
  var ATTR_OTELHOOK_AGENT_VERSION2 = "otelhook.agent.version";
10852
- var ATTR_OTELHOOK_SESSION_KIND = "otelhook.session.kind";
11384
+ var ATTR_OTELHOOK_SESSION_KIND2 = "otelhook.session.kind";
10853
11385
  var ATTR_OTELHOOK_PROMPT_SOURCE = "otelhook.prompt.source";
10854
11386
  var ATTR_OTELHOOK_PROMPT_TURN_INDEX = "otelhook.prompt.turn_index";
10855
11387
  var ATTR_OTELHOOK_GENERATION_ID2 = "otelhook.generation.id";
@@ -10993,15 +11525,15 @@ var eventAttributes = (event3) => {
10993
11525
  switch (event3.type) {
10994
11526
  case "session.start":
10995
11527
  return {
10996
- [ATTR_OTELHOOK_SESSION_KIND]: event3.sessionKind,
11528
+ [ATTR_OTELHOOK_SESSION_KIND2]: event3.sessionKind,
10997
11529
  ...event3.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME2]: event3.agentName },
10998
11530
  ...event3.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION2]: event3.agentVersion },
10999
- ...event3.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL2]: event3.model.modelId },
11531
+ ...event3.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL3]: event3.model.modelId },
11000
11532
  ...targetAttributes(event3)
11001
11533
  };
11002
11534
  case "session.end":
11003
11535
  return {
11004
- [ATTR_OTELHOOK_OUTCOME2]: event3.reason,
11536
+ [ATTR_OTELHOOK_OUTCOME3]: event3.reason,
11005
11537
  ...usageAttributes2(event3.usage)
11006
11538
  };
11007
11539
  case "prompt.submitted":
@@ -11012,25 +11544,25 @@ var eventAttributes = (event3) => {
11012
11544
  };
11013
11545
  case "generation.start":
11014
11546
  return {
11015
- [ATTR_GEN_AI_OPERATION_NAME2]: "chat",
11547
+ [ATTR_GEN_AI_OPERATION_NAME3]: "chat",
11016
11548
  [ATTR_OTELHOOK_GENERATION_ID2]: event3.generationId,
11017
- [ATTR_GEN_AI_REQUEST_MODEL2]: event3.model.modelId,
11549
+ [ATTR_GEN_AI_REQUEST_MODEL3]: event3.model.modelId,
11018
11550
  ...event3.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event3.model.vendor }
11019
11551
  };
11020
11552
  case "generation.end":
11021
11553
  return {
11022
- [ATTR_GEN_AI_OPERATION_NAME2]: "chat",
11554
+ [ATTR_GEN_AI_OPERATION_NAME3]: "chat",
11023
11555
  [ATTR_OTELHOOK_GENERATION_ID2]: event3.generationId,
11024
- [ATTR_GEN_AI_RESPONSE_MODEL2]: event3.model.modelId,
11556
+ [ATTR_GEN_AI_RESPONSE_MODEL3]: event3.model.modelId,
11025
11557
  ...event3.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event3.model.vendor },
11026
- [ATTR_OTELHOOK_OUTCOME2]: event3.outcome,
11558
+ [ATTR_OTELHOOK_OUTCOME3]: event3.outcome,
11027
11559
  ...event3.stopReason === void 0 ? {} : { [ATTR_OTELHOOK_STOP_REASON]: event3.stopReason },
11028
11560
  ...usageAttributes2(event3.usage),
11029
11561
  ...event3.usage === void 0 || event3.usagePartial === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_PARTIAL]: event3.usagePartial }
11030
11562
  };
11031
11563
  case "tool.start":
11032
11564
  return {
11033
- [ATTR_GEN_AI_TOOL_NAME2]: event3.toolName,
11565
+ [ATTR_GEN_AI_TOOL_NAME3]: event3.toolName,
11034
11566
  [ATTR_GEN_AI_TOOL_CALL_ID2]: event3.toolCallId,
11035
11567
  [ATTR_OTELHOOK_TOOL_KIND2]: event3.toolKind,
11036
11568
  ...event3.generationId === void 0 ? {} : { [ATTR_OTELHOOK_GENERATION_ID2]: event3.generationId },
@@ -11038,9 +11570,9 @@ var eventAttributes = (event3) => {
11038
11570
  };
11039
11571
  case "tool.end":
11040
11572
  return {
11041
- [ATTR_GEN_AI_TOOL_NAME2]: event3.toolName,
11573
+ [ATTR_GEN_AI_TOOL_NAME3]: event3.toolName,
11042
11574
  [ATTR_GEN_AI_TOOL_CALL_ID2]: event3.toolCallId,
11043
- [ATTR_OTELHOOK_OUTCOME2]: event3.outcome,
11575
+ [ATTR_OTELHOOK_OUTCOME3]: event3.outcome,
11044
11576
  ...event3.permissionDecision === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_PERMISSION]: event3.permissionDecision },
11045
11577
  ...targetAttributes(event3)
11046
11578
  };
@@ -11048,11 +11580,11 @@ var eventAttributes = (event3) => {
11048
11580
  return {
11049
11581
  [ATTR_OTELHOOK_DELEGATION_DEPTH2]: event3.delegationDepth,
11050
11582
  ...event3.subagentType === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_TYPE]: event3.subagentType },
11051
- ...event3.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL2]: event3.model.modelId }
11583
+ ...event3.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL3]: event3.model.modelId }
11052
11584
  };
11053
11585
  case "subagent.end":
11054
11586
  return {
11055
- [ATTR_OTELHOOK_OUTCOME2]: event3.outcome,
11587
+ [ATTR_OTELHOOK_OUTCOME3]: event3.outcome,
11056
11588
  ...usageAttributes2(event3.usage)
11057
11589
  };
11058
11590
  case "compaction.performed":
@@ -11065,7 +11597,7 @@ var eventAttributes = (event3) => {
11065
11597
  };
11066
11598
  case "error.raised":
11067
11599
  return {
11068
- [ATTR_ERROR_TYPE2]: event3.errorCode,
11600
+ [ATTR_ERROR_TYPE3]: event3.errorCode,
11069
11601
  [ATTR_OTELHOOK_ERROR_PHASE]: event3.phase,
11070
11602
  [ATTR_OTELHOOK_ERROR_RETRYABLE]: event3.retryable,
11071
11603
  [ATTR_OTELHOOK_ERROR_SEVERITY]: event3.severity
@@ -11660,8 +12192,356 @@ var shareCorrelationPerBatch = (correlate) => {
11660
12192
  };
11661
12193
  };
11662
12194
 
12195
+ // src/telemetry/durable-metric-spool.ts
12196
+ var MAX_SPOOLED_METRIC_POINTS_PER_BATCH = 4096;
12197
+ var MAX_STRING_LENGTH = 8192;
12198
+ var MAX_ATTRIBUTES_PER_POINT = 64;
12199
+ var MAX_BUCKETS = 64;
12200
+ var isPlainObject5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
12201
+ var isFiniteNonNegative3 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
12202
+ var isBoundedString3 = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_STRING_LENGTH;
12203
+ var isPrimitiveAttribute2 = (value) => typeof value === "string" && value.length <= MAX_STRING_LENGTH || typeof value === "number" && Number.isFinite(value) || typeof value === "boolean";
12204
+ var isReplayablePoint = (value) => {
12205
+ if (!isPlainObject5(value) || !isMetricInstrumentName(value.instrument)) {
12206
+ return false;
12207
+ }
12208
+ if (value.temporality !== "cumulative" && value.temporality !== "delta") {
12209
+ return false;
12210
+ }
12211
+ if (!isFiniteNonNegative3(value.startTimeMillis) || !isFiniteNonNegative3(value.timeMillis)) {
12212
+ return false;
12213
+ }
12214
+ if (!isPlainObject5(value.attributes)) {
12215
+ return false;
12216
+ }
12217
+ const entries = Object.entries(value.attributes);
12218
+ if (entries.length > MAX_ATTRIBUTES_PER_POINT || !entries.every(([, item]) => isPrimitiveAttribute2(item))) {
12219
+ return false;
12220
+ }
12221
+ const instrument = METRIC_INSTRUMENTS[value.instrument];
12222
+ if (instrument.kind === "counter") {
12223
+ return isFiniteNonNegative3(value.value) && value.histogram === void 0;
12224
+ }
12225
+ const histogram = value.histogram;
12226
+ if (!isPlainObject5(histogram) || value.value !== void 0) {
12227
+ return false;
12228
+ }
12229
+ const buckets = histogram.bucketCounts;
12230
+ 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));
12231
+ };
12232
+ var validateMetricSpoolBatch = (value, identity) => {
12233
+ if (!isPlainObject5(value)) {
12234
+ return { rejection: "not-an-object" };
12235
+ }
12236
+ if (value.providerId !== identity.providerId || value.installationId !== identity.installationId) {
12237
+ return { rejection: "identity-mismatch" };
12238
+ }
12239
+ if (!isPlainObject5(value.resourceAttributes)) {
12240
+ return { rejection: "resource-attributes-invalid" };
12241
+ }
12242
+ if (!isPlainObject5(value.instrumentationScope) || !isBoundedString3(value.instrumentationScope.name)) {
12243
+ return { rejection: "instrumentation-scope-invalid" };
12244
+ }
12245
+ if (value.instrumentationScope.version !== void 0 && typeof value.instrumentationScope.version !== "string") {
12246
+ return { rejection: "instrumentation-scope-invalid" };
12247
+ }
12248
+ if (!Array.isArray(value.points) || value.points.length === 0 || value.points.length > MAX_SPOOLED_METRIC_POINTS_PER_BATCH) {
12249
+ return { rejection: "points-invalid" };
12250
+ }
12251
+ if (!value.points.every(isReplayablePoint)) {
12252
+ return { rejection: "point-field-invalid" };
12253
+ }
12254
+ if (!isFiniteNonNegative3(value.enqueuedAt)) {
12255
+ return { rejection: "not-an-object" };
12256
+ }
12257
+ return { batch: value };
12258
+ };
12259
+ var DEFAULT_MAX_METRIC_SPOOL_FILES = 500;
12260
+ var createFileDurableMetricSpool = (options) => createSpoolQueue({
12261
+ rootDir: options.rootDir,
12262
+ providerId: options.providerId,
12263
+ installationId: options.installationId,
12264
+ clock: options.clock,
12265
+ ...options.logger === void 0 ? {} : { logger: options.logger },
12266
+ maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_METRIC_SPOOL_FILES,
12267
+ queueName: options.queueName ?? "spool-metrics",
12268
+ ...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
12269
+ ...options.maxAgeMillis === void 0 ? {} : { maxAgeMillis: options.maxAgeMillis },
12270
+ ...options.overflow === void 0 ? {} : { overflow: options.overflow },
12271
+ validate: validateMetricSpoolBatch
12272
+ });
12273
+
12274
+ // src/telemetry/otlp-metric-sink.ts
12275
+ import { ValueType } from "@opentelemetry/api";
12276
+ import { ExportResultCode as ExportResultCode3, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
12277
+ import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
12278
+ import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
12279
+ import {
12280
+ AggregationTemporality,
12281
+ DataPointType
12282
+ } from "@opentelemetry/sdk-metrics";
12283
+ var resolveMetricsEndpoint = (exporter) => {
12284
+ const stated = exporter.metrics?.endpoint;
12285
+ if (stated !== void 0) {
12286
+ return { endpoint: stated, derived: false };
12287
+ }
12288
+ if (exporter.endpoint === void 0) {
12289
+ return { unresolvable: "no-endpoint" };
12290
+ }
12291
+ return { endpoint: siblingSignalEndpoint(exporter.endpoint, "metrics"), derived: true };
12292
+ };
12293
+ var describeMetricsDeliverability = (exporter) => {
12294
+ if (exporter.metrics?.enabled !== true) {
12295
+ return { status: "disabled", reason: "metrics-disabled" };
12296
+ }
12297
+ if (!exporter.enabled) {
12298
+ return { status: "disabled", reason: "exporter-disabled" };
12299
+ }
12300
+ if (exporter.protocol === "none") {
12301
+ return { status: "disabled", reason: "protocol-none" };
12302
+ }
12303
+ if (exporter.protocol !== "http/protobuf") {
12304
+ return { status: "disabled", reason: "protocol-unsupported" };
12305
+ }
12306
+ const resolved = resolveMetricsEndpoint(exporter);
12307
+ if ("unresolvable" in resolved) {
12308
+ return { status: "disabled", reason: "no-endpoint" };
12309
+ }
12310
+ return { status: "configured", endpoint: resolved.endpoint, derivedEndpoint: resolved.derived };
12311
+ };
12312
+ var DISABLED_DETAIL2 = Object.freeze({
12313
+ "exporter-disabled": "otlp metric sink disabled: the exporter is disabled",
12314
+ "protocol-none": "otlp metric sink disabled: protocol is none",
12315
+ "protocol-unsupported": "otlp metric sink disabled: protocol not supported by this build",
12316
+ "no-endpoint": "otlp metric sink disabled: no metrics endpoint configured and none could be derived"
12317
+ });
12318
+ var createDisabledMetricSink = (destination) => {
12319
+ const health = createHealthTracker(
12320
+ "telemetry-metric-sink",
12321
+ destination === void 0 ? {} : { destination }
12322
+ );
12323
+ return {
12324
+ enabled: false,
12325
+ exportPoints: () => Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),
12326
+ flush: () => Promise.resolve(),
12327
+ shutdown: () => Promise.resolve(),
12328
+ health: () => health.snapshot(),
12329
+ drainSpool: () => Promise.resolve({ drained: 0, remaining: 0, failed: 0 })
12330
+ };
12331
+ };
12332
+ var createDisabledOtlpMetricSink = createDisabledMetricSink;
12333
+ var toMetricData = (points) => {
12334
+ const byInstrument = /* @__PURE__ */ new Map();
12335
+ for (const point of points) {
12336
+ const key = `${point.instrument}|${point.temporality}`;
12337
+ const group = byInstrument.get(key) ?? [];
12338
+ group.push(point);
12339
+ byInstrument.set(key, group);
12340
+ }
12341
+ const metrics = [];
12342
+ for (const group of byInstrument.values()) {
12343
+ const first = group[0];
12344
+ if (first === void 0) {
12345
+ continue;
12346
+ }
12347
+ const instrument = METRIC_INSTRUMENTS[first.instrument];
12348
+ const descriptor = {
12349
+ name: instrument.name,
12350
+ description: instrument.description,
12351
+ unit: instrument.unit,
12352
+ valueType: instrument.valueType === "int" ? ValueType.INT : ValueType.DOUBLE
12353
+ };
12354
+ const aggregationTemporality = first.temporality === "cumulative" ? AggregationTemporality.CUMULATIVE : AggregationTemporality.DELTA;
12355
+ const times = (point) => ({
12356
+ startTime: millisToHrTime4(point.startTimeMillis),
12357
+ endTime: millisToHrTime4(point.timeMillis)
12358
+ });
12359
+ if (instrument.kind === "counter") {
12360
+ metrics.push({
12361
+ descriptor,
12362
+ aggregationTemporality,
12363
+ dataPointType: DataPointType.SUM,
12364
+ isMonotonic: true,
12365
+ dataPoints: group.map((point) => ({
12366
+ ...times(point),
12367
+ attributes: { ...point.attributes },
12368
+ value: point.value ?? 0
12369
+ }))
12370
+ });
12371
+ continue;
12372
+ }
12373
+ metrics.push({
12374
+ descriptor,
12375
+ aggregationTemporality,
12376
+ dataPointType: DataPointType.HISTOGRAM,
12377
+ dataPoints: group.map((point) => {
12378
+ const histogram = point.histogram;
12379
+ return {
12380
+ ...times(point),
12381
+ attributes: { ...point.attributes },
12382
+ value: {
12383
+ buckets: {
12384
+ boundaries: [...instrument.boundaries ?? []],
12385
+ counts: [...histogram?.bucketCounts ?? []]
12386
+ },
12387
+ count: histogram?.count ?? 0,
12388
+ sum: histogram?.sum ?? 0,
12389
+ ...histogram === void 0 || histogram.count === 0 ? {} : { min: histogram.min, max: histogram.max }
12390
+ }
12391
+ };
12392
+ })
12393
+ });
12394
+ }
12395
+ return metrics;
12396
+ };
12397
+ var createOtlpMetricSink = (options) => {
12398
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
12399
+ const deliverability = describeMetricsDeliverability(options.exporter);
12400
+ if (deliverability.status === "disabled") {
12401
+ if (deliverability.reason !== "metrics-disabled") {
12402
+ options.logger?.warn(DISABLED_DETAIL2[deliverability.reason], {
12403
+ "exporter.protocol": options.exporter.protocol,
12404
+ ...destinationFields
12405
+ });
12406
+ }
12407
+ return createDisabledMetricSink(options.destination);
12408
+ }
12409
+ const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
12410
+ const resource = resourceFromAttributes2(
12411
+ withoutAccountIdentity(resourceFromExporterPolicy(options.exporter).attributes)
12412
+ );
12413
+ const health = createHealthTracker(
12414
+ "telemetry-metric-sink",
12415
+ options.destination === void 0 ? {} : { destination: options.destination }
12416
+ );
12417
+ const exporter = new OTLPMetricExporter({
12418
+ url: deliverability.endpoint,
12419
+ headers: { ...options.headers },
12420
+ timeoutMillis: options.exporter.timeoutMillis
12421
+ });
12422
+ let shutdownCompleted = false;
12423
+ const exportResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve5) => {
12424
+ const payload = {
12425
+ resource: batchResource,
12426
+ scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }]
12427
+ };
12428
+ try {
12429
+ exporter.export(payload, (result) => resolve5(result));
12430
+ } catch (thrown) {
12431
+ resolve5({
12432
+ code: ExportResultCode3.FAILED,
12433
+ error: thrown instanceof Error ? thrown : new Error("export threw")
12434
+ });
12435
+ }
12436
+ });
12437
+ const toSpoolBatch = (points) => ({
12438
+ providerId: options.providerId,
12439
+ installationId: options.installationId,
12440
+ resourceAttributes: { ...resource.attributes },
12441
+ instrumentationScope: {
12442
+ name: scope.name,
12443
+ ...scope.version === void 0 ? {} : { version: scope.version }
12444
+ },
12445
+ points: points.map((point) => ({ ...point })),
12446
+ enqueuedAt: options.clock.now()
12447
+ });
12448
+ const sendSerializedBatch = async (batch) => {
12449
+ const batchResource = resourceFromAttributes2(
12450
+ withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes)
12451
+ );
12452
+ const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);
12453
+ if (result.code === ExportResultCode3.SUCCESS) {
12454
+ return true;
12455
+ }
12456
+ return isPermanentExportFailure(result) ? "discard" : false;
12457
+ };
12458
+ const exportPoints = async (points) => {
12459
+ if (points.length === 0) {
12460
+ return { accepted: 0, rejected: 0, errors: [] };
12461
+ }
12462
+ const result = await exportResourceMetrics(points, resource, scope);
12463
+ if (result.code === ExportResultCode3.SUCCESS) {
12464
+ health.recordSuccess(points.length, options.clock.now());
12465
+ return { accepted: points.length, rejected: 0, errors: [] };
12466
+ }
12467
+ health.recordFailure("telemetry-export-failure", points.length, options.clock.now());
12468
+ const permanent = isPermanentExportFailure(result);
12469
+ if (options.spool !== void 0 && !permanent) {
12470
+ const spooled = await options.spool.enqueue(toSpoolBatch(points)).catch(() => ({
12471
+ spooled: false,
12472
+ reason: "capacity-exceeded"
12473
+ }));
12474
+ if (spooled.spooled) {
12475
+ options.logger?.warn("metric batch not delivered; spooled for the next invocation", {
12476
+ "export.batch_size": points.length,
12477
+ ...destinationFields
12478
+ });
12479
+ return { accepted: points.length, rejected: 0, errors: [] };
12480
+ }
12481
+ }
12482
+ return {
12483
+ accepted: 0,
12484
+ rejected: points.length,
12485
+ errors: [
12486
+ createErrorInfo({
12487
+ code: "telemetry-export-failure",
12488
+ phase: "export",
12489
+ detail: permanent ? "collector refused a metric batch with a non-retryable status" : "collector rejected or was unreachable for a metric batch",
12490
+ details: {
12491
+ "export.batch_size": points.length,
12492
+ "export.signal": "metrics",
12493
+ ...destinationFields
12494
+ }
12495
+ })
12496
+ ]
12497
+ };
12498
+ };
12499
+ const drainSpool = async (maxBatches) => {
12500
+ if (options.spool === void 0) {
12501
+ return { drained: 0, remaining: 0, failed: 0 };
12502
+ }
12503
+ const result = await options.spool.drain(sendSerializedBatch, {
12504
+ ...maxBatches === void 0 ? {} : { maxBatches }
12505
+ });
12506
+ if (result.drained > 0) {
12507
+ health.recordSuccess(result.drained, options.clock.now());
12508
+ }
12509
+ return result;
12510
+ };
12511
+ const flush = async () => {
12512
+ try {
12513
+ await exporter.forceFlush();
12514
+ } catch {
12515
+ }
12516
+ await drainSpool().catch(() => void 0);
12517
+ };
12518
+ const shutdown = async () => {
12519
+ if (shutdownCompleted) {
12520
+ return;
12521
+ }
12522
+ shutdownCompleted = true;
12523
+ await flush();
12524
+ try {
12525
+ await exporter.shutdown();
12526
+ } catch {
12527
+ }
12528
+ };
12529
+ return {
12530
+ enabled: true,
12531
+ exportPoints,
12532
+ flush,
12533
+ shutdown,
12534
+ health: () => health.snapshot(),
12535
+ drainSpool
12536
+ };
12537
+ };
12538
+
11663
12539
  // src/telemetry/export-destinations.ts
11664
- var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs" } : { traces: `destinations/${destination}/spool`, logs: `destinations/${destination}/spool-logs` };
12540
+ var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs", metrics: "spool-metrics" } : {
12541
+ traces: `destinations/${destination}/spool`,
12542
+ logs: `destinations/${destination}/spool-logs`,
12543
+ metrics: `destinations/${destination}/spool-metrics`
12544
+ };
11665
12545
  var exporterPolicyForDestination = (exporter, destination) => {
11666
12546
  if (destination.source === "exporter") {
11667
12547
  return exporter;
@@ -11678,8 +12558,10 @@ var exporterPolicyForDestination = (exporter, destination) => {
11678
12558
  });
11679
12559
  return "endpoint" in derived ? derived.endpoint : void 0;
11680
12560
  })());
12561
+ const { metrics: sharedMetrics, ...rest } = shared;
12562
+ const derivedMetrics = destination.metricsEndpoint ?? (destination.endpoint === void 0 ? void 0 : siblingSignalEndpoint(destination.endpoint, "metrics"));
11681
12563
  return {
11682
- ...shared,
12564
+ ...rest,
11683
12565
  protocol: destination.protocol,
11684
12566
  ...tracesEndpoint === void 0 ? {} : { endpoint: tracesEndpoint },
11685
12567
  headerNames: Object.keys(destination.headers).sort(),
@@ -11687,6 +12569,11 @@ var exporterPolicyForDestination = (exporter, destination) => {
11687
12569
  ...logs,
11688
12570
  enabled: destination.signals.logs,
11689
12571
  ...derivedLogs === void 0 ? {} : { endpoint: derivedLogs }
12572
+ },
12573
+ metrics: {
12574
+ ...effectiveMetricsPolicy({ ...exporter, metrics: sharedMetrics }),
12575
+ enabled: destination.signals.metrics,
12576
+ ...derivedMetrics === void 0 ? {} : { endpoint: derivedMetrics }
11690
12577
  }
11691
12578
  };
11692
12579
  };
@@ -11758,6 +12645,12 @@ var createExportDestinationSinks = (options) => {
11758
12645
  ...bounds,
11759
12646
  queueName: queues.logs
11760
12647
  });
12648
+ const metricSpool = options.spoolRootDir === void 0 || !destination.signals.metrics ? void 0 : createFileDurableMetricSpool({
12649
+ rootDir: options.spoolRootDir,
12650
+ ...shared,
12651
+ ...bounds,
12652
+ queueName: queues.metrics
12653
+ });
11761
12654
  const sinkShared = {
11762
12655
  exporter: policy,
11763
12656
  ...shared,
@@ -11775,12 +12668,21 @@ var createExportDestinationSinks = (options) => {
11775
12668
  ...logSpool === void 0 ? {} : { spool: logSpool },
11776
12669
  content: options.logContent
11777
12670
  });
12671
+ const metrics = destination.signals.metrics ? createOtlpMetricSink({
12672
+ exporter: policy,
12673
+ ...shared,
12674
+ ...label === void 0 ? {} : { destination: label },
12675
+ ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
12676
+ ...metricSpool === void 0 ? {} : { spool: metricSpool }
12677
+ }) : createDisabledOtlpMetricSink(label);
11778
12678
  destinations.push({
11779
12679
  name: destination.name,
11780
12680
  traces,
11781
12681
  logs,
12682
+ metrics,
11782
12683
  ...spool === void 0 ? {} : { spool },
11783
- ...logSpool === void 0 ? {} : { logSpool }
12684
+ ...logSpool === void 0 ? {} : { logSpool },
12685
+ ...metricSpool === void 0 ? {} : { metricSpool }
11784
12686
  });
11785
12687
  }
11786
12688
  return { destinations, skipped };
@@ -11946,6 +12848,12 @@ var createHookRuntime = (options) => {
11946
12848
  const hook = createOtelHook({ ...hookDeps, sink });
11947
12849
  const deduplicator = createCallbackDeduplicator({ stateStore, clock });
11948
12850
  const usageAccumulator = createUsageAccumulator({ stateStore, clock });
12851
+ const metricSeries = createMetricSeriesStore({ stateStore, clock });
12852
+ const metricsPolicy = effectiveMetricsPolicy(options.config.exporter);
12853
+ const metricDestinations = exportDestinations.destinations.filter(
12854
+ (destination) => destination.metrics.enabled
12855
+ );
12856
+ const metricResource = resourceFromExporterPolicy(options.config.exporter);
11949
12857
  const deliveryRetentionMillis = options.deliveryRetentionMillis ?? lifecycleMaxAge;
11950
12858
  if (deliveryRetentionMillis < staleClaimMillis) {
11951
12859
  logger.warn("delivery retention is shorter than the stale-claim window", {
@@ -11957,6 +12865,7 @@ var createHookRuntime = (options) => {
11957
12865
  spanCorrelator,
11958
12866
  deduplicator,
11959
12867
  usageAccumulator,
12868
+ metricSeries,
11960
12869
  spanMaxAgeMillis: lifecycleMaxAge,
11961
12870
  dedupMaxAgeMillis: deliveryRetentionMillis,
11962
12871
  // The *effective* window, not the requested one: a sweep that considered a
@@ -11967,6 +12876,86 @@ var createHookRuntime = (options) => {
11967
12876
  });
11968
12877
  const deliveryLock = createAsyncLock();
11969
12878
  const stateDiagnostic = (thrown) => errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() });
12879
+ const generationStartsFor = async (events) => {
12880
+ const needed = events.some(
12881
+ (event3) => event3.type === "generation.end" && event3.durationMillis === void 0 && !events.some(
12882
+ (other) => other.type === "generation.start" && other.generationId === event3.generationId
12883
+ )
12884
+ );
12885
+ if (!needed) {
12886
+ return void 0;
12887
+ }
12888
+ try {
12889
+ const starts = /* @__PURE__ */ new Map();
12890
+ for (const correlation of await correlate(events)) {
12891
+ if (correlation.ref.family !== "generation" || correlation.startMillis === void 0) {
12892
+ continue;
12893
+ }
12894
+ const requestModel = correlation.attributes?.["gen_ai.request.model"];
12895
+ starts.set(correlation.ref.scopeKey, {
12896
+ startMillis: correlation.startMillis,
12897
+ ...typeof requestModel === "string" ? { requestModel } : {}
12898
+ });
12899
+ }
12900
+ return (generationId) => starts.get(generationId);
12901
+ } catch {
12902
+ return void 0;
12903
+ }
12904
+ };
12905
+ const recordMetrics = async (ingest, deliveryToken, diagnostics) => {
12906
+ if (metricDestinations.length === 0 || ingest.events.length === 0) {
12907
+ return void 0;
12908
+ }
12909
+ try {
12910
+ for (const event3 of ingest.events) {
12911
+ if (event3.type === "prompt.submitted") {
12912
+ await metricSeries.recordTurnStart(event3.sessionId, event3.occurredAt);
12913
+ }
12914
+ }
12915
+ const generationStarts = await generationStartsFor(ingest.events);
12916
+ const turnStarts = /* @__PURE__ */ new Map();
12917
+ for (const event3 of ingest.events) {
12918
+ if (event3.type === "generation.end" && !turnStarts.has(event3.sessionId)) {
12919
+ turnStarts.set(event3.sessionId, await metricSeries.readTurnStart(event3.sessionId));
12920
+ }
12921
+ }
12922
+ const observations = deriveMetricObservations({
12923
+ events: ingest.events,
12924
+ usage: ingest.usageObservations,
12925
+ resource: metricResource,
12926
+ includeSessionId: metricsPolicy.includeSessionId,
12927
+ ...generationStarts === void 0 ? {} : { generationStarts },
12928
+ turnStart: (sessionId) => turnStarts.get(sessionId)
12929
+ });
12930
+ if (observations.length === 0) {
12931
+ return void 0;
12932
+ }
12933
+ const points = metricsPolicy.temporality === "delta" ? aggregateDeltaPoints(observations, clock.now()) : await metricSeries.recordCumulative(observations, {
12934
+ perSession: metricsPolicy.includeSessionId,
12935
+ ...deliveryToken === void 0 ? {} : { deliveryToken }
12936
+ });
12937
+ const results = await Promise.all(
12938
+ metricDestinations.map(async (destination) => {
12939
+ const result = await destination.metrics.exportPoints(points).catch(
12940
+ (thrown) => ({
12941
+ accepted: 0,
12942
+ rejected: points.length,
12943
+ errors: [
12944
+ errorInfoFromThrown(thrown, { code: "telemetry-export-failure", phase: "export" })
12945
+ ]
12946
+ })
12947
+ );
12948
+ diagnostics.push(...result.errors);
12949
+ return { name: destination.name, accepted: result.accepted, rejected: result.rejected };
12950
+ })
12951
+ );
12952
+ return { points: points.length, destinations: results };
12953
+ } catch (thrown) {
12954
+ diagnostics.push(stateDiagnostic(thrown));
12955
+ logger.warn("hook-derived metrics could not be recorded for this callback", {});
12956
+ return void 0;
12957
+ }
12958
+ };
11970
12959
  const rollupDeliveryToken = (identity) => {
11971
12960
  const token = ids.newOpaqueId(["usage-delivery", identity.scope, identity.callbackId]).replace(/[^A-Za-z0-9_-]/g, "").slice(0, 128);
11972
12961
  return token.length === 0 ? void 0 : token;
@@ -12087,6 +13076,11 @@ var createHookRuntime = (options) => {
12087
13076
  identity === void 0 ? void 0 : rollupDeliveryToken(identity)
12088
13077
  );
12089
13078
  }
13079
+ const metrics = !duplicateDelivery && ingest.identity !== void 0 && isCommittable(ingest.durability) ? await recordMetrics(
13080
+ ingest,
13081
+ identity === void 0 ? void 0 : rollupDeliveryToken(identity),
13082
+ diagnostics
13083
+ ) : void 0;
12090
13084
  if (owned && identity !== void 0) {
12091
13085
  try {
12092
13086
  if (isCommittable(ingest.durability)) {
@@ -12153,6 +13147,7 @@ var createHookRuntime = (options) => {
12153
13147
  duplicateDelivery,
12154
13148
  delivery,
12155
13149
  usageRollups,
13150
+ ...metrics === void 0 ? {} : { metrics },
12156
13151
  ...cleanup === void 0 ? {} : { cleanup },
12157
13152
  diagnostics
12158
13153
  };
@@ -12169,12 +13164,20 @@ var createHookRuntime = (options) => {
12169
13164
  () => runProcess(input, identified.identity, report, diagnostics)
12170
13165
  );
12171
13166
  };
12172
- const snapshots = () => sink.health();
13167
+ const snapshots = () => [
13168
+ ...sink.health(),
13169
+ ...metricDestinations.map((destination) => destination.metrics.health())
13170
+ ];
12173
13171
  let shutdownReport;
12174
13172
  const shutdown = () => {
12175
13173
  shutdownReport ??= (async () => {
12176
13174
  const raced = await Promise.race([
12177
- hook.shutdown().then(() => "completed"),
13175
+ Promise.all([
13176
+ hook.shutdown(),
13177
+ // Metric sinks are not behind the hook's sink: they replay their own
13178
+ // spools here, inside the same bounded window.
13179
+ ...metricDestinations.map((destination) => destination.metrics.shutdown().catch(() => void 0))
13180
+ ]).then(() => "completed"),
12178
13181
  delay(flushTimeoutMillis)
12179
13182
  ]);
12180
13183
  if (raced === "timeout") {
@@ -12204,6 +13207,7 @@ var createHookRuntime = (options) => {
12204
13207
  deduplicator,
12205
13208
  usageAccumulator,
12206
13209
  spanCorrelator,
13210
+ metricSeries,
12207
13211
  janitor,
12208
13212
  process: process_,
12209
13213
  shutdown,
@@ -12212,12 +13216,12 @@ var createHookRuntime = (options) => {
12212
13216
  };
12213
13217
 
12214
13218
  // src/providers/antigravity/registration.ts
12215
- var isPlainObject5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
13219
+ var isPlainObject6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
12216
13220
  var mergeAntigravityHookRegistration = (input) => {
12217
13221
  const events = input.events ?? ANTIGRAVITY_HOOK_EVENT_NAMES;
12218
- const base = isPlainObject5(input.existing) ? input.existing : {};
12219
- const existingHooks = isPlainObject5(base.hooks) ? base.hooks : {};
12220
- let changed = !isPlainObject5(input.existing) || !isPlainObject5(base.hooks);
13222
+ const base = isPlainObject6(input.existing) ? input.existing : {};
13223
+ const existingHooks = isPlainObject6(base.hooks) ? base.hooks : {};
13224
+ let changed = !isPlainObject6(input.existing) || !isPlainObject6(base.hooks);
12221
13225
  const nextHooks = { ...existingHooks };
12222
13226
  const identifies = input.identifies ?? ((entry) => entry.command === input.command);
12223
13227
  const desired = {
@@ -12226,7 +13230,7 @@ var mergeAntigravityHookRegistration = (input) => {
12226
13230
  };
12227
13231
  for (const event3 of events) {
12228
13232
  const currentList = Array.isArray(existingHooks[event3]) ? [...existingHooks[event3]] : [];
12229
- const managedIndex = currentList.findIndex((entry) => isPlainObject5(entry) && identifies(entry));
13233
+ const managedIndex = currentList.findIndex((entry) => isPlainObject6(entry) && identifies(entry));
12230
13234
  if (managedIndex === -1) {
12231
13235
  changed = true;
12232
13236
  nextHooks[event3] = [...currentList, desired];
@@ -12235,7 +13239,7 @@ var mergeAntigravityHookRegistration = (input) => {
12235
13239
  const managed = currentList[managedIndex];
12236
13240
  const updated = { ...managed, ...desired };
12237
13241
  const next = currentList.filter(
12238
- (entry, index) => index === managedIndex || !(isPlainObject5(entry) && identifies(entry))
13242
+ (entry, index) => index === managedIndex || !(isPlainObject6(entry) && identifies(entry))
12239
13243
  );
12240
13244
  next[next.indexOf(managed)] = updated;
12241
13245
  const rewritten = Object.entries(desired).some(([key, value]) => managed[key] !== value);
@@ -12250,8 +13254,8 @@ var mergeAntigravityHookRegistration = (input) => {
12250
13254
  };
12251
13255
  };
12252
13256
  var removeAntigravityHookRegistration = (input) => {
12253
- const base = isPlainObject5(input.existing) ? { ...input.existing } : {};
12254
- if (!isPlainObject5(base.hooks)) {
13257
+ const base = isPlainObject6(input.existing) ? { ...input.existing } : {};
13258
+ if (!isPlainObject6(base.hooks)) {
12255
13259
  return { config: base, changed: false };
12256
13260
  }
12257
13261
  const nextHooks = { ...base.hooks };
@@ -12263,7 +13267,7 @@ var removeAntigravityHookRegistration = (input) => {
12263
13267
  continue;
12264
13268
  }
12265
13269
  const kept = currentList.filter(
12266
- (entry) => !(isPlainObject5(entry) && input.identifies(entry))
13270
+ (entry) => !(isPlainObject6(entry) && input.identifies(entry))
12267
13271
  );
12268
13272
  if (kept.length === currentList.length) {
12269
13273
  continue;
@@ -12288,7 +13292,7 @@ var removeAntigravityHookRegistration = (input) => {
12288
13292
  };
12289
13293
  var readAntigravityHookRegistrations = (existing, identifies) => {
12290
13294
  const found = /* @__PURE__ */ new Map();
12291
- if (!isPlainObject5(existing) || !isPlainObject5(existing.hooks)) {
13295
+ if (!isPlainObject6(existing) || !isPlainObject6(existing.hooks)) {
12292
13296
  return found;
12293
13297
  }
12294
13298
  for (const [event3, list] of Object.entries(existing.hooks)) {
@@ -12296,7 +13300,7 @@ var readAntigravityHookRegistrations = (existing, identifies) => {
12296
13300
  continue;
12297
13301
  }
12298
13302
  const commands = list.filter(
12299
- (entry) => isPlainObject5(entry) && typeof entry.command === "string" && identifies(entry)
13303
+ (entry) => isPlainObject6(entry) && typeof entry.command === "string" && identifies(entry)
12300
13304
  ).map((entry) => entry.command);
12301
13305
  if (commands.length > 0) {
12302
13306
  found.set(event3, commands);
@@ -12306,10 +13310,10 @@ var readAntigravityHookRegistrations = (existing, identifies) => {
12306
13310
  };
12307
13311
 
12308
13312
  // src/providers/hook-document.ts
12309
- var isPlainObject6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
13313
+ var isPlainObject7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
12310
13314
  var normalizeMatcher = (value) => typeof value === "string" && value !== "" && value !== "*" ? value : void 0;
12311
- var isManaged = (value, identifies) => isPlainObject6(value) && identifies(value);
12312
- var cloneGroup = (value) => isPlainObject6(value) && Array.isArray(value.hooks) ? { ...value, hooks: [...value.hooks] } : void 0;
13315
+ var isManaged = (value, identifies) => isPlainObject7(value) && identifies(value);
13316
+ var cloneGroup = (value) => isPlainObject7(value) && Array.isArray(value.hooks) ? { ...value, hooks: [...value.hooks] } : void 0;
12313
13317
  var matchesDesired = (existing, desired) => {
12314
13318
  for (const [key, value] of Object.entries(desired)) {
12315
13319
  if (existing[key] !== value) {
@@ -12337,7 +13341,7 @@ var readHooksObject = (base, conflicts) => {
12337
13341
  if (raw === void 0) {
12338
13342
  return {};
12339
13343
  }
12340
- if (!isPlainObject6(raw)) {
13344
+ if (!isPlainObject7(raw)) {
12341
13345
  conflicts.push({
12342
13346
  location: "hooks",
12343
13347
  detail: `expected an object keyed by hook event name, found ${Array.isArray(raw) ? "an array" : raw === null ? "null" : typeof raw}`
@@ -12346,7 +13350,7 @@ var readHooksObject = (base, conflicts) => {
12346
13350
  }
12347
13351
  return { ...raw };
12348
13352
  };
12349
- var pruneEventList = (list) => list.filter((group) => !(isPlainObject6(group) && Array.isArray(group.hooks) && group.hooks.length === 0));
13353
+ var pruneEventList = (list) => list.filter((group) => !(isPlainObject7(group) && Array.isArray(group.hooks) && group.hooks.length === 0));
12350
13354
  var finalize = (base, hooks) => {
12351
13355
  const next = { ...base };
12352
13356
  if (Object.keys(hooks).length === 0) {
@@ -12357,7 +13361,7 @@ var finalize = (base, hooks) => {
12357
13361
  return next;
12358
13362
  };
12359
13363
  var mergeNestedHookRegistration = (input) => {
12360
- const base = isPlainObject6(input.existing) ? { ...input.existing } : {};
13364
+ const base = isPlainObject7(input.existing) ? { ...input.existing } : {};
12361
13365
  const conflicts = [];
12362
13366
  const hooks = readHooksObject(base, conflicts);
12363
13367
  if (hooks === void 0) {
@@ -12373,7 +13377,7 @@ var mergeNestedHookRegistration = (input) => {
12373
13377
  }
12374
13378
  const groups = list.map((group) => cloneGroup(group) ?? group);
12375
13379
  const usableGroups = groups.filter(
12376
- (group) => isPlainObject6(group) && Array.isArray(group.hooks)
13380
+ (group) => isPlainObject7(group) && Array.isArray(group.hooks)
12377
13381
  );
12378
13382
  let ownHandler;
12379
13383
  let ownGroup;
@@ -12438,7 +13442,7 @@ var mergeNestedHookRegistration = (input) => {
12438
13442
  return { document: finalize(base, hooks), changed, changes, conflicts };
12439
13443
  };
12440
13444
  var removeNestedHookRegistrations = (input) => {
12441
- const base = isPlainObject6(input.existing) ? { ...input.existing } : {};
13445
+ const base = isPlainObject7(input.existing) ? { ...input.existing } : {};
12442
13446
  const conflicts = [];
12443
13447
  const hooks = readHooksObject(base, conflicts);
12444
13448
  if (hooks === void 0) {
@@ -12491,7 +13495,7 @@ var removeNestedHookRegistrations = (input) => {
12491
13495
  };
12492
13496
  var readNestedHookRegistrations = (existing, identifies) => {
12493
13497
  const found = /* @__PURE__ */ new Map();
12494
- if (!isPlainObject6(existing) || !isPlainObject6(existing.hooks)) {
13498
+ if (!isPlainObject7(existing) || !isPlainObject7(existing.hooks)) {
12495
13499
  return found;
12496
13500
  }
12497
13501
  for (const [event3, list] of Object.entries(existing.hooks)) {
@@ -12500,7 +13504,7 @@ var readNestedHookRegistrations = (existing, identifies) => {
12500
13504
  }
12501
13505
  const commands = [];
12502
13506
  for (const group of list) {
12503
- if (!isPlainObject6(group) || !Array.isArray(group.hooks)) {
13507
+ if (!isPlainObject7(group) || !Array.isArray(group.hooks)) {
12504
13508
  continue;
12505
13509
  }
12506
13510
  for (const handler of group.hooks) {
@@ -12640,7 +13644,7 @@ var CURSOR_UNREGISTERED_HOOK_EVENTS = Object.freeze({
12640
13644
  workspaceOpen: "an app-lifecycle hook that carries no conversation_id, so it has no session to attribute telemetry to"
12641
13645
  });
12642
13646
  var CURSOR_HOOKS_DOCUMENT_VERSION = 1;
12643
- var isPlainObject7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
13647
+ var isPlainObject8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
12644
13648
  var buildEntry3 = (input) => ({
12645
13649
  type: "command",
12646
13650
  command: input.command,
@@ -12649,8 +13653,8 @@ var buildEntry3 = (input) => ({
12649
13653
  });
12650
13654
  var mergeCursorHookRegistration = (input) => {
12651
13655
  const events = input.events ?? CURSOR_REGISTRABLE_HOOK_EVENTS;
12652
- const base = isPlainObject7(input.existing) ? { ...input.existing } : {};
12653
- const existingHooks = isPlainObject7(base.hooks) ? base.hooks : {};
13656
+ const base = isPlainObject8(input.existing) ? { ...input.existing } : {};
13657
+ const existingHooks = isPlainObject8(base.hooks) ? base.hooks : {};
12654
13658
  const nextHooks = { ...existingHooks };
12655
13659
  const desired = buildEntry3(input);
12656
13660
  let changed = false;
@@ -12661,7 +13665,7 @@ var mergeCursorHookRegistration = (input) => {
12661
13665
  for (const event3 of events) {
12662
13666
  const currentList = Array.isArray(existingHooks[event3]) ? [...existingHooks[event3]] : [];
12663
13667
  const managed = currentList.filter(
12664
- (entry) => isPlainObject7(entry) && input.identifies(entry)
13668
+ (entry) => isPlainObject8(entry) && input.identifies(entry)
12665
13669
  );
12666
13670
  const [ours] = managed;
12667
13671
  if (ours === void 0) {
@@ -12670,7 +13674,7 @@ var mergeCursorHookRegistration = (input) => {
12670
13674
  continue;
12671
13675
  }
12672
13676
  const rewritten = { ...ours, ...desired };
12673
- const next = currentList.filter((entry) => entry === ours || !(isPlainObject7(entry) && input.identifies(entry))).map((entry) => entry === ours ? rewritten : entry);
13677
+ const next = currentList.filter((entry) => entry === ours || !(isPlainObject8(entry) && input.identifies(entry))).map((entry) => entry === ours ? rewritten : entry);
12674
13678
  const entryChanged = Object.entries(desired).some(([key, value]) => ours[key] !== value);
12675
13679
  if (entryChanged || managed.length > 1) {
12676
13680
  changed = true;
@@ -12680,8 +13684,8 @@ var mergeCursorHookRegistration = (input) => {
12680
13684
  return { config: { ...base, hooks: nextHooks }, changed };
12681
13685
  };
12682
13686
  var removeCursorHookRegistration = (input) => {
12683
- const base = isPlainObject7(input.existing) ? { ...input.existing } : {};
12684
- if (!isPlainObject7(base.hooks)) {
13687
+ const base = isPlainObject8(input.existing) ? { ...input.existing } : {};
13688
+ if (!isPlainObject8(base.hooks)) {
12685
13689
  return { config: base, changed: false };
12686
13690
  }
12687
13691
  const nextHooks = { ...base.hooks };
@@ -12693,7 +13697,7 @@ var removeCursorHookRegistration = (input) => {
12693
13697
  continue;
12694
13698
  }
12695
13699
  const kept = currentList.filter(
12696
- (entry) => !(isPlainObject7(entry) && input.identifies(entry))
13700
+ (entry) => !(isPlainObject8(entry) && input.identifies(entry))
12697
13701
  );
12698
13702
  if (kept.length === currentList.length) {
12699
13703
  continue;
@@ -12721,7 +13725,7 @@ var removeCursorHookRegistration = (input) => {
12721
13725
  };
12722
13726
  var readCursorHookRegistrations = (existing, identifies) => {
12723
13727
  const found = /* @__PURE__ */ new Map();
12724
- if (!isPlainObject7(existing) || !isPlainObject7(existing.hooks)) {
13728
+ if (!isPlainObject8(existing) || !isPlainObject8(existing.hooks)) {
12725
13729
  return found;
12726
13730
  }
12727
13731
  for (const [event3, list] of Object.entries(existing.hooks)) {
@@ -12729,7 +13733,7 @@ var readCursorHookRegistrations = (existing, identifies) => {
12729
13733
  continue;
12730
13734
  }
12731
13735
  const commands = list.filter(
12732
- (entry) => isPlainObject7(entry) && typeof entry.command === "string" && identifies(entry)
13736
+ (entry) => isPlainObject8(entry) && typeof entry.command === "string" && identifies(entry)
12733
13737
  ).map((entry) => entry.command);
12734
13738
  if (commands.length > 0) {
12735
13739
  found.set(event3, commands);
@@ -12829,7 +13833,7 @@ var managedHookPredicate = (marker) => {
12829
13833
  }
12830
13834
  return (handler) => handler.name === MANAGED_HOOK_NAME || typeof handler.command === "string" && handler.command.includes(marker);
12831
13835
  };
12832
- var isPlainObject8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
13836
+ var isPlainObject9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
12833
13837
  var adaptFlatResult = (read, existing, events, identifies, result, removal) => {
12834
13838
  const before = read(existing, identifies);
12835
13839
  const after = read(result.config, identifies);
@@ -12853,10 +13857,10 @@ var adaptFlatResult = (read, existing, events, identifies, result, removal) => {
12853
13857
  return { document: result.config, changed: result.changed, changes, conflicts: [] };
12854
13858
  };
12855
13859
  var flatHookConflicts = (existing) => {
12856
- if (!isPlainObject8(existing) || existing.hooks === void 0) {
13860
+ if (!isPlainObject9(existing) || existing.hooks === void 0) {
12857
13861
  return [];
12858
13862
  }
12859
- if (!isPlainObject8(existing.hooks)) {
13863
+ if (!isPlainObject9(existing.hooks)) {
12860
13864
  return [
12861
13865
  {
12862
13866
  location: "hooks",
@@ -12876,7 +13880,7 @@ var flatHookConflicts = (existing) => {
12876
13880
  return conflicts;
12877
13881
  };
12878
13882
  var asAntigravityEvents = (events) => events;
12879
- var documentEventNames = (existing) => isPlainObject8(existing) && isPlainObject8(existing.hooks) ? Object.keys(existing.hooks) : [];
13883
+ var documentEventNames = (existing) => isPlainObject9(existing) && isPlainObject9(existing.hooks) ? Object.keys(existing.hooks) : [];
12880
13884
  var PLANNERS = Object.freeze([
12881
13885
  Object.freeze({
12882
13886
  providerId: ANTIGRAVITY_PROVIDER_ID,
@@ -12885,7 +13889,7 @@ var PLANNERS = Object.freeze([
12885
13889
  const conflicts = flatHookConflicts(input.existing);
12886
13890
  if (conflicts.length > 0) {
12887
13891
  return {
12888
- document: isPlainObject8(input.existing) ? input.existing : {},
13892
+ document: isPlainObject9(input.existing) ? input.existing : {},
12889
13893
  changed: false,
12890
13894
  changes: [],
12891
13895
  conflicts
@@ -12911,7 +13915,7 @@ var PLANNERS = Object.freeze([
12911
13915
  const conflicts = flatHookConflicts(input.existing);
12912
13916
  if (conflicts.length > 0) {
12913
13917
  return {
12914
- document: isPlainObject8(input.existing) ? input.existing : {},
13918
+ document: isPlainObject9(input.existing) ? input.existing : {},
12915
13919
  changed: false,
12916
13920
  changes: [],
12917
13921
  conflicts
@@ -12954,7 +13958,7 @@ var PLANNERS = Object.freeze([
12954
13958
  const conflicts = flatHookConflicts(input.existing);
12955
13959
  if (conflicts.length > 0) {
12956
13960
  return {
12957
- document: isPlainObject8(input.existing) ? input.existing : {},
13961
+ document: isPlainObject9(input.existing) ? input.existing : {},
12958
13962
  changed: false,
12959
13963
  changes: [],
12960
13964
  conflicts
@@ -12981,7 +13985,7 @@ var PLANNERS = Object.freeze([
12981
13985
  const conflicts = flatHookConflicts(input.existing);
12982
13986
  if (conflicts.length > 0) {
12983
13987
  return {
12984
- document: isPlainObject8(input.existing) ? input.existing : {},
13988
+ document: isPlainObject9(input.existing) ? input.existing : {},
12985
13989
  changed: false,
12986
13990
  changes: [],
12987
13991
  conflicts
@@ -13749,6 +14753,7 @@ export {
13749
14753
  DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS,
13750
14754
  DEFAULT_CONFIG,
13751
14755
  DEFAULT_DESTINATION_NAME,
14756
+ DEFAULT_DESTINATION_SIGNALS,
13752
14757
  DEFAULT_DETECTION_POLICY,
13753
14758
  DEFAULT_DIAGNOSTICS_POLICY,
13754
14759
  DEFAULT_DOCUMENT_FORMAT,
@@ -13757,6 +14762,7 @@ export {
13757
14762
  DEFAULT_INSTRUMENTATION_SCOPE,
13758
14763
  DEFAULT_LOGS_POLICY,
13759
14764
  DEFAULT_MANAGED_COMMAND_MARKER,
14765
+ DEFAULT_METRICS_POLICY,
13760
14766
  DEFAULT_PRIVACY_LIMITS,
13761
14767
  DEFAULT_PRIVACY_POLICY,
13762
14768
  DEFAULT_PROVIDERS_POLICY,
@@ -13808,7 +14814,14 @@ export {
13808
14814
  MAX_TARGET_PATH_LENGTH,
13809
14815
  MAX_WORKTREE_WALK_DEPTH,
13810
14816
  MCP_TOOL_NAME_PATTERN,
14817
+ METRIC_COST_USAGE,
14818
+ METRIC_INSTRUMENTS,
14819
+ METRIC_OPERATION_DURATION,
14820
+ METRIC_SESSIONS,
14821
+ METRIC_TOKEN_USAGE,
14822
+ METRIC_TOOL_CALLS,
13811
14823
  NO_LOG_CONTENT,
14824
+ OPERATION_DURATION_BUCKETS,
13812
14825
  OTLP_ENDPOINT_VARIABLES,
13813
14826
  OTLP_HEADER_VARIABLES,
13814
14827
  OtelHookError,
@@ -13829,6 +14842,7 @@ export {
13829
14842
  SUBAGENT_ID_PATTERN,
13830
14843
  SUPPORTED_REGISTRATION_PROVIDER_IDS,
13831
14844
  TARGETED_EVENT_TYPES,
14845
+ TOKEN_USAGE_BUCKETS,
13832
14846
  UNKNOWN_PROVIDER_ID,
13833
14847
  UNKNOWN_WORKSPACE_ID,
13834
14848
  UsageNormalizationError,
@@ -13836,6 +14850,7 @@ export {
13836
14850
  WORKSPACE_ID_PATTERN,
13837
14851
  adapterSupports,
13838
14852
  addUsage,
14853
+ aggregateDeltaPoints,
13839
14854
  appliedDeliverySchema,
13840
14855
  asProviderId,
13841
14856
  attachClaudeTranscriptTurn,
@@ -13882,6 +14897,7 @@ export {
13882
14897
  createEventFactory,
13883
14898
  createExportDestinationSinks,
13884
14899
  createFileDurableLogSpool,
14900
+ createFileDurableMetricSpool,
13885
14901
  createFileDurableSpool,
13886
14902
  createFilesystemStateStore,
13887
14903
  createFilesystemWorktreeLocator,
@@ -13891,10 +14907,12 @@ export {
13891
14907
  createHookRuntime,
13892
14908
  createInMemoryStateStore,
13893
14909
  createLifecycleJanitor,
14910
+ createMetricSeriesStore,
13894
14911
  createNullLogger,
13895
14912
  createNullTelemetrySink,
13896
14913
  createOtelHook,
13897
14914
  createOtlpLogSink,
14915
+ createOtlpMetricSink,
13898
14916
  createOtlpTraceSink,
13899
14917
  createPrivacyService,
13900
14918
  createProviderRegistry,
@@ -13911,11 +14929,13 @@ export {
13911
14929
  deliveryComponentSchema,
13912
14930
  deliveryGapReasonSchema,
13913
14931
  deliveryIdentifierSupportSchema,
14932
+ deriveMetricObservations,
13914
14933
  deriveWorkspaceIdentity,
13915
14934
  describeAdapter,
13916
14935
  describeErrorCode,
13917
14936
  describeExportDestinations,
13918
14937
  describeLogsDeliverability,
14938
+ describeMetricsDeliverability,
13919
14939
  describeOtlpHeaderNames,
13920
14940
  describeProviderCatalog,
13921
14941
  describeResolvedConfig,
@@ -13926,6 +14946,7 @@ export {
13926
14946
  detectionPolicySchema,
13927
14947
  diagnosticsPolicySchema,
13928
14948
  durationMillisSchema,
14949
+ effectiveMetricsPolicy,
13929
14950
  effectiveSpoolPolicy,
13930
14951
  emptyExtensions,
13931
14952
  endpointOrigin,
@@ -13982,6 +15003,7 @@ export {
13982
15003
  mergeGeminiHookRegistration,
13983
15004
  mergeNestedHookRegistration,
13984
15005
  mergeOtlpHeaders,
15006
+ metricsPolicySchema,
13985
15007
  minimumStaleClaimMillis,
13986
15008
  modelDescriptorSchema,
13987
15009
  nonEmptyStringSchema,
@@ -14041,6 +15063,7 @@ export {
14041
15063
  resolveInstallPath,
14042
15064
  resolveInvocationIdentity,
14043
15065
  resolveLogsEndpoint,
15066
+ resolveMetricsEndpoint,
14044
15067
  resolveOtlpHeaders,
14045
15068
  resolvePrivacyPolicy,
14046
15069
  resolvedProviderIdSchema,
@@ -14080,6 +15103,7 @@ export {
14080
15103
  usageScopeSchema,
14081
15104
  usageTemporalitySchema,
14082
15105
  validateCanonicalEvent,
15106
+ validateMetricSpoolBatch,
14083
15107
  withFileLock,
14084
15108
  withOptionalSessionLock,
14085
15109
  workspaceIdSchema,