@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
@@ -161,7 +161,7 @@ var HEADER_ENV_REFERENCE_PREFIX = "env:";
161
161
  var HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
162
162
  var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
163
163
  var MAX_HEADER_VALUE_LENGTH = 8192;
164
- var exportSignalSchema = z3.enum(["traces", "logs"]);
164
+ var exportSignalSchema = z3.enum(["traces", "logs", "metrics"]);
165
165
  var headerValueSchema = z3.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
166
166
  (value) => !isUnsafeHeaderValue(value),
167
167
  "header values may not contain line breaks, control characters, or characters beyond Latin-1"
@@ -184,6 +184,8 @@ var exportDestinationSchema = z3.strictObject({
184
184
  tracesEndpoint: endpointSchema.optional(),
185
185
  /** Per-signal override of the derived logs URL. */
186
186
  logsEndpoint: endpointSchema.optional(),
187
+ /** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */
188
+ metricsEndpoint: endpointSchema.optional(),
187
189
  /** Defaults to `exporter.protocol`. */
188
190
  protocol: z3.enum(["http/protobuf", "http/json", "none"]).optional(),
189
191
  /**
@@ -196,15 +198,17 @@ var exportDestinationSchema = z3.strictObject({
196
198
  `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
197
199
  ).optional(),
198
200
  /**
199
- * Which signals this destination receives. Default: both. The logs signal is
200
- * still governed by `exporter.logs.enabled`, which stays the one opt-in for a
201
- * second stream leaving the host.
201
+ * Which signals this destination receives. Default: traces and logs. The logs
202
+ * signal is still governed by `exporter.logs.enabled`, which stays the one
203
+ * opt-in for content-bearing records leaving the host. `metrics` is never on by
204
+ * default: a destination receives hook-derived metrics only when it lists them.
202
205
  */
203
- signals: z3.array(exportSignalSchema).min(1).max(2).readonly().optional()
206
+ signals: z3.array(exportSignalSchema).min(1).max(3).readonly().optional()
204
207
  }).refine(
205
- (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0,
206
- "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint"
208
+ (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
209
+ "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
207
210
  );
211
+ var DEFAULT_DESTINATION_SIGNALS = Object.freeze(["traces", "logs"]);
208
212
  var exportDestinationsSchema = z3.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
209
213
  const seen = /* @__PURE__ */ new Set();
210
214
  destinations.forEach((destination, index) => {
@@ -249,7 +253,8 @@ var legacyDestination = (exporter) => ({
249
253
  protocol: exporter.protocol,
250
254
  ...exporter.endpoint === void 0 ? {} : { endpoint: exporter.endpoint },
251
255
  ...exporter.logs.endpoint === void 0 ? {} : { logsEndpoint: exporter.logs.endpoint },
252
- signals: { traces: true, logs: exporter.logs.enabled },
256
+ ...exporter.metrics?.endpoint === void 0 ? {} : { metricsEndpoint: exporter.metrics.endpoint },
257
+ signals: { traces: true, logs: exporter.logs.enabled, metrics: exporter.metrics?.enabled === true },
253
258
  headers: {}
254
259
  });
255
260
  var hasConfiguredDestinations = (exporter) => exporter.destinations !== void 0 && exporter.destinations.length > 0;
@@ -258,14 +263,14 @@ var resolveExportDestinations = (exporter) => {
258
263
  return [legacyDestination(exporter)];
259
264
  }
260
265
  const resolved = [];
261
- if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0) {
266
+ if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0 || exporter.metrics?.endpoint !== void 0) {
262
267
  resolved.push(legacyDestination(exporter));
263
268
  }
264
269
  for (const destination of exporter.destinations ?? []) {
265
270
  if (destination.enabled === false) {
266
271
  continue;
267
272
  }
268
- const signals = destination.signals ?? exportSignalSchema.options;
273
+ const signals = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;
269
274
  resolved.push({
270
275
  name: destination.name,
271
276
  source: "destinations",
@@ -273,9 +278,11 @@ var resolveExportDestinations = (exporter) => {
273
278
  ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
274
279
  ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
275
280
  ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
281
+ ...destination.metricsEndpoint === void 0 ? {} : { metricsEndpoint: destination.metricsEndpoint },
276
282
  signals: {
277
283
  traces: signals.includes("traces"),
278
- logs: exporter.logs.enabled && signals.includes("logs")
284
+ logs: exporter.logs.enabled && signals.includes("logs"),
285
+ metrics: signals.includes("metrics")
279
286
  },
280
287
  headers: { ...destination.headers ?? {} }
281
288
  });
@@ -405,6 +412,18 @@ var DEFAULT_LOGS_POLICY = Object.freeze({
405
412
  includeContent: false,
406
413
  maxBatchSize: 128
407
414
  });
415
+ var metricsPolicySchema = z5.strictObject({
416
+ enabled: z5.boolean(),
417
+ /** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */
418
+ endpoint: z5.string().url().max(2048).optional(),
419
+ temporality: z5.enum(["cumulative", "delta"]),
420
+ includeSessionId: z5.boolean()
421
+ });
422
+ var DEFAULT_METRICS_POLICY = Object.freeze({
423
+ enabled: false,
424
+ temporality: "cumulative",
425
+ includeSessionId: true
426
+ });
408
427
  var exporterPolicySchema = z5.strictObject({
409
428
  enabled: z5.boolean(),
410
429
  protocol: z5.enum(["http/protobuf", "http/json", "none"]),
@@ -435,6 +454,11 @@ var exporterPolicySchema = z5.strictObject({
435
454
  * a second top-level section would invite two of each to drift apart.
436
455
  */
437
456
  logs: logsPolicySchema,
457
+ /**
458
+ * Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before
459
+ * metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.
460
+ */
461
+ metrics: metricsPolicySchema.optional(),
438
462
  /**
439
463
  * Additional OTLP destinations, each sent every batch in parallel.
440
464
  *
@@ -483,8 +507,9 @@ var otelHookConfigPatchSchema = z5.strictObject({
483
507
  // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
484
508
  // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
485
509
  // without also restating the endpoint and the batch size.
486
- exporter: exporterPolicySchema.omit({ logs: true, spool: true }).partial().extend({
510
+ exporter: exporterPolicySchema.omit({ logs: true, metrics: true, spool: true }).partial().extend({
487
511
  logs: logsPolicySchema.partial().optional(),
512
+ metrics: metricsPolicySchema.partial().optional(),
488
513
  spool: spoolPolicySchema.partial().optional()
489
514
  }).optional(),
490
515
  privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
@@ -504,7 +529,8 @@ var DEFAULT_EXPORTER_POLICY = Object.freeze({
504
529
  maxRetryAttempts: 2,
505
530
  serviceName: "coding-agent",
506
531
  resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
507
- logs: DEFAULT_LOGS_POLICY
532
+ logs: DEFAULT_LOGS_POLICY,
533
+ metrics: DEFAULT_METRICS_POLICY
508
534
  });
509
535
  var DEFAULT_DETECTION_POLICY = Object.freeze({
510
536
  minimumConfidence: "strong",
@@ -526,6 +552,10 @@ var DEFAULT_CONFIG = Object.freeze({
526
552
  providers: DEFAULT_PROVIDERS_POLICY
527
553
  });
528
554
  var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
555
+ var effectiveMetricsPolicy = (exporter) => ({
556
+ ...DEFAULT_METRICS_POLICY,
557
+ ...exporter.metrics ?? {}
558
+ });
529
559
 
530
560
  // src/diagnostics/health.ts
531
561
  var createHealthTracker = (subsystem, options = {}) => {
@@ -934,6 +964,8 @@ var rollupUsageKey = (sessionId, scope, scopeKey) => `${rollupScanPrefix(session
934
964
  var rollupEpochKey = (sessionId, scope, scopeKey) => `${rollupEpochScanPrefix(sessionId)}${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;
935
965
  var rollupScanPrefix = (sessionId) => sessionId === void 0 ? `${LIFECYCLE_PREFIX}:usage:` : `${LIFECYCLE_PREFIX}:usage:${encodeSegment(sessionId)}:`;
936
966
  var rollupEpochScanPrefix = (sessionId) => sessionId === void 0 ? `${LIFECYCLE_PREFIX}:epoch:` : `${LIFECYCLE_PREFIX}:epoch:${encodeSegment(sessionId)}:`;
967
+ var metricSeriesKey = (sessionScope2, seriesDigest) => `${metricSeriesScanPrefix(sessionScope2)}${encodeSegment(seriesDigest)}`;
968
+ var metricSeriesScanPrefix = (sessionScope2) => sessionScope2 === void 0 ? `${LIFECYCLE_PREFIX}:metric:v1:` : `${LIFECYCLE_PREFIX}:metric:v1:${encodeSegment(sessionScope2)}:`;
937
969
 
938
970
  // src/lifecycle/dedup.ts
939
971
  var DEFAULT_STALE_CLAIM_MILLIS = 6e4;
@@ -1103,59 +1135,8 @@ var createCallbackDeduplicator = (deps) => {
1103
1135
  return { checkAndMark, claim, commit, release, cleanup };
1104
1136
  };
1105
1137
 
1106
- // src/lifecycle/janitor.ts
1107
- var DEFAULT_MAX_AGE_MILLIS = 24 * 60 * 60 * 1e3;
1108
- var DEFAULT_MAX_ENTRIES_PER_COMPONENT = 1e3;
1109
- var createLifecycleJanitor = (options) => {
1110
- const maxEntries = options.maxEntriesPerComponent ?? DEFAULT_MAX_ENTRIES_PER_COMPONENT;
1111
- const spanMaxAge = options.spanMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
1112
- const dedupMaxAge = options.dedupMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
1113
- const usageMaxAge = options.usageMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
1114
- const runOnce = async (sessionId) => {
1115
- const scope = { maxEntries, ...sessionId === void 0 ? {} : { sessionId } };
1116
- const [span, dedup, usage] = await Promise.all([
1117
- options.spanCorrelator?.cleanup(spanMaxAge, scope),
1118
- // Deduplication is deliberately swept across every scope rather than the
1119
- // ending session's: a delivery scope is a host-chosen namespace or a
1120
- // digest of provider/installation/session, never a session id, so scoping
1121
- // this sweep by `sessionId` would match nothing and let records accumulate
1122
- // forever. The sweep is TTL-driven and still bounded by `maxEntries`.
1123
- options.deduplicator?.cleanup(dedupMaxAge, {
1124
- maxEntries,
1125
- ...options.dedupStaleClaimMillis === void 0 ? {} : { staleClaimMillis: options.dedupStaleClaimMillis }
1126
- }),
1127
- options.usageAccumulator?.cleanup(usageMaxAge, scope)
1128
- ]);
1129
- return {
1130
- ...span === void 0 ? {} : { span },
1131
- ...dedup === void 0 ? {} : { dedup },
1132
- ...usage === void 0 ? {} : { usage }
1133
- };
1134
- };
1135
- return { runOnce };
1136
- };
1137
-
1138
- // src/telemetry/semconv.ts
1138
+ // src/lifecycle/metric-series.ts
1139
1139
  import { createHash } from "crypto";
1140
- import { SpanKind, SpanStatusCode, TraceFlags } from "@opentelemetry/api";
1141
- import { millisToHrTime } from "@opentelemetry/core";
1142
- import {
1143
- ATTR_ERROR_TYPE,
1144
- ATTR_GEN_AI_OPERATION_NAME,
1145
- ATTR_GEN_AI_REQUEST_MODEL,
1146
- ATTR_GEN_AI_RESPONSE_MODEL,
1147
- ATTR_GEN_AI_SYSTEM,
1148
- ATTR_GEN_AI_TOOL_CALL_ID,
1149
- ATTR_GEN_AI_TOOL_NAME,
1150
- ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,
1151
- ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,
1152
- ATTR_GEN_AI_USAGE_INPUT_TOKENS,
1153
- ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,
1154
- ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS
1155
- } from "@opentelemetry/semantic-conventions/incubating";
1156
-
1157
- // src/version.ts
1158
- var VERSION = "0.10.0";
1159
1140
 
1160
1141
  // src/telemetry/export-identity.ts
1161
1142
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -1942,6 +1923,475 @@ var exportIdentityAttributes = (event2, resource, ids) => {
1942
1923
  };
1943
1924
  };
1944
1925
 
1926
+ // src/telemetry/metric-model.ts
1927
+ var TOKEN_USAGE_BUCKETS = Object.freeze([
1928
+ 1,
1929
+ 4,
1930
+ 16,
1931
+ 64,
1932
+ 256,
1933
+ 1024,
1934
+ 4096,
1935
+ 16384,
1936
+ 65536,
1937
+ 262144,
1938
+ 1048576,
1939
+ 4194304,
1940
+ 16777216,
1941
+ 67108864
1942
+ ]);
1943
+ var OPERATION_DURATION_BUCKETS = Object.freeze([
1944
+ 0.01,
1945
+ 0.02,
1946
+ 0.04,
1947
+ 0.08,
1948
+ 0.16,
1949
+ 0.32,
1950
+ 0.64,
1951
+ 1.28,
1952
+ 2.56,
1953
+ 5.12,
1954
+ 10.24,
1955
+ 20.48,
1956
+ 40.96,
1957
+ 81.92
1958
+ ]);
1959
+ var METRIC_TOKEN_USAGE = "gen_ai.client.token.usage";
1960
+ var METRIC_OPERATION_DURATION = "gen_ai.client.operation.duration";
1961
+ var METRIC_SESSIONS = "otelhook.sessions";
1962
+ var METRIC_TOOL_CALLS = "otelhook.tool.calls";
1963
+ var METRIC_COST_USAGE = "otelhook.cost.usage";
1964
+ var METRIC_INSTRUMENTS = Object.freeze({
1965
+ [METRIC_TOKEN_USAGE]: {
1966
+ name: METRIC_TOKEN_USAGE,
1967
+ kind: "histogram",
1968
+ unit: "{token}",
1969
+ description: "Tokens used per generation, by token type (hook-derived)",
1970
+ valueType: "int",
1971
+ boundaries: TOKEN_USAGE_BUCKETS
1972
+ },
1973
+ [METRIC_OPERATION_DURATION]: {
1974
+ name: METRIC_OPERATION_DURATION,
1975
+ kind: "histogram",
1976
+ unit: "s",
1977
+ description: "Generation duration, from its start hook to its end hook (hook-derived)",
1978
+ valueType: "double",
1979
+ boundaries: OPERATION_DURATION_BUCKETS
1980
+ },
1981
+ [METRIC_SESSIONS]: {
1982
+ name: METRIC_SESSIONS,
1983
+ kind: "counter",
1984
+ unit: "{session}",
1985
+ description: "Agent sessions started",
1986
+ valueType: "int"
1987
+ },
1988
+ [METRIC_TOOL_CALLS]: {
1989
+ name: METRIC_TOOL_CALLS,
1990
+ kind: "counter",
1991
+ unit: "{call}",
1992
+ description: "Completed tool calls, by tool name and outcome",
1993
+ valueType: "int"
1994
+ },
1995
+ [METRIC_COST_USAGE]: {
1996
+ name: METRIC_COST_USAGE,
1997
+ kind: "counter",
1998
+ unit: "USD",
1999
+ description: "Cost reported by the provider; never estimated",
2000
+ valueType: "double"
2001
+ }
2002
+ });
2003
+ var isMetricInstrumentName = (value) => typeof value === "string" && Object.hasOwn(METRIC_INSTRUMENTS, value);
2004
+ var ATTR_GEN_AI_TOKEN_TYPE = "gen_ai.token.type";
2005
+ var ATTR_GEN_AI_PROVIDER_NAME = "gen_ai.provider.name";
2006
+ var ATTR_GEN_AI_OPERATION_NAME = "gen_ai.operation.name";
2007
+ var ATTR_GEN_AI_REQUEST_MODEL = "gen_ai.request.model";
2008
+ var ATTR_GEN_AI_RESPONSE_MODEL = "gen_ai.response.model";
2009
+ var ATTR_GEN_AI_TOOL_NAME = "gen_ai.tool.name";
2010
+ var ATTR_ERROR_TYPE = "error.type";
2011
+ var ATTR_SESSION_ID2 = "session.id";
2012
+ var ATTR_OTELHOOK_PROVIDER_ID2 = "otelhook.provider.id";
2013
+ var ATTR_OTELHOOK_OUTCOME = "otelhook.outcome";
2014
+ var ATTR_OTELHOOK_SESSION_KIND = "otelhook.session.kind";
2015
+ var commonAttributes = (event2, resource, includeSessionId) => ({
2016
+ [ATTR_OTELHOOK_PROVIDER_ID2]: event2.provenance.providerId,
2017
+ ...includeSessionId ? { [ATTR_SESSION_ID2]: resolveExportedSessionId(event2.sessionId, resource).sessionId } : {}
2018
+ });
2019
+ var generationAttributes = (end, requestModel) => ({
2020
+ [ATTR_GEN_AI_OPERATION_NAME]: "chat",
2021
+ ...end.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_PROVIDER_NAME]: end.model.vendor },
2022
+ [ATTR_GEN_AI_REQUEST_MODEL]: requestModel ?? end.model.modelId,
2023
+ [ATTR_GEN_AI_RESPONSE_MODEL]: end.model.modelId
2024
+ });
2025
+ var TOKEN_FIELDS = [
2026
+ ["input", (usage) => usage.inputTokens],
2027
+ ["output", (usage) => usage.outputTokens],
2028
+ ["cache_read", (usage) => usage.cachedInputTokens],
2029
+ ["cache_creation", (usage) => usage.cacheCreationInputTokens]
2030
+ ];
2031
+ var isFailedOutcome = (outcome) => outcome !== "ok" && outcome !== "unknown" && outcome !== "cancelled";
2032
+ var deriveMetricObservations = (input) => {
2033
+ const includeSessionId = input.includeSessionId ?? true;
2034
+ const observations = [];
2035
+ const byId = /* @__PURE__ */ new Map();
2036
+ const startsInBatch = /* @__PURE__ */ new Map();
2037
+ for (const event2 of input.events) {
2038
+ byId.set(event2.eventId, event2);
2039
+ if (event2.type === "generation.start") {
2040
+ startsInBatch.set(event2.generationId, {
2041
+ startMillis: event2.occurredAt,
2042
+ requestModel: event2.model.modelId
2043
+ });
2044
+ }
2045
+ }
2046
+ const requestModelOf = (generationId) => startsInBatch.get(generationId)?.requestModel ?? input.generationStarts?.(generationId)?.requestModel;
2047
+ let lastPromptInBatch;
2048
+ for (const event2 of input.events) {
2049
+ if (event2.type === "prompt.submitted") {
2050
+ lastPromptInBatch ??= /* @__PURE__ */ new Map();
2051
+ lastPromptInBatch.set(event2.sessionId, Math.max(lastPromptInBatch.get(event2.sessionId) ?? 0, event2.occurredAt));
2052
+ }
2053
+ }
2054
+ const measuredDurationOf = (end) => {
2055
+ if (end.durationMillis !== void 0) {
2056
+ return end.durationMillis;
2057
+ }
2058
+ const recovered = startsInBatch.has(end.generationId) ? void 0 : input.generationStarts?.(end.generationId);
2059
+ if (recovered !== void 0) {
2060
+ return end.occurredAt - recovered.startMillis;
2061
+ }
2062
+ const turn = lastPromptInBatch?.get(end.sessionId) ?? input.turnStart?.(end.sessionId);
2063
+ return turn === void 0 || turn > end.occurredAt ? void 0 : end.occurredAt - turn;
2064
+ };
2065
+ const push = (event2, instrument, value, attributes) => {
2066
+ if (!Number.isFinite(value) || value < 0) {
2067
+ return;
2068
+ }
2069
+ observations.push({
2070
+ instrument,
2071
+ value,
2072
+ attributes: { ...commonAttributes(event2, input.resource, includeSessionId), ...attributes },
2073
+ timeMillis: event2.occurredAt,
2074
+ sessionId: event2.sessionId
2075
+ });
2076
+ };
2077
+ for (const event2 of input.events) {
2078
+ switch (event2.type) {
2079
+ case "session.start":
2080
+ push(event2, METRIC_SESSIONS, 1, { [ATTR_OTELHOOK_SESSION_KIND]: event2.sessionKind });
2081
+ break;
2082
+ case "tool.end":
2083
+ push(event2, METRIC_TOOL_CALLS, 1, {
2084
+ [ATTR_GEN_AI_TOOL_NAME]: event2.toolName,
2085
+ [ATTR_OTELHOOK_OUTCOME]: event2.outcome
2086
+ });
2087
+ break;
2088
+ case "generation.end": {
2089
+ const attributes = generationAttributes(event2, requestModelOf(event2.generationId));
2090
+ const durationMillis = measuredDurationOf(event2);
2091
+ if (durationMillis !== void 0 && durationMillis >= 0) {
2092
+ push(event2, METRIC_OPERATION_DURATION, durationMillis / 1e3, {
2093
+ ...attributes,
2094
+ ...isFailedOutcome(event2.outcome) ? { [ATTR_ERROR_TYPE]: event2.outcome } : {}
2095
+ });
2096
+ }
2097
+ if (event2.cost !== void 0 && event2.cost.source === "provider-reported" && event2.cost.currency === "USD") {
2098
+ push(event2, METRIC_COST_USAGE, event2.cost.amount, attributes);
2099
+ }
2100
+ break;
2101
+ }
2102
+ default:
2103
+ break;
2104
+ }
2105
+ }
2106
+ for (const observation of input.usage) {
2107
+ if (observation.scope !== "generation") {
2108
+ continue;
2109
+ }
2110
+ const event2 = byId.get(observation.eventId);
2111
+ if (event2?.type !== "generation.end") {
2112
+ continue;
2113
+ }
2114
+ const attributes = generationAttributes(event2, requestModelOf(event2.generationId));
2115
+ for (const [tokenType, read] of TOKEN_FIELDS) {
2116
+ const value = read(observation.delta);
2117
+ if (value === 0 && (tokenType === "cache_read" || tokenType === "cache_creation")) {
2118
+ continue;
2119
+ }
2120
+ push(event2, METRIC_TOKEN_USAGE, value, { ...attributes, [ATTR_GEN_AI_TOKEN_TYPE]: tokenType });
2121
+ }
2122
+ }
2123
+ return observations;
2124
+ };
2125
+ var emptyHistogram = (boundaries) => ({
2126
+ count: 0,
2127
+ sum: 0,
2128
+ min: Number.POSITIVE_INFINITY,
2129
+ max: Number.NEGATIVE_INFINITY,
2130
+ bucketCounts: new Array(boundaries.length + 1).fill(0)
2131
+ });
2132
+ var bucketIndex = (boundaries, value) => {
2133
+ for (let index = 0; index < boundaries.length; index += 1) {
2134
+ const bound = boundaries[index];
2135
+ if (bound !== void 0 && value <= bound) {
2136
+ return index;
2137
+ }
2138
+ }
2139
+ return boundaries.length;
2140
+ };
2141
+ var recordIntoHistogram = (state, boundaries, value) => {
2142
+ const bucketCounts = [...state.bucketCounts];
2143
+ const index = bucketIndex(boundaries, value);
2144
+ bucketCounts[index] = (bucketCounts[index] ?? 0) + 1;
2145
+ return {
2146
+ count: state.count + 1,
2147
+ sum: state.sum + value,
2148
+ min: Math.min(state.min, value),
2149
+ max: Math.max(state.max, value),
2150
+ bucketCounts
2151
+ };
2152
+ };
2153
+ var seriesIdentity = (instrument, attributes) => JSON.stringify([
2154
+ instrument,
2155
+ Object.entries(attributes).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
2156
+ ]);
2157
+ var aggregateDeltaPoints = (observations, nowMillis) => {
2158
+ const series = /* @__PURE__ */ new Map();
2159
+ for (const observation of observations) {
2160
+ const instrument = METRIC_INSTRUMENTS[observation.instrument];
2161
+ const key = seriesIdentity(observation.instrument, observation.attributes);
2162
+ const existing = series.get(key) ?? {
2163
+ observation,
2164
+ start: observation.timeMillis,
2165
+ value: 0,
2166
+ ...instrument.boundaries === void 0 ? {} : { histogram: emptyHistogram(instrument.boundaries) }
2167
+ };
2168
+ existing.start = Math.min(existing.start, observation.timeMillis);
2169
+ if (existing.histogram !== void 0 && instrument.boundaries !== void 0) {
2170
+ existing.histogram = recordIntoHistogram(existing.histogram, instrument.boundaries, observation.value);
2171
+ } else {
2172
+ existing.value += observation.value;
2173
+ }
2174
+ series.set(key, existing);
2175
+ }
2176
+ return [...series.values()].map((entry) => ({
2177
+ instrument: entry.observation.instrument,
2178
+ temporality: "delta",
2179
+ attributes: entry.observation.attributes,
2180
+ startTimeMillis: Math.min(entry.start, nowMillis),
2181
+ timeMillis: Math.max(nowMillis, entry.start),
2182
+ ...entry.histogram === void 0 ? { value: entry.value } : { histogram: entry.histogram }
2183
+ }));
2184
+ };
2185
+ var FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES = Object.freeze([
2186
+ "user.",
2187
+ "enduser.",
2188
+ "organization."
2189
+ ]);
2190
+ var withoutAccountIdentity = (attributes) => Object.fromEntries(
2191
+ Object.entries(attributes).filter(
2192
+ ([key]) => !FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES.some((prefix) => key.startsWith(prefix))
2193
+ )
2194
+ );
2195
+
2196
+ // src/lifecycle/metric-series.ts
2197
+ var TURN_START_SEGMENT = "turn-start";
2198
+ var SHARED_SCOPE = "all";
2199
+ var SHARED_LOCK = "otelhook.metrics.shared";
2200
+ var sessionScope = (sessionId) => `s=${sessionId}`;
2201
+ var digest = (identity) => createHash("sha256").update(identity).digest("base64url").slice(0, 43);
2202
+ var toStoredHistogram = (histogram) => ({
2203
+ count: histogram.count,
2204
+ sum: histogram.sum,
2205
+ // An empty histogram has infinite min/max, which JSON cannot hold. A stored
2206
+ // histogram always has at least one value, so these are finite in practice.
2207
+ min: Number.isFinite(histogram.min) ? histogram.min : 0,
2208
+ max: Number.isFinite(histogram.max) ? histogram.max : 0,
2209
+ bucketCounts: [...histogram.bucketCounts]
2210
+ });
2211
+ var createMetricSeriesStore = (deps) => {
2212
+ const { stateStore, clock } = deps;
2213
+ const readSeries = async (key) => {
2214
+ const record = await stateStore.read(key);
2215
+ if (record?.value.kind !== "metric-series") {
2216
+ return void 0;
2217
+ }
2218
+ return record.value;
2219
+ };
2220
+ const recordGroup = async (scope, observations, deliveryToken) => {
2221
+ const bySeries = /* @__PURE__ */ new Map();
2222
+ for (const observation of observations) {
2223
+ const identity = seriesIdentity(observation.instrument, observation.attributes);
2224
+ const group = bySeries.get(identity) ?? [];
2225
+ group.push(observation);
2226
+ bySeries.set(identity, group);
2227
+ }
2228
+ const now = clock.now();
2229
+ const points = [];
2230
+ for (const [identity, group] of bySeries) {
2231
+ const first = group[0];
2232
+ if (first === void 0) {
2233
+ continue;
2234
+ }
2235
+ const instrument = METRIC_INSTRUMENTS[first.instrument];
2236
+ const key = metricSeriesKey(scope, digest(identity));
2237
+ const existing = await readSeries(key);
2238
+ const boundaries = instrument.boundaries;
2239
+ const compatible = existing !== void 0 && (boundaries === void 0 ? existing.value !== void 0 : existing.histogram?.bucketCounts.length === boundaries.length + 1);
2240
+ const base = compatible ? existing : void 0;
2241
+ const replay = deliveryToken !== void 0 && base?.appliedDelivery === deliveryToken;
2242
+ const earliest = Math.min(...group.map((observation) => observation.timeMillis));
2243
+ const startTimeMillis = base?.startTimeMillis ?? Math.min(earliest, now);
2244
+ let value = base?.value ?? 0;
2245
+ let histogram = boundaries === void 0 ? void 0 : base?.histogram === void 0 ? emptyHistogram(boundaries) : base.histogram;
2246
+ if (!replay) {
2247
+ for (const observation of group) {
2248
+ if (histogram !== void 0 && boundaries !== void 0) {
2249
+ histogram = recordIntoHistogram(histogram, boundaries, observation.value);
2250
+ } else {
2251
+ value += observation.value;
2252
+ }
2253
+ }
2254
+ await stateStore.write(key, {
2255
+ kind: "metric-series",
2256
+ startTimeMillis,
2257
+ ...histogram === void 0 ? { value } : { histogram: toStoredHistogram(histogram) },
2258
+ ...deliveryToken === void 0 ? {} : { appliedDelivery: deliveryToken }
2259
+ });
2260
+ }
2261
+ points.push({
2262
+ instrument: first.instrument,
2263
+ temporality: "cumulative",
2264
+ attributes: first.attributes,
2265
+ startTimeMillis,
2266
+ timeMillis: Math.max(now, startTimeMillis),
2267
+ ...histogram === void 0 ? { value } : { histogram }
2268
+ });
2269
+ }
2270
+ return points;
2271
+ };
2272
+ const recordCumulative = async (observations, options) => {
2273
+ if (observations.length === 0) {
2274
+ return [];
2275
+ }
2276
+ if (options?.perSession === false) {
2277
+ return withOptionalSessionLock(
2278
+ stateStore,
2279
+ SHARED_LOCK,
2280
+ () => recordGroup(SHARED_SCOPE, observations, options.deliveryToken)
2281
+ );
2282
+ }
2283
+ const bySession = /* @__PURE__ */ new Map();
2284
+ for (const observation of observations) {
2285
+ const group = bySession.get(observation.sessionId) ?? [];
2286
+ group.push(observation);
2287
+ bySession.set(observation.sessionId, group);
2288
+ }
2289
+ const points = [];
2290
+ for (const [sessionId, group] of bySession) {
2291
+ points.push(
2292
+ ...await withOptionalSessionLock(
2293
+ stateStore,
2294
+ sessionId,
2295
+ () => recordGroup(sessionScope(sessionId), group, options?.deliveryToken)
2296
+ )
2297
+ );
2298
+ }
2299
+ return points;
2300
+ };
2301
+ const cleanup = async (maxAgeMillis, options) => {
2302
+ const cap = options?.maxEntries ?? 1e3;
2303
+ const now = clock.now();
2304
+ let removed = 0;
2305
+ let scanned = 0;
2306
+ const prefix = metricSeriesScanPrefix(
2307
+ options?.sessionId === void 0 ? void 0 : sessionScope(options.sessionId)
2308
+ );
2309
+ for (const key of await stateStore.keys(prefix)) {
2310
+ if (scanned >= cap) {
2311
+ break;
2312
+ }
2313
+ scanned += 1;
2314
+ const record = await stateStore.read(key);
2315
+ if (record !== void 0 && now - record.updatedAt > maxAgeMillis) {
2316
+ await stateStore.delete(key);
2317
+ removed += 1;
2318
+ }
2319
+ }
2320
+ return { removed, scanned };
2321
+ };
2322
+ const turnKey = (sessionId) => metricSeriesKey(sessionScope(sessionId), TURN_START_SEGMENT);
2323
+ const recordTurnStart = (sessionId, startMillis) => withOptionalSessionLock(stateStore, sessionId, async () => {
2324
+ const existing = await stateStore.read(turnKey(sessionId));
2325
+ const previous = existing?.value.kind === "attributes" && typeof existing.value.attributes.startMillis === "number" ? existing.value.attributes.startMillis : void 0;
2326
+ if (previous !== void 0 && previous >= startMillis) {
2327
+ return;
2328
+ }
2329
+ await stateStore.write(turnKey(sessionId), { kind: "attributes", attributes: { startMillis } });
2330
+ });
2331
+ const readTurnStart = async (sessionId) => {
2332
+ const record = await stateStore.read(turnKey(sessionId));
2333
+ const value = record?.value.kind === "attributes" ? record.value.attributes.startMillis : void 0;
2334
+ return typeof value === "number" ? value : void 0;
2335
+ };
2336
+ return { recordCumulative, recordTurnStart, readTurnStart, cleanup };
2337
+ };
2338
+
2339
+ // src/lifecycle/janitor.ts
2340
+ var DEFAULT_MAX_AGE_MILLIS = 24 * 60 * 60 * 1e3;
2341
+ var DEFAULT_MAX_ENTRIES_PER_COMPONENT = 1e3;
2342
+ var createLifecycleJanitor = (options) => {
2343
+ const maxEntries = options.maxEntriesPerComponent ?? DEFAULT_MAX_ENTRIES_PER_COMPONENT;
2344
+ const spanMaxAge = options.spanMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
2345
+ const dedupMaxAge = options.dedupMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
2346
+ const usageMaxAge = options.usageMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
2347
+ const runOnce = async (sessionId) => {
2348
+ const scope = { maxEntries, ...sessionId === void 0 ? {} : { sessionId } };
2349
+ const [span, dedup, usage, metrics] = await Promise.all([
2350
+ options.spanCorrelator?.cleanup(spanMaxAge, scope),
2351
+ // Deduplication is deliberately swept across every scope rather than the
2352
+ // ending session's: a delivery scope is a host-chosen namespace or a
2353
+ // digest of provider/installation/session, never a session id, so scoping
2354
+ // this sweep by `sessionId` would match nothing and let records accumulate
2355
+ // forever. The sweep is TTL-driven and still bounded by `maxEntries`.
2356
+ options.deduplicator?.cleanup(dedupMaxAge, {
2357
+ maxEntries,
2358
+ ...options.dedupStaleClaimMillis === void 0 ? {} : { staleClaimMillis: options.dedupStaleClaimMillis }
2359
+ }),
2360
+ options.usageAccumulator?.cleanup(usageMaxAge, scope),
2361
+ options.metricSeries?.cleanup(usageMaxAge, scope)
2362
+ ]);
2363
+ return {
2364
+ ...span === void 0 ? {} : { span },
2365
+ ...dedup === void 0 ? {} : { dedup },
2366
+ ...usage === void 0 ? {} : { usage },
2367
+ ...metrics === void 0 ? {} : { metrics }
2368
+ };
2369
+ };
2370
+ return { runOnce };
2371
+ };
2372
+
2373
+ // src/telemetry/semconv.ts
2374
+ import { createHash as createHash2 } from "crypto";
2375
+ import { SpanKind, SpanStatusCode, TraceFlags } from "@opentelemetry/api";
2376
+ import { millisToHrTime } from "@opentelemetry/core";
2377
+ import {
2378
+ ATTR_ERROR_TYPE as ATTR_ERROR_TYPE2,
2379
+ ATTR_GEN_AI_OPERATION_NAME as ATTR_GEN_AI_OPERATION_NAME2,
2380
+ ATTR_GEN_AI_REQUEST_MODEL as ATTR_GEN_AI_REQUEST_MODEL2,
2381
+ ATTR_GEN_AI_RESPONSE_MODEL as ATTR_GEN_AI_RESPONSE_MODEL2,
2382
+ ATTR_GEN_AI_SYSTEM,
2383
+ ATTR_GEN_AI_TOOL_CALL_ID,
2384
+ ATTR_GEN_AI_TOOL_NAME as ATTR_GEN_AI_TOOL_NAME2,
2385
+ ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,
2386
+ ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,
2387
+ ATTR_GEN_AI_USAGE_INPUT_TOKENS,
2388
+ ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,
2389
+ ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS
2390
+ } from "@opentelemetry/semantic-conventions/incubating";
2391
+
2392
+ // src/version.ts
2393
+ var VERSION = "0.11.0";
2394
+
1945
2395
  // src/telemetry/semconv.ts
1946
2396
  var SCOPE_NAME = "@osfactory/otel-hook";
1947
2397
  var DEFAULT_INSTRUMENTATION_SCOPE = Object.freeze({
@@ -1951,7 +2401,7 @@ var DEFAULT_INSTRUMENTATION_SCOPE = Object.freeze({
1951
2401
  var ATTR_OTELHOOK_SPAN_PAIRED = "otelhook.span.paired";
1952
2402
  var ATTR_OTELHOOK_SPAN_PAIRING = "otelhook.span.pairing";
1953
2403
  var ATTR_OTELHOOK_SPAN_ORPHAN = "otelhook.span.orphan";
1954
- var ATTR_OTELHOOK_OUTCOME = "otelhook.outcome";
2404
+ var ATTR_OTELHOOK_OUTCOME2 = "otelhook.outcome";
1955
2405
  var ATTR_OTELHOOK_RESET_DETECTED = "otelhook.usage.reset_detected";
1956
2406
  var ATTR_OTELHOOK_USAGE_PARTIAL = "otelhook.usage.partial";
1957
2407
  var ATTR_OTELHOOK_TOOL_KIND = "otelhook.tool.kind";
@@ -1961,7 +2411,7 @@ var ATTR_OTELHOOK_AGENT_NAME = "otelhook.agent.name";
1961
2411
  var ATTR_OTELHOOK_AGENT_VERSION = "otelhook.agent.version";
1962
2412
  var ATTR_OTELHOOK_GENERATION_ID = "otelhook.generation.id";
1963
2413
  var FIELD_SEPARATOR = "\0";
1964
- var digestHex = (parts, length) => createHash("sha256").update(parts.join(FIELD_SEPARATOR)).digest("hex").slice(0, length);
2414
+ var digestHex = (parts, length) => createHash2("sha256").update(parts.join(FIELD_SEPARATOR)).digest("hex").slice(0, length);
1965
2415
  var MAX_RECOVERED_START_ATTRIBUTES = 16;
1966
2416
  var familyOf = (type) => {
1967
2417
  switch (type) {
@@ -2024,7 +2474,7 @@ var startOnlySpanAttributes = (event2) => {
2024
2474
  };
2025
2475
  case "generation.start":
2026
2476
  return {
2027
- [ATTR_GEN_AI_REQUEST_MODEL]: event2.model.modelId,
2477
+ [ATTR_GEN_AI_REQUEST_MODEL2]: event2.model.modelId,
2028
2478
  ...event2.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM]: event2.model.vendor }
2029
2479
  };
2030
2480
  // `toolName` and `toolCallId` are on both tool edges, so they are not
@@ -2202,7 +2652,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
2202
2652
  ...strongestTarget([pickTarget(resolved.recovered), start === void 0 ? {} : targetAttributes(start)]),
2203
2653
  ...start?.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName },
2204
2654
  ...start?.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion },
2205
- ...end === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.reason },
2655
+ ...end === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME2]: end.reason },
2206
2656
  ...usageAttributes(end?.usage, false)
2207
2657
  };
2208
2658
  if (end?.reason === "error" || end?.reason === "timeout") {
@@ -2218,14 +2668,14 @@ var buildLifecycleSpan = (plan, resource, scope) => {
2218
2668
  kind = SpanKind.CLIENT;
2219
2669
  attributes = {
2220
2670
  ...attributes,
2221
- [ATTR_GEN_AI_OPERATION_NAME]: "chat",
2671
+ [ATTR_GEN_AI_OPERATION_NAME2]: "chat",
2222
2672
  ...model?.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM]: model.vendor },
2223
- ...start?.model?.modelId === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL]: start.model.modelId },
2224
- ...end?.model?.modelId === void 0 ? {} : { [ATTR_GEN_AI_RESPONSE_MODEL]: end.model.modelId },
2673
+ ...start?.model?.modelId === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL2]: start.model.modelId },
2674
+ ...end?.model?.modelId === void 0 ? {} : { [ATTR_GEN_AI_RESPONSE_MODEL2]: end.model.modelId },
2225
2675
  // The provider's own id for this unit of work (Cursor generation,
2226
2676
  // Codex turn): the key a consumer stores a usage observation under.
2227
2677
  [ATTR_OTELHOOK_GENERATION_ID]: group.ref.scopeKey,
2228
- ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
2678
+ ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME2]: end.outcome },
2229
2679
  ...usageAttributes(end?.usage, false),
2230
2680
  ...end?.usage === void 0 || end.usagePartial === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_PARTIAL]: end.usagePartial }
2231
2681
  };
@@ -2241,10 +2691,10 @@ var buildLifecycleSpan = (plan, resource, scope) => {
2241
2691
  attributes = {
2242
2692
  // Target keys are re-chosen below as one unit, never mixed across edges.
2243
2693
  ...withoutTarget(attributes, resource),
2244
- [ATTR_GEN_AI_TOOL_NAME]: toolName,
2694
+ [ATTR_GEN_AI_TOOL_NAME2]: toolName,
2245
2695
  [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,
2246
2696
  ...start?.toolKind === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind },
2247
- ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
2697
+ ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME2]: end.outcome },
2248
2698
  ...strongestTarget([
2249
2699
  pickTarget(resolved.recovered),
2250
2700
  start === void 0 ? {} : targetAttributes(start),
@@ -2262,7 +2712,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
2262
2712
  attributes = {
2263
2713
  ...attributes,
2264
2714
  ...start?.delegationDepth === void 0 ? {} : { [ATTR_OTELHOOK_DELEGATION_DEPTH]: start.delegationDepth },
2265
- ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
2715
+ ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME2]: end.outcome },
2266
2716
  ...usageAttributes(end?.usage, false)
2267
2717
  };
2268
2718
  status = outcomeStatus(end?.outcome);
@@ -2270,7 +2720,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
2270
2720
  }
2271
2721
  }
2272
2722
  if (status.code === SpanStatusCode.ERROR) {
2273
- attributes = { ...attributes, [ATTR_ERROR_TYPE]: status.message ?? "error" };
2723
+ attributes = { ...attributes, [ATTR_ERROR_TYPE2]: status.message ?? "error" };
2274
2724
  }
2275
2725
  return toReadableSpan({
2276
2726
  name,
@@ -2320,7 +2770,7 @@ var buildStandaloneSpan = (event2, resource, scope) => {
2320
2770
  status = { code: SpanStatusCode.ERROR, message: event2.errorCode };
2321
2771
  attributes = {
2322
2772
  ...attributes,
2323
- [ATTR_ERROR_TYPE]: event2.errorCode,
2773
+ [ATTR_ERROR_TYPE2]: event2.errorCode,
2324
2774
  "otelhook.error.phase": event2.phase,
2325
2775
  "otelhook.error.retryable": event2.retryable
2326
2776
  };
@@ -2979,7 +3429,7 @@ var createUsageAccumulator = (deps) => {
2979
3429
  };
2980
3430
 
2981
3431
  // src/privacy/service.ts
2982
- import { createHash as createHash2 } from "crypto";
3432
+ import { createHash as createHash3 } from "crypto";
2983
3433
  var compilePatterns = (sources, flags) => {
2984
3434
  const compiled = [];
2985
3435
  for (const source of sources) {
@@ -3056,7 +3506,7 @@ var createPrivacyService = (policyInput) => {
3056
3506
  const limits = policy.limits;
3057
3507
  const secretKeyPatterns = compilePatterns(policy.secretKeyPatterns, "i");
3058
3508
  const secretValuePatterns = compilePatterns(policy.secretValuePatterns, "g");
3059
- const hash = (value) => `sha256:${createHash2("sha256").update(policy.hashSalt).update("\0").update(value, "utf8").digest("hex")}`;
3509
+ const hash = (value) => `sha256:${createHash3("sha256").update(policy.hashSalt).update("\0").update(value, "utf8").digest("hex")}`;
3060
3510
  const isSecretKey = (key) => secretKeyPatterns.some((pattern) => pattern.test(key));
3061
3511
  const boundString = (value) => {
3062
3512
  const length = codePointLength(value);
@@ -3322,7 +3772,7 @@ var createPrivacyService = (policyInput) => {
3322
3772
  };
3323
3773
 
3324
3774
  // src/providers/claude/transcript.ts
3325
- import { createHash as createHash3 } from "crypto";
3775
+ import { createHash as createHash4 } from "crypto";
3326
3776
  import { open, stat } from "fs/promises";
3327
3777
  import path from "path";
3328
3778
 
@@ -3995,7 +4445,7 @@ var hasUsage = (record) => record.usage !== void 0 || record.token_usage !== voi
3995
4445
  var eventNameOf = (record) => record.hook_event_name ?? record.hookEventName;
3996
4446
  var transcriptPathOf = (record) => record.transcript_path ?? record.transcriptPath;
3997
4447
  var CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
3998
- var sourceDigest = (transcriptPath) => createHash3("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
4448
+ var sourceDigest = (transcriptPath) => createHash4("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
3999
4449
  var createClaudeTranscriptUsageEnricher = (options = {}) => {
4000
4450
  const fileSize = async (transcriptPath) => {
4001
4451
  try {
@@ -4233,9 +4683,9 @@ var resolveDeliveryIdentity = (input) => {
4233
4683
  };
4234
4684
 
4235
4685
  // src/runtime/ids.ts
4236
- import { createHash as createHash4, randomUUID } from "crypto";
4237
- var digest = (namespace, parts) => {
4238
- const hash = createHash4("sha256");
4686
+ import { createHash as createHash5, randomUUID } from "crypto";
4687
+ var digest2 = (namespace, parts) => {
4688
+ const hash = createHash5("sha256");
4239
4689
  hash.update(namespace);
4240
4690
  for (const part of parts) {
4241
4691
  hash.update("\0");
@@ -4250,7 +4700,7 @@ var createDeterministicIdGenerator = (options = {}) => {
4250
4700
  return {
4251
4701
  newInvocationId: (seed) => invocationIdSchema.parse(
4252
4702
  `inv_${truncate(
4253
- digest(`${namespace}/invocation`, [
4703
+ digest2(`${namespace}/invocation`, [
4254
4704
  seed.providerId,
4255
4705
  seed.sessionId,
4256
4706
  seed.sourceEventName,
@@ -4261,7 +4711,7 @@ var createDeterministicIdGenerator = (options = {}) => {
4261
4711
  ),
4262
4712
  newEventId: (seed) => eventIdSchema.parse(
4263
4713
  `evt_${truncate(
4264
- digest(`${namespace}/event`, [
4714
+ digest2(`${namespace}/event`, [
4265
4715
  seed.invocationId,
4266
4716
  seed.sequence,
4267
4717
  seed.eventType,
@@ -4269,7 +4719,7 @@ var createDeterministicIdGenerator = (options = {}) => {
4269
4719
  ])
4270
4720
  )}`
4271
4721
  ),
4272
- newOpaqueId: (parts) => truncate(digest(`${namespace}/opaque`, parts))
4722
+ newOpaqueId: (parts) => truncate(digest2(`${namespace}/opaque`, parts))
4273
4723
  };
4274
4724
  };
4275
4725
 
@@ -4314,6 +4764,29 @@ var stateValueSchema = z17.discriminatedUnion("kind", [
4314
4764
  * (Claude Code's transcript), so the next read starts where the last ended.
4315
4765
  * `source` is an opaque digest of what was read, never a path.
4316
4766
  */
4767
+ /**
4768
+ * Running state of one metric series (issue #69), so a cumulative data point
4769
+ * exported by a later hook process continues the same total. Holds numbers and
4770
+ * a series digest only; the series' attributes are re-supplied by the caller
4771
+ * and never read back from disk.
4772
+ */
4773
+ z17.strictObject({
4774
+ kind: z17.literal("metric-series"),
4775
+ /** Start of the cumulative interval. */
4776
+ startTimeMillis: epochMillisSchema,
4777
+ /** Counters: the running total. */
4778
+ value: z17.number().finite().min(0).optional(),
4779
+ /** Histograms: the running aggregation. */
4780
+ histogram: z17.strictObject({
4781
+ count: z17.number().int().min(0),
4782
+ sum: z17.number().finite().min(0),
4783
+ min: z17.number().finite(),
4784
+ max: z17.number().finite(),
4785
+ bucketCounts: z17.array(z17.number().int().min(0)).max(64)
4786
+ }).optional(),
4787
+ /** Opaque digest of the last delivery folded in; makes a replay a no-op. */
4788
+ appliedDelivery: z17.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional()
4789
+ }),
4317
4790
  z17.strictObject({
4318
4791
  kind: z17.literal("read-cursor"),
4319
4792
  source: z17.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
@@ -5487,20 +5960,20 @@ import { mkdir, open as open3, readFile, readdir, rename, unlink, writeFile } fr
5487
5960
  import * as path4 from "path";
5488
5961
 
5489
5962
  // src/state/keys.ts
5490
- import { createHash as createHash5 } from "crypto";
5963
+ import { createHash as createHash6 } from "crypto";
5491
5964
  var SAFE_SEGMENT_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
5492
5965
  var isSafeSegment = (segment) => SAFE_SEGMENT_PATTERN.test(segment);
5493
5966
  var sanitizeSegment = (segment) => {
5494
5967
  if (isSafeSegment(segment)) {
5495
5968
  return segment;
5496
5969
  }
5497
- return `h_${createHash5("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
5970
+ return `h_${createHash6("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
5498
5971
  };
5499
5972
  var namespaceSegments = (namespace) => [
5500
5973
  sanitizeSegment(namespace.providerId),
5501
5974
  sanitizeSegment(namespace.installationId)
5502
5975
  ];
5503
- var keyDigest = (key) => createHash5("sha256").update(key, "utf8").digest("hex");
5976
+ var keyDigest = (key) => createHash6("sha256").update(key, "utf8").digest("hex");
5504
5977
 
5505
5978
  // src/state/filesystem-store.ts
5506
5979
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
@@ -5768,6 +6241,40 @@ var createFilesystemStateStore = (options) => {
5768
6241
  };
5769
6242
  };
5770
6243
 
6244
+ // src/config/otlp-endpoint.ts
6245
+ var OTLP_ENDPOINT_VARIABLES = Object.freeze({
6246
+ generic: "OTEL_EXPORTER_OTLP_ENDPOINT",
6247
+ traces: "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
6248
+ logs: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
6249
+ metrics: "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"
6250
+ });
6251
+ var OTLP_TRACES_PATH = "/v1/traces";
6252
+ var OTLP_LOGS_PATH = "/v1/logs";
6253
+ var OTLP_METRICS_PATH = "/v1/metrics";
6254
+ var SIGNAL_PATHS = Object.freeze({
6255
+ traces: OTLP_TRACES_PATH,
6256
+ logs: OTLP_LOGS_PATH,
6257
+ metrics: OTLP_METRICS_PATH
6258
+ });
6259
+ var withoutTrailingSlashes = (value) => {
6260
+ let end = value.length;
6261
+ while (end > 0 && value.charCodeAt(end - 1) === 47) {
6262
+ end -= 1;
6263
+ }
6264
+ return value.slice(0, end);
6265
+ };
6266
+ var siblingSignalEndpoint = (tracesEndpoint, signal) => {
6267
+ const trimmed = withoutTrailingSlashes(tracesEndpoint);
6268
+ const target = SIGNAL_PATHS[signal];
6269
+ if (trimmed.endsWith(target)) {
6270
+ return trimmed;
6271
+ }
6272
+ if (trimmed.endsWith(OTLP_TRACES_PATH)) {
6273
+ return `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${target}`;
6274
+ }
6275
+ return `${trimmed}${target}`;
6276
+ };
6277
+
5771
6278
  // src/telemetry/spool-queue.ts
5772
6279
  import { randomBytes as randomBytes3 } from "crypto";
5773
6280
  import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, rename as rename2, stat as stat3, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
@@ -6168,20 +6675,99 @@ var createFileDurableLogSpool = (options) => createSpoolQueue({
6168
6675
  validate: validateLogSpoolBatch
6169
6676
  });
6170
6677
 
6171
- // src/telemetry/durable-spool.ts
6172
- var MAX_SPOOLED_SPANS_PER_BATCH = 4096;
6173
- var MAX_SPOOLED_STRING_LENGTH = 8192;
6174
- var MAX_SPOOLED_ATTRIBUTES_PER_SPAN = 256;
6175
- var TRACE_ID_PATTERN2 = /^[0-9a-f]{32}$/;
6176
- var SPAN_ID_PATTERN2 = /^[0-9a-f]{16}$/;
6177
- var isFiniteNonNegative2 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
6178
- var isBoundedString2 = (value, maxLength = MAX_SPOOLED_STRING_LENGTH) => typeof value === "string" && value.length > 0 && value.length <= maxLength;
6678
+ // src/telemetry/durable-metric-spool.ts
6679
+ var MAX_SPOOLED_METRIC_POINTS_PER_BATCH = 4096;
6680
+ var MAX_STRING_LENGTH = 8192;
6681
+ var MAX_ATTRIBUTES_PER_POINT = 64;
6682
+ var MAX_BUCKETS = 64;
6179
6683
  var isPlainObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6180
- var isReplayableSpan = (value) => {
6684
+ var isFiniteNonNegative2 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
6685
+ var isBoundedString2 = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_STRING_LENGTH;
6686
+ var isPrimitiveAttribute2 = (value) => typeof value === "string" && value.length <= MAX_STRING_LENGTH || typeof value === "number" && Number.isFinite(value) || typeof value === "boolean";
6687
+ var isReplayablePoint = (value) => {
6688
+ if (!isPlainObject2(value) || !isMetricInstrumentName(value.instrument)) {
6689
+ return false;
6690
+ }
6691
+ if (value.temporality !== "cumulative" && value.temporality !== "delta") {
6692
+ return false;
6693
+ }
6694
+ if (!isFiniteNonNegative2(value.startTimeMillis) || !isFiniteNonNegative2(value.timeMillis)) {
6695
+ return false;
6696
+ }
6697
+ if (!isPlainObject2(value.attributes)) {
6698
+ return false;
6699
+ }
6700
+ const entries = Object.entries(value.attributes);
6701
+ if (entries.length > MAX_ATTRIBUTES_PER_POINT || !entries.every(([, item]) => isPrimitiveAttribute2(item))) {
6702
+ return false;
6703
+ }
6704
+ const instrument = METRIC_INSTRUMENTS[value.instrument];
6705
+ if (instrument.kind === "counter") {
6706
+ return isFiniteNonNegative2(value.value) && value.histogram === void 0;
6707
+ }
6708
+ const histogram = value.histogram;
6709
+ if (!isPlainObject2(histogram) || value.value !== void 0) {
6710
+ return false;
6711
+ }
6712
+ const buckets = histogram.bucketCounts;
6713
+ return isFiniteNonNegative2(histogram.count) && Number.isInteger(histogram.count) && isFiniteNonNegative2(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) => isFiniteNonNegative2(count) && Number.isInteger(count));
6714
+ };
6715
+ var validateMetricSpoolBatch = (value, identity) => {
6181
6716
  if (!isPlainObject2(value)) {
6717
+ return { rejection: "not-an-object" };
6718
+ }
6719
+ if (value.providerId !== identity.providerId || value.installationId !== identity.installationId) {
6720
+ return { rejection: "identity-mismatch" };
6721
+ }
6722
+ if (!isPlainObject2(value.resourceAttributes)) {
6723
+ return { rejection: "resource-attributes-invalid" };
6724
+ }
6725
+ if (!isPlainObject2(value.instrumentationScope) || !isBoundedString2(value.instrumentationScope.name)) {
6726
+ return { rejection: "instrumentation-scope-invalid" };
6727
+ }
6728
+ if (value.instrumentationScope.version !== void 0 && typeof value.instrumentationScope.version !== "string") {
6729
+ return { rejection: "instrumentation-scope-invalid" };
6730
+ }
6731
+ if (!Array.isArray(value.points) || value.points.length === 0 || value.points.length > MAX_SPOOLED_METRIC_POINTS_PER_BATCH) {
6732
+ return { rejection: "points-invalid" };
6733
+ }
6734
+ if (!value.points.every(isReplayablePoint)) {
6735
+ return { rejection: "point-field-invalid" };
6736
+ }
6737
+ if (!isFiniteNonNegative2(value.enqueuedAt)) {
6738
+ return { rejection: "not-an-object" };
6739
+ }
6740
+ return { batch: value };
6741
+ };
6742
+ var DEFAULT_MAX_METRIC_SPOOL_FILES = 500;
6743
+ var createFileDurableMetricSpool = (options) => createSpoolQueue({
6744
+ rootDir: options.rootDir,
6745
+ providerId: options.providerId,
6746
+ installationId: options.installationId,
6747
+ clock: options.clock,
6748
+ ...options.logger === void 0 ? {} : { logger: options.logger },
6749
+ maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_METRIC_SPOOL_FILES,
6750
+ queueName: options.queueName ?? "spool-metrics",
6751
+ ...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
6752
+ ...options.maxAgeMillis === void 0 ? {} : { maxAgeMillis: options.maxAgeMillis },
6753
+ ...options.overflow === void 0 ? {} : { overflow: options.overflow },
6754
+ validate: validateMetricSpoolBatch
6755
+ });
6756
+
6757
+ // src/telemetry/durable-spool.ts
6758
+ var MAX_SPOOLED_SPANS_PER_BATCH = 4096;
6759
+ var MAX_SPOOLED_STRING_LENGTH = 8192;
6760
+ var MAX_SPOOLED_ATTRIBUTES_PER_SPAN = 256;
6761
+ var TRACE_ID_PATTERN2 = /^[0-9a-f]{32}$/;
6762
+ var SPAN_ID_PATTERN2 = /^[0-9a-f]{16}$/;
6763
+ var isFiniteNonNegative3 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
6764
+ var isBoundedString3 = (value, maxLength = MAX_SPOOLED_STRING_LENGTH) => typeof value === "string" && value.length > 0 && value.length <= maxLength;
6765
+ var isPlainObject3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6766
+ var isReplayableSpan = (value) => {
6767
+ if (!isPlainObject3(value)) {
6182
6768
  return false;
6183
6769
  }
6184
- if (!isBoundedString2(value.name) || !isFiniteNonNegative2(value.kind)) {
6770
+ if (!isBoundedString3(value.name) || !isFiniteNonNegative3(value.kind)) {
6185
6771
  return false;
6186
6772
  }
6187
6773
  if (typeof value.traceId !== "string" || !TRACE_ID_PATTERN2.test(value.traceId)) {
@@ -6193,16 +6779,16 @@ var isReplayableSpan = (value) => {
6193
6779
  if (value.parentSpanId !== void 0 && (typeof value.parentSpanId !== "string" || !SPAN_ID_PATTERN2.test(value.parentSpanId))) {
6194
6780
  return false;
6195
6781
  }
6196
- if (!isFiniteNonNegative2(value.startMillis) || !isFiniteNonNegative2(value.endMillis)) {
6782
+ if (!isFiniteNonNegative3(value.startMillis) || !isFiniteNonNegative3(value.endMillis)) {
6197
6783
  return false;
6198
6784
  }
6199
- if (!isFiniteNonNegative2(value.statusCode)) {
6785
+ if (!isFiniteNonNegative3(value.statusCode)) {
6200
6786
  return false;
6201
6787
  }
6202
6788
  if (value.statusMessage !== void 0 && typeof value.statusMessage !== "string") {
6203
6789
  return false;
6204
6790
  }
6205
- if (!isPlainObject2(value.attributes)) {
6791
+ if (!isPlainObject3(value.attributes)) {
6206
6792
  return false;
6207
6793
  }
6208
6794
  const entries = Object.entries(value.attributes);
@@ -6219,16 +6805,16 @@ var isReplayableSpan = (value) => {
6219
6805
  });
6220
6806
  };
6221
6807
  var validateSpoolBatch = (value, identity) => {
6222
- if (!isPlainObject2(value)) {
6808
+ if (!isPlainObject3(value)) {
6223
6809
  return { rejection: "not-an-object" };
6224
6810
  }
6225
6811
  if (value.providerId !== identity.providerId || value.installationId !== identity.installationId) {
6226
6812
  return { rejection: "identity-mismatch" };
6227
6813
  }
6228
- if (!isPlainObject2(value.resourceAttributes)) {
6814
+ if (!isPlainObject3(value.resourceAttributes)) {
6229
6815
  return { rejection: "resource-attributes-invalid" };
6230
6816
  }
6231
- if (!isPlainObject2(value.instrumentationScope) || !isBoundedString2(value.instrumentationScope.name)) {
6817
+ if (!isPlainObject3(value.instrumentationScope) || !isBoundedString3(value.instrumentationScope.name)) {
6232
6818
  return { rejection: "instrumentation-scope-invalid" };
6233
6819
  }
6234
6820
  if (value.instrumentationScope.version !== void 0 && typeof value.instrumentationScope.version !== "string") {
@@ -6243,7 +6829,7 @@ var validateSpoolBatch = (value, identity) => {
6243
6829
  if (!value.spans.every(isReplayableSpan)) {
6244
6830
  return { rejection: "span-field-invalid" };
6245
6831
  }
6246
- if (!isFiniteNonNegative2(value.enqueuedAt)) {
6832
+ if (!isFiniteNonNegative3(value.enqueuedAt)) {
6247
6833
  return { rejection: "not-an-object" };
6248
6834
  }
6249
6835
  return { batch: value };
@@ -6269,22 +6855,6 @@ import { ExportResultCode } from "@opentelemetry/core";
6269
6855
  import { millisToHrTime as millisToHrTime3 } from "@opentelemetry/core";
6270
6856
  import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
6271
6857
 
6272
- // src/config/otlp-endpoint.ts
6273
- var OTLP_ENDPOINT_VARIABLES = Object.freeze({
6274
- generic: "OTEL_EXPORTER_OTLP_ENDPOINT",
6275
- traces: "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
6276
- logs: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT"
6277
- });
6278
- var OTLP_TRACES_PATH = "/v1/traces";
6279
- var OTLP_LOGS_PATH = "/v1/logs";
6280
- var withoutTrailingSlashes = (value) => {
6281
- let end = value.length;
6282
- while (end > 0 && value.charCodeAt(end - 1) === 47) {
6283
- end -= 1;
6284
- }
6285
- return value.slice(0, end);
6286
- };
6287
-
6288
6858
  // src/telemetry/export-failure.ts
6289
6859
  var RETRYABLE_HTTP_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
6290
6860
  var isPermanentExportFailure = (result) => {
@@ -6331,13 +6901,13 @@ var replayResource = (attributes, policy) => {
6331
6901
  import { SeverityNumber, TraceFlags as TraceFlags2 } from "@opentelemetry/api";
6332
6902
  import { millisToHrTime as millisToHrTime2 } from "@opentelemetry/core";
6333
6903
  import {
6334
- ATTR_ERROR_TYPE as ATTR_ERROR_TYPE2,
6335
- ATTR_GEN_AI_OPERATION_NAME as ATTR_GEN_AI_OPERATION_NAME2,
6336
- ATTR_GEN_AI_REQUEST_MODEL as ATTR_GEN_AI_REQUEST_MODEL2,
6337
- ATTR_GEN_AI_RESPONSE_MODEL as ATTR_GEN_AI_RESPONSE_MODEL2,
6904
+ ATTR_ERROR_TYPE as ATTR_ERROR_TYPE3,
6905
+ ATTR_GEN_AI_OPERATION_NAME as ATTR_GEN_AI_OPERATION_NAME3,
6906
+ ATTR_GEN_AI_REQUEST_MODEL as ATTR_GEN_AI_REQUEST_MODEL3,
6907
+ ATTR_GEN_AI_RESPONSE_MODEL as ATTR_GEN_AI_RESPONSE_MODEL3,
6338
6908
  ATTR_GEN_AI_SYSTEM as ATTR_GEN_AI_SYSTEM2,
6339
6909
  ATTR_GEN_AI_TOOL_CALL_ID as ATTR_GEN_AI_TOOL_CALL_ID2,
6340
- ATTR_GEN_AI_TOOL_NAME as ATTR_GEN_AI_TOOL_NAME2,
6910
+ ATTR_GEN_AI_TOOL_NAME as ATTR_GEN_AI_TOOL_NAME3,
6341
6911
  ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS as ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS2,
6342
6912
  ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS as ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS2,
6343
6913
  ATTR_GEN_AI_USAGE_INPUT_TOKENS as ATTR_GEN_AI_USAGE_INPUT_TOKENS2,
@@ -6353,14 +6923,14 @@ var ATTR_OTELHOOK_EVENT_ID = "otelhook.event.id";
6353
6923
  var ATTR_OTELHOOK_EVENT_SEQUENCE = "otelhook.event.sequence";
6354
6924
  var ATTR_OTELHOOK_LOG_SIGNAL = "otelhook.log.signal";
6355
6925
  var ATTR_OTELHOOK_LOG_MAPPING_VERSION = "otelhook.log.mapping_version";
6356
- var ATTR_OTELHOOK_OUTCOME2 = "otelhook.outcome";
6926
+ var ATTR_OTELHOOK_OUTCOME3 = "otelhook.outcome";
6357
6927
  var ATTR_OTELHOOK_TOOL_KIND2 = "otelhook.tool.kind";
6358
6928
  var ATTR_OTELHOOK_TOOL_PERMISSION = "otelhook.tool.permission_decision";
6359
6929
  var ATTR_OTELHOOK_DELEGATION_DEPTH2 = "otelhook.delegation_depth";
6360
6930
  var ATTR_OTELHOOK_SUBAGENT_TYPE = "otelhook.subagent.type";
6361
6931
  var ATTR_OTELHOOK_AGENT_NAME2 = "otelhook.agent.name";
6362
6932
  var ATTR_OTELHOOK_AGENT_VERSION2 = "otelhook.agent.version";
6363
- var ATTR_OTELHOOK_SESSION_KIND = "otelhook.session.kind";
6933
+ var ATTR_OTELHOOK_SESSION_KIND2 = "otelhook.session.kind";
6364
6934
  var ATTR_OTELHOOK_PROMPT_SOURCE = "otelhook.prompt.source";
6365
6935
  var ATTR_OTELHOOK_PROMPT_TURN_INDEX = "otelhook.prompt.turn_index";
6366
6936
  var ATTR_OTELHOOK_GENERATION_ID2 = "otelhook.generation.id";
@@ -6464,15 +7034,15 @@ var eventAttributes = (event2) => {
6464
7034
  switch (event2.type) {
6465
7035
  case "session.start":
6466
7036
  return {
6467
- [ATTR_OTELHOOK_SESSION_KIND]: event2.sessionKind,
7037
+ [ATTR_OTELHOOK_SESSION_KIND2]: event2.sessionKind,
6468
7038
  ...event2.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME2]: event2.agentName },
6469
7039
  ...event2.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION2]: event2.agentVersion },
6470
- ...event2.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL2]: event2.model.modelId },
7040
+ ...event2.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL3]: event2.model.modelId },
6471
7041
  ...targetAttributes(event2)
6472
7042
  };
6473
7043
  case "session.end":
6474
7044
  return {
6475
- [ATTR_OTELHOOK_OUTCOME2]: event2.reason,
7045
+ [ATTR_OTELHOOK_OUTCOME3]: event2.reason,
6476
7046
  ...usageAttributes2(event2.usage)
6477
7047
  };
6478
7048
  case "prompt.submitted":
@@ -6483,25 +7053,25 @@ var eventAttributes = (event2) => {
6483
7053
  };
6484
7054
  case "generation.start":
6485
7055
  return {
6486
- [ATTR_GEN_AI_OPERATION_NAME2]: "chat",
7056
+ [ATTR_GEN_AI_OPERATION_NAME3]: "chat",
6487
7057
  [ATTR_OTELHOOK_GENERATION_ID2]: event2.generationId,
6488
- [ATTR_GEN_AI_REQUEST_MODEL2]: event2.model.modelId,
7058
+ [ATTR_GEN_AI_REQUEST_MODEL3]: event2.model.modelId,
6489
7059
  ...event2.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event2.model.vendor }
6490
7060
  };
6491
7061
  case "generation.end":
6492
7062
  return {
6493
- [ATTR_GEN_AI_OPERATION_NAME2]: "chat",
7063
+ [ATTR_GEN_AI_OPERATION_NAME3]: "chat",
6494
7064
  [ATTR_OTELHOOK_GENERATION_ID2]: event2.generationId,
6495
- [ATTR_GEN_AI_RESPONSE_MODEL2]: event2.model.modelId,
7065
+ [ATTR_GEN_AI_RESPONSE_MODEL3]: event2.model.modelId,
6496
7066
  ...event2.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event2.model.vendor },
6497
- [ATTR_OTELHOOK_OUTCOME2]: event2.outcome,
7067
+ [ATTR_OTELHOOK_OUTCOME3]: event2.outcome,
6498
7068
  ...event2.stopReason === void 0 ? {} : { [ATTR_OTELHOOK_STOP_REASON]: event2.stopReason },
6499
7069
  ...usageAttributes2(event2.usage),
6500
7070
  ...event2.usage === void 0 || event2.usagePartial === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_PARTIAL]: event2.usagePartial }
6501
7071
  };
6502
7072
  case "tool.start":
6503
7073
  return {
6504
- [ATTR_GEN_AI_TOOL_NAME2]: event2.toolName,
7074
+ [ATTR_GEN_AI_TOOL_NAME3]: event2.toolName,
6505
7075
  [ATTR_GEN_AI_TOOL_CALL_ID2]: event2.toolCallId,
6506
7076
  [ATTR_OTELHOOK_TOOL_KIND2]: event2.toolKind,
6507
7077
  ...event2.generationId === void 0 ? {} : { [ATTR_OTELHOOK_GENERATION_ID2]: event2.generationId },
@@ -6509,9 +7079,9 @@ var eventAttributes = (event2) => {
6509
7079
  };
6510
7080
  case "tool.end":
6511
7081
  return {
6512
- [ATTR_GEN_AI_TOOL_NAME2]: event2.toolName,
7082
+ [ATTR_GEN_AI_TOOL_NAME3]: event2.toolName,
6513
7083
  [ATTR_GEN_AI_TOOL_CALL_ID2]: event2.toolCallId,
6514
- [ATTR_OTELHOOK_OUTCOME2]: event2.outcome,
7084
+ [ATTR_OTELHOOK_OUTCOME3]: event2.outcome,
6515
7085
  ...event2.permissionDecision === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_PERMISSION]: event2.permissionDecision },
6516
7086
  ...targetAttributes(event2)
6517
7087
  };
@@ -6519,11 +7089,11 @@ var eventAttributes = (event2) => {
6519
7089
  return {
6520
7090
  [ATTR_OTELHOOK_DELEGATION_DEPTH2]: event2.delegationDepth,
6521
7091
  ...event2.subagentType === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_TYPE]: event2.subagentType },
6522
- ...event2.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL2]: event2.model.modelId }
7092
+ ...event2.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL3]: event2.model.modelId }
6523
7093
  };
6524
7094
  case "subagent.end":
6525
7095
  return {
6526
- [ATTR_OTELHOOK_OUTCOME2]: event2.outcome,
7096
+ [ATTR_OTELHOOK_OUTCOME3]: event2.outcome,
6527
7097
  ...usageAttributes2(event2.usage)
6528
7098
  };
6529
7099
  case "compaction.performed":
@@ -6536,7 +7106,7 @@ var eventAttributes = (event2) => {
6536
7106
  };
6537
7107
  case "error.raised":
6538
7108
  return {
6539
- [ATTR_ERROR_TYPE2]: event2.errorCode,
7109
+ [ATTR_ERROR_TYPE3]: event2.errorCode,
6540
7110
  [ATTR_OTELHOOK_ERROR_PHASE]: event2.phase,
6541
7111
  [ATTR_OTELHOOK_ERROR_RETRYABLE]: event2.retryable,
6542
7112
  [ATTR_OTELHOOK_ERROR_SEVERITY]: event2.severity
@@ -6983,8 +7553,273 @@ var createOtlpLogSink = (options) => {
6983
7553
  };
6984
7554
  };
6985
7555
 
7556
+ // src/telemetry/otlp-metric-sink.ts
7557
+ import { ValueType } from "@opentelemetry/api";
7558
+ import { ExportResultCode as ExportResultCode2, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
7559
+ import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
7560
+ import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
7561
+ import {
7562
+ AggregationTemporality,
7563
+ DataPointType
7564
+ } from "@opentelemetry/sdk-metrics";
7565
+ var resolveMetricsEndpoint = (exporter) => {
7566
+ const stated = exporter.metrics?.endpoint;
7567
+ if (stated !== void 0) {
7568
+ return { endpoint: stated, derived: false };
7569
+ }
7570
+ if (exporter.endpoint === void 0) {
7571
+ return { unresolvable: "no-endpoint" };
7572
+ }
7573
+ return { endpoint: siblingSignalEndpoint(exporter.endpoint, "metrics"), derived: true };
7574
+ };
7575
+ var describeMetricsDeliverability = (exporter) => {
7576
+ if (exporter.metrics?.enabled !== true) {
7577
+ return { status: "disabled", reason: "metrics-disabled" };
7578
+ }
7579
+ if (!exporter.enabled) {
7580
+ return { status: "disabled", reason: "exporter-disabled" };
7581
+ }
7582
+ if (exporter.protocol === "none") {
7583
+ return { status: "disabled", reason: "protocol-none" };
7584
+ }
7585
+ if (exporter.protocol !== "http/protobuf") {
7586
+ return { status: "disabled", reason: "protocol-unsupported" };
7587
+ }
7588
+ const resolved = resolveMetricsEndpoint(exporter);
7589
+ if ("unresolvable" in resolved) {
7590
+ return { status: "disabled", reason: "no-endpoint" };
7591
+ }
7592
+ return { status: "configured", endpoint: resolved.endpoint, derivedEndpoint: resolved.derived };
7593
+ };
7594
+ var DISABLED_DETAIL2 = Object.freeze({
7595
+ "exporter-disabled": "otlp metric sink disabled: the exporter is disabled",
7596
+ "protocol-none": "otlp metric sink disabled: protocol is none",
7597
+ "protocol-unsupported": "otlp metric sink disabled: protocol not supported by this build",
7598
+ "no-endpoint": "otlp metric sink disabled: no metrics endpoint configured and none could be derived"
7599
+ });
7600
+ var createDisabledMetricSink = (destination) => {
7601
+ const health = createHealthTracker(
7602
+ "telemetry-metric-sink",
7603
+ destination === void 0 ? {} : { destination }
7604
+ );
7605
+ return {
7606
+ enabled: false,
7607
+ exportPoints: () => Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),
7608
+ flush: () => Promise.resolve(),
7609
+ shutdown: () => Promise.resolve(),
7610
+ health: () => health.snapshot(),
7611
+ drainSpool: () => Promise.resolve({ drained: 0, remaining: 0, failed: 0 })
7612
+ };
7613
+ };
7614
+ var createDisabledOtlpMetricSink = createDisabledMetricSink;
7615
+ var toMetricData = (points) => {
7616
+ const byInstrument = /* @__PURE__ */ new Map();
7617
+ for (const point of points) {
7618
+ const key = `${point.instrument}|${point.temporality}`;
7619
+ const group = byInstrument.get(key) ?? [];
7620
+ group.push(point);
7621
+ byInstrument.set(key, group);
7622
+ }
7623
+ const metrics = [];
7624
+ for (const group of byInstrument.values()) {
7625
+ const first = group[0];
7626
+ if (first === void 0) {
7627
+ continue;
7628
+ }
7629
+ const instrument = METRIC_INSTRUMENTS[first.instrument];
7630
+ const descriptor = {
7631
+ name: instrument.name,
7632
+ description: instrument.description,
7633
+ unit: instrument.unit,
7634
+ valueType: instrument.valueType === "int" ? ValueType.INT : ValueType.DOUBLE
7635
+ };
7636
+ const aggregationTemporality = first.temporality === "cumulative" ? AggregationTemporality.CUMULATIVE : AggregationTemporality.DELTA;
7637
+ const times = (point) => ({
7638
+ startTime: millisToHrTime4(point.startTimeMillis),
7639
+ endTime: millisToHrTime4(point.timeMillis)
7640
+ });
7641
+ if (instrument.kind === "counter") {
7642
+ metrics.push({
7643
+ descriptor,
7644
+ aggregationTemporality,
7645
+ dataPointType: DataPointType.SUM,
7646
+ isMonotonic: true,
7647
+ dataPoints: group.map((point) => ({
7648
+ ...times(point),
7649
+ attributes: { ...point.attributes },
7650
+ value: point.value ?? 0
7651
+ }))
7652
+ });
7653
+ continue;
7654
+ }
7655
+ metrics.push({
7656
+ descriptor,
7657
+ aggregationTemporality,
7658
+ dataPointType: DataPointType.HISTOGRAM,
7659
+ dataPoints: group.map((point) => {
7660
+ const histogram = point.histogram;
7661
+ return {
7662
+ ...times(point),
7663
+ attributes: { ...point.attributes },
7664
+ value: {
7665
+ buckets: {
7666
+ boundaries: [...instrument.boundaries ?? []],
7667
+ counts: [...histogram?.bucketCounts ?? []]
7668
+ },
7669
+ count: histogram?.count ?? 0,
7670
+ sum: histogram?.sum ?? 0,
7671
+ ...histogram === void 0 || histogram.count === 0 ? {} : { min: histogram.min, max: histogram.max }
7672
+ }
7673
+ };
7674
+ })
7675
+ });
7676
+ }
7677
+ return metrics;
7678
+ };
7679
+ var createOtlpMetricSink = (options) => {
7680
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
7681
+ const deliverability = describeMetricsDeliverability(options.exporter);
7682
+ if (deliverability.status === "disabled") {
7683
+ if (deliverability.reason !== "metrics-disabled") {
7684
+ options.logger?.warn(DISABLED_DETAIL2[deliverability.reason], {
7685
+ "exporter.protocol": options.exporter.protocol,
7686
+ ...destinationFields
7687
+ });
7688
+ }
7689
+ return createDisabledMetricSink(options.destination);
7690
+ }
7691
+ const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
7692
+ const resource = resourceFromAttributes2(
7693
+ withoutAccountIdentity(resourceFromExporterPolicy(options.exporter).attributes)
7694
+ );
7695
+ const health = createHealthTracker(
7696
+ "telemetry-metric-sink",
7697
+ options.destination === void 0 ? {} : { destination: options.destination }
7698
+ );
7699
+ const exporter = new OTLPMetricExporter({
7700
+ url: deliverability.endpoint,
7701
+ headers: { ...options.headers },
7702
+ timeoutMillis: options.exporter.timeoutMillis
7703
+ });
7704
+ let shutdownCompleted = false;
7705
+ const exportResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve3) => {
7706
+ const payload = {
7707
+ resource: batchResource,
7708
+ scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }]
7709
+ };
7710
+ try {
7711
+ exporter.export(payload, (result) => resolve3(result));
7712
+ } catch (thrown) {
7713
+ resolve3({
7714
+ code: ExportResultCode2.FAILED,
7715
+ error: thrown instanceof Error ? thrown : new Error("export threw")
7716
+ });
7717
+ }
7718
+ });
7719
+ const toSpoolBatch = (points) => ({
7720
+ providerId: options.providerId,
7721
+ installationId: options.installationId,
7722
+ resourceAttributes: { ...resource.attributes },
7723
+ instrumentationScope: {
7724
+ name: scope.name,
7725
+ ...scope.version === void 0 ? {} : { version: scope.version }
7726
+ },
7727
+ points: points.map((point) => ({ ...point })),
7728
+ enqueuedAt: options.clock.now()
7729
+ });
7730
+ const sendSerializedBatch = async (batch) => {
7731
+ const batchResource = resourceFromAttributes2(
7732
+ withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes)
7733
+ );
7734
+ const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);
7735
+ if (result.code === ExportResultCode2.SUCCESS) {
7736
+ return true;
7737
+ }
7738
+ return isPermanentExportFailure(result) ? "discard" : false;
7739
+ };
7740
+ const exportPoints = async (points) => {
7741
+ if (points.length === 0) {
7742
+ return { accepted: 0, rejected: 0, errors: [] };
7743
+ }
7744
+ const result = await exportResourceMetrics(points, resource, scope);
7745
+ if (result.code === ExportResultCode2.SUCCESS) {
7746
+ health.recordSuccess(points.length, options.clock.now());
7747
+ return { accepted: points.length, rejected: 0, errors: [] };
7748
+ }
7749
+ health.recordFailure("telemetry-export-failure", points.length, options.clock.now());
7750
+ const permanent = isPermanentExportFailure(result);
7751
+ if (options.spool !== void 0 && !permanent) {
7752
+ const spooled = await options.spool.enqueue(toSpoolBatch(points)).catch(() => ({
7753
+ spooled: false,
7754
+ reason: "capacity-exceeded"
7755
+ }));
7756
+ if (spooled.spooled) {
7757
+ options.logger?.warn("metric batch not delivered; spooled for the next invocation", {
7758
+ "export.batch_size": points.length,
7759
+ ...destinationFields
7760
+ });
7761
+ return { accepted: points.length, rejected: 0, errors: [] };
7762
+ }
7763
+ }
7764
+ return {
7765
+ accepted: 0,
7766
+ rejected: points.length,
7767
+ errors: [
7768
+ createErrorInfo({
7769
+ code: "telemetry-export-failure",
7770
+ phase: "export",
7771
+ detail: permanent ? "collector refused a metric batch with a non-retryable status" : "collector rejected or was unreachable for a metric batch",
7772
+ details: {
7773
+ "export.batch_size": points.length,
7774
+ "export.signal": "metrics",
7775
+ ...destinationFields
7776
+ }
7777
+ })
7778
+ ]
7779
+ };
7780
+ };
7781
+ const drainSpool = async (maxBatches) => {
7782
+ if (options.spool === void 0) {
7783
+ return { drained: 0, remaining: 0, failed: 0 };
7784
+ }
7785
+ const result = await options.spool.drain(sendSerializedBatch, {
7786
+ ...maxBatches === void 0 ? {} : { maxBatches }
7787
+ });
7788
+ if (result.drained > 0) {
7789
+ health.recordSuccess(result.drained, options.clock.now());
7790
+ }
7791
+ return result;
7792
+ };
7793
+ const flush = async () => {
7794
+ try {
7795
+ await exporter.forceFlush();
7796
+ } catch {
7797
+ }
7798
+ await drainSpool().catch(() => void 0);
7799
+ };
7800
+ const shutdown = async () => {
7801
+ if (shutdownCompleted) {
7802
+ return;
7803
+ }
7804
+ shutdownCompleted = true;
7805
+ await flush();
7806
+ try {
7807
+ await exporter.shutdown();
7808
+ } catch {
7809
+ }
7810
+ };
7811
+ return {
7812
+ enabled: true,
7813
+ exportPoints,
7814
+ flush,
7815
+ shutdown,
7816
+ health: () => health.snapshot(),
7817
+ drainSpool
7818
+ };
7819
+ };
7820
+
6986
7821
  // src/telemetry/otlp-sink.ts
6987
- import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
7822
+ import { ExportResultCode as ExportResultCode3 } from "@opentelemetry/core";
6988
7823
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
6989
7824
  var chunk2 = (items, size) => {
6990
7825
  if (size <= 0 || items.length <= size) {
@@ -7080,7 +7915,7 @@ var createOtlpTraceSink = (options) => {
7080
7915
  const batchResource = replayResource(batch.resourceAttributes, options.exporter);
7081
7916
  const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));
7082
7917
  const result = await exportSpans(spans);
7083
- if (result.code === ExportResultCode2.SUCCESS) {
7918
+ if (result.code === ExportResultCode3.SUCCESS) {
7084
7919
  return true;
7085
7920
  }
7086
7921
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -7118,9 +7953,9 @@ var createOtlpTraceSink = (options) => {
7118
7953
  try {
7119
7954
  result = await exportSpans(batch);
7120
7955
  } catch (thrown) {
7121
- result = { code: ExportResultCode2.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
7956
+ result = { code: ExportResultCode3.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
7122
7957
  }
7123
- if (result.code === ExportResultCode2.SUCCESS) {
7958
+ if (result.code === ExportResultCode3.SUCCESS) {
7124
7959
  accepted += batch.length;
7125
7960
  health.recordSuccess(batch.length, options.clock.now());
7126
7961
  continue;
@@ -7233,7 +8068,11 @@ var shareCorrelationPerBatch = (correlate) => {
7233
8068
  };
7234
8069
 
7235
8070
  // src/telemetry/export-destinations.ts
7236
- var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs" } : { traces: `destinations/${destination}/spool`, logs: `destinations/${destination}/spool-logs` };
8071
+ var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs", metrics: "spool-metrics" } : {
8072
+ traces: `destinations/${destination}/spool`,
8073
+ logs: `destinations/${destination}/spool-logs`,
8074
+ metrics: `destinations/${destination}/spool-metrics`
8075
+ };
7237
8076
  var exporterPolicyForDestination = (exporter, destination) => {
7238
8077
  if (destination.source === "exporter") {
7239
8078
  return exporter;
@@ -7250,8 +8089,10 @@ var exporterPolicyForDestination = (exporter, destination) => {
7250
8089
  });
7251
8090
  return "endpoint" in derived ? derived.endpoint : void 0;
7252
8091
  })());
8092
+ const { metrics: sharedMetrics, ...rest } = shared;
8093
+ const derivedMetrics = destination.metricsEndpoint ?? (destination.endpoint === void 0 ? void 0 : siblingSignalEndpoint(destination.endpoint, "metrics"));
7253
8094
  return {
7254
- ...shared,
8095
+ ...rest,
7255
8096
  protocol: destination.protocol,
7256
8097
  ...tracesEndpoint === void 0 ? {} : { endpoint: tracesEndpoint },
7257
8098
  headerNames: Object.keys(destination.headers).sort(),
@@ -7259,6 +8100,11 @@ var exporterPolicyForDestination = (exporter, destination) => {
7259
8100
  ...logs,
7260
8101
  enabled: destination.signals.logs,
7261
8102
  ...derivedLogs === void 0 ? {} : { endpoint: derivedLogs }
8103
+ },
8104
+ metrics: {
8105
+ ...effectiveMetricsPolicy({ ...exporter, metrics: sharedMetrics }),
8106
+ enabled: destination.signals.metrics,
8107
+ ...derivedMetrics === void 0 ? {} : { endpoint: derivedMetrics }
7262
8108
  }
7263
8109
  };
7264
8110
  };
@@ -7330,6 +8176,12 @@ var createExportDestinationSinks = (options) => {
7330
8176
  ...bounds,
7331
8177
  queueName: queues.logs
7332
8178
  });
8179
+ const metricSpool = options.spoolRootDir === void 0 || !destination.signals.metrics ? void 0 : createFileDurableMetricSpool({
8180
+ rootDir: options.spoolRootDir,
8181
+ ...shared,
8182
+ ...bounds,
8183
+ queueName: queues.metrics
8184
+ });
7333
8185
  const sinkShared = {
7334
8186
  exporter: policy,
7335
8187
  ...shared,
@@ -7347,12 +8199,21 @@ var createExportDestinationSinks = (options) => {
7347
8199
  ...logSpool === void 0 ? {} : { spool: logSpool },
7348
8200
  content: options.logContent
7349
8201
  });
8202
+ const metrics = destination.signals.metrics ? createOtlpMetricSink({
8203
+ exporter: policy,
8204
+ ...shared,
8205
+ ...label === void 0 ? {} : { destination: label },
8206
+ ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
8207
+ ...metricSpool === void 0 ? {} : { spool: metricSpool }
8208
+ }) : createDisabledOtlpMetricSink(label);
7350
8209
  destinations.push({
7351
8210
  name: destination.name,
7352
8211
  traces,
7353
8212
  logs,
8213
+ metrics,
7354
8214
  ...spool === void 0 ? {} : { spool },
7355
- ...logSpool === void 0 ? {} : { logSpool }
8215
+ ...logSpool === void 0 ? {} : { logSpool },
8216
+ ...metricSpool === void 0 ? {} : { metricSpool }
7356
8217
  });
7357
8218
  }
7358
8219
  return { destinations, skipped };
@@ -7518,6 +8379,12 @@ var createHookRuntime = (options) => {
7518
8379
  const hook = createOtelHook({ ...hookDeps, sink });
7519
8380
  const deduplicator = createCallbackDeduplicator({ stateStore, clock });
7520
8381
  const usageAccumulator = createUsageAccumulator({ stateStore, clock });
8382
+ const metricSeries = createMetricSeriesStore({ stateStore, clock });
8383
+ const metricsPolicy = effectiveMetricsPolicy(options.config.exporter);
8384
+ const metricDestinations = exportDestinations.destinations.filter(
8385
+ (destination) => destination.metrics.enabled
8386
+ );
8387
+ const metricResource = resourceFromExporterPolicy(options.config.exporter);
7521
8388
  const deliveryRetentionMillis = options.deliveryRetentionMillis ?? lifecycleMaxAge;
7522
8389
  if (deliveryRetentionMillis < staleClaimMillis) {
7523
8390
  logger.warn("delivery retention is shorter than the stale-claim window", {
@@ -7529,6 +8396,7 @@ var createHookRuntime = (options) => {
7529
8396
  spanCorrelator,
7530
8397
  deduplicator,
7531
8398
  usageAccumulator,
8399
+ metricSeries,
7532
8400
  spanMaxAgeMillis: lifecycleMaxAge,
7533
8401
  dedupMaxAgeMillis: deliveryRetentionMillis,
7534
8402
  // The *effective* window, not the requested one: a sweep that considered a
@@ -7539,6 +8407,86 @@ var createHookRuntime = (options) => {
7539
8407
  });
7540
8408
  const deliveryLock = createAsyncLock();
7541
8409
  const stateDiagnostic = (thrown) => errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() });
8410
+ const generationStartsFor = async (events) => {
8411
+ const needed = events.some(
8412
+ (event2) => event2.type === "generation.end" && event2.durationMillis === void 0 && !events.some(
8413
+ (other) => other.type === "generation.start" && other.generationId === event2.generationId
8414
+ )
8415
+ );
8416
+ if (!needed) {
8417
+ return void 0;
8418
+ }
8419
+ try {
8420
+ const starts = /* @__PURE__ */ new Map();
8421
+ for (const correlation of await correlate(events)) {
8422
+ if (correlation.ref.family !== "generation" || correlation.startMillis === void 0) {
8423
+ continue;
8424
+ }
8425
+ const requestModel = correlation.attributes?.["gen_ai.request.model"];
8426
+ starts.set(correlation.ref.scopeKey, {
8427
+ startMillis: correlation.startMillis,
8428
+ ...typeof requestModel === "string" ? { requestModel } : {}
8429
+ });
8430
+ }
8431
+ return (generationId) => starts.get(generationId);
8432
+ } catch {
8433
+ return void 0;
8434
+ }
8435
+ };
8436
+ const recordMetrics = async (ingest, deliveryToken, diagnostics) => {
8437
+ if (metricDestinations.length === 0 || ingest.events.length === 0) {
8438
+ return void 0;
8439
+ }
8440
+ try {
8441
+ for (const event2 of ingest.events) {
8442
+ if (event2.type === "prompt.submitted") {
8443
+ await metricSeries.recordTurnStart(event2.sessionId, event2.occurredAt);
8444
+ }
8445
+ }
8446
+ const generationStarts = await generationStartsFor(ingest.events);
8447
+ const turnStarts = /* @__PURE__ */ new Map();
8448
+ for (const event2 of ingest.events) {
8449
+ if (event2.type === "generation.end" && !turnStarts.has(event2.sessionId)) {
8450
+ turnStarts.set(event2.sessionId, await metricSeries.readTurnStart(event2.sessionId));
8451
+ }
8452
+ }
8453
+ const observations = deriveMetricObservations({
8454
+ events: ingest.events,
8455
+ usage: ingest.usageObservations,
8456
+ resource: metricResource,
8457
+ includeSessionId: metricsPolicy.includeSessionId,
8458
+ ...generationStarts === void 0 ? {} : { generationStarts },
8459
+ turnStart: (sessionId) => turnStarts.get(sessionId)
8460
+ });
8461
+ if (observations.length === 0) {
8462
+ return void 0;
8463
+ }
8464
+ const points = metricsPolicy.temporality === "delta" ? aggregateDeltaPoints(observations, clock.now()) : await metricSeries.recordCumulative(observations, {
8465
+ perSession: metricsPolicy.includeSessionId,
8466
+ ...deliveryToken === void 0 ? {} : { deliveryToken }
8467
+ });
8468
+ const results = await Promise.all(
8469
+ metricDestinations.map(async (destination) => {
8470
+ const result = await destination.metrics.exportPoints(points).catch(
8471
+ (thrown) => ({
8472
+ accepted: 0,
8473
+ rejected: points.length,
8474
+ errors: [
8475
+ errorInfoFromThrown(thrown, { code: "telemetry-export-failure", phase: "export" })
8476
+ ]
8477
+ })
8478
+ );
8479
+ diagnostics.push(...result.errors);
8480
+ return { name: destination.name, accepted: result.accepted, rejected: result.rejected };
8481
+ })
8482
+ );
8483
+ return { points: points.length, destinations: results };
8484
+ } catch (thrown) {
8485
+ diagnostics.push(stateDiagnostic(thrown));
8486
+ logger.warn("hook-derived metrics could not be recorded for this callback", {});
8487
+ return void 0;
8488
+ }
8489
+ };
7542
8490
  const rollupDeliveryToken = (identity) => {
7543
8491
  const token = ids.newOpaqueId(["usage-delivery", identity.scope, identity.callbackId]).replace(/[^A-Za-z0-9_-]/g, "").slice(0, 128);
7544
8492
  return token.length === 0 ? void 0 : token;
@@ -7659,6 +8607,11 @@ var createHookRuntime = (options) => {
7659
8607
  identity === void 0 ? void 0 : rollupDeliveryToken(identity)
7660
8608
  );
7661
8609
  }
8610
+ const metrics = !duplicateDelivery && ingest.identity !== void 0 && isCommittable(ingest.durability) ? await recordMetrics(
8611
+ ingest,
8612
+ identity === void 0 ? void 0 : rollupDeliveryToken(identity),
8613
+ diagnostics
8614
+ ) : void 0;
7662
8615
  if (owned && identity !== void 0) {
7663
8616
  try {
7664
8617
  if (isCommittable(ingest.durability)) {
@@ -7725,6 +8678,7 @@ var createHookRuntime = (options) => {
7725
8678
  duplicateDelivery,
7726
8679
  delivery,
7727
8680
  usageRollups,
8681
+ ...metrics === void 0 ? {} : { metrics },
7728
8682
  ...cleanup === void 0 ? {} : { cleanup },
7729
8683
  diagnostics
7730
8684
  };
@@ -7741,12 +8695,20 @@ var createHookRuntime = (options) => {
7741
8695
  () => runProcess(input, identified.identity, report, diagnostics)
7742
8696
  );
7743
8697
  };
7744
- const snapshots = () => sink.health();
8698
+ const snapshots = () => [
8699
+ ...sink.health(),
8700
+ ...metricDestinations.map((destination) => destination.metrics.health())
8701
+ ];
7745
8702
  let shutdownReport;
7746
8703
  const shutdown = () => {
7747
8704
  shutdownReport ??= (async () => {
7748
8705
  const raced = await Promise.race([
7749
- hook.shutdown().then(() => "completed"),
8706
+ Promise.all([
8707
+ hook.shutdown(),
8708
+ // Metric sinks are not behind the hook's sink: they replay their own
8709
+ // spools here, inside the same bounded window.
8710
+ ...metricDestinations.map((destination) => destination.metrics.shutdown().catch(() => void 0))
8711
+ ]).then(() => "completed"),
7750
8712
  delay(flushTimeoutMillis)
7751
8713
  ]);
7752
8714
  if (raced === "timeout") {
@@ -7776,6 +8738,7 @@ var createHookRuntime = (options) => {
7776
8738
  deduplicator,
7777
8739
  usageAccumulator,
7778
8740
  spanCorrelator,
8741
+ metricSeries,
7779
8742
  janitor,
7780
8743
  process: process_,
7781
8744
  shutdown,