@osfactory/otel-hook 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +108 -4
  2. package/dist/{adapter-B9RwW6TO.d.ts → adapter-DQiPu8xF.d.ts} +2 -2
  3. package/dist/cli.js +1495 -135
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +11 -4
  6. package/dist/config.js +116 -21
  7. package/dist/config.js.map +1 -1
  8. package/dist/{destinations-DWOkVxV1.d.ts → destinations-DvqsPulb.d.ts} +12 -2
  9. package/dist/diagnostics.d.ts +1 -1
  10. package/dist/diagnostics.js.map +1 -1
  11. package/dist/{events-CSD_YiJ2.d.ts → events-fcomX6d5.d.ts} +22 -0
  12. package/dist/{export-destinations-lORbe25J.d.ts → export-destinations-CI7z4n3i.d.ts} +136 -6
  13. package/dist/{filesystem-store-DX3dGIgu.d.ts → filesystem-store-CmnUlj1O.d.ts} +1 -1
  14. package/dist/{hook-BAxXoKsp.d.ts → hook-vM_cgqS2.d.ts} +11 -5
  15. package/dist/index.d.ts +16 -16
  16. package/dist/index.js +1496 -183
  17. package/dist/index.js.map +1 -1
  18. package/dist/install.d.ts +4 -4
  19. package/dist/install.js +9 -1
  20. package/dist/install.js.map +1 -1
  21. package/dist/integration.d.ts +36 -12
  22. package/dist/integration.js +1464 -231
  23. package/dist/integration.js.map +1 -1
  24. package/dist/lifecycle.d.ts +55 -4
  25. package/dist/lifecycle.js +279 -5
  26. package/dist/lifecycle.js.map +1 -1
  27. package/dist/{memory-aJilVG4R.d.ts → memory-DdU1U91y.d.ts} +2 -2
  28. package/dist/{semconv-Dw7gcQcg.d.ts → metric-model-C9lLqqpI.d.ts} +157 -2
  29. package/dist/model.d.ts +1 -1
  30. package/dist/model.js +9 -1
  31. package/dist/model.js.map +1 -1
  32. package/dist/{payload-D7gc0-WQ.d.ts → payload-BT19hiVZ.d.ts} +1 -1
  33. package/dist/{ports-plO5MKrY.d.ts → ports-C3k_5eOQ.d.ts} +57 -2
  34. package/dist/providers.d.ts +10 -10
  35. package/dist/providers.js +10 -1
  36. package/dist/providers.js.map +1 -1
  37. package/dist/{registry-C7XO4DzD.d.ts → registry-gyJqaWmp.d.ts} +2 -2
  38. package/dist/runtime.d.ts +97 -9
  39. package/dist/runtime.js +312 -33
  40. package/dist/runtime.js.map +1 -1
  41. package/dist/{schema-CHb3GU1r.d.ts → schema-SpFM6YQY.d.ts} +87 -1
  42. package/dist/state.d.ts +4 -4
  43. package/dist/state.js +32 -1
  44. package/dist/state.js.map +1 -1
  45. package/dist/telemetry.d.ts +6 -6
  46. package/dist/telemetry.js +929 -31
  47. package/dist/telemetry.js.map +1 -1
  48. package/dist/testing.d.ts +11 -9
  49. package/dist/testing.js +164 -33
  50. package/dist/testing.js.map +1 -1
  51. package/package.json +3 -1
@@ -1,4 +1,5 @@
1
1
  // src/config/schema.ts
2
+ import { isAbsolute } from "path";
2
3
  import { z as z5 } from "zod";
3
4
 
4
5
  // src/model/primitives.ts
@@ -161,7 +162,7 @@ var HEADER_ENV_REFERENCE_PREFIX = "env:";
161
162
  var HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
162
163
  var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
163
164
  var MAX_HEADER_VALUE_LENGTH = 8192;
164
- var exportSignalSchema = z3.enum(["traces", "logs"]);
165
+ var exportSignalSchema = z3.enum(["traces", "logs", "metrics"]);
165
166
  var headerValueSchema = z3.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
166
167
  (value) => !isUnsafeHeaderValue(value),
167
168
  "header values may not contain line breaks, control characters, or characters beyond Latin-1"
@@ -184,6 +185,8 @@ var exportDestinationSchema = z3.strictObject({
184
185
  tracesEndpoint: endpointSchema.optional(),
185
186
  /** Per-signal override of the derived logs URL. */
186
187
  logsEndpoint: endpointSchema.optional(),
188
+ /** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */
189
+ metricsEndpoint: endpointSchema.optional(),
187
190
  /** Defaults to `exporter.protocol`. */
188
191
  protocol: z3.enum(["http/protobuf", "http/json", "none"]).optional(),
189
192
  /**
@@ -196,15 +199,17 @@ var exportDestinationSchema = z3.strictObject({
196
199
  `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
197
200
  ).optional(),
198
201
  /**
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.
202
+ * Which signals this destination receives. Default: traces and logs. The logs
203
+ * signal is still governed by `exporter.logs.enabled`, which stays the one
204
+ * opt-in for content-bearing records leaving the host. `metrics` is never on by
205
+ * default: a destination receives hook-derived metrics only when it lists them.
202
206
  */
203
- signals: z3.array(exportSignalSchema).min(1).max(2).readonly().optional()
207
+ signals: z3.array(exportSignalSchema).min(1).max(3).readonly().optional()
204
208
  }).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"
209
+ (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
210
+ "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
207
211
  );
212
+ var DEFAULT_DESTINATION_SIGNALS = Object.freeze(["traces", "logs"]);
208
213
  var exportDestinationsSchema = z3.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
209
214
  const seen = /* @__PURE__ */ new Set();
210
215
  destinations.forEach((destination, index) => {
@@ -249,7 +254,8 @@ var legacyDestination = (exporter) => ({
249
254
  protocol: exporter.protocol,
250
255
  ...exporter.endpoint === void 0 ? {} : { endpoint: exporter.endpoint },
251
256
  ...exporter.logs.endpoint === void 0 ? {} : { logsEndpoint: exporter.logs.endpoint },
252
- signals: { traces: true, logs: exporter.logs.enabled },
257
+ ...exporter.metrics?.endpoint === void 0 ? {} : { metricsEndpoint: exporter.metrics.endpoint },
258
+ signals: { traces: true, logs: exporter.logs.enabled, metrics: exporter.metrics?.enabled === true },
253
259
  headers: {}
254
260
  });
255
261
  var hasConfiguredDestinations = (exporter) => exporter.destinations !== void 0 && exporter.destinations.length > 0;
@@ -258,14 +264,14 @@ var resolveExportDestinations = (exporter) => {
258
264
  return [legacyDestination(exporter)];
259
265
  }
260
266
  const resolved = [];
261
- if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0) {
267
+ if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0 || exporter.metrics?.endpoint !== void 0) {
262
268
  resolved.push(legacyDestination(exporter));
263
269
  }
264
270
  for (const destination of exporter.destinations ?? []) {
265
271
  if (destination.enabled === false) {
266
272
  continue;
267
273
  }
268
- const signals = destination.signals ?? exportSignalSchema.options;
274
+ const signals = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;
269
275
  resolved.push({
270
276
  name: destination.name,
271
277
  source: "destinations",
@@ -273,9 +279,11 @@ var resolveExportDestinations = (exporter) => {
273
279
  ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
274
280
  ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
275
281
  ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
282
+ ...destination.metricsEndpoint === void 0 ? {} : { metricsEndpoint: destination.metricsEndpoint },
276
283
  signals: {
277
284
  traces: signals.includes("traces"),
278
- logs: exporter.logs.enabled && signals.includes("logs")
285
+ logs: exporter.logs.enabled && signals.includes("logs"),
286
+ metrics: signals.includes("metrics")
279
287
  },
280
288
  headers: { ...destination.headers ?? {} }
281
289
  });
@@ -405,6 +413,18 @@ var DEFAULT_LOGS_POLICY = Object.freeze({
405
413
  includeContent: false,
406
414
  maxBatchSize: 128
407
415
  });
416
+ var metricsPolicySchema = z5.strictObject({
417
+ enabled: z5.boolean(),
418
+ /** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */
419
+ endpoint: z5.string().url().max(2048).optional(),
420
+ temporality: z5.enum(["cumulative", "delta"]),
421
+ includeSessionId: z5.boolean()
422
+ });
423
+ var DEFAULT_METRICS_POLICY = Object.freeze({
424
+ enabled: false,
425
+ temporality: "cumulative",
426
+ includeSessionId: true
427
+ });
408
428
  var exporterPolicySchema = z5.strictObject({
409
429
  enabled: z5.boolean(),
410
430
  protocol: z5.enum(["http/protobuf", "http/json", "none"]),
@@ -435,6 +455,11 @@ var exporterPolicySchema = z5.strictObject({
435
455
  * a second top-level section would invite two of each to drift apart.
436
456
  */
437
457
  logs: logsPolicySchema,
458
+ /**
459
+ * Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before
460
+ * metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.
461
+ */
462
+ metrics: metricsPolicySchema.optional(),
438
463
  /**
439
464
  * Additional OTLP destinations, each sent every batch in parallel.
440
465
  *
@@ -471,20 +496,27 @@ var providersPolicySchema = z5.strictObject({
471
496
  readTranscriptUsage: z5.boolean()
472
497
  }).optional()
473
498
  });
499
+ var sessionContextPolicySchema = z5.strictObject({
500
+ /** Absolute path of the context directory. */
501
+ dir: z5.string().min(1).max(4096).refine((value) => isAbsolute(value), { message: "must be an absolute path" })
502
+ });
474
503
  var otelHookConfigSchema = z5.strictObject({
475
504
  exporter: exporterPolicySchema,
476
505
  privacy: privacyPolicySchema,
477
506
  detection: detectionPolicySchema,
478
507
  diagnostics: diagnosticsPolicySchema,
479
508
  /** Optional so a hand-built configuration from before it existed stays valid. */
480
- providers: providersPolicySchema.optional()
509
+ providers: providersPolicySchema.optional(),
510
+ /** Optional: absent means no session context is read. */
511
+ sessionContext: sessionContextPolicySchema.optional()
481
512
  });
482
513
  var otelHookConfigPatchSchema = z5.strictObject({
483
514
  // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
484
515
  // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
485
516
  // without also restating the endpoint and the batch size.
486
- exporter: exporterPolicySchema.omit({ logs: true, spool: true }).partial().extend({
517
+ exporter: exporterPolicySchema.omit({ logs: true, metrics: true, spool: true }).partial().extend({
487
518
  logs: logsPolicySchema.partial().optional(),
519
+ metrics: metricsPolicySchema.partial().optional(),
488
520
  spool: spoolPolicySchema.partial().optional()
489
521
  }).optional(),
490
522
  privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
@@ -492,7 +524,8 @@ var otelHookConfigPatchSchema = z5.strictObject({
492
524
  diagnostics: diagnosticsPolicySchema.partial().optional(),
493
525
  providers: z5.strictObject({
494
526
  claudeCode: z5.strictObject({ readTranscriptUsage: z5.boolean() }).partial().optional()
495
- }).partial().optional()
527
+ }).partial().optional(),
528
+ sessionContext: sessionContextPolicySchema.partial().optional()
496
529
  });
497
530
  var DEFAULT_EXPORTER_POLICY = Object.freeze({
498
531
  enabled: true,
@@ -504,7 +537,8 @@ var DEFAULT_EXPORTER_POLICY = Object.freeze({
504
537
  maxRetryAttempts: 2,
505
538
  serviceName: "coding-agent",
506
539
  resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
507
- logs: DEFAULT_LOGS_POLICY
540
+ logs: DEFAULT_LOGS_POLICY,
541
+ metrics: DEFAULT_METRICS_POLICY
508
542
  });
509
543
  var DEFAULT_DETECTION_POLICY = Object.freeze({
510
544
  minimumConfidence: "strong",
@@ -526,6 +560,11 @@ var DEFAULT_CONFIG = Object.freeze({
526
560
  providers: DEFAULT_PROVIDERS_POLICY
527
561
  });
528
562
  var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
563
+ var sessionContextDir = (config) => config.sessionContext?.dir;
564
+ var effectiveMetricsPolicy = (exporter) => ({
565
+ ...DEFAULT_METRICS_POLICY,
566
+ ...exporter.metrics ?? {}
567
+ });
529
568
 
530
569
  // src/diagnostics/health.ts
531
570
  var createHealthTracker = (subsystem, options = {}) => {
@@ -934,6 +973,8 @@ var rollupUsageKey = (sessionId, scope, scopeKey) => `${rollupScanPrefix(session
934
973
  var rollupEpochKey = (sessionId, scope, scopeKey) => `${rollupEpochScanPrefix(sessionId)}${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;
935
974
  var rollupScanPrefix = (sessionId) => sessionId === void 0 ? `${LIFECYCLE_PREFIX}:usage:` : `${LIFECYCLE_PREFIX}:usage:${encodeSegment(sessionId)}:`;
936
975
  var rollupEpochScanPrefix = (sessionId) => sessionId === void 0 ? `${LIFECYCLE_PREFIX}:epoch:` : `${LIFECYCLE_PREFIX}:epoch:${encodeSegment(sessionId)}:`;
976
+ var metricSeriesKey = (sessionScope2, seriesDigest) => `${metricSeriesScanPrefix(sessionScope2)}${encodeSegment(seriesDigest)}`;
977
+ var metricSeriesScanPrefix = (sessionScope2) => sessionScope2 === void 0 ? `${LIFECYCLE_PREFIX}:metric:v1:` : `${LIFECYCLE_PREFIX}:metric:v1:${encodeSegment(sessionScope2)}:`;
937
978
 
938
979
  // src/lifecycle/dedup.ts
939
980
  var DEFAULT_STALE_CLAIM_MILLIS = 6e4;
@@ -1103,59 +1144,8 @@ var createCallbackDeduplicator = (deps) => {
1103
1144
  return { checkAndMark, claim, commit, release, cleanup };
1104
1145
  };
1105
1146
 
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
1147
+ // src/lifecycle/metric-series.ts
1139
1148
  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
1149
 
1160
1150
  // src/telemetry/export-identity.ts
1161
1151
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -1722,7 +1712,15 @@ var baseEventFields = {
1722
1712
  * factory, never by hand.
1723
1713
  */
1724
1714
  subagentId: subagentIdSchema.optional(),
1725
- extensions: extensionsSchema.default(emptyExtensions)
1715
+ extensions: extensionsSchema.default(emptyExtensions),
1716
+ /**
1717
+ * Attributes of the session context segment in force when the event
1718
+ * occurred (`docs/session-context.md`), stamped by the core from a file a
1719
+ * harness wrote. Exported on every record of the event, over the same keys
1720
+ * from the Resource. Absent when no context applies. Set by the core only,
1721
+ * never by an adapter.
1722
+ */
1723
+ contextAttributes: z14.record(z14.string().min(1).max(255), z14.union([z14.string(), z14.number(), z14.boolean()])).optional()
1726
1724
  };
1727
1725
  var event = (shape) => z14.strictObject({ ...baseEventFields, ...shape });
1728
1726
  var sessionStartEventSchema = event({
@@ -1909,6 +1907,11 @@ var passthroughResourceAttributes = (resource) => {
1909
1907
  }
1910
1908
  return attributes;
1911
1909
  };
1910
+ var contextAttributesOf = (event2) => event2.contextAttributes === void 0 ? {} : { ...event2.contextAttributes };
1911
+ var profileAttributes = (event2, resource) => ({
1912
+ ...passthroughResourceAttributes(resource),
1913
+ ...contextAttributesOf(event2)
1914
+ });
1912
1915
  var resolveExportedSessionId = (eventSessionId, resource) => {
1913
1916
  for (const key of EXTERNAL_SESSION_KEY_ATTRIBUTES) {
1914
1917
  const supplied = resource.attributes[key];
@@ -1929,6 +1932,8 @@ var hexTraceAttributes = (ids) => ({
1929
1932
  var exportIdentityAttributes = (event2, resource, ids) => {
1930
1933
  const { sessionId, providerSessionId } = resolveExportedSessionId(event2.sessionId, resource);
1931
1934
  return {
1935
+ // First, so nothing in the profile layer can replace an identity attribute.
1936
+ ...profileAttributes(event2, resource),
1932
1937
  [ATTR_SESSION_ID]: sessionId,
1933
1938
  [ATTR_OTELHOOK_SESSION_ID]: providerSessionId,
1934
1939
  [ATTR_GEN_AI_CONVERSATION_ID]: providerSessionId,
@@ -1937,11 +1942,482 @@ var exportIdentityAttributes = (event2, resource, ids) => {
1937
1942
  ...event2.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event2.provenance.providerVersion },
1938
1943
  [ATTR_OTELHOOK_WORKSPACE_ID]: event2.workspace.workspaceId,
1939
1944
  ...event2.subagentId === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event2.subagentId },
1940
- ...passthroughResourceAttributes(resource),
1941
1945
  ...hexTraceAttributes(ids)
1942
1946
  };
1943
1947
  };
1944
1948
 
1949
+ // src/telemetry/metric-model.ts
1950
+ var TOKEN_USAGE_BUCKETS = Object.freeze([
1951
+ 1,
1952
+ 4,
1953
+ 16,
1954
+ 64,
1955
+ 256,
1956
+ 1024,
1957
+ 4096,
1958
+ 16384,
1959
+ 65536,
1960
+ 262144,
1961
+ 1048576,
1962
+ 4194304,
1963
+ 16777216,
1964
+ 67108864
1965
+ ]);
1966
+ var OPERATION_DURATION_BUCKETS = Object.freeze([
1967
+ 0.01,
1968
+ 0.02,
1969
+ 0.04,
1970
+ 0.08,
1971
+ 0.16,
1972
+ 0.32,
1973
+ 0.64,
1974
+ 1.28,
1975
+ 2.56,
1976
+ 5.12,
1977
+ 10.24,
1978
+ 20.48,
1979
+ 40.96,
1980
+ 81.92
1981
+ ]);
1982
+ var METRIC_TOKEN_USAGE = "gen_ai.client.token.usage";
1983
+ var METRIC_OPERATION_DURATION = "gen_ai.client.operation.duration";
1984
+ var METRIC_SESSIONS = "otelhook.sessions";
1985
+ var METRIC_TOOL_CALLS = "otelhook.tool.calls";
1986
+ var METRIC_COST_USAGE = "otelhook.cost.usage";
1987
+ var METRIC_INSTRUMENTS = Object.freeze({
1988
+ [METRIC_TOKEN_USAGE]: {
1989
+ name: METRIC_TOKEN_USAGE,
1990
+ kind: "histogram",
1991
+ unit: "{token}",
1992
+ description: "Tokens used per generation, by token type (hook-derived)",
1993
+ valueType: "int",
1994
+ boundaries: TOKEN_USAGE_BUCKETS
1995
+ },
1996
+ [METRIC_OPERATION_DURATION]: {
1997
+ name: METRIC_OPERATION_DURATION,
1998
+ kind: "histogram",
1999
+ unit: "s",
2000
+ description: "Generation duration, from its start hook to its end hook (hook-derived)",
2001
+ valueType: "double",
2002
+ boundaries: OPERATION_DURATION_BUCKETS
2003
+ },
2004
+ [METRIC_SESSIONS]: {
2005
+ name: METRIC_SESSIONS,
2006
+ kind: "counter",
2007
+ unit: "{session}",
2008
+ description: "Agent sessions started",
2009
+ valueType: "int"
2010
+ },
2011
+ [METRIC_TOOL_CALLS]: {
2012
+ name: METRIC_TOOL_CALLS,
2013
+ kind: "counter",
2014
+ unit: "{call}",
2015
+ description: "Completed tool calls, by tool name and outcome",
2016
+ valueType: "int"
2017
+ },
2018
+ [METRIC_COST_USAGE]: {
2019
+ name: METRIC_COST_USAGE,
2020
+ kind: "counter",
2021
+ unit: "USD",
2022
+ description: "Cost reported by the provider; never estimated",
2023
+ valueType: "double"
2024
+ }
2025
+ });
2026
+ var isMetricInstrumentName = (value) => typeof value === "string" && Object.hasOwn(METRIC_INSTRUMENTS, value);
2027
+ var ATTR_GEN_AI_TOKEN_TYPE = "gen_ai.token.type";
2028
+ var ATTR_GEN_AI_PROVIDER_NAME = "gen_ai.provider.name";
2029
+ var ATTR_GEN_AI_OPERATION_NAME = "gen_ai.operation.name";
2030
+ var ATTR_GEN_AI_REQUEST_MODEL = "gen_ai.request.model";
2031
+ var ATTR_GEN_AI_RESPONSE_MODEL = "gen_ai.response.model";
2032
+ var ATTR_GEN_AI_TOOL_NAME = "gen_ai.tool.name";
2033
+ var ATTR_ERROR_TYPE = "error.type";
2034
+ var ATTR_SESSION_ID2 = "session.id";
2035
+ var ATTR_OTELHOOK_PROVIDER_ID2 = "otelhook.provider.id";
2036
+ var ATTR_OTELHOOK_OUTCOME = "otelhook.outcome";
2037
+ var ATTR_OTELHOOK_SESSION_KIND = "otelhook.session.kind";
2038
+ var commonAttributes = (event2, resource, includeSessionId) => ({
2039
+ // Session context first, so the metric's own attributes always win; and never
2040
+ // anything account-shaped, whatever the context says.
2041
+ ...event2.contextAttributes === void 0 ? {} : withoutAccountIdentity(event2.contextAttributes),
2042
+ [ATTR_OTELHOOK_PROVIDER_ID2]: event2.provenance.providerId,
2043
+ ...includeSessionId ? { [ATTR_SESSION_ID2]: resolveExportedSessionId(event2.sessionId, resource).sessionId } : {}
2044
+ });
2045
+ var generationAttributes = (end, requestModel) => ({
2046
+ [ATTR_GEN_AI_OPERATION_NAME]: "chat",
2047
+ ...end.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_PROVIDER_NAME]: end.model.vendor },
2048
+ [ATTR_GEN_AI_REQUEST_MODEL]: requestModel ?? end.model.modelId,
2049
+ [ATTR_GEN_AI_RESPONSE_MODEL]: end.model.modelId
2050
+ });
2051
+ var TOKEN_FIELDS = [
2052
+ ["input", (usage) => usage.inputTokens],
2053
+ ["output", (usage) => usage.outputTokens],
2054
+ ["cache_read", (usage) => usage.cachedInputTokens],
2055
+ ["cache_creation", (usage) => usage.cacheCreationInputTokens]
2056
+ ];
2057
+ var isFailedOutcome = (outcome) => outcome !== "ok" && outcome !== "unknown" && outcome !== "cancelled";
2058
+ var deriveMetricObservations = (input) => {
2059
+ const includeSessionId = input.includeSessionId ?? true;
2060
+ const observations = [];
2061
+ const byId = /* @__PURE__ */ new Map();
2062
+ const startsInBatch = /* @__PURE__ */ new Map();
2063
+ for (const event2 of input.events) {
2064
+ byId.set(event2.eventId, event2);
2065
+ if (event2.type === "generation.start") {
2066
+ startsInBatch.set(event2.generationId, {
2067
+ startMillis: event2.occurredAt,
2068
+ requestModel: event2.model.modelId
2069
+ });
2070
+ }
2071
+ }
2072
+ const requestModelOf = (generationId) => startsInBatch.get(generationId)?.requestModel ?? input.generationStarts?.(generationId)?.requestModel;
2073
+ let lastPromptInBatch;
2074
+ for (const event2 of input.events) {
2075
+ if (event2.type === "prompt.submitted") {
2076
+ lastPromptInBatch ??= /* @__PURE__ */ new Map();
2077
+ lastPromptInBatch.set(event2.sessionId, Math.max(lastPromptInBatch.get(event2.sessionId) ?? 0, event2.occurredAt));
2078
+ }
2079
+ }
2080
+ const measuredDurationOf = (end) => {
2081
+ if (end.durationMillis !== void 0) {
2082
+ return end.durationMillis;
2083
+ }
2084
+ const recovered = startsInBatch.has(end.generationId) ? void 0 : input.generationStarts?.(end.generationId);
2085
+ if (recovered !== void 0) {
2086
+ return end.occurredAt - recovered.startMillis;
2087
+ }
2088
+ const turn = lastPromptInBatch?.get(end.sessionId) ?? input.turnStart?.(end.sessionId);
2089
+ return turn === void 0 || turn > end.occurredAt ? void 0 : end.occurredAt - turn;
2090
+ };
2091
+ const push = (event2, instrument, value, attributes) => {
2092
+ if (!Number.isFinite(value) || value < 0) {
2093
+ return;
2094
+ }
2095
+ observations.push({
2096
+ instrument,
2097
+ value,
2098
+ attributes: { ...commonAttributes(event2, input.resource, includeSessionId), ...attributes },
2099
+ timeMillis: event2.occurredAt,
2100
+ sessionId: event2.sessionId
2101
+ });
2102
+ };
2103
+ for (const event2 of input.events) {
2104
+ switch (event2.type) {
2105
+ case "session.start":
2106
+ push(event2, METRIC_SESSIONS, 1, { [ATTR_OTELHOOK_SESSION_KIND]: event2.sessionKind });
2107
+ break;
2108
+ case "tool.end":
2109
+ push(event2, METRIC_TOOL_CALLS, 1, {
2110
+ [ATTR_GEN_AI_TOOL_NAME]: event2.toolName,
2111
+ [ATTR_OTELHOOK_OUTCOME]: event2.outcome
2112
+ });
2113
+ break;
2114
+ case "generation.end": {
2115
+ const attributes = generationAttributes(event2, requestModelOf(event2.generationId));
2116
+ const durationMillis = measuredDurationOf(event2);
2117
+ if (durationMillis !== void 0 && durationMillis >= 0) {
2118
+ push(event2, METRIC_OPERATION_DURATION, durationMillis / 1e3, {
2119
+ ...attributes,
2120
+ ...isFailedOutcome(event2.outcome) ? { [ATTR_ERROR_TYPE]: event2.outcome } : {}
2121
+ });
2122
+ }
2123
+ if (event2.cost !== void 0 && event2.cost.source === "provider-reported" && event2.cost.currency === "USD") {
2124
+ push(event2, METRIC_COST_USAGE, event2.cost.amount, attributes);
2125
+ }
2126
+ break;
2127
+ }
2128
+ default:
2129
+ break;
2130
+ }
2131
+ }
2132
+ for (const observation of input.usage) {
2133
+ if (observation.scope !== "generation") {
2134
+ continue;
2135
+ }
2136
+ const event2 = byId.get(observation.eventId);
2137
+ if (event2?.type !== "generation.end") {
2138
+ continue;
2139
+ }
2140
+ const attributes = generationAttributes(event2, requestModelOf(event2.generationId));
2141
+ for (const [tokenType, read] of TOKEN_FIELDS) {
2142
+ const value = read(observation.delta);
2143
+ if (value === 0 && (tokenType === "cache_read" || tokenType === "cache_creation")) {
2144
+ continue;
2145
+ }
2146
+ push(event2, METRIC_TOKEN_USAGE, value, { ...attributes, [ATTR_GEN_AI_TOKEN_TYPE]: tokenType });
2147
+ }
2148
+ }
2149
+ return observations;
2150
+ };
2151
+ var emptyHistogram = (boundaries) => ({
2152
+ count: 0,
2153
+ sum: 0,
2154
+ min: Number.POSITIVE_INFINITY,
2155
+ max: Number.NEGATIVE_INFINITY,
2156
+ bucketCounts: new Array(boundaries.length + 1).fill(0)
2157
+ });
2158
+ var bucketIndex = (boundaries, value) => {
2159
+ for (let index = 0; index < boundaries.length; index += 1) {
2160
+ const bound = boundaries[index];
2161
+ if (bound !== void 0 && value <= bound) {
2162
+ return index;
2163
+ }
2164
+ }
2165
+ return boundaries.length;
2166
+ };
2167
+ var recordIntoHistogram = (state, boundaries, value) => {
2168
+ const bucketCounts = [...state.bucketCounts];
2169
+ const index = bucketIndex(boundaries, value);
2170
+ bucketCounts[index] = (bucketCounts[index] ?? 0) + 1;
2171
+ return {
2172
+ count: state.count + 1,
2173
+ sum: state.sum + value,
2174
+ min: Math.min(state.min, value),
2175
+ max: Math.max(state.max, value),
2176
+ bucketCounts
2177
+ };
2178
+ };
2179
+ var seriesIdentity = (instrument, attributes) => JSON.stringify([
2180
+ instrument,
2181
+ Object.entries(attributes).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
2182
+ ]);
2183
+ var aggregateDeltaPoints = (observations, nowMillis) => {
2184
+ const series = /* @__PURE__ */ new Map();
2185
+ for (const observation of observations) {
2186
+ const instrument = METRIC_INSTRUMENTS[observation.instrument];
2187
+ const key = seriesIdentity(observation.instrument, observation.attributes);
2188
+ const existing = series.get(key) ?? {
2189
+ observation,
2190
+ start: observation.timeMillis,
2191
+ value: 0,
2192
+ ...instrument.boundaries === void 0 ? {} : { histogram: emptyHistogram(instrument.boundaries) }
2193
+ };
2194
+ existing.start = Math.min(existing.start, observation.timeMillis);
2195
+ if (existing.histogram !== void 0 && instrument.boundaries !== void 0) {
2196
+ existing.histogram = recordIntoHistogram(existing.histogram, instrument.boundaries, observation.value);
2197
+ } else {
2198
+ existing.value += observation.value;
2199
+ }
2200
+ series.set(key, existing);
2201
+ }
2202
+ return [...series.values()].map((entry) => ({
2203
+ instrument: entry.observation.instrument,
2204
+ temporality: "delta",
2205
+ attributes: entry.observation.attributes,
2206
+ startTimeMillis: Math.min(entry.start, nowMillis),
2207
+ timeMillis: Math.max(nowMillis, entry.start),
2208
+ ...entry.histogram === void 0 ? { value: entry.value } : { histogram: entry.histogram }
2209
+ }));
2210
+ };
2211
+ var FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES = Object.freeze([
2212
+ "user.",
2213
+ "enduser.",
2214
+ "organization."
2215
+ ]);
2216
+ var withoutAccountIdentity = (attributes) => Object.fromEntries(
2217
+ Object.entries(attributes).filter(
2218
+ ([key]) => !FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES.some((prefix) => key.startsWith(prefix))
2219
+ )
2220
+ );
2221
+
2222
+ // src/lifecycle/metric-series.ts
2223
+ var TURN_START_SEGMENT = "turn-start";
2224
+ var SHARED_SCOPE = "all";
2225
+ var SHARED_LOCK = "otelhook.metrics.shared";
2226
+ var sessionScope = (sessionId) => `s=${sessionId}`;
2227
+ var digest = (identity) => createHash("sha256").update(identity).digest("base64url").slice(0, 43);
2228
+ var toStoredHistogram = (histogram) => ({
2229
+ count: histogram.count,
2230
+ sum: histogram.sum,
2231
+ // An empty histogram has infinite min/max, which JSON cannot hold. A stored
2232
+ // histogram always has at least one value, so these are finite in practice.
2233
+ min: Number.isFinite(histogram.min) ? histogram.min : 0,
2234
+ max: Number.isFinite(histogram.max) ? histogram.max : 0,
2235
+ bucketCounts: [...histogram.bucketCounts]
2236
+ });
2237
+ var createMetricSeriesStore = (deps) => {
2238
+ const { stateStore, clock } = deps;
2239
+ const readSeries = async (key) => {
2240
+ const record = await stateStore.read(key);
2241
+ if (record?.value.kind !== "metric-series") {
2242
+ return void 0;
2243
+ }
2244
+ return record.value;
2245
+ };
2246
+ const recordGroup = async (scope, observations, deliveryToken) => {
2247
+ const bySeries = /* @__PURE__ */ new Map();
2248
+ for (const observation of observations) {
2249
+ const identity = seriesIdentity(observation.instrument, observation.attributes);
2250
+ const group = bySeries.get(identity) ?? [];
2251
+ group.push(observation);
2252
+ bySeries.set(identity, group);
2253
+ }
2254
+ const now = clock.now();
2255
+ const points = [];
2256
+ for (const [identity, group] of bySeries) {
2257
+ const first = group[0];
2258
+ if (first === void 0) {
2259
+ continue;
2260
+ }
2261
+ const instrument = METRIC_INSTRUMENTS[first.instrument];
2262
+ const key = metricSeriesKey(scope, digest(identity));
2263
+ const existing = await readSeries(key);
2264
+ const boundaries = instrument.boundaries;
2265
+ const compatible = existing !== void 0 && (boundaries === void 0 ? existing.value !== void 0 : existing.histogram?.bucketCounts.length === boundaries.length + 1);
2266
+ const base = compatible ? existing : void 0;
2267
+ const replay = deliveryToken !== void 0 && base?.appliedDelivery === deliveryToken;
2268
+ const earliest = Math.min(...group.map((observation) => observation.timeMillis));
2269
+ const startTimeMillis = base?.startTimeMillis ?? Math.min(earliest, now);
2270
+ let value = base?.value ?? 0;
2271
+ let histogram = boundaries === void 0 ? void 0 : base?.histogram === void 0 ? emptyHistogram(boundaries) : base.histogram;
2272
+ if (!replay) {
2273
+ for (const observation of group) {
2274
+ if (histogram !== void 0 && boundaries !== void 0) {
2275
+ histogram = recordIntoHistogram(histogram, boundaries, observation.value);
2276
+ } else {
2277
+ value += observation.value;
2278
+ }
2279
+ }
2280
+ await stateStore.write(key, {
2281
+ kind: "metric-series",
2282
+ startTimeMillis,
2283
+ ...histogram === void 0 ? { value } : { histogram: toStoredHistogram(histogram) },
2284
+ ...deliveryToken === void 0 ? {} : { appliedDelivery: deliveryToken }
2285
+ });
2286
+ }
2287
+ points.push({
2288
+ instrument: first.instrument,
2289
+ temporality: "cumulative",
2290
+ attributes: first.attributes,
2291
+ startTimeMillis,
2292
+ timeMillis: Math.max(now, startTimeMillis),
2293
+ ...histogram === void 0 ? { value } : { histogram }
2294
+ });
2295
+ }
2296
+ return points;
2297
+ };
2298
+ const recordCumulative = async (observations, options) => {
2299
+ if (observations.length === 0) {
2300
+ return [];
2301
+ }
2302
+ if (options?.perSession === false) {
2303
+ return withOptionalSessionLock(
2304
+ stateStore,
2305
+ SHARED_LOCK,
2306
+ () => recordGroup(SHARED_SCOPE, observations, options.deliveryToken)
2307
+ );
2308
+ }
2309
+ const bySession = /* @__PURE__ */ new Map();
2310
+ for (const observation of observations) {
2311
+ const group = bySession.get(observation.sessionId) ?? [];
2312
+ group.push(observation);
2313
+ bySession.set(observation.sessionId, group);
2314
+ }
2315
+ const points = [];
2316
+ for (const [sessionId, group] of bySession) {
2317
+ points.push(
2318
+ ...await withOptionalSessionLock(
2319
+ stateStore,
2320
+ sessionId,
2321
+ () => recordGroup(sessionScope(sessionId), group, options?.deliveryToken)
2322
+ )
2323
+ );
2324
+ }
2325
+ return points;
2326
+ };
2327
+ const cleanup = async (maxAgeMillis, options) => {
2328
+ const cap = options?.maxEntries ?? 1e3;
2329
+ const now = clock.now();
2330
+ let removed = 0;
2331
+ let scanned = 0;
2332
+ const prefix = metricSeriesScanPrefix(
2333
+ options?.sessionId === void 0 ? void 0 : sessionScope(options.sessionId)
2334
+ );
2335
+ for (const key of await stateStore.keys(prefix)) {
2336
+ if (scanned >= cap) {
2337
+ break;
2338
+ }
2339
+ scanned += 1;
2340
+ const record = await stateStore.read(key);
2341
+ if (record !== void 0 && now - record.updatedAt > maxAgeMillis) {
2342
+ await stateStore.delete(key);
2343
+ removed += 1;
2344
+ }
2345
+ }
2346
+ return { removed, scanned };
2347
+ };
2348
+ const turnKey = (sessionId) => metricSeriesKey(sessionScope(sessionId), TURN_START_SEGMENT);
2349
+ const recordTurnStart = (sessionId, startMillis) => withOptionalSessionLock(stateStore, sessionId, async () => {
2350
+ const existing = await stateStore.read(turnKey(sessionId));
2351
+ const previous = existing?.value.kind === "attributes" && typeof existing.value.attributes.startMillis === "number" ? existing.value.attributes.startMillis : void 0;
2352
+ if (previous !== void 0 && previous >= startMillis) {
2353
+ return;
2354
+ }
2355
+ await stateStore.write(turnKey(sessionId), { kind: "attributes", attributes: { startMillis } });
2356
+ });
2357
+ const readTurnStart = async (sessionId) => {
2358
+ const record = await stateStore.read(turnKey(sessionId));
2359
+ const value = record?.value.kind === "attributes" ? record.value.attributes.startMillis : void 0;
2360
+ return typeof value === "number" ? value : void 0;
2361
+ };
2362
+ return { recordCumulative, recordTurnStart, readTurnStart, cleanup };
2363
+ };
2364
+
2365
+ // src/lifecycle/janitor.ts
2366
+ var DEFAULT_MAX_AGE_MILLIS = 24 * 60 * 60 * 1e3;
2367
+ var DEFAULT_MAX_ENTRIES_PER_COMPONENT = 1e3;
2368
+ var createLifecycleJanitor = (options) => {
2369
+ const maxEntries = options.maxEntriesPerComponent ?? DEFAULT_MAX_ENTRIES_PER_COMPONENT;
2370
+ const spanMaxAge = options.spanMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
2371
+ const dedupMaxAge = options.dedupMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
2372
+ const usageMaxAge = options.usageMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
2373
+ const runOnce = async (sessionId) => {
2374
+ const scope = { maxEntries, ...sessionId === void 0 ? {} : { sessionId } };
2375
+ const [span, dedup, usage, metrics] = await Promise.all([
2376
+ options.spanCorrelator?.cleanup(spanMaxAge, scope),
2377
+ // Deduplication is deliberately swept across every scope rather than the
2378
+ // ending session's: a delivery scope is a host-chosen namespace or a
2379
+ // digest of provider/installation/session, never a session id, so scoping
2380
+ // this sweep by `sessionId` would match nothing and let records accumulate
2381
+ // forever. The sweep is TTL-driven and still bounded by `maxEntries`.
2382
+ options.deduplicator?.cleanup(dedupMaxAge, {
2383
+ maxEntries,
2384
+ ...options.dedupStaleClaimMillis === void 0 ? {} : { staleClaimMillis: options.dedupStaleClaimMillis }
2385
+ }),
2386
+ options.usageAccumulator?.cleanup(usageMaxAge, scope),
2387
+ options.metricSeries?.cleanup(usageMaxAge, scope)
2388
+ ]);
2389
+ return {
2390
+ ...span === void 0 ? {} : { span },
2391
+ ...dedup === void 0 ? {} : { dedup },
2392
+ ...usage === void 0 ? {} : { usage },
2393
+ ...metrics === void 0 ? {} : { metrics }
2394
+ };
2395
+ };
2396
+ return { runOnce };
2397
+ };
2398
+
2399
+ // src/telemetry/semconv.ts
2400
+ import { createHash as createHash2 } from "crypto";
2401
+ import { SpanKind, SpanStatusCode, TraceFlags } from "@opentelemetry/api";
2402
+ import { millisToHrTime } from "@opentelemetry/core";
2403
+ import {
2404
+ ATTR_ERROR_TYPE as ATTR_ERROR_TYPE2,
2405
+ ATTR_GEN_AI_OPERATION_NAME as ATTR_GEN_AI_OPERATION_NAME2,
2406
+ ATTR_GEN_AI_REQUEST_MODEL as ATTR_GEN_AI_REQUEST_MODEL2,
2407
+ ATTR_GEN_AI_RESPONSE_MODEL as ATTR_GEN_AI_RESPONSE_MODEL2,
2408
+ ATTR_GEN_AI_SYSTEM,
2409
+ ATTR_GEN_AI_TOOL_CALL_ID,
2410
+ ATTR_GEN_AI_TOOL_NAME as ATTR_GEN_AI_TOOL_NAME2,
2411
+ ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,
2412
+ ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,
2413
+ ATTR_GEN_AI_USAGE_INPUT_TOKENS,
2414
+ ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,
2415
+ ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS
2416
+ } from "@opentelemetry/semantic-conventions/incubating";
2417
+
2418
+ // src/version.ts
2419
+ var VERSION = "0.12.0";
2420
+
1945
2421
  // src/telemetry/semconv.ts
1946
2422
  var SCOPE_NAME = "@osfactory/otel-hook";
1947
2423
  var DEFAULT_INSTRUMENTATION_SCOPE = Object.freeze({
@@ -1951,7 +2427,7 @@ var DEFAULT_INSTRUMENTATION_SCOPE = Object.freeze({
1951
2427
  var ATTR_OTELHOOK_SPAN_PAIRED = "otelhook.span.paired";
1952
2428
  var ATTR_OTELHOOK_SPAN_PAIRING = "otelhook.span.pairing";
1953
2429
  var ATTR_OTELHOOK_SPAN_ORPHAN = "otelhook.span.orphan";
1954
- var ATTR_OTELHOOK_OUTCOME = "otelhook.outcome";
2430
+ var ATTR_OTELHOOK_OUTCOME2 = "otelhook.outcome";
1955
2431
  var ATTR_OTELHOOK_RESET_DETECTED = "otelhook.usage.reset_detected";
1956
2432
  var ATTR_OTELHOOK_USAGE_PARTIAL = "otelhook.usage.partial";
1957
2433
  var ATTR_OTELHOOK_TOOL_KIND = "otelhook.tool.kind";
@@ -1961,7 +2437,7 @@ var ATTR_OTELHOOK_AGENT_NAME = "otelhook.agent.name";
1961
2437
  var ATTR_OTELHOOK_AGENT_VERSION = "otelhook.agent.version";
1962
2438
  var ATTR_OTELHOOK_GENERATION_ID = "otelhook.generation.id";
1963
2439
  var FIELD_SEPARATOR = "\0";
1964
- var digestHex = (parts, length) => createHash("sha256").update(parts.join(FIELD_SEPARATOR)).digest("hex").slice(0, length);
2440
+ var digestHex = (parts, length) => createHash2("sha256").update(parts.join(FIELD_SEPARATOR)).digest("hex").slice(0, length);
1965
2441
  var MAX_RECOVERED_START_ATTRIBUTES = 16;
1966
2442
  var familyOf = (type) => {
1967
2443
  switch (type) {
@@ -2024,7 +2500,7 @@ var startOnlySpanAttributes = (event2) => {
2024
2500
  };
2025
2501
  case "generation.start":
2026
2502
  return {
2027
- [ATTR_GEN_AI_REQUEST_MODEL]: event2.model.modelId,
2503
+ [ATTR_GEN_AI_REQUEST_MODEL2]: event2.model.modelId,
2028
2504
  ...event2.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM]: event2.model.vendor }
2029
2505
  };
2030
2506
  // `toolName` and `toolCallId` are on both tool edges, so they are not
@@ -2088,12 +2564,12 @@ var pickTarget = (attributes) => {
2088
2564
  }
2089
2565
  return picked;
2090
2566
  };
2091
- var withoutTarget = (attributes, resource) => {
2567
+ var withoutTarget = (attributes, resource, event2) => {
2092
2568
  const rest = { ...attributes };
2093
2569
  for (const key of TARGET_KEYS) {
2094
2570
  delete rest[key];
2095
2571
  }
2096
- return { ...rest, ...pickTarget(passthroughResourceAttributes(resource)) };
2572
+ return { ...rest, ...pickTarget(profileAttributes(event2, resource)) };
2097
2573
  };
2098
2574
  var rankOf = (candidate) => {
2099
2575
  const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];
@@ -2198,11 +2674,11 @@ var buildLifecycleSpan = (plan, resource, scope) => {
2198
2674
  name = "session";
2199
2675
  kind = SpanKind.INTERNAL;
2200
2676
  attributes = {
2201
- ...withoutTarget(attributes, resource),
2677
+ ...withoutTarget(attributes, resource, anchor),
2202
2678
  ...strongestTarget([pickTarget(resolved.recovered), start === void 0 ? {} : targetAttributes(start)]),
2203
2679
  ...start?.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName },
2204
2680
  ...start?.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion },
2205
- ...end === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.reason },
2681
+ ...end === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME2]: end.reason },
2206
2682
  ...usageAttributes(end?.usage, false)
2207
2683
  };
2208
2684
  if (end?.reason === "error" || end?.reason === "timeout") {
@@ -2218,14 +2694,14 @@ var buildLifecycleSpan = (plan, resource, scope) => {
2218
2694
  kind = SpanKind.CLIENT;
2219
2695
  attributes = {
2220
2696
  ...attributes,
2221
- [ATTR_GEN_AI_OPERATION_NAME]: "chat",
2697
+ [ATTR_GEN_AI_OPERATION_NAME2]: "chat",
2222
2698
  ...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 },
2699
+ ...start?.model?.modelId === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL2]: start.model.modelId },
2700
+ ...end?.model?.modelId === void 0 ? {} : { [ATTR_GEN_AI_RESPONSE_MODEL2]: end.model.modelId },
2225
2701
  // The provider's own id for this unit of work (Cursor generation,
2226
2702
  // Codex turn): the key a consumer stores a usage observation under.
2227
2703
  [ATTR_OTELHOOK_GENERATION_ID]: group.ref.scopeKey,
2228
- ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
2704
+ ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME2]: end.outcome },
2229
2705
  ...usageAttributes(end?.usage, false),
2230
2706
  ...end?.usage === void 0 || end.usagePartial === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_PARTIAL]: end.usagePartial }
2231
2707
  };
@@ -2240,11 +2716,11 @@ var buildLifecycleSpan = (plan, resource, scope) => {
2240
2716
  kind = SpanKind.CLIENT;
2241
2717
  attributes = {
2242
2718
  // Target keys are re-chosen below as one unit, never mixed across edges.
2243
- ...withoutTarget(attributes, resource),
2244
- [ATTR_GEN_AI_TOOL_NAME]: toolName,
2719
+ ...withoutTarget(attributes, resource, anchor),
2720
+ [ATTR_GEN_AI_TOOL_NAME2]: toolName,
2245
2721
  [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,
2246
2722
  ...start?.toolKind === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind },
2247
- ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
2723
+ ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME2]: end.outcome },
2248
2724
  ...strongestTarget([
2249
2725
  pickTarget(resolved.recovered),
2250
2726
  start === void 0 ? {} : targetAttributes(start),
@@ -2262,7 +2738,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
2262
2738
  attributes = {
2263
2739
  ...attributes,
2264
2740
  ...start?.delegationDepth === void 0 ? {} : { [ATTR_OTELHOOK_DELEGATION_DEPTH]: start.delegationDepth },
2265
- ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
2741
+ ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME2]: end.outcome },
2266
2742
  ...usageAttributes(end?.usage, false)
2267
2743
  };
2268
2744
  status = outcomeStatus(end?.outcome);
@@ -2270,7 +2746,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
2270
2746
  }
2271
2747
  }
2272
2748
  if (status.code === SpanStatusCode.ERROR) {
2273
- attributes = { ...attributes, [ATTR_ERROR_TYPE]: status.message ?? "error" };
2749
+ attributes = { ...attributes, [ATTR_ERROR_TYPE2]: status.message ?? "error" };
2274
2750
  }
2275
2751
  return toReadableSpan({
2276
2752
  name,
@@ -2320,7 +2796,7 @@ var buildStandaloneSpan = (event2, resource, scope) => {
2320
2796
  status = { code: SpanStatusCode.ERROR, message: event2.errorCode };
2321
2797
  attributes = {
2322
2798
  ...attributes,
2323
- [ATTR_ERROR_TYPE]: event2.errorCode,
2799
+ [ATTR_ERROR_TYPE2]: event2.errorCode,
2324
2800
  "otelhook.error.phase": event2.phase,
2325
2801
  "otelhook.error.retryable": event2.retryable
2326
2802
  };
@@ -2979,7 +3455,7 @@ var createUsageAccumulator = (deps) => {
2979
3455
  };
2980
3456
 
2981
3457
  // src/privacy/service.ts
2982
- import { createHash as createHash2 } from "crypto";
3458
+ import { createHash as createHash3 } from "crypto";
2983
3459
  var compilePatterns = (sources, flags) => {
2984
3460
  const compiled = [];
2985
3461
  for (const source of sources) {
@@ -3056,7 +3532,7 @@ var createPrivacyService = (policyInput) => {
3056
3532
  const limits = policy.limits;
3057
3533
  const secretKeyPatterns = compilePatterns(policy.secretKeyPatterns, "i");
3058
3534
  const secretValuePatterns = compilePatterns(policy.secretValuePatterns, "g");
3059
- const hash = (value) => `sha256:${createHash2("sha256").update(policy.hashSalt).update("\0").update(value, "utf8").digest("hex")}`;
3535
+ const hash = (value) => `sha256:${createHash3("sha256").update(policy.hashSalt).update("\0").update(value, "utf8").digest("hex")}`;
3060
3536
  const isSecretKey = (key) => secretKeyPatterns.some((pattern) => pattern.test(key));
3061
3537
  const boundString = (value) => {
3062
3538
  const length = codePointLength(value);
@@ -3197,11 +3673,11 @@ var createPrivacyService = (policyInput) => {
3197
3673
  };
3198
3674
  const flattenToAttributes = (value, prefix) => {
3199
3675
  const attributes = {};
3200
- const walk = (current, path6) => {
3676
+ const walk = (current, path7) => {
3201
3677
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
3202
3678
  const primitive = toAttributePrimitive(current);
3203
3679
  if (primitive !== void 0) {
3204
- attributes[path6] = primitive;
3680
+ attributes[path7] = primitive;
3205
3681
  }
3206
3682
  return;
3207
3683
  }
@@ -3220,16 +3696,16 @@ var createPrivacyService = (policyInput) => {
3220
3696
  primitives.push(entryPrimitive);
3221
3697
  }
3222
3698
  if (uniform) {
3223
- attributes[path6] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
3699
+ attributes[path7] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
3224
3700
  return;
3225
3701
  }
3226
3702
  for (const [index, entry] of current.entries()) {
3227
- walk(entry, `${path6}.${index}`);
3703
+ walk(entry, `${path7}.${index}`);
3228
3704
  }
3229
3705
  return;
3230
3706
  }
3231
3707
  for (const [key, entry] of Object.entries(current)) {
3232
- walk(entry, path6 === "" ? key : `${path6}.${key}`);
3708
+ walk(entry, path7 === "" ? key : `${path7}.${key}`);
3233
3709
  }
3234
3710
  };
3235
3711
  walk(value, prefix);
@@ -3322,7 +3798,7 @@ var createPrivacyService = (policyInput) => {
3322
3798
  };
3323
3799
 
3324
3800
  // src/providers/claude/transcript.ts
3325
- import { createHash as createHash3 } from "crypto";
3801
+ import { createHash as createHash4 } from "crypto";
3326
3802
  import { open, stat } from "fs/promises";
3327
3803
  import path from "path";
3328
3804
 
@@ -3995,7 +4471,7 @@ var hasUsage = (record) => record.usage !== void 0 || record.token_usage !== voi
3995
4471
  var eventNameOf = (record) => record.hook_event_name ?? record.hookEventName;
3996
4472
  var transcriptPathOf = (record) => record.transcript_path ?? record.transcriptPath;
3997
4473
  var CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
3998
- var sourceDigest = (transcriptPath) => createHash3("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
4474
+ var sourceDigest = (transcriptPath) => createHash4("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
3999
4475
  var createClaudeTranscriptUsageEnricher = (options = {}) => {
4000
4476
  const fileSize = async (transcriptPath) => {
4001
4477
  try {
@@ -4078,7 +4554,7 @@ var createSystemClock = () => ({
4078
4554
  });
4079
4555
 
4080
4556
  // src/runtime/hook.ts
4081
- import { z as z18 } from "zod";
4557
+ import { z as z19 } from "zod";
4082
4558
 
4083
4559
  // src/providers/registry.ts
4084
4560
  var createProviderRegistry = (adapters) => {
@@ -4233,9 +4709,9 @@ var resolveDeliveryIdentity = (input) => {
4233
4709
  };
4234
4710
 
4235
4711
  // src/runtime/ids.ts
4236
- import { createHash as createHash4, randomUUID } from "crypto";
4237
- var digest = (namespace, parts) => {
4238
- const hash = createHash4("sha256");
4712
+ import { createHash as createHash5, randomUUID } from "crypto";
4713
+ var digest2 = (namespace, parts) => {
4714
+ const hash = createHash5("sha256");
4239
4715
  hash.update(namespace);
4240
4716
  for (const part of parts) {
4241
4717
  hash.update("\0");
@@ -4250,7 +4726,7 @@ var createDeterministicIdGenerator = (options = {}) => {
4250
4726
  return {
4251
4727
  newInvocationId: (seed) => invocationIdSchema.parse(
4252
4728
  `inv_${truncate(
4253
- digest(`${namespace}/invocation`, [
4729
+ digest2(`${namespace}/invocation`, [
4254
4730
  seed.providerId,
4255
4731
  seed.sessionId,
4256
4732
  seed.sourceEventName,
@@ -4261,7 +4737,7 @@ var createDeterministicIdGenerator = (options = {}) => {
4261
4737
  ),
4262
4738
  newEventId: (seed) => eventIdSchema.parse(
4263
4739
  `evt_${truncate(
4264
- digest(`${namespace}/event`, [
4740
+ digest2(`${namespace}/event`, [
4265
4741
  seed.invocationId,
4266
4742
  seed.sequence,
4267
4743
  seed.eventType,
@@ -4269,7 +4745,7 @@ var createDeterministicIdGenerator = (options = {}) => {
4269
4745
  ])
4270
4746
  )}`
4271
4747
  ),
4272
- newOpaqueId: (parts) => truncate(digest(`${namespace}/opaque`, parts))
4748
+ newOpaqueId: (parts) => truncate(digest2(`${namespace}/opaque`, parts))
4273
4749
  };
4274
4750
  };
4275
4751
 
@@ -4314,6 +4790,29 @@ var stateValueSchema = z17.discriminatedUnion("kind", [
4314
4790
  * (Claude Code's transcript), so the next read starts where the last ended.
4315
4791
  * `source` is an opaque digest of what was read, never a path.
4316
4792
  */
4793
+ /**
4794
+ * Running state of one metric series (issue #69), so a cumulative data point
4795
+ * exported by a later hook process continues the same total. Holds numbers and
4796
+ * a series digest only; the series' attributes are re-supplied by the caller
4797
+ * and never read back from disk.
4798
+ */
4799
+ z17.strictObject({
4800
+ kind: z17.literal("metric-series"),
4801
+ /** Start of the cumulative interval. */
4802
+ startTimeMillis: epochMillisSchema,
4803
+ /** Counters: the running total. */
4804
+ value: z17.number().finite().min(0).optional(),
4805
+ /** Histograms: the running aggregation. */
4806
+ histogram: z17.strictObject({
4807
+ count: z17.number().int().min(0),
4808
+ sum: z17.number().finite().min(0),
4809
+ min: z17.number().finite(),
4810
+ max: z17.number().finite(),
4811
+ bucketCounts: z17.array(z17.number().int().min(0)).max(64)
4812
+ }).optional(),
4813
+ /** Opaque digest of the last delivery folded in; makes a replay a no-op. */
4814
+ appliedDelivery: z17.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional()
4815
+ }),
4317
4816
  z17.strictObject({
4318
4817
  kind: z17.literal("read-cursor"),
4319
4818
  source: z17.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
@@ -4480,27 +4979,219 @@ var resolveEventTargets = async (input) => {
4480
4979
  return { events, resolved: settled.size, timedOut: finished === "timeout" };
4481
4980
  };
4482
4981
 
4483
- // src/runtime/hook.ts
4484
- var usageScopeSchema = z18.enum(["session", "generation", "subagent"]);
4485
- var classifyDurability = (input) => {
4486
- if (!input.attempted) {
4487
- return "nothing-to-deliver";
4488
- }
4489
- if (input.rejected === 0) {
4490
- return input.accepted === 0 ? "nothing-to-deliver" : "delivered";
4982
+ // src/runtime/session-context.ts
4983
+ import { open as open2 } from "fs/promises";
4984
+ import * as path3 from "path";
4985
+ import { z as z18 } from "zod";
4986
+ var SESSION_CONTEXT_FILE_VERSION = 1;
4987
+ var DEFAULT_SESSION_CONTEXT_MAX_BYTES = 256 * 1024;
4988
+ var DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS = 100;
4989
+ var MAX_SESSION_CONTEXT_SEGMENTS = 1024;
4990
+ var SESSION_CONTEXT_AGENT_TOOLS = Object.freeze({
4991
+ "claude-code": "claude_code",
4992
+ codex: "codex",
4993
+ cursor: "cursor",
4994
+ "gemini-cli": "gemini_cli",
4995
+ antigravity: "antigravity"
4996
+ });
4997
+ var sessionContextAgentTool = (providerId) => Object.hasOwn(SESSION_CONTEXT_AGENT_TOOLS, providerId) ? SESSION_CONTEXT_AGENT_TOOLS[providerId] : void 0;
4998
+ var SESSION_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
4999
+ var isSessionContextFileName = (sessionId) => SESSION_FILE_NAME_PATTERN.test(sessionId) && !sessionId.includes("..");
5000
+ var sessionContextFilePath = (dir, providerId, sessionId) => {
5001
+ const tool = sessionContextAgentTool(providerId);
5002
+ if (tool === void 0 || !isSessionContextFileName(sessionId) || !path3.isAbsolute(dir)) {
5003
+ return void 0;
4491
5004
  }
4492
- return input.accepted === 0 ? "lost" : "partial";
5005
+ return path3.join(dir, tool, `${sessionId}.json`);
4493
5006
  };
4494
- var isCommittable = (durability) => durability !== "lost";
4495
- var MAX_ERROR_EVENTS = 8;
4496
- var collectContentFacts = (event2) => {
4497
- const facts = [];
4498
- const push = (fact) => {
4499
- if (fact !== void 0) {
4500
- facts.push(fact);
4501
- }
4502
- };
4503
- switch (event2.type) {
5007
+ var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([
5008
+ "session.id",
5009
+ "trace_id",
5010
+ "span_id",
5011
+ "parent_span_id",
5012
+ "gen_ai.conversation.id",
5013
+ "factory.local"
5014
+ ]);
5015
+ var RESERVED_CONTEXT_PREFIXES = Object.freeze(["factory.local.", "otelhook."]);
5016
+ var isReservedSessionContextKey = (key) => RESERVED_CONTEXT_KEYS.has(key) || RESERVED_CONTEXT_PREFIXES.some((prefix) => key.startsWith(prefix));
5017
+ var sanitizeSessionContextAttributes = (attributes) => {
5018
+ const kept = {};
5019
+ let count = 0;
5020
+ for (const [key, value] of Object.entries(attributes)) {
5021
+ if (count >= MAX_RESOURCE_ATTRIBUTES) {
5022
+ break;
5023
+ }
5024
+ if (checkResourceAttributeKey(key) !== void 0 || isReservedSessionContextKey(key)) {
5025
+ continue;
5026
+ }
5027
+ if (typeof value === "string") {
5028
+ if (value.length > MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) {
5029
+ continue;
5030
+ }
5031
+ } else if (typeof value === "number") {
5032
+ if (!Number.isFinite(value)) {
5033
+ continue;
5034
+ }
5035
+ } else if (typeof value !== "boolean") {
5036
+ continue;
5037
+ }
5038
+ kept[key] = value;
5039
+ count += 1;
5040
+ }
5041
+ return kept;
5042
+ };
5043
+ var ISO_INSTANT_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}:\d{2})$/;
5044
+ var isoInstantSchema = z18.string().max(64).regex(ISO_INSTANT_PATTERN).transform((value, ctx) => {
5045
+ const millis = Date.parse(value);
5046
+ if (!Number.isFinite(millis)) {
5047
+ ctx.issues.push({ code: "custom", input: value, message: "not a valid instant" });
5048
+ return z18.NEVER;
5049
+ }
5050
+ return millis;
5051
+ });
5052
+ var segmentSchema = z18.object({
5053
+ from: isoInstantSchema,
5054
+ to: isoInstantSchema.nullable(),
5055
+ reason: z18.string().max(256).optional(),
5056
+ attributes: z18.record(z18.string(), z18.unknown())
5057
+ });
5058
+ var sessionContextFileSchema = z18.object({
5059
+ version: z18.literal(SESSION_CONTEXT_FILE_VERSION),
5060
+ agentTool: z18.string().max(64).optional(),
5061
+ sessionId: z18.string().max(256).optional(),
5062
+ segments: z18.array(segmentSchema).max(MAX_SESSION_CONTEXT_SEGMENTS)
5063
+ });
5064
+ var parseSessionContextFile = (value, expected) => {
5065
+ const parsed = sessionContextFileSchema.safeParse(value);
5066
+ if (!parsed.success) {
5067
+ return void 0;
5068
+ }
5069
+ const file = parsed.data;
5070
+ if (expected?.agentTool !== void 0 && file.agentTool !== void 0 && file.agentTool !== expected.agentTool || expected?.sessionId !== void 0 && file.sessionId !== void 0 && file.sessionId !== expected.sessionId) {
5071
+ return void 0;
5072
+ }
5073
+ return file.segments.map((segment) => ({
5074
+ from: segment.from,
5075
+ to: segment.to,
5076
+ attributes: sanitizeSessionContextAttributes(segment.attributes)
5077
+ }));
5078
+ };
5079
+ var segmentInForce = (segments, at) => {
5080
+ let best;
5081
+ for (const segment of segments) {
5082
+ if (segment.from <= at && (segment.to === null || at < segment.to)) {
5083
+ if (best === void 0 || segment.from >= best.from) {
5084
+ best = segment;
5085
+ }
5086
+ }
5087
+ }
5088
+ return best;
5089
+ };
5090
+ var stampSessionContext = (events, segments) => events.map((event2) => {
5091
+ const { contextAttributes: _discarded, ...rest } = event2;
5092
+ const segment = segments === void 0 ? void 0 : segmentInForce(segments, event2.occurredAt);
5093
+ if (segment === void 0 || Object.keys(segment.attributes).length === 0) {
5094
+ return _discarded === void 0 ? event2 : rest;
5095
+ }
5096
+ return { ...rest, contextAttributes: { ...segment.attributes } };
5097
+ });
5098
+ var readBounded = async (file, maxBytes) => {
5099
+ let handle;
5100
+ try {
5101
+ handle = await open2(file, "r");
5102
+ } catch {
5103
+ return void 0;
5104
+ }
5105
+ try {
5106
+ const stats = await handle.stat();
5107
+ if (!stats.isFile() || stats.size > maxBytes) {
5108
+ return void 0;
5109
+ }
5110
+ const buffer = Buffer.alloc(maxBytes + 1);
5111
+ let length = 0;
5112
+ while (length < buffer.length) {
5113
+ const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
5114
+ if (bytesRead === 0) {
5115
+ break;
5116
+ }
5117
+ length += bytesRead;
5118
+ }
5119
+ if (length > maxBytes) {
5120
+ return void 0;
5121
+ }
5122
+ return buffer.subarray(0, length).toString("utf8");
5123
+ } catch {
5124
+ return void 0;
5125
+ } finally {
5126
+ await handle.close().catch(() => void 0);
5127
+ }
5128
+ };
5129
+ var createDirectorySessionContextReader = (options) => {
5130
+ const maxBytes = options.maxBytes ?? DEFAULT_SESSION_CONTEXT_MAX_BYTES;
5131
+ const budgetMillis = options.budgetMillis ?? DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS;
5132
+ const readOnce = async (providerId, sessionId) => {
5133
+ const file = sessionContextFilePath(options.dir, providerId, sessionId);
5134
+ if (file === void 0) {
5135
+ return void 0;
5136
+ }
5137
+ const text = await readBounded(file, maxBytes);
5138
+ if (text === void 0) {
5139
+ return void 0;
5140
+ }
5141
+ let decoded;
5142
+ try {
5143
+ decoded = JSON.parse(text);
5144
+ } catch {
5145
+ return void 0;
5146
+ }
5147
+ const agentTool = sessionContextAgentTool(providerId);
5148
+ return parseSessionContextFile(decoded, {
5149
+ ...agentTool === void 0 ? {} : { agentTool },
5150
+ sessionId
5151
+ });
5152
+ };
5153
+ return {
5154
+ read: async (request) => {
5155
+ let timer;
5156
+ const timeout = new Promise((resolve3) => {
5157
+ timer = setTimeout(() => resolve3(void 0), budgetMillis);
5158
+ timer.unref?.();
5159
+ });
5160
+ try {
5161
+ return await Promise.race([
5162
+ readOnce(request.providerId, request.sessionId).catch(() => void 0),
5163
+ timeout
5164
+ ]);
5165
+ } finally {
5166
+ if (timer !== void 0) {
5167
+ clearTimeout(timer);
5168
+ }
5169
+ }
5170
+ }
5171
+ };
5172
+ };
5173
+
5174
+ // src/runtime/hook.ts
5175
+ var usageScopeSchema = z19.enum(["session", "generation", "subagent"]);
5176
+ var classifyDurability = (input) => {
5177
+ if (!input.attempted) {
5178
+ return "nothing-to-deliver";
5179
+ }
5180
+ if (input.rejected === 0) {
5181
+ return input.accepted === 0 ? "nothing-to-deliver" : "delivered";
5182
+ }
5183
+ return input.accepted === 0 ? "lost" : "partial";
5184
+ };
5185
+ var isCommittable = (durability) => durability !== "lost";
5186
+ var MAX_ERROR_EVENTS = 8;
5187
+ var collectContentFacts = (event2) => {
5188
+ const facts = [];
5189
+ const push = (fact) => {
5190
+ if (fact !== void 0) {
5191
+ facts.push(fact);
5192
+ }
5193
+ };
5194
+ switch (event2.type) {
4504
5195
  case "prompt.submitted":
4505
5196
  push(event2.content);
4506
5197
  break;
@@ -5190,6 +5881,10 @@ var createOtelHook = (deps) => {
5190
5881
  });
5191
5882
  }
5192
5883
  }
5884
+ batch = stampSessionContext(
5885
+ batch,
5886
+ !suppress && batch.length > 0 && deps.sessionContext !== void 0 ? await readSessionContext(deps.sessionContext, detection.providerId, identity.sessionId) : void 0
5887
+ );
5193
5888
  let emitted = 0;
5194
5889
  let exportRejected = 0;
5195
5890
  if (!suppress && batch.length > 0) {
@@ -5305,6 +6000,13 @@ var createOtelHook = (deps) => {
5305
6000
  };
5306
6001
  return { resolveDelivery, ingest, flush, shutdown, config };
5307
6002
  };
6003
+ var readSessionContext = async (reader, providerId, sessionId) => {
6004
+ try {
6005
+ return await reader.read({ providerId, sessionId });
6006
+ } catch {
6007
+ return void 0;
6008
+ }
6009
+ };
5308
6010
  var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
5309
6011
  const events = [];
5310
6012
  for (const [index, info] of diagnostics.slice(0, MAX_ERROR_EVENTS).entries()) {
@@ -5339,8 +6041,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
5339
6041
  };
5340
6042
 
5341
6043
  // src/runtime/git-worktree.ts
5342
- import { lstat, open as open2, stat as stat2 } from "fs/promises";
5343
- import * as path3 from "path";
6044
+ import { lstat, open as open3, stat as stat2 } from "fs/promises";
6045
+ import * as path4 from "path";
5344
6046
  var MAX_WORKTREE_WALK_DEPTH = 128;
5345
6047
  var MAX_GIT_FILE_BYTES = 4096;
5346
6048
  var MAX_CACHE_ENTRIES = 1024;
@@ -5348,10 +6050,10 @@ var DEFAULT_WORKTREE_CACHE_TTL_MILLIS = 5e3;
5348
6050
  var MAX_BRANCH_NAME_LENGTH = 255;
5349
6051
  var ABSENT = Object.freeze({ kind: "absent" });
5350
6052
  var INVALID = Object.freeze({ kind: "invalid" });
5351
- var readBounded = async (filePath) => {
6053
+ var readBounded2 = async (filePath) => {
5352
6054
  let handle;
5353
6055
  try {
5354
- handle = await open2(filePath, "r");
6056
+ handle = await open3(filePath, "r");
5355
6057
  const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
5356
6058
  const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
5357
6059
  return buffer.subarray(0, bytesRead).toString("utf8");
@@ -5372,7 +6074,7 @@ var parseHeadBranch = (head) => {
5372
6074
  return branch;
5373
6075
  };
5374
6076
  var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
5375
- var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path3.resolve(base, target);
6077
+ var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path4.resolve(base, target);
5376
6078
  var parseGitDirFile = (content, worktreeRoot) => {
5377
6079
  const line = firstLine(content);
5378
6080
  return resolveGitPath(
@@ -5398,17 +6100,17 @@ var isDirectory = async (directory) => {
5398
6100
  }
5399
6101
  };
5400
6102
  var repositoryOf = async (worktreeRoot, gitDir) => {
5401
- const commonDirFile = path3.join(gitDir, "commondir");
5402
- const content = await readBounded(commonDirFile);
6103
+ const commonDirFile = path4.join(gitDir, "commondir");
6104
+ const content = await readBounded2(commonDirFile);
5403
6105
  if (content === void 0) {
5404
6106
  return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
5405
6107
  }
5406
6108
  const commonDir = parseCommonDirFile(content, gitDir);
5407
- const mainRoot = commonDir !== void 0 && path3.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path3.dirname(commonDir) : void 0;
6109
+ const mainRoot = commonDir !== void 0 && path4.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path4.dirname(commonDir) : void 0;
5408
6110
  return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
5409
6111
  };
5410
6112
  var probeDirectory = async (directory) => {
5411
- const dotGit = path3.join(directory, ".git");
6113
+ const dotGit = path4.join(directory, ".git");
5412
6114
  let info;
5413
6115
  try {
5414
6116
  info = await stat2(dotGit);
@@ -5419,13 +6121,13 @@ var probeDirectory = async (directory) => {
5419
6121
  if (info.isDirectory()) {
5420
6122
  gitDir = dotGit;
5421
6123
  } else if (info.isFile()) {
5422
- const content = await readBounded(dotGit);
6124
+ const content = await readBounded2(dotGit);
5423
6125
  gitDir = content === void 0 ? void 0 : parseGitDirFile(content, directory);
5424
6126
  }
5425
6127
  if (gitDir === void 0) {
5426
6128
  return INVALID;
5427
6129
  }
5428
- const head = await readBounded(path3.join(gitDir, "HEAD"));
6130
+ const head = await readBounded2(path4.join(gitDir, "HEAD"));
5429
6131
  if (head === void 0) {
5430
6132
  return INVALID;
5431
6133
  }
@@ -5455,10 +6157,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
5455
6157
  };
5456
6158
  const locate = async (absolutePath) => {
5457
6159
  try {
5458
- if (!path3.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
6160
+ if (!path4.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
5459
6161
  return void 0;
5460
6162
  }
5461
- let directory = path3.resolve(absolutePath);
6163
+ let directory = path4.resolve(absolutePath);
5462
6164
  for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
5463
6165
  const probe = await cachedProbe(directory);
5464
6166
  if (probe.kind === "worktree") {
@@ -5467,7 +6169,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
5467
6169
  if (probe.kind === "invalid") {
5468
6170
  return void 0;
5469
6171
  }
5470
- const parent = path3.dirname(directory);
6172
+ const parent = path4.dirname(directory);
5471
6173
  if (parent === directory) {
5472
6174
  return void 0;
5473
6175
  }
@@ -5483,24 +6185,24 @@ var createFilesystemWorktreeLocator = (options = {}) => {
5483
6185
 
5484
6186
  // src/state/filesystem-store.ts
5485
6187
  import { randomBytes as randomBytes2 } from "crypto";
5486
- import { mkdir, open as open3, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
5487
- import * as path4 from "path";
6188
+ import { mkdir, open as open4, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
6189
+ import * as path5 from "path";
5488
6190
 
5489
6191
  // src/state/keys.ts
5490
- import { createHash as createHash5 } from "crypto";
6192
+ import { createHash as createHash6 } from "crypto";
5491
6193
  var SAFE_SEGMENT_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
5492
6194
  var isSafeSegment = (segment) => SAFE_SEGMENT_PATTERN.test(segment);
5493
6195
  var sanitizeSegment = (segment) => {
5494
6196
  if (isSafeSegment(segment)) {
5495
6197
  return segment;
5496
6198
  }
5497
- return `h_${createHash5("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
6199
+ return `h_${createHash6("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
5498
6200
  };
5499
6201
  var namespaceSegments = (namespace) => [
5500
6202
  sanitizeSegment(namespace.providerId),
5501
6203
  sanitizeSegment(namespace.installationId)
5502
6204
  ];
5503
- var keyDigest = (key) => createHash5("sha256").update(key, "utf8").digest("hex");
6205
+ var keyDigest = (key) => createHash6("sha256").update(key, "utf8").digest("hex");
5504
6206
 
5505
6207
  // src/state/filesystem-store.ts
5506
6208
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
@@ -5516,10 +6218,10 @@ var wrapFsError = (thrown, operation) => {
5516
6218
  };
5517
6219
  var createFilesystemStateStore = (options) => {
5518
6220
  const [providerSegment, installationSegment] = namespaceSegments(options);
5519
- const baseDir = path4.join(options.rootDir, providerSegment, installationSegment);
5520
- const recordsDir = path4.join(baseDir, "records");
5521
- const quarantineDir = path4.join(baseDir, "quarantine");
5522
- const locksDir = path4.join(baseDir, "locks");
6221
+ const baseDir = path5.join(options.rootDir, providerSegment, installationSegment);
6222
+ const recordsDir = path5.join(baseDir, "records");
6223
+ const quarantineDir = path5.join(baseDir, "quarantine");
6224
+ const locksDir = path5.join(baseDir, "locks");
5523
6225
  const lockTimeoutMillis = options.lockTimeoutMillis ?? 5e3;
5524
6226
  const lockStaleMillis = options.lockStaleMillis ?? 3e4;
5525
6227
  const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;
@@ -5543,11 +6245,11 @@ var createFilesystemStateStore = (options) => {
5543
6245
  throw wrapFsError(thrown, "ensure-dirs");
5544
6246
  }
5545
6247
  };
5546
- const recordPath = (key) => path4.join(recordsDir, `${keyDigest(key)}.json`);
5547
- const tempPath = (key) => path4.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
5548
- const lockPath = (sessionId) => path4.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
6248
+ const recordPath = (key) => path5.join(recordsDir, `${keyDigest(key)}.json`);
6249
+ const tempPath = (key) => path5.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
6250
+ const lockPath = (sessionId) => path5.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
5549
6251
  const quarantine = async (filePath, key, reason) => {
5550
- const dest = path4.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
6252
+ const dest = path5.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
5551
6253
  try {
5552
6254
  await rename(filePath, dest);
5553
6255
  } catch {
@@ -5611,7 +6313,7 @@ var createFilesystemStateStore = (options) => {
5611
6313
  const startedAt = options.clock.monotonicMillis();
5612
6314
  for (; ; ) {
5613
6315
  try {
5614
- const handle = await open3(filePath, "wx");
6316
+ const handle = await open4(filePath, "wx");
5615
6317
  try {
5616
6318
  await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));
5617
6319
  } finally {
@@ -5679,7 +6381,7 @@ var createFilesystemStateStore = (options) => {
5679
6381
  }
5680
6382
  let raw;
5681
6383
  try {
5682
- raw = await readFile(path4.join(recordsDir, entry), "utf8");
6384
+ raw = await readFile(path5.join(recordsDir, entry), "utf8");
5683
6385
  } catch {
5684
6386
  continue;
5685
6387
  }
@@ -5732,7 +6434,7 @@ var createFilesystemStateStore = (options) => {
5732
6434
  continue;
5733
6435
  }
5734
6436
  scanned += 1;
5735
- const filePath = path4.join(recordsDir, entry);
6437
+ const filePath = path5.join(recordsDir, entry);
5736
6438
  try {
5737
6439
  const raw = await readFile(filePath, "utf8");
5738
6440
  const envelope = JSON.parse(raw);
@@ -5752,7 +6454,7 @@ var createFilesystemStateStore = (options) => {
5752
6454
  lockEntries = [];
5753
6455
  }
5754
6456
  for (const entry of lockEntries) {
5755
- const filePath = path4.join(locksDir, entry);
6457
+ const filePath = path5.join(locksDir, entry);
5756
6458
  try {
5757
6459
  const raw = await readFile(filePath, "utf8");
5758
6460
  const parsed = JSON.parse(raw);
@@ -5768,10 +6470,44 @@ var createFilesystemStateStore = (options) => {
5768
6470
  };
5769
6471
  };
5770
6472
 
6473
+ // src/config/otlp-endpoint.ts
6474
+ var OTLP_ENDPOINT_VARIABLES = Object.freeze({
6475
+ generic: "OTEL_EXPORTER_OTLP_ENDPOINT",
6476
+ traces: "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
6477
+ logs: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
6478
+ metrics: "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"
6479
+ });
6480
+ var OTLP_TRACES_PATH = "/v1/traces";
6481
+ var OTLP_LOGS_PATH = "/v1/logs";
6482
+ var OTLP_METRICS_PATH = "/v1/metrics";
6483
+ var SIGNAL_PATHS = Object.freeze({
6484
+ traces: OTLP_TRACES_PATH,
6485
+ logs: OTLP_LOGS_PATH,
6486
+ metrics: OTLP_METRICS_PATH
6487
+ });
6488
+ var withoutTrailingSlashes = (value) => {
6489
+ let end = value.length;
6490
+ while (end > 0 && value.charCodeAt(end - 1) === 47) {
6491
+ end -= 1;
6492
+ }
6493
+ return value.slice(0, end);
6494
+ };
6495
+ var siblingSignalEndpoint = (tracesEndpoint, signal) => {
6496
+ const trimmed = withoutTrailingSlashes(tracesEndpoint);
6497
+ const target = SIGNAL_PATHS[signal];
6498
+ if (trimmed.endsWith(target)) {
6499
+ return trimmed;
6500
+ }
6501
+ if (trimmed.endsWith(OTLP_TRACES_PATH)) {
6502
+ return `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${target}`;
6503
+ }
6504
+ return `${trimmed}${target}`;
6505
+ };
6506
+
5771
6507
  // src/telemetry/spool-queue.ts
5772
6508
  import { randomBytes as randomBytes3 } from "crypto";
5773
6509
  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";
5774
- import * as path5 from "path";
6510
+ import * as path6 from "path";
5775
6511
  var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
5776
6512
  total: 0,
5777
6513
  age: 0,
@@ -5787,7 +6523,7 @@ var enqueuedAtOf = (fileName) => {
5787
6523
  var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
5788
6524
  var readSpoolDropCounts = async (queueDir) => {
5789
6525
  try {
5790
- const parsed = JSON.parse(await readFile2(path5.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
6526
+ const parsed = JSON.parse(await readFile2(path6.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
5791
6527
  if (typeof parsed !== "object" || parsed === null) {
5792
6528
  return EMPTY_SPOOL_DROP_COUNTS;
5793
6529
  }
@@ -5816,7 +6552,7 @@ var readSpoolQueueStats = async (queueDir) => {
5816
6552
  let bytes = 0;
5817
6553
  for (const file of files) {
5818
6554
  try {
5819
- bytes += (await stat3(path5.join(queueDir, file))).size;
6555
+ bytes += (await stat3(path6.join(queueDir, file))).size;
5820
6556
  } catch {
5821
6557
  }
5822
6558
  }
@@ -5832,8 +6568,8 @@ var DEFAULT_DRAIN_MAX_BATCHES = 20;
5832
6568
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
5833
6569
  var createSpoolQueue = (options) => {
5834
6570
  const [providerSegment, installationSegment] = namespaceSegments(options);
5835
- const queueDir = path5.join(options.rootDir, providerSegment, installationSegment, options.queueName);
5836
- const corruptDir = path5.join(
6571
+ const queueDir = path6.join(options.rootDir, providerSegment, installationSegment, options.queueName);
6572
+ const corruptDir = path6.join(
5837
6573
  options.rootDir,
5838
6574
  providerSegment,
5839
6575
  installationSegment,
@@ -5880,9 +6616,9 @@ var createSpoolQueue = (options) => {
5880
6616
  [reason]: current[reason] + dropped,
5881
6617
  lastDroppedAt: options.clock.now()
5882
6618
  };
5883
- const tmp = path5.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
6619
+ const tmp = path6.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
5884
6620
  await writeFile2(tmp, JSON.stringify(next), "utf8");
5885
- await rename2(tmp, path5.join(queueDir, SPOOL_DROPS_FILE));
6621
+ await rename2(tmp, path6.join(queueDir, SPOOL_DROPS_FILE));
5886
6622
  } catch {
5887
6623
  }
5888
6624
  options.logger?.warn("durable spool dropped batches", {
@@ -5898,7 +6634,7 @@ var createSpoolQueue = (options) => {
5898
6634
  let bytes = 0;
5899
6635
  if (options.maxBytes !== void 0) {
5900
6636
  try {
5901
- bytes = (await stat3(path5.join(queueDir, name))).size;
6637
+ bytes = (await stat3(path6.join(queueDir, name))).size;
5902
6638
  } catch {
5903
6639
  continue;
5904
6640
  }
@@ -5912,7 +6648,7 @@ var createSpoolQueue = (options) => {
5912
6648
  let removed = 0;
5913
6649
  for (const file of files) {
5914
6650
  try {
5915
- await unlink2(path5.join(queueDir, file.name));
6651
+ await unlink2(path6.join(queueDir, file.name));
5916
6652
  removed += 1;
5917
6653
  } catch {
5918
6654
  }
@@ -5972,8 +6708,8 @@ var createSpoolQueue = (options) => {
5972
6708
  }
5973
6709
  }
5974
6710
  const fileName = `${String(now).padStart(16, "0")}-${randomBytes3(6).toString("hex")}.json`;
5975
- const target = path5.join(queueDir, fileName);
5976
- const tmp = path5.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
6711
+ const target = path6.join(queueDir, fileName);
6712
+ const tmp = path6.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
5977
6713
  await writeFile2(tmp, serialized, "utf8");
5978
6714
  await rename2(tmp, target);
5979
6715
  return { spooled: true };
@@ -6003,7 +6739,7 @@ var createSpoolQueue = (options) => {
6003
6739
  if (fileName === void 0) {
6004
6740
  break;
6005
6741
  }
6006
- const filePath = path5.join(queueDir, fileName);
6742
+ const filePath = path6.join(queueDir, fileName);
6007
6743
  const quarantine = async (rejection) => {
6008
6744
  quarantined += 1;
6009
6745
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -6012,7 +6748,7 @@ var createSpoolQueue = (options) => {
6012
6748
  "spool.queue": options.queueName
6013
6749
  });
6014
6750
  try {
6015
- await rename2(filePath, path5.join(corruptDir, fileName));
6751
+ await rename2(filePath, path6.join(corruptDir, fileName));
6016
6752
  } catch {
6017
6753
  await unlink2(filePath).catch(() => void 0);
6018
6754
  }
@@ -6168,20 +6904,99 @@ var createFileDurableLogSpool = (options) => createSpoolQueue({
6168
6904
  validate: validateLogSpoolBatch
6169
6905
  });
6170
6906
 
6907
+ // src/telemetry/durable-metric-spool.ts
6908
+ var MAX_SPOOLED_METRIC_POINTS_PER_BATCH = 4096;
6909
+ var MAX_STRING_LENGTH = 8192;
6910
+ var MAX_ATTRIBUTES_PER_POINT = 64;
6911
+ var MAX_BUCKETS = 64;
6912
+ var isPlainObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6913
+ var isFiniteNonNegative2 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
6914
+ var isBoundedString2 = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_STRING_LENGTH;
6915
+ var isPrimitiveAttribute2 = (value) => typeof value === "string" && value.length <= MAX_STRING_LENGTH || typeof value === "number" && Number.isFinite(value) || typeof value === "boolean";
6916
+ var isReplayablePoint = (value) => {
6917
+ if (!isPlainObject2(value) || !isMetricInstrumentName(value.instrument)) {
6918
+ return false;
6919
+ }
6920
+ if (value.temporality !== "cumulative" && value.temporality !== "delta") {
6921
+ return false;
6922
+ }
6923
+ if (!isFiniteNonNegative2(value.startTimeMillis) || !isFiniteNonNegative2(value.timeMillis)) {
6924
+ return false;
6925
+ }
6926
+ if (!isPlainObject2(value.attributes)) {
6927
+ return false;
6928
+ }
6929
+ const entries = Object.entries(value.attributes);
6930
+ if (entries.length > MAX_ATTRIBUTES_PER_POINT || !entries.every(([, item]) => isPrimitiveAttribute2(item))) {
6931
+ return false;
6932
+ }
6933
+ const instrument = METRIC_INSTRUMENTS[value.instrument];
6934
+ if (instrument.kind === "counter") {
6935
+ return isFiniteNonNegative2(value.value) && value.histogram === void 0;
6936
+ }
6937
+ const histogram = value.histogram;
6938
+ if (!isPlainObject2(histogram) || value.value !== void 0) {
6939
+ return false;
6940
+ }
6941
+ const buckets = histogram.bucketCounts;
6942
+ 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));
6943
+ };
6944
+ var validateMetricSpoolBatch = (value, identity) => {
6945
+ if (!isPlainObject2(value)) {
6946
+ return { rejection: "not-an-object" };
6947
+ }
6948
+ if (value.providerId !== identity.providerId || value.installationId !== identity.installationId) {
6949
+ return { rejection: "identity-mismatch" };
6950
+ }
6951
+ if (!isPlainObject2(value.resourceAttributes)) {
6952
+ return { rejection: "resource-attributes-invalid" };
6953
+ }
6954
+ if (!isPlainObject2(value.instrumentationScope) || !isBoundedString2(value.instrumentationScope.name)) {
6955
+ return { rejection: "instrumentation-scope-invalid" };
6956
+ }
6957
+ if (value.instrumentationScope.version !== void 0 && typeof value.instrumentationScope.version !== "string") {
6958
+ return { rejection: "instrumentation-scope-invalid" };
6959
+ }
6960
+ if (!Array.isArray(value.points) || value.points.length === 0 || value.points.length > MAX_SPOOLED_METRIC_POINTS_PER_BATCH) {
6961
+ return { rejection: "points-invalid" };
6962
+ }
6963
+ if (!value.points.every(isReplayablePoint)) {
6964
+ return { rejection: "point-field-invalid" };
6965
+ }
6966
+ if (!isFiniteNonNegative2(value.enqueuedAt)) {
6967
+ return { rejection: "not-an-object" };
6968
+ }
6969
+ return { batch: value };
6970
+ };
6971
+ var DEFAULT_MAX_METRIC_SPOOL_FILES = 500;
6972
+ var createFileDurableMetricSpool = (options) => createSpoolQueue({
6973
+ rootDir: options.rootDir,
6974
+ providerId: options.providerId,
6975
+ installationId: options.installationId,
6976
+ clock: options.clock,
6977
+ ...options.logger === void 0 ? {} : { logger: options.logger },
6978
+ maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_METRIC_SPOOL_FILES,
6979
+ queueName: options.queueName ?? "spool-metrics",
6980
+ ...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
6981
+ ...options.maxAgeMillis === void 0 ? {} : { maxAgeMillis: options.maxAgeMillis },
6982
+ ...options.overflow === void 0 ? {} : { overflow: options.overflow },
6983
+ validate: validateMetricSpoolBatch
6984
+ });
6985
+
6171
6986
  // src/telemetry/durable-spool.ts
6172
6987
  var MAX_SPOOLED_SPANS_PER_BATCH = 4096;
6173
6988
  var MAX_SPOOLED_STRING_LENGTH = 8192;
6174
6989
  var MAX_SPOOLED_ATTRIBUTES_PER_SPAN = 256;
6175
6990
  var TRACE_ID_PATTERN2 = /^[0-9a-f]{32}$/;
6176
6991
  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;
6179
- var isPlainObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6992
+ var isFiniteNonNegative3 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
6993
+ var isBoundedString3 = (value, maxLength = MAX_SPOOLED_STRING_LENGTH) => typeof value === "string" && value.length > 0 && value.length <= maxLength;
6994
+ var isPlainObject3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6180
6995
  var isReplayableSpan = (value) => {
6181
- if (!isPlainObject2(value)) {
6996
+ if (!isPlainObject3(value)) {
6182
6997
  return false;
6183
6998
  }
6184
- if (!isBoundedString2(value.name) || !isFiniteNonNegative2(value.kind)) {
6999
+ if (!isBoundedString3(value.name) || !isFiniteNonNegative3(value.kind)) {
6185
7000
  return false;
6186
7001
  }
6187
7002
  if (typeof value.traceId !== "string" || !TRACE_ID_PATTERN2.test(value.traceId)) {
@@ -6193,16 +7008,16 @@ var isReplayableSpan = (value) => {
6193
7008
  if (value.parentSpanId !== void 0 && (typeof value.parentSpanId !== "string" || !SPAN_ID_PATTERN2.test(value.parentSpanId))) {
6194
7009
  return false;
6195
7010
  }
6196
- if (!isFiniteNonNegative2(value.startMillis) || !isFiniteNonNegative2(value.endMillis)) {
7011
+ if (!isFiniteNonNegative3(value.startMillis) || !isFiniteNonNegative3(value.endMillis)) {
6197
7012
  return false;
6198
7013
  }
6199
- if (!isFiniteNonNegative2(value.statusCode)) {
7014
+ if (!isFiniteNonNegative3(value.statusCode)) {
6200
7015
  return false;
6201
7016
  }
6202
7017
  if (value.statusMessage !== void 0 && typeof value.statusMessage !== "string") {
6203
7018
  return false;
6204
7019
  }
6205
- if (!isPlainObject2(value.attributes)) {
7020
+ if (!isPlainObject3(value.attributes)) {
6206
7021
  return false;
6207
7022
  }
6208
7023
  const entries = Object.entries(value.attributes);
@@ -6219,16 +7034,16 @@ var isReplayableSpan = (value) => {
6219
7034
  });
6220
7035
  };
6221
7036
  var validateSpoolBatch = (value, identity) => {
6222
- if (!isPlainObject2(value)) {
7037
+ if (!isPlainObject3(value)) {
6223
7038
  return { rejection: "not-an-object" };
6224
7039
  }
6225
7040
  if (value.providerId !== identity.providerId || value.installationId !== identity.installationId) {
6226
7041
  return { rejection: "identity-mismatch" };
6227
7042
  }
6228
- if (!isPlainObject2(value.resourceAttributes)) {
7043
+ if (!isPlainObject3(value.resourceAttributes)) {
6229
7044
  return { rejection: "resource-attributes-invalid" };
6230
7045
  }
6231
- if (!isPlainObject2(value.instrumentationScope) || !isBoundedString2(value.instrumentationScope.name)) {
7046
+ if (!isPlainObject3(value.instrumentationScope) || !isBoundedString3(value.instrumentationScope.name)) {
6232
7047
  return { rejection: "instrumentation-scope-invalid" };
6233
7048
  }
6234
7049
  if (value.instrumentationScope.version !== void 0 && typeof value.instrumentationScope.version !== "string") {
@@ -6243,7 +7058,7 @@ var validateSpoolBatch = (value, identity) => {
6243
7058
  if (!value.spans.every(isReplayableSpan)) {
6244
7059
  return { rejection: "span-field-invalid" };
6245
7060
  }
6246
- if (!isFiniteNonNegative2(value.enqueuedAt)) {
7061
+ if (!isFiniteNonNegative3(value.enqueuedAt)) {
6247
7062
  return { rejection: "not-an-object" };
6248
7063
  }
6249
7064
  return { batch: value };
@@ -6269,22 +7084,6 @@ import { ExportResultCode } from "@opentelemetry/core";
6269
7084
  import { millisToHrTime as millisToHrTime3 } from "@opentelemetry/core";
6270
7085
  import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
6271
7086
 
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
7087
  // src/telemetry/export-failure.ts
6289
7088
  var RETRYABLE_HTTP_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
6290
7089
  var isPermanentExportFailure = (result) => {
@@ -6326,18 +7125,45 @@ var replayResource = (attributes, policy) => {
6326
7125
  }
6327
7126
  return resourceFromAttributes(safe);
6328
7127
  };
7128
+ var agreedContextAttributes = (events) => {
7129
+ const [first, ...rest] = events;
7130
+ if (first?.contextAttributes === void 0) {
7131
+ return {};
7132
+ }
7133
+ const agreed = { ...first.contextAttributes };
7134
+ for (const event2 of rest) {
7135
+ for (const key of Object.keys(agreed)) {
7136
+ if (event2.contextAttributes?.[key] !== agreed[key]) {
7137
+ delete agreed[key];
7138
+ }
7139
+ }
7140
+ }
7141
+ return agreed;
7142
+ };
7143
+ var resourceWithContext = (resource, context) => {
7144
+ const overrides = {};
7145
+ for (const [key, value] of Object.entries(context)) {
7146
+ if (Object.hasOwn(resource.attributes, key) && !isReservedResourceAttributeKey(key) && resource.attributes[key] !== value) {
7147
+ overrides[key] = value;
7148
+ }
7149
+ }
7150
+ if (Object.keys(overrides).length === 0) {
7151
+ return resource;
7152
+ }
7153
+ return resourceFromAttributes({ ...resource.attributes, ...overrides });
7154
+ };
6329
7155
 
6330
7156
  // src/telemetry/log-records.ts
6331
7157
  import { SeverityNumber, TraceFlags as TraceFlags2 } from "@opentelemetry/api";
6332
7158
  import { millisToHrTime as millisToHrTime2 } from "@opentelemetry/core";
6333
7159
  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,
7160
+ ATTR_ERROR_TYPE as ATTR_ERROR_TYPE3,
7161
+ ATTR_GEN_AI_OPERATION_NAME as ATTR_GEN_AI_OPERATION_NAME3,
7162
+ ATTR_GEN_AI_REQUEST_MODEL as ATTR_GEN_AI_REQUEST_MODEL3,
7163
+ ATTR_GEN_AI_RESPONSE_MODEL as ATTR_GEN_AI_RESPONSE_MODEL3,
6338
7164
  ATTR_GEN_AI_SYSTEM as ATTR_GEN_AI_SYSTEM2,
6339
7165
  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,
7166
+ ATTR_GEN_AI_TOOL_NAME as ATTR_GEN_AI_TOOL_NAME3,
6341
7167
  ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS as ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS2,
6342
7168
  ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS as ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS2,
6343
7169
  ATTR_GEN_AI_USAGE_INPUT_TOKENS as ATTR_GEN_AI_USAGE_INPUT_TOKENS2,
@@ -6353,14 +7179,14 @@ var ATTR_OTELHOOK_EVENT_ID = "otelhook.event.id";
6353
7179
  var ATTR_OTELHOOK_EVENT_SEQUENCE = "otelhook.event.sequence";
6354
7180
  var ATTR_OTELHOOK_LOG_SIGNAL = "otelhook.log.signal";
6355
7181
  var ATTR_OTELHOOK_LOG_MAPPING_VERSION = "otelhook.log.mapping_version";
6356
- var ATTR_OTELHOOK_OUTCOME2 = "otelhook.outcome";
7182
+ var ATTR_OTELHOOK_OUTCOME3 = "otelhook.outcome";
6357
7183
  var ATTR_OTELHOOK_TOOL_KIND2 = "otelhook.tool.kind";
6358
7184
  var ATTR_OTELHOOK_TOOL_PERMISSION = "otelhook.tool.permission_decision";
6359
7185
  var ATTR_OTELHOOK_DELEGATION_DEPTH2 = "otelhook.delegation_depth";
6360
7186
  var ATTR_OTELHOOK_SUBAGENT_TYPE = "otelhook.subagent.type";
6361
7187
  var ATTR_OTELHOOK_AGENT_NAME2 = "otelhook.agent.name";
6362
7188
  var ATTR_OTELHOOK_AGENT_VERSION2 = "otelhook.agent.version";
6363
- var ATTR_OTELHOOK_SESSION_KIND = "otelhook.session.kind";
7189
+ var ATTR_OTELHOOK_SESSION_KIND2 = "otelhook.session.kind";
6364
7190
  var ATTR_OTELHOOK_PROMPT_SOURCE = "otelhook.prompt.source";
6365
7191
  var ATTR_OTELHOOK_PROMPT_TURN_INDEX = "otelhook.prompt.turn_index";
6366
7192
  var ATTR_OTELHOOK_GENERATION_ID2 = "otelhook.generation.id";
@@ -6464,15 +7290,15 @@ var eventAttributes = (event2) => {
6464
7290
  switch (event2.type) {
6465
7291
  case "session.start":
6466
7292
  return {
6467
- [ATTR_OTELHOOK_SESSION_KIND]: event2.sessionKind,
7293
+ [ATTR_OTELHOOK_SESSION_KIND2]: event2.sessionKind,
6468
7294
  ...event2.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME2]: event2.agentName },
6469
7295
  ...event2.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION2]: event2.agentVersion },
6470
- ...event2.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL2]: event2.model.modelId },
7296
+ ...event2.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL3]: event2.model.modelId },
6471
7297
  ...targetAttributes(event2)
6472
7298
  };
6473
7299
  case "session.end":
6474
7300
  return {
6475
- [ATTR_OTELHOOK_OUTCOME2]: event2.reason,
7301
+ [ATTR_OTELHOOK_OUTCOME3]: event2.reason,
6476
7302
  ...usageAttributes2(event2.usage)
6477
7303
  };
6478
7304
  case "prompt.submitted":
@@ -6483,25 +7309,25 @@ var eventAttributes = (event2) => {
6483
7309
  };
6484
7310
  case "generation.start":
6485
7311
  return {
6486
- [ATTR_GEN_AI_OPERATION_NAME2]: "chat",
7312
+ [ATTR_GEN_AI_OPERATION_NAME3]: "chat",
6487
7313
  [ATTR_OTELHOOK_GENERATION_ID2]: event2.generationId,
6488
- [ATTR_GEN_AI_REQUEST_MODEL2]: event2.model.modelId,
7314
+ [ATTR_GEN_AI_REQUEST_MODEL3]: event2.model.modelId,
6489
7315
  ...event2.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event2.model.vendor }
6490
7316
  };
6491
7317
  case "generation.end":
6492
7318
  return {
6493
- [ATTR_GEN_AI_OPERATION_NAME2]: "chat",
7319
+ [ATTR_GEN_AI_OPERATION_NAME3]: "chat",
6494
7320
  [ATTR_OTELHOOK_GENERATION_ID2]: event2.generationId,
6495
- [ATTR_GEN_AI_RESPONSE_MODEL2]: event2.model.modelId,
7321
+ [ATTR_GEN_AI_RESPONSE_MODEL3]: event2.model.modelId,
6496
7322
  ...event2.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event2.model.vendor },
6497
- [ATTR_OTELHOOK_OUTCOME2]: event2.outcome,
7323
+ [ATTR_OTELHOOK_OUTCOME3]: event2.outcome,
6498
7324
  ...event2.stopReason === void 0 ? {} : { [ATTR_OTELHOOK_STOP_REASON]: event2.stopReason },
6499
7325
  ...usageAttributes2(event2.usage),
6500
7326
  ...event2.usage === void 0 || event2.usagePartial === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_PARTIAL]: event2.usagePartial }
6501
7327
  };
6502
7328
  case "tool.start":
6503
7329
  return {
6504
- [ATTR_GEN_AI_TOOL_NAME2]: event2.toolName,
7330
+ [ATTR_GEN_AI_TOOL_NAME3]: event2.toolName,
6505
7331
  [ATTR_GEN_AI_TOOL_CALL_ID2]: event2.toolCallId,
6506
7332
  [ATTR_OTELHOOK_TOOL_KIND2]: event2.toolKind,
6507
7333
  ...event2.generationId === void 0 ? {} : { [ATTR_OTELHOOK_GENERATION_ID2]: event2.generationId },
@@ -6509,9 +7335,9 @@ var eventAttributes = (event2) => {
6509
7335
  };
6510
7336
  case "tool.end":
6511
7337
  return {
6512
- [ATTR_GEN_AI_TOOL_NAME2]: event2.toolName,
7338
+ [ATTR_GEN_AI_TOOL_NAME3]: event2.toolName,
6513
7339
  [ATTR_GEN_AI_TOOL_CALL_ID2]: event2.toolCallId,
6514
- [ATTR_OTELHOOK_OUTCOME2]: event2.outcome,
7340
+ [ATTR_OTELHOOK_OUTCOME3]: event2.outcome,
6515
7341
  ...event2.permissionDecision === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_PERMISSION]: event2.permissionDecision },
6516
7342
  ...targetAttributes(event2)
6517
7343
  };
@@ -6519,11 +7345,11 @@ var eventAttributes = (event2) => {
6519
7345
  return {
6520
7346
  [ATTR_OTELHOOK_DELEGATION_DEPTH2]: event2.delegationDepth,
6521
7347
  ...event2.subagentType === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_TYPE]: event2.subagentType },
6522
- ...event2.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL2]: event2.model.modelId }
7348
+ ...event2.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL3]: event2.model.modelId }
6523
7349
  };
6524
7350
  case "subagent.end":
6525
7351
  return {
6526
- [ATTR_OTELHOOK_OUTCOME2]: event2.outcome,
7352
+ [ATTR_OTELHOOK_OUTCOME3]: event2.outcome,
6527
7353
  ...usageAttributes2(event2.usage)
6528
7354
  };
6529
7355
  case "compaction.performed":
@@ -6536,7 +7362,7 @@ var eventAttributes = (event2) => {
6536
7362
  };
6537
7363
  case "error.raised":
6538
7364
  return {
6539
- [ATTR_ERROR_TYPE2]: event2.errorCode,
7365
+ [ATTR_ERROR_TYPE3]: event2.errorCode,
6540
7366
  [ATTR_OTELHOOK_ERROR_PHASE]: event2.phase,
6541
7367
  [ATTR_OTELHOOK_ERROR_RETRYABLE]: event2.retryable,
6542
7368
  [ATTR_OTELHOOK_ERROR_SEVERITY]: event2.severity
@@ -6841,10 +7667,10 @@ var createOtlpLogSink = (options) => {
6841
7667
  const exportRecords = (records) => new Promise((resolve3) => {
6842
7668
  exporter.export([...records], (result) => resolve3(result));
6843
7669
  });
6844
- const toSpoolBatch = (records) => ({
7670
+ const toSpoolBatch = (records, batchResource) => ({
6845
7671
  providerId: options.providerId,
6846
7672
  installationId: options.installationId,
6847
- resourceAttributes: { ...resource.attributes },
7673
+ resourceAttributes: { ...batchResource.attributes },
6848
7674
  instrumentationScope: {
6849
7675
  name: scope.name,
6850
7676
  ...scope.version === void 0 ? {} : { version: scope.version }
@@ -6879,8 +7705,9 @@ var createOtlpLogSink = (options) => {
6879
7705
  return { accepted: 0, rejected: 0, errors: [] };
6880
7706
  }
6881
7707
  const resolved = await resolveCorrelations(events);
7708
+ const batchResource = resourceWithContext(resource, agreedContextAttributes(events));
6882
7709
  const mapped = canonicalEventsToLogRecords(events, {
6883
- resource,
7710
+ resource: batchResource,
6884
7711
  instrumentationScope: scope,
6885
7712
  content,
6886
7713
  correlations: resolved.correlations,
@@ -6915,7 +7742,7 @@ var createOtlpLogSink = (options) => {
6915
7742
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
6916
7743
  const permanent = isPermanentExportFailure(result);
6917
7744
  if (options.spool !== void 0 && !permanent) {
6918
- const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
7745
+ const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({
6919
7746
  spooled: false,
6920
7747
  reason: "capacity-exceeded"
6921
7748
  }));
@@ -6983,8 +7810,274 @@ var createOtlpLogSink = (options) => {
6983
7810
  };
6984
7811
  };
6985
7812
 
7813
+ // src/telemetry/otlp-metric-sink.ts
7814
+ import { ValueType } from "@opentelemetry/api";
7815
+ import { ExportResultCode as ExportResultCode2, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
7816
+ import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
7817
+ import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
7818
+ import {
7819
+ AggregationTemporality,
7820
+ DataPointType
7821
+ } from "@opentelemetry/sdk-metrics";
7822
+ var resolveMetricsEndpoint = (exporter) => {
7823
+ const stated = exporter.metrics?.endpoint;
7824
+ if (stated !== void 0) {
7825
+ return { endpoint: stated, derived: false };
7826
+ }
7827
+ if (exporter.endpoint === void 0) {
7828
+ return { unresolvable: "no-endpoint" };
7829
+ }
7830
+ return { endpoint: siblingSignalEndpoint(exporter.endpoint, "metrics"), derived: true };
7831
+ };
7832
+ var describeMetricsDeliverability = (exporter) => {
7833
+ if (exporter.metrics?.enabled !== true) {
7834
+ return { status: "disabled", reason: "metrics-disabled" };
7835
+ }
7836
+ if (!exporter.enabled) {
7837
+ return { status: "disabled", reason: "exporter-disabled" };
7838
+ }
7839
+ if (exporter.protocol === "none") {
7840
+ return { status: "disabled", reason: "protocol-none" };
7841
+ }
7842
+ if (exporter.protocol !== "http/protobuf") {
7843
+ return { status: "disabled", reason: "protocol-unsupported" };
7844
+ }
7845
+ const resolved = resolveMetricsEndpoint(exporter);
7846
+ if ("unresolvable" in resolved) {
7847
+ return { status: "disabled", reason: "no-endpoint" };
7848
+ }
7849
+ return { status: "configured", endpoint: resolved.endpoint, derivedEndpoint: resolved.derived };
7850
+ };
7851
+ var DISABLED_DETAIL2 = Object.freeze({
7852
+ "exporter-disabled": "otlp metric sink disabled: the exporter is disabled",
7853
+ "protocol-none": "otlp metric sink disabled: protocol is none",
7854
+ "protocol-unsupported": "otlp metric sink disabled: protocol not supported by this build",
7855
+ "no-endpoint": "otlp metric sink disabled: no metrics endpoint configured and none could be derived"
7856
+ });
7857
+ var createDisabledMetricSink = (destination) => {
7858
+ const health = createHealthTracker(
7859
+ "telemetry-metric-sink",
7860
+ destination === void 0 ? {} : { destination }
7861
+ );
7862
+ return {
7863
+ enabled: false,
7864
+ exportPoints: () => Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),
7865
+ flush: () => Promise.resolve(),
7866
+ shutdown: () => Promise.resolve(),
7867
+ health: () => health.snapshot(),
7868
+ drainSpool: () => Promise.resolve({ drained: 0, remaining: 0, failed: 0 })
7869
+ };
7870
+ };
7871
+ var createDisabledOtlpMetricSink = createDisabledMetricSink;
7872
+ var toMetricData = (points) => {
7873
+ const byInstrument = /* @__PURE__ */ new Map();
7874
+ for (const point of points) {
7875
+ const key = `${point.instrument}|${point.temporality}`;
7876
+ const group = byInstrument.get(key) ?? [];
7877
+ group.push(point);
7878
+ byInstrument.set(key, group);
7879
+ }
7880
+ const metrics = [];
7881
+ for (const group of byInstrument.values()) {
7882
+ const first = group[0];
7883
+ if (first === void 0) {
7884
+ continue;
7885
+ }
7886
+ const instrument = METRIC_INSTRUMENTS[first.instrument];
7887
+ const descriptor = {
7888
+ name: instrument.name,
7889
+ description: instrument.description,
7890
+ unit: instrument.unit,
7891
+ valueType: instrument.valueType === "int" ? ValueType.INT : ValueType.DOUBLE
7892
+ };
7893
+ const aggregationTemporality = first.temporality === "cumulative" ? AggregationTemporality.CUMULATIVE : AggregationTemporality.DELTA;
7894
+ const times = (point) => ({
7895
+ startTime: millisToHrTime4(point.startTimeMillis),
7896
+ endTime: millisToHrTime4(point.timeMillis)
7897
+ });
7898
+ if (instrument.kind === "counter") {
7899
+ metrics.push({
7900
+ descriptor,
7901
+ aggregationTemporality,
7902
+ dataPointType: DataPointType.SUM,
7903
+ isMonotonic: true,
7904
+ dataPoints: group.map((point) => ({
7905
+ ...times(point),
7906
+ attributes: { ...point.attributes },
7907
+ value: point.value ?? 0
7908
+ }))
7909
+ });
7910
+ continue;
7911
+ }
7912
+ metrics.push({
7913
+ descriptor,
7914
+ aggregationTemporality,
7915
+ dataPointType: DataPointType.HISTOGRAM,
7916
+ dataPoints: group.map((point) => {
7917
+ const histogram = point.histogram;
7918
+ return {
7919
+ ...times(point),
7920
+ attributes: { ...point.attributes },
7921
+ value: {
7922
+ buckets: {
7923
+ boundaries: [...instrument.boundaries ?? []],
7924
+ counts: [...histogram?.bucketCounts ?? []]
7925
+ },
7926
+ count: histogram?.count ?? 0,
7927
+ sum: histogram?.sum ?? 0,
7928
+ ...histogram === void 0 || histogram.count === 0 ? {} : { min: histogram.min, max: histogram.max }
7929
+ }
7930
+ };
7931
+ })
7932
+ });
7933
+ }
7934
+ return metrics;
7935
+ };
7936
+ var createOtlpMetricSink = (options) => {
7937
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
7938
+ const deliverability = describeMetricsDeliverability(options.exporter);
7939
+ if (deliverability.status === "disabled") {
7940
+ if (deliverability.reason !== "metrics-disabled") {
7941
+ options.logger?.warn(DISABLED_DETAIL2[deliverability.reason], {
7942
+ "exporter.protocol": options.exporter.protocol,
7943
+ ...destinationFields
7944
+ });
7945
+ }
7946
+ return createDisabledMetricSink(options.destination);
7947
+ }
7948
+ const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
7949
+ const resource = resourceFromAttributes2(
7950
+ withoutAccountIdentity(resourceFromExporterPolicy(options.exporter).attributes)
7951
+ );
7952
+ const health = createHealthTracker(
7953
+ "telemetry-metric-sink",
7954
+ options.destination === void 0 ? {} : { destination: options.destination }
7955
+ );
7956
+ const exporter = new OTLPMetricExporter({
7957
+ url: deliverability.endpoint,
7958
+ headers: { ...options.headers },
7959
+ timeoutMillis: options.exporter.timeoutMillis
7960
+ });
7961
+ let shutdownCompleted = false;
7962
+ const exportResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve3) => {
7963
+ const payload = {
7964
+ resource: batchResource,
7965
+ scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }]
7966
+ };
7967
+ try {
7968
+ exporter.export(payload, (result) => resolve3(result));
7969
+ } catch (thrown) {
7970
+ resolve3({
7971
+ code: ExportResultCode2.FAILED,
7972
+ error: thrown instanceof Error ? thrown : new Error("export threw")
7973
+ });
7974
+ }
7975
+ });
7976
+ const toSpoolBatch = (points, batchResource) => ({
7977
+ providerId: options.providerId,
7978
+ installationId: options.installationId,
7979
+ resourceAttributes: { ...batchResource.attributes },
7980
+ instrumentationScope: {
7981
+ name: scope.name,
7982
+ ...scope.version === void 0 ? {} : { version: scope.version }
7983
+ },
7984
+ points: points.map((point) => ({ ...point })),
7985
+ enqueuedAt: options.clock.now()
7986
+ });
7987
+ const sendSerializedBatch = async (batch) => {
7988
+ const batchResource = resourceFromAttributes2(
7989
+ withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes)
7990
+ );
7991
+ const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);
7992
+ if (result.code === ExportResultCode2.SUCCESS) {
7993
+ return true;
7994
+ }
7995
+ return isPermanentExportFailure(result) ? "discard" : false;
7996
+ };
7997
+ const exportPoints = async (points, context) => {
7998
+ if (points.length === 0) {
7999
+ return { accepted: 0, rejected: 0, errors: [] };
8000
+ }
8001
+ const batchResource = context === void 0 ? resource : resourceWithContext(resource, context);
8002
+ const result = await exportResourceMetrics(points, batchResource, scope);
8003
+ if (result.code === ExportResultCode2.SUCCESS) {
8004
+ health.recordSuccess(points.length, options.clock.now());
8005
+ return { accepted: points.length, rejected: 0, errors: [] };
8006
+ }
8007
+ health.recordFailure("telemetry-export-failure", points.length, options.clock.now());
8008
+ const permanent = isPermanentExportFailure(result);
8009
+ if (options.spool !== void 0 && !permanent) {
8010
+ const spooled = await options.spool.enqueue(toSpoolBatch(points, batchResource)).catch(() => ({
8011
+ spooled: false,
8012
+ reason: "capacity-exceeded"
8013
+ }));
8014
+ if (spooled.spooled) {
8015
+ options.logger?.warn("metric batch not delivered; spooled for the next invocation", {
8016
+ "export.batch_size": points.length,
8017
+ ...destinationFields
8018
+ });
8019
+ return { accepted: points.length, rejected: 0, errors: [] };
8020
+ }
8021
+ }
8022
+ return {
8023
+ accepted: 0,
8024
+ rejected: points.length,
8025
+ errors: [
8026
+ createErrorInfo({
8027
+ code: "telemetry-export-failure",
8028
+ phase: "export",
8029
+ detail: permanent ? "collector refused a metric batch with a non-retryable status" : "collector rejected or was unreachable for a metric batch",
8030
+ details: {
8031
+ "export.batch_size": points.length,
8032
+ "export.signal": "metrics",
8033
+ ...destinationFields
8034
+ }
8035
+ })
8036
+ ]
8037
+ };
8038
+ };
8039
+ const drainSpool = async (maxBatches) => {
8040
+ if (options.spool === void 0) {
8041
+ return { drained: 0, remaining: 0, failed: 0 };
8042
+ }
8043
+ const result = await options.spool.drain(sendSerializedBatch, {
8044
+ ...maxBatches === void 0 ? {} : { maxBatches }
8045
+ });
8046
+ if (result.drained > 0) {
8047
+ health.recordSuccess(result.drained, options.clock.now());
8048
+ }
8049
+ return result;
8050
+ };
8051
+ const flush = async () => {
8052
+ try {
8053
+ await exporter.forceFlush();
8054
+ } catch {
8055
+ }
8056
+ await drainSpool().catch(() => void 0);
8057
+ };
8058
+ const shutdown = async () => {
8059
+ if (shutdownCompleted) {
8060
+ return;
8061
+ }
8062
+ shutdownCompleted = true;
8063
+ await flush();
8064
+ try {
8065
+ await exporter.shutdown();
8066
+ } catch {
8067
+ }
8068
+ };
8069
+ return {
8070
+ enabled: true,
8071
+ exportPoints,
8072
+ flush,
8073
+ shutdown,
8074
+ health: () => health.snapshot(),
8075
+ drainSpool
8076
+ };
8077
+ };
8078
+
6986
8079
  // src/telemetry/otlp-sink.ts
6987
- import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
8080
+ import { ExportResultCode as ExportResultCode3 } from "@opentelemetry/core";
6988
8081
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
6989
8082
  var chunk2 = (items, size) => {
6990
8083
  if (size <= 0 || items.length <= size) {
@@ -7068,10 +8161,10 @@ var createOtlpTraceSink = (options) => {
7068
8161
  const exportSpans = (spans) => new Promise((resolve3) => {
7069
8162
  exporter.export([...spans], (result) => resolve3(result));
7070
8163
  });
7071
- const toSpoolBatch = (spans) => ({
8164
+ const toSpoolBatch = (spans, batchResource) => ({
7072
8165
  providerId: options.providerId,
7073
8166
  installationId: options.installationId,
7074
- resourceAttributes: { ...resource.attributes },
8167
+ resourceAttributes: { ...batchResource.attributes },
7075
8168
  instrumentationScope: { name: scope.name, ...scope.version === void 0 ? {} : { version: scope.version } },
7076
8169
  spans: spans.map(serializeSpan),
7077
8170
  enqueuedAt: options.clock.now()
@@ -7080,7 +8173,7 @@ var createOtlpTraceSink = (options) => {
7080
8173
  const batchResource = replayResource(batch.resourceAttributes, options.exporter);
7081
8174
  const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));
7082
8175
  const result = await exportSpans(spans);
7083
- if (result.code === ExportResultCode2.SUCCESS) {
8176
+ if (result.code === ExportResultCode3.SUCCESS) {
7084
8177
  return true;
7085
8178
  }
7086
8179
  return isPermanentExportFailure(result) ? "discard" : false;
@@ -7101,8 +8194,9 @@ var createOtlpTraceSink = (options) => {
7101
8194
  return { accepted: 0, rejected: 0, errors: [] };
7102
8195
  }
7103
8196
  const resolved = await resolveCorrelations(events);
8197
+ const batchResource = resourceWithContext(resource, agreedContextAttributes(events));
7104
8198
  const spans = canonicalEventsToReadableSpans(events, {
7105
- resource,
8199
+ resource: batchResource,
7106
8200
  instrumentationScope: scope,
7107
8201
  correlations: resolved.correlations,
7108
8202
  ...resolved.available === void 0 ? {} : { correlationAvailable: resolved.available }
@@ -7118,9 +8212,9 @@ var createOtlpTraceSink = (options) => {
7118
8212
  try {
7119
8213
  result = await exportSpans(batch);
7120
8214
  } catch (thrown) {
7121
- result = { code: ExportResultCode2.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
8215
+ result = { code: ExportResultCode3.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
7122
8216
  }
7123
- if (result.code === ExportResultCode2.SUCCESS) {
8217
+ if (result.code === ExportResultCode3.SUCCESS) {
7124
8218
  accepted += batch.length;
7125
8219
  health.recordSuccess(batch.length, options.clock.now());
7126
8220
  continue;
@@ -7128,7 +8222,7 @@ var createOtlpTraceSink = (options) => {
7128
8222
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
7129
8223
  const permanent = isPermanentExportFailure(result);
7130
8224
  if (options.spool !== void 0 && !permanent) {
7131
- const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
8225
+ const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({
7132
8226
  spooled: false,
7133
8227
  reason: "capacity-exceeded"
7134
8228
  }));
@@ -7233,7 +8327,11 @@ var shareCorrelationPerBatch = (correlate) => {
7233
8327
  };
7234
8328
 
7235
8329
  // 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` };
8330
+ var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs", metrics: "spool-metrics" } : {
8331
+ traces: `destinations/${destination}/spool`,
8332
+ logs: `destinations/${destination}/spool-logs`,
8333
+ metrics: `destinations/${destination}/spool-metrics`
8334
+ };
7237
8335
  var exporterPolicyForDestination = (exporter, destination) => {
7238
8336
  if (destination.source === "exporter") {
7239
8337
  return exporter;
@@ -7250,8 +8348,10 @@ var exporterPolicyForDestination = (exporter, destination) => {
7250
8348
  });
7251
8349
  return "endpoint" in derived ? derived.endpoint : void 0;
7252
8350
  })());
8351
+ const { metrics: sharedMetrics, ...rest } = shared;
8352
+ const derivedMetrics = destination.metricsEndpoint ?? (destination.endpoint === void 0 ? void 0 : siblingSignalEndpoint(destination.endpoint, "metrics"));
7253
8353
  return {
7254
- ...shared,
8354
+ ...rest,
7255
8355
  protocol: destination.protocol,
7256
8356
  ...tracesEndpoint === void 0 ? {} : { endpoint: tracesEndpoint },
7257
8357
  headerNames: Object.keys(destination.headers).sort(),
@@ -7259,6 +8359,11 @@ var exporterPolicyForDestination = (exporter, destination) => {
7259
8359
  ...logs,
7260
8360
  enabled: destination.signals.logs,
7261
8361
  ...derivedLogs === void 0 ? {} : { endpoint: derivedLogs }
8362
+ },
8363
+ metrics: {
8364
+ ...effectiveMetricsPolicy({ ...exporter, metrics: sharedMetrics }),
8365
+ enabled: destination.signals.metrics,
8366
+ ...derivedMetrics === void 0 ? {} : { endpoint: derivedMetrics }
7262
8367
  }
7263
8368
  };
7264
8369
  };
@@ -7330,6 +8435,12 @@ var createExportDestinationSinks = (options) => {
7330
8435
  ...bounds,
7331
8436
  queueName: queues.logs
7332
8437
  });
8438
+ const metricSpool = options.spoolRootDir === void 0 || !destination.signals.metrics ? void 0 : createFileDurableMetricSpool({
8439
+ rootDir: options.spoolRootDir,
8440
+ ...shared,
8441
+ ...bounds,
8442
+ queueName: queues.metrics
8443
+ });
7333
8444
  const sinkShared = {
7334
8445
  exporter: policy,
7335
8446
  ...shared,
@@ -7347,12 +8458,21 @@ var createExportDestinationSinks = (options) => {
7347
8458
  ...logSpool === void 0 ? {} : { spool: logSpool },
7348
8459
  content: options.logContent
7349
8460
  });
8461
+ const metrics = destination.signals.metrics ? createOtlpMetricSink({
8462
+ exporter: policy,
8463
+ ...shared,
8464
+ ...label === void 0 ? {} : { destination: label },
8465
+ ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
8466
+ ...metricSpool === void 0 ? {} : { spool: metricSpool }
8467
+ }) : createDisabledOtlpMetricSink(label);
7350
8468
  destinations.push({
7351
8469
  name: destination.name,
7352
8470
  traces,
7353
8471
  logs,
8472
+ metrics,
7354
8473
  ...spool === void 0 ? {} : { spool },
7355
- ...logSpool === void 0 ? {} : { logSpool }
8474
+ ...logSpool === void 0 ? {} : { logSpool },
8475
+ ...metricSpool === void 0 ? {} : { metricSpool }
7356
8476
  });
7357
8477
  }
7358
8478
  return { destinations, skipped };
@@ -7511,6 +8631,16 @@ var createHookRuntime = (options) => {
7511
8631
  logger,
7512
8632
  installationId: options.installationId,
7513
8633
  payloadEnrichers: options.payloadEnrichers ?? (readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : []),
8634
+ ...(() => {
8635
+ if (options.sessionContextReader === null) {
8636
+ return {};
8637
+ }
8638
+ if (options.sessionContextReader !== void 0) {
8639
+ return { sessionContext: options.sessionContextReader };
8640
+ }
8641
+ const dir = sessionContextDir(options.config);
8642
+ return dir === void 0 ? {} : { sessionContext: createDirectorySessionContextReader({ dir }) };
8643
+ })(),
7514
8644
  ...options.worktreeLocator === null ? {} : {
7515
8645
  worktreeLocator: options.worktreeLocator ?? createFilesystemWorktreeLocator({ monotonicMillis: () => clock.monotonicMillis() })
7516
8646
  }
@@ -7518,6 +8648,12 @@ var createHookRuntime = (options) => {
7518
8648
  const hook = createOtelHook({ ...hookDeps, sink });
7519
8649
  const deduplicator = createCallbackDeduplicator({ stateStore, clock });
7520
8650
  const usageAccumulator = createUsageAccumulator({ stateStore, clock });
8651
+ const metricSeries = createMetricSeriesStore({ stateStore, clock });
8652
+ const metricsPolicy = effectiveMetricsPolicy(options.config.exporter);
8653
+ const metricDestinations = exportDestinations.destinations.filter(
8654
+ (destination) => destination.metrics.enabled
8655
+ );
8656
+ const metricResource = resourceFromExporterPolicy(options.config.exporter);
7521
8657
  const deliveryRetentionMillis = options.deliveryRetentionMillis ?? lifecycleMaxAge;
7522
8658
  if (deliveryRetentionMillis < staleClaimMillis) {
7523
8659
  logger.warn("delivery retention is shorter than the stale-claim window", {
@@ -7529,6 +8665,7 @@ var createHookRuntime = (options) => {
7529
8665
  spanCorrelator,
7530
8666
  deduplicator,
7531
8667
  usageAccumulator,
8668
+ metricSeries,
7532
8669
  spanMaxAgeMillis: lifecycleMaxAge,
7533
8670
  dedupMaxAgeMillis: deliveryRetentionMillis,
7534
8671
  // The *effective* window, not the requested one: a sweep that considered a
@@ -7539,6 +8676,87 @@ var createHookRuntime = (options) => {
7539
8676
  });
7540
8677
  const deliveryLock = createAsyncLock();
7541
8678
  const stateDiagnostic = (thrown) => errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() });
8679
+ const generationStartsFor = async (events) => {
8680
+ const needed = events.some(
8681
+ (event2) => event2.type === "generation.end" && event2.durationMillis === void 0 && !events.some(
8682
+ (other) => other.type === "generation.start" && other.generationId === event2.generationId
8683
+ )
8684
+ );
8685
+ if (!needed) {
8686
+ return void 0;
8687
+ }
8688
+ try {
8689
+ const starts = /* @__PURE__ */ new Map();
8690
+ for (const correlation of await correlate(events)) {
8691
+ if (correlation.ref.family !== "generation" || correlation.startMillis === void 0) {
8692
+ continue;
8693
+ }
8694
+ const requestModel = correlation.attributes?.["gen_ai.request.model"];
8695
+ starts.set(correlation.ref.scopeKey, {
8696
+ startMillis: correlation.startMillis,
8697
+ ...typeof requestModel === "string" ? { requestModel } : {}
8698
+ });
8699
+ }
8700
+ return (generationId) => starts.get(generationId);
8701
+ } catch {
8702
+ return void 0;
8703
+ }
8704
+ };
8705
+ const recordMetrics = async (ingest, deliveryToken, diagnostics) => {
8706
+ if (metricDestinations.length === 0 || ingest.events.length === 0) {
8707
+ return void 0;
8708
+ }
8709
+ try {
8710
+ for (const event2 of ingest.events) {
8711
+ if (event2.type === "prompt.submitted") {
8712
+ await metricSeries.recordTurnStart(event2.sessionId, event2.occurredAt);
8713
+ }
8714
+ }
8715
+ const generationStarts = await generationStartsFor(ingest.events);
8716
+ const turnStarts = /* @__PURE__ */ new Map();
8717
+ for (const event2 of ingest.events) {
8718
+ if (event2.type === "generation.end" && !turnStarts.has(event2.sessionId)) {
8719
+ turnStarts.set(event2.sessionId, await metricSeries.readTurnStart(event2.sessionId));
8720
+ }
8721
+ }
8722
+ const observations = deriveMetricObservations({
8723
+ events: ingest.events,
8724
+ usage: ingest.usageObservations,
8725
+ resource: metricResource,
8726
+ includeSessionId: metricsPolicy.includeSessionId,
8727
+ ...generationStarts === void 0 ? {} : { generationStarts },
8728
+ turnStart: (sessionId) => turnStarts.get(sessionId)
8729
+ });
8730
+ if (observations.length === 0) {
8731
+ return void 0;
8732
+ }
8733
+ const points = metricsPolicy.temporality === "delta" ? aggregateDeltaPoints(observations, clock.now()) : await metricSeries.recordCumulative(observations, {
8734
+ perSession: metricsPolicy.includeSessionId,
8735
+ ...deliveryToken === void 0 ? {} : { deliveryToken }
8736
+ });
8737
+ const context = agreedContextAttributes(ingest.events);
8738
+ const results = await Promise.all(
8739
+ metricDestinations.map(async (destination) => {
8740
+ const result = await destination.metrics.exportPoints(points, context).catch(
8741
+ (thrown) => ({
8742
+ accepted: 0,
8743
+ rejected: points.length,
8744
+ errors: [
8745
+ errorInfoFromThrown(thrown, { code: "telemetry-export-failure", phase: "export" })
8746
+ ]
8747
+ })
8748
+ );
8749
+ diagnostics.push(...result.errors);
8750
+ return { name: destination.name, accepted: result.accepted, rejected: result.rejected };
8751
+ })
8752
+ );
8753
+ return { points: points.length, destinations: results };
8754
+ } catch (thrown) {
8755
+ diagnostics.push(stateDiagnostic(thrown));
8756
+ logger.warn("hook-derived metrics could not be recorded for this callback", {});
8757
+ return void 0;
8758
+ }
8759
+ };
7542
8760
  const rollupDeliveryToken = (identity) => {
7543
8761
  const token = ids.newOpaqueId(["usage-delivery", identity.scope, identity.callbackId]).replace(/[^A-Za-z0-9_-]/g, "").slice(0, 128);
7544
8762
  return token.length === 0 ? void 0 : token;
@@ -7659,6 +8877,11 @@ var createHookRuntime = (options) => {
7659
8877
  identity === void 0 ? void 0 : rollupDeliveryToken(identity)
7660
8878
  );
7661
8879
  }
8880
+ const metrics = !duplicateDelivery && ingest.identity !== void 0 && isCommittable(ingest.durability) ? await recordMetrics(
8881
+ ingest,
8882
+ identity === void 0 ? void 0 : rollupDeliveryToken(identity),
8883
+ diagnostics
8884
+ ) : void 0;
7662
8885
  if (owned && identity !== void 0) {
7663
8886
  try {
7664
8887
  if (isCommittable(ingest.durability)) {
@@ -7725,6 +8948,7 @@ var createHookRuntime = (options) => {
7725
8948
  duplicateDelivery,
7726
8949
  delivery,
7727
8950
  usageRollups,
8951
+ ...metrics === void 0 ? {} : { metrics },
7728
8952
  ...cleanup === void 0 ? {} : { cleanup },
7729
8953
  diagnostics
7730
8954
  };
@@ -7741,12 +8965,20 @@ var createHookRuntime = (options) => {
7741
8965
  () => runProcess(input, identified.identity, report, diagnostics)
7742
8966
  );
7743
8967
  };
7744
- const snapshots = () => sink.health();
8968
+ const snapshots = () => [
8969
+ ...sink.health(),
8970
+ ...metricDestinations.map((destination) => destination.metrics.health())
8971
+ ];
7745
8972
  let shutdownReport;
7746
8973
  const shutdown = () => {
7747
8974
  shutdownReport ??= (async () => {
7748
8975
  const raced = await Promise.race([
7749
- hook.shutdown().then(() => "completed"),
8976
+ Promise.all([
8977
+ hook.shutdown(),
8978
+ // Metric sinks are not behind the hook's sink: they replay their own
8979
+ // spools here, inside the same bounded window.
8980
+ ...metricDestinations.map((destination) => destination.metrics.shutdown().catch(() => void 0))
8981
+ ]).then(() => "completed"),
7750
8982
  delay(flushTimeoutMillis)
7751
8983
  ]);
7752
8984
  if (raced === "timeout") {
@@ -7776,6 +9008,7 @@ var createHookRuntime = (options) => {
7776
9008
  deduplicator,
7777
9009
  usageAccumulator,
7778
9010
  spanCorrelator,
9011
+ metricSeries,
7779
9012
  janitor,
7780
9013
  process: process_,
7781
9014
  shutdown,