@osfactory/otel-hook 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +108 -4
  2. package/dist/{adapter-B9RwW6TO.d.ts → adapter-DQiPu8xF.d.ts} +2 -2
  3. package/dist/cli.js +1495 -135
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +11 -4
  6. package/dist/config.js +116 -21
  7. package/dist/config.js.map +1 -1
  8. package/dist/{destinations-DWOkVxV1.d.ts → destinations-DvqsPulb.d.ts} +12 -2
  9. package/dist/diagnostics.d.ts +1 -1
  10. package/dist/diagnostics.js.map +1 -1
  11. package/dist/{events-CSD_YiJ2.d.ts → events-fcomX6d5.d.ts} +22 -0
  12. package/dist/{export-destinations-lORbe25J.d.ts → export-destinations-CI7z4n3i.d.ts} +136 -6
  13. package/dist/{filesystem-store-DX3dGIgu.d.ts → filesystem-store-CmnUlj1O.d.ts} +1 -1
  14. package/dist/{hook-BAxXoKsp.d.ts → hook-vM_cgqS2.d.ts} +11 -5
  15. package/dist/index.d.ts +16 -16
  16. package/dist/index.js +1496 -183
  17. package/dist/index.js.map +1 -1
  18. package/dist/install.d.ts +4 -4
  19. package/dist/install.js +9 -1
  20. package/dist/install.js.map +1 -1
  21. package/dist/integration.d.ts +36 -12
  22. package/dist/integration.js +1464 -231
  23. package/dist/integration.js.map +1 -1
  24. package/dist/lifecycle.d.ts +55 -4
  25. package/dist/lifecycle.js +279 -5
  26. package/dist/lifecycle.js.map +1 -1
  27. package/dist/{memory-aJilVG4R.d.ts → memory-DdU1U91y.d.ts} +2 -2
  28. package/dist/{semconv-Dw7gcQcg.d.ts → metric-model-C9lLqqpI.d.ts} +157 -2
  29. package/dist/model.d.ts +1 -1
  30. package/dist/model.js +9 -1
  31. package/dist/model.js.map +1 -1
  32. package/dist/{payload-D7gc0-WQ.d.ts → payload-BT19hiVZ.d.ts} +1 -1
  33. package/dist/{ports-plO5MKrY.d.ts → ports-C3k_5eOQ.d.ts} +57 -2
  34. package/dist/providers.d.ts +10 -10
  35. package/dist/providers.js +10 -1
  36. package/dist/providers.js.map +1 -1
  37. package/dist/{registry-C7XO4DzD.d.ts → registry-gyJqaWmp.d.ts} +2 -2
  38. package/dist/runtime.d.ts +97 -9
  39. package/dist/runtime.js +312 -33
  40. package/dist/runtime.js.map +1 -1
  41. package/dist/{schema-CHb3GU1r.d.ts → schema-SpFM6YQY.d.ts} +87 -1
  42. package/dist/state.d.ts +4 -4
  43. package/dist/state.js +32 -1
  44. package/dist/state.js.map +1 -1
  45. package/dist/telemetry.d.ts +6 -6
  46. package/dist/telemetry.js +929 -31
  47. package/dist/telemetry.js.map +1 -1
  48. package/dist/testing.d.ts +11 -9
  49. package/dist/testing.js +164 -33
  50. package/dist/testing.js.map +1 -1
  51. package/package.json +3 -1
package/dist/index.js CHANGED
@@ -833,7 +833,15 @@ var baseEventFields = {
833
833
  * factory, never by hand.
834
834
  */
835
835
  subagentId: subagentIdSchema.optional(),
836
- extensions: extensionsSchema.default(emptyExtensions)
836
+ extensions: extensionsSchema.default(emptyExtensions),
837
+ /**
838
+ * Attributes of the session context segment in force when the event
839
+ * occurred (`docs/session-context.md`), stamped by the core from a file a
840
+ * harness wrote. Exported on every record of the event, over the same keys
841
+ * from the Resource. Absent when no context applies. Set by the core only,
842
+ * never by an adapter.
843
+ */
844
+ contextAttributes: z9.record(z9.string().min(1).max(255), z9.union([z9.string(), z9.number(), z9.boolean()])).optional()
837
845
  };
838
846
  var event = (shape) => z9.strictObject({ ...baseEventFields, ...shape });
839
847
  var sessionStartEventSchema = event({
@@ -1352,11 +1360,11 @@ var createPrivacyService = (policyInput) => {
1352
1360
  };
1353
1361
  const flattenToAttributes = (value, prefix) => {
1354
1362
  const attributes = {};
1355
- const walk = (current, path10) => {
1363
+ const walk = (current, path11) => {
1356
1364
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
1357
1365
  const primitive = toAttributePrimitive(current);
1358
1366
  if (primitive !== void 0) {
1359
- attributes[path10] = primitive;
1367
+ attributes[path11] = primitive;
1360
1368
  }
1361
1369
  return;
1362
1370
  }
@@ -1375,16 +1383,16 @@ var createPrivacyService = (policyInput) => {
1375
1383
  primitives.push(entryPrimitive);
1376
1384
  }
1377
1385
  if (uniform) {
1378
- attributes[path10] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
1386
+ attributes[path11] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
1379
1387
  return;
1380
1388
  }
1381
1389
  for (const [index, entry] of current.entries()) {
1382
- walk(entry, `${path10}.${index}`);
1390
+ walk(entry, `${path11}.${index}`);
1383
1391
  }
1384
1392
  return;
1385
1393
  }
1386
1394
  for (const [key, entry] of Object.entries(current)) {
1387
- walk(entry, path10 === "" ? key : `${path10}.${key}`);
1395
+ walk(entry, path11 === "" ? key : `${path11}.${key}`);
1388
1396
  }
1389
1397
  };
1390
1398
  walk(value, prefix);
@@ -1683,6 +1691,7 @@ var sanitizeResourceAttributes = (attributes) => {
1683
1691
  var describeResourceAttributeNames = (attributes) => Object.keys(attributes).sort();
1684
1692
 
1685
1693
  // src/config/schema.ts
1694
+ import { isAbsolute } from "path";
1686
1695
  import { z as z14 } from "zod";
1687
1696
 
1688
1697
  // src/config/destinations.ts
@@ -1820,7 +1829,7 @@ var HEADER_ENV_REFERENCE_PREFIX = "env:";
1820
1829
  var HEADER_NAME_PATTERN2 = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
1821
1830
  var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
1822
1831
  var MAX_HEADER_VALUE_LENGTH = 8192;
1823
- var exportSignalSchema = z13.enum(["traces", "logs"]);
1832
+ var exportSignalSchema = z13.enum(["traces", "logs", "metrics"]);
1824
1833
  var headerValueSchema = z13.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
1825
1834
  (value) => !isUnsafeHeaderValue(value),
1826
1835
  "header values may not contain line breaks, control characters, or characters beyond Latin-1"
@@ -1843,6 +1852,8 @@ var exportDestinationSchema = z13.strictObject({
1843
1852
  tracesEndpoint: endpointSchema.optional(),
1844
1853
  /** Per-signal override of the derived logs URL. */
1845
1854
  logsEndpoint: endpointSchema.optional(),
1855
+ /** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */
1856
+ metricsEndpoint: endpointSchema.optional(),
1846
1857
  /** Defaults to `exporter.protocol`. */
1847
1858
  protocol: z13.enum(["http/protobuf", "http/json", "none"]).optional(),
1848
1859
  /**
@@ -1855,15 +1866,17 @@ var exportDestinationSchema = z13.strictObject({
1855
1866
  `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
1856
1867
  ).optional(),
1857
1868
  /**
1858
- * Which signals this destination receives. Default: both. The logs signal is
1859
- * still governed by `exporter.logs.enabled`, which stays the one opt-in for a
1860
- * second stream leaving the host.
1869
+ * Which signals this destination receives. Default: traces and logs. The logs
1870
+ * signal is still governed by `exporter.logs.enabled`, which stays the one
1871
+ * opt-in for content-bearing records leaving the host. `metrics` is never on by
1872
+ * default: a destination receives hook-derived metrics only when it lists them.
1861
1873
  */
1862
- signals: z13.array(exportSignalSchema).min(1).max(2).readonly().optional()
1874
+ signals: z13.array(exportSignalSchema).min(1).max(3).readonly().optional()
1863
1875
  }).refine(
1864
- (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0,
1865
- "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint"
1876
+ (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
1877
+ "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
1866
1878
  );
1879
+ var DEFAULT_DESTINATION_SIGNALS = Object.freeze(["traces", "logs"]);
1867
1880
  var exportDestinationsSchema = z13.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
1868
1881
  const seen = /* @__PURE__ */ new Set();
1869
1882
  destinations.forEach((destination, index) => {
@@ -1908,7 +1921,8 @@ var legacyDestination = (exporter) => ({
1908
1921
  protocol: exporter.protocol,
1909
1922
  ...exporter.endpoint === void 0 ? {} : { endpoint: exporter.endpoint },
1910
1923
  ...exporter.logs.endpoint === void 0 ? {} : { logsEndpoint: exporter.logs.endpoint },
1911
- signals: { traces: true, logs: exporter.logs.enabled },
1924
+ ...exporter.metrics?.endpoint === void 0 ? {} : { metricsEndpoint: exporter.metrics.endpoint },
1925
+ signals: { traces: true, logs: exporter.logs.enabled, metrics: exporter.metrics?.enabled === true },
1912
1926
  headers: {}
1913
1927
  });
1914
1928
  var hasConfiguredDestinations = (exporter) => exporter.destinations !== void 0 && exporter.destinations.length > 0;
@@ -1917,14 +1931,14 @@ var resolveExportDestinations = (exporter) => {
1917
1931
  return [legacyDestination(exporter)];
1918
1932
  }
1919
1933
  const resolved = [];
1920
- if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0) {
1934
+ if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0 || exporter.metrics?.endpoint !== void 0) {
1921
1935
  resolved.push(legacyDestination(exporter));
1922
1936
  }
1923
1937
  for (const destination of exporter.destinations ?? []) {
1924
1938
  if (destination.enabled === false) {
1925
1939
  continue;
1926
1940
  }
1927
- const signals = destination.signals ?? exportSignalSchema.options;
1941
+ const signals = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;
1928
1942
  resolved.push({
1929
1943
  name: destination.name,
1930
1944
  source: "destinations",
@@ -1932,9 +1946,11 @@ var resolveExportDestinations = (exporter) => {
1932
1946
  ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
1933
1947
  ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
1934
1948
  ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
1949
+ ...destination.metricsEndpoint === void 0 ? {} : { metricsEndpoint: destination.metricsEndpoint },
1935
1950
  signals: {
1936
1951
  traces: signals.includes("traces"),
1937
- logs: exporter.logs.enabled && signals.includes("logs")
1952
+ logs: exporter.logs.enabled && signals.includes("logs"),
1953
+ metrics: signals.includes("metrics")
1938
1954
  },
1939
1955
  headers: { ...destination.headers ?? {} }
1940
1956
  });
@@ -1976,6 +1992,9 @@ var describeExportDestinations = (exporter) => {
1976
1992
  const logsOrigin = endpointOrigin(
1977
1993
  destination.logsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint
1978
1994
  );
1995
+ const metricsOrigin = endpointOrigin(
1996
+ destination.metricsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint
1997
+ );
1979
1998
  const variables = Object.values(destination.headers).map(parseHeaderValueReference).flatMap((reference) => reference.kind === "env" ? [reference.variable] : []);
1980
1999
  return {
1981
2000
  name: destination.name,
@@ -1984,6 +2003,7 @@ var describeExportDestinations = (exporter) => {
1984
2003
  signals: exportSignalSchema.options.filter((signal) => destination.signals[signal]),
1985
2004
  ...tracesOrigin === void 0 || !destination.signals.traces ? {} : { tracesEndpointOrigin: tracesOrigin },
1986
2005
  ...logsOrigin === void 0 || !destination.signals.logs ? {} : { logsEndpointOrigin: logsOrigin },
2006
+ ...metricsOrigin === void 0 || !destination.signals.metrics ? {} : { metricsEndpointOrigin: metricsOrigin },
1987
2007
  headerNames: destination.source === "exporter" ? [...exporter.headerNames].sort() : Object.keys(destination.headers).sort(),
1988
2008
  headerVariables: [...new Set(variables)].sort()
1989
2009
  };
@@ -1998,7 +2018,7 @@ var describeExportDestinations = (exporter) => {
1998
2018
  source: "destinations",
1999
2019
  protocol: destination.protocol ?? exporter.protocol,
2000
2020
  ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
2001
- signals: { traces: false, logs: false },
2021
+ signals: { traces: false, logs: false, metrics: false },
2002
2022
  headers: { ...destination.headers ?? {} }
2003
2023
  },
2004
2024
  false
@@ -2025,6 +2045,18 @@ var DEFAULT_LOGS_POLICY = Object.freeze({
2025
2045
  includeContent: false,
2026
2046
  maxBatchSize: 128
2027
2047
  });
2048
+ var metricsPolicySchema = z14.strictObject({
2049
+ enabled: z14.boolean(),
2050
+ /** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */
2051
+ endpoint: z14.string().url().max(2048).optional(),
2052
+ temporality: z14.enum(["cumulative", "delta"]),
2053
+ includeSessionId: z14.boolean()
2054
+ });
2055
+ var DEFAULT_METRICS_POLICY = Object.freeze({
2056
+ enabled: false,
2057
+ temporality: "cumulative",
2058
+ includeSessionId: true
2059
+ });
2028
2060
  var exporterPolicySchema = z14.strictObject({
2029
2061
  enabled: z14.boolean(),
2030
2062
  protocol: z14.enum(["http/protobuf", "http/json", "none"]),
@@ -2055,6 +2087,11 @@ var exporterPolicySchema = z14.strictObject({
2055
2087
  * a second top-level section would invite two of each to drift apart.
2056
2088
  */
2057
2089
  logs: logsPolicySchema,
2090
+ /**
2091
+ * Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before
2092
+ * metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.
2093
+ */
2094
+ metrics: metricsPolicySchema.optional(),
2058
2095
  /**
2059
2096
  * Additional OTLP destinations, each sent every batch in parallel.
2060
2097
  *
@@ -2091,20 +2128,27 @@ var providersPolicySchema = z14.strictObject({
2091
2128
  readTranscriptUsage: z14.boolean()
2092
2129
  }).optional()
2093
2130
  });
2131
+ var sessionContextPolicySchema = z14.strictObject({
2132
+ /** Absolute path of the context directory. */
2133
+ dir: z14.string().min(1).max(4096).refine((value) => isAbsolute(value), { message: "must be an absolute path" })
2134
+ });
2094
2135
  var otelHookConfigSchema = z14.strictObject({
2095
2136
  exporter: exporterPolicySchema,
2096
2137
  privacy: privacyPolicySchema,
2097
2138
  detection: detectionPolicySchema,
2098
2139
  diagnostics: diagnosticsPolicySchema,
2099
2140
  /** Optional so a hand-built configuration from before it existed stays valid. */
2100
- providers: providersPolicySchema.optional()
2141
+ providers: providersPolicySchema.optional(),
2142
+ /** Optional: absent means no session context is read. */
2143
+ sessionContext: sessionContextPolicySchema.optional()
2101
2144
  });
2102
2145
  var otelHookConfigPatchSchema = z14.strictObject({
2103
2146
  // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
2104
2147
  // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
2105
2148
  // without also restating the endpoint and the batch size.
2106
- exporter: exporterPolicySchema.omit({ logs: true, spool: true }).partial().extend({
2149
+ exporter: exporterPolicySchema.omit({ logs: true, metrics: true, spool: true }).partial().extend({
2107
2150
  logs: logsPolicySchema.partial().optional(),
2151
+ metrics: metricsPolicySchema.partial().optional(),
2108
2152
  spool: spoolPolicySchema.partial().optional()
2109
2153
  }).optional(),
2110
2154
  privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
@@ -2112,7 +2156,8 @@ var otelHookConfigPatchSchema = z14.strictObject({
2112
2156
  diagnostics: diagnosticsPolicySchema.partial().optional(),
2113
2157
  providers: z14.strictObject({
2114
2158
  claudeCode: z14.strictObject({ readTranscriptUsage: z14.boolean() }).partial().optional()
2115
- }).partial().optional()
2159
+ }).partial().optional(),
2160
+ sessionContext: sessionContextPolicySchema.partial().optional()
2116
2161
  });
2117
2162
  var DEFAULT_EXPORTER_POLICY = Object.freeze({
2118
2163
  enabled: true,
@@ -2124,7 +2169,8 @@ var DEFAULT_EXPORTER_POLICY = Object.freeze({
2124
2169
  maxRetryAttempts: 2,
2125
2170
  serviceName: "coding-agent",
2126
2171
  resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
2127
- logs: DEFAULT_LOGS_POLICY
2172
+ logs: DEFAULT_LOGS_POLICY,
2173
+ metrics: DEFAULT_METRICS_POLICY
2128
2174
  });
2129
2175
  var DEFAULT_DETECTION_POLICY = Object.freeze({
2130
2176
  minimumConfidence: "strong",
@@ -2146,18 +2192,23 @@ var DEFAULT_CONFIG = Object.freeze({
2146
2192
  providers: DEFAULT_PROVIDERS_POLICY
2147
2193
  });
2148
2194
  var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
2195
+ var sessionContextDir = (config) => config.sessionContext?.dir;
2196
+ var effectiveMetricsPolicy = (exporter) => ({
2197
+ ...DEFAULT_METRICS_POLICY,
2198
+ ...exporter.metrics ?? {}
2199
+ });
2149
2200
 
2150
2201
  // src/config/resolve.ts
2151
2202
  import { z as z15 } from "zod";
2152
2203
  var CONFIG_SOURCE_PRECEDENCE = ["defaults", "file", "environment", "inline-override"];
2153
2204
  var configSourceSchema = z15.enum(CONFIG_SOURCE_PRECEDENCE);
2154
2205
  var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2155
- var mergeLeaf = (target, patch, source, provenance, path10) => {
2206
+ var mergeLeaf = (target, patch, source, provenance, path11) => {
2156
2207
  for (const [key, value] of Object.entries(patch)) {
2157
2208
  if (value === void 0) {
2158
2209
  continue;
2159
2210
  }
2160
- const childPath = path10 === "" ? key : `${path10}.${key}`;
2211
+ const childPath = path11 === "" ? key : `${path11}.${key}`;
2161
2212
  const existing = target[key];
2162
2213
  if (isPlainObject(value) && (isPlainObject(existing) || existing === void 0)) {
2163
2214
  const child = { ...existing ?? {} };
@@ -2171,14 +2222,14 @@ var mergeLeaf = (target, patch, source, provenance, path10) => {
2171
2222
  };
2172
2223
  var initialProvenance = (config) => {
2173
2224
  const provenance = {};
2174
- const walk = (value, path10) => {
2225
+ const walk = (value, path11) => {
2175
2226
  if (isPlainObject(value)) {
2176
2227
  for (const [key, child] of Object.entries(value)) {
2177
- walk(child, path10 === "" ? key : `${path10}.${key}`);
2228
+ walk(child, path11 === "" ? key : `${path11}.${key}`);
2178
2229
  }
2179
2230
  return;
2180
2231
  }
2181
- provenance[path10] = "defaults";
2232
+ provenance[path11] = "defaults";
2182
2233
  };
2183
2234
  walk(config, "");
2184
2235
  return provenance;
@@ -2257,6 +2308,11 @@ var resolveConfig = (layers = []) => {
2257
2308
  "exporter.logs.enabled is true but neither a logs endpoint nor a trace endpoint to derive one from is configured"
2258
2309
  );
2259
2310
  }
2311
+ if (!withDestinations && parsed.data.exporter.metrics?.enabled === true && parsed.data.exporter.metrics.endpoint === void 0 && parsed.data.exporter.endpoint === void 0) {
2312
+ notes.push(
2313
+ "exporter.metrics.enabled is true but neither a metrics endpoint nor a trace endpoint to derive one from is configured"
2314
+ );
2315
+ }
2260
2316
  if (parsed.data.exporter.logs.includeContent && parsed.data.privacy.contentMode === "omit") {
2261
2317
  notes.push(
2262
2318
  "exporter.logs.includeContent is true but privacy.contentMode is omit, so no content is disclosed to describe"
@@ -2288,6 +2344,9 @@ var describeDestinationAttributes = (config) => {
2288
2344
  if (destination.logsEndpointOrigin !== void 0) {
2289
2345
  attributes[`${prefix}.logs_endpoint_origin`] = destination.logsEndpointOrigin;
2290
2346
  }
2347
+ if (destination.metricsEndpointOrigin !== void 0) {
2348
+ attributes[`${prefix}.metrics_endpoint_origin`] = destination.metricsEndpointOrigin;
2349
+ }
2291
2350
  attributes[`${prefix}.header_names`] = [...destination.headerNames];
2292
2351
  attributes[`${prefix}.header_variables`] = [...destination.headerVariables];
2293
2352
  }
@@ -2306,6 +2365,8 @@ var describeResolvedConfig = (config) => {
2306
2365
  };
2307
2366
  const endpointOrigin2 = originOf(config.exporter.endpoint);
2308
2367
  const logsEndpointOrigin = originOf(config.exporter.logs.endpoint);
2368
+ const metrics = effectiveMetricsPolicy(config.exporter);
2369
+ const metricsEndpointOrigin = originOf(metrics.endpoint);
2309
2370
  return {
2310
2371
  "exporter.enabled": config.exporter.enabled,
2311
2372
  "exporter.protocol": config.exporter.protocol,
@@ -2314,6 +2375,10 @@ var describeResolvedConfig = (config) => {
2314
2375
  "exporter.logs_include_content": config.exporter.logs.includeContent,
2315
2376
  "exporter.logs_max_batch_size": config.exporter.logs.maxBatchSize,
2316
2377
  ...logsEndpointOrigin === void 0 ? {} : { "exporter.logs_endpoint_origin": logsEndpointOrigin },
2378
+ "exporter.metrics_enabled": metrics.enabled,
2379
+ "exporter.metrics_temporality": metrics.temporality,
2380
+ "exporter.metrics_include_session_id": metrics.includeSessionId,
2381
+ ...metricsEndpointOrigin === void 0 ? {} : { "exporter.metrics_endpoint_origin": metricsEndpointOrigin },
2317
2382
  "exporter.header_names": [...config.exporter.headerNames],
2318
2383
  // Names only. A resource attribute *name* is already on the wire in every
2319
2384
  // exported resource, so disclosing it here adds nothing; a *value* may hold
@@ -2335,7 +2400,9 @@ var describeResolvedConfig = (config) => {
2335
2400
  "detection.minimum_confidence": config.detection.minimumConfidence,
2336
2401
  "detection.allow_ambiguous_fallback": config.detection.allowAmbiguousFallback,
2337
2402
  "diagnostics.log_level": config.diagnostics.logLevel,
2338
- "diagnostics.emit_error_events": config.diagnostics.emitErrorEvents
2403
+ "diagnostics.emit_error_events": config.diagnostics.emitErrorEvents,
2404
+ // Whether, never where: the directory is a local path.
2405
+ "session_context.enabled": config.sessionContext?.dir !== void 0
2339
2406
  };
2340
2407
  };
2341
2408
 
@@ -2343,10 +2410,17 @@ var describeResolvedConfig = (config) => {
2343
2410
  var OTLP_ENDPOINT_VARIABLES = Object.freeze({
2344
2411
  generic: "OTEL_EXPORTER_OTLP_ENDPOINT",
2345
2412
  traces: "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
2346
- logs: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT"
2413
+ logs: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
2414
+ metrics: "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"
2347
2415
  });
2348
2416
  var OTLP_TRACES_PATH = "/v1/traces";
2349
2417
  var OTLP_LOGS_PATH = "/v1/logs";
2418
+ var OTLP_METRICS_PATH = "/v1/metrics";
2419
+ var SIGNAL_PATHS = Object.freeze({
2420
+ traces: OTLP_TRACES_PATH,
2421
+ logs: OTLP_LOGS_PATH,
2422
+ metrics: OTLP_METRICS_PATH
2423
+ });
2350
2424
  var withoutTrailingSlashes = (value) => {
2351
2425
  let end = value.length;
2352
2426
  while (end > 0 && value.charCodeAt(end - 1) === 47) {
@@ -2357,9 +2431,20 @@ var withoutTrailingSlashes = (value) => {
2357
2431
  var otlpSignalEndpointFromBase = (base, signal) => {
2358
2432
  const trimmed = withoutTrailingSlashes(base);
2359
2433
  if (trimmed.endsWith(OTLP_TRACES_PATH)) {
2360
- return signal === "traces" ? trimmed : `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${OTLP_LOGS_PATH}`;
2434
+ return signal === "traces" ? trimmed : `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${SIGNAL_PATHS[signal]}`;
2435
+ }
2436
+ return `${trimmed}${SIGNAL_PATHS[signal]}`;
2437
+ };
2438
+ var siblingSignalEndpoint = (tracesEndpoint, signal) => {
2439
+ const trimmed = withoutTrailingSlashes(tracesEndpoint);
2440
+ const target = SIGNAL_PATHS[signal];
2441
+ if (trimmed.endsWith(target)) {
2442
+ return trimmed;
2443
+ }
2444
+ if (trimmed.endsWith(OTLP_TRACES_PATH)) {
2445
+ return `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${target}`;
2361
2446
  }
2362
- return `${trimmed}${signal === "traces" ? OTLP_TRACES_PATH : OTLP_LOGS_PATH}`;
2447
+ return `${trimmed}${target}`;
2363
2448
  };
2364
2449
 
2365
2450
  // src/config/environment.ts
@@ -2380,6 +2465,12 @@ var ENVIRONMENT_VARIABLES = Object.freeze({
2380
2465
  /** Standard per-signal endpoint; the weaker source of the two. */
2381
2466
  otlpLogsEndpoint: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
2382
2467
  logsIncludeContent: "OTEL_HOOK_LOGS_INCLUDE_CONTENT",
2468
+ metricsEnabled: "OTEL_HOOK_METRICS_ENABLED",
2469
+ metricsEndpoint: "OTEL_HOOK_METRICS_ENDPOINT",
2470
+ /** Standard per-signal endpoint; the weaker source of the two. */
2471
+ otlpMetricsEndpoint: "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT",
2472
+ /** Standard: `cumulative`, `delta`, or `lowmemory` (read as `delta` here). */
2473
+ otlpMetricsTemporality: "OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE",
2383
2474
  serviceName: "OTEL_HOOK_SERVICE_NAME",
2384
2475
  otlpServiceName: "OTEL_SERVICE_NAME",
2385
2476
  serviceNamespace: "OTEL_HOOK_SERVICE_NAMESPACE",
@@ -2542,6 +2633,22 @@ var parseEnvironmentConfig = (env) => {
2542
2633
  ...logsEndpoint === void 0 ? {} : { endpoint: logsEndpoint },
2543
2634
  ...logsIncludeContent === void 0 ? {} : { includeContent: logsIncludeContent }
2544
2635
  };
2636
+ const metricsEnabled = readBoolean(ENVIRONMENT_VARIABLES.metricsEnabled);
2637
+ const metricsEndpoint = readString(ENVIRONMENT_VARIABLES.metricsEndpoint) ?? readString(ENVIRONMENT_VARIABLES.otlpMetricsEndpoint) ?? (hookEndpoint === void 0 && otlpTracesEndpoint !== void 0 && otlpBaseEndpoint !== void 0 ? otlpSignalEndpointFromBase(otlpBaseEndpoint, "metrics") : void 0);
2638
+ const temporalityRaw = readString(ENVIRONMENT_VARIABLES.otlpMetricsTemporality)?.toLowerCase();
2639
+ let metricsTemporality;
2640
+ if (temporalityRaw === "cumulative") {
2641
+ metricsTemporality = "cumulative";
2642
+ } else if (temporalityRaw === "delta" || temporalityRaw === "lowmemory") {
2643
+ metricsTemporality = "delta";
2644
+ } else if (temporalityRaw !== void 0) {
2645
+ warn(ENVIRONMENT_VARIABLES.otlpMetricsTemporality, "expected cumulative, delta, or lowmemory");
2646
+ }
2647
+ const metrics = {
2648
+ ...metricsEnabled === void 0 ? {} : { enabled: metricsEnabled },
2649
+ ...metricsEndpoint === void 0 ? {} : { endpoint: metricsEndpoint },
2650
+ ...metricsTemporality === void 0 ? {} : { temporality: metricsTemporality }
2651
+ };
2545
2652
  const otlpHeaders = resolveOtlpHeaders(env);
2546
2653
  for (const { variable, detail } of otlpHeaders.warnings) {
2547
2654
  warn(variable, detail);
@@ -2556,7 +2663,8 @@ var parseEnvironmentConfig = (env) => {
2556
2663
  ...serviceName === void 0 ? {} : { serviceName },
2557
2664
  ...serviceNamespace === void 0 ? {} : { serviceNamespace },
2558
2665
  ...Object.keys(resourceAttributes).length === 0 ? {} : { resourceAttributes },
2559
- ...Object.keys(logs).length === 0 ? {} : { logs }
2666
+ ...Object.keys(logs).length === 0 ? {} : { logs },
2667
+ ...Object.keys(metrics).length === 0 ? {} : { metrics }
2560
2668
  };
2561
2669
  const limits = {
2562
2670
  ...maxStringLength === void 0 ? {} : { maxStringLength },
@@ -2746,6 +2854,7 @@ var createEventFactory = (input) => {
2746
2854
  const rest = { ...drafted };
2747
2855
  delete rest.target;
2748
2856
  delete rest.subagentId;
2857
+ delete rest.contextAttributes;
2749
2858
  const sanitized = extensions === void 0 ? { extensions: {}, droppedKeys: [] } : context.privacy.sanitizeExtensions(extensions);
2750
2859
  dropped.push(...sanitized.droppedKeys);
2751
2860
  const currentSequence = sequence;
@@ -6938,6 +7047,29 @@ var stateValueSchema = z22.discriminatedUnion("kind", [
6938
7047
  * (Claude Code's transcript), so the next read starts where the last ended.
6939
7048
  * `source` is an opaque digest of what was read, never a path.
6940
7049
  */
7050
+ /**
7051
+ * Running state of one metric series (issue #69), so a cumulative data point
7052
+ * exported by a later hook process continues the same total. Holds numbers and
7053
+ * a series digest only; the series' attributes are re-supplied by the caller
7054
+ * and never read back from disk.
7055
+ */
7056
+ z22.strictObject({
7057
+ kind: z22.literal("metric-series"),
7058
+ /** Start of the cumulative interval. */
7059
+ startTimeMillis: epochMillisSchema,
7060
+ /** Counters: the running total. */
7061
+ value: z22.number().finite().min(0).optional(),
7062
+ /** Histograms: the running aggregation. */
7063
+ histogram: z22.strictObject({
7064
+ count: z22.number().int().min(0),
7065
+ sum: z22.number().finite().min(0),
7066
+ min: z22.number().finite(),
7067
+ max: z22.number().finite(),
7068
+ bucketCounts: z22.array(z22.number().int().min(0)).max(64)
7069
+ }).optional(),
7070
+ /** Opaque digest of the last delivery folded in; makes a replay a no-op. */
7071
+ appliedDelivery: z22.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional()
7072
+ }),
6941
7073
  z22.strictObject({
6942
7074
  kind: z22.literal("read-cursor"),
6943
7075
  source: z22.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
@@ -7222,7 +7354,7 @@ var resolveDeliveryIdentity = (input) => {
7222
7354
  };
7223
7355
 
7224
7356
  // src/runtime/hook.ts
7225
- import { z as z23 } from "zod";
7357
+ import { z as z24 } from "zod";
7226
7358
 
7227
7359
  // src/runtime/target-resolution.ts
7228
7360
  import * as path2 from "path";
@@ -7391,8 +7523,200 @@ var withOptionalSessionLock = async (store, sessionId, fn, options) => {
7391
7523
  return fn();
7392
7524
  };
7393
7525
 
7526
+ // src/runtime/session-context.ts
7527
+ import { open as open2 } from "fs/promises";
7528
+ import * as path3 from "path";
7529
+ import { z as z23 } from "zod";
7530
+ var SESSION_CONTEXT_FILE_VERSION = 1;
7531
+ var DEFAULT_SESSION_CONTEXT_MAX_BYTES = 256 * 1024;
7532
+ var DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS = 100;
7533
+ var MAX_SESSION_CONTEXT_SEGMENTS = 1024;
7534
+ var SESSION_CONTEXT_AGENT_TOOLS = Object.freeze({
7535
+ "claude-code": "claude_code",
7536
+ codex: "codex",
7537
+ cursor: "cursor",
7538
+ "gemini-cli": "gemini_cli",
7539
+ antigravity: "antigravity"
7540
+ });
7541
+ var sessionContextAgentTool = (providerId) => Object.hasOwn(SESSION_CONTEXT_AGENT_TOOLS, providerId) ? SESSION_CONTEXT_AGENT_TOOLS[providerId] : void 0;
7542
+ var SESSION_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
7543
+ var isSessionContextFileName = (sessionId) => SESSION_FILE_NAME_PATTERN.test(sessionId) && !sessionId.includes("..");
7544
+ var sessionContextFilePath = (dir, providerId, sessionId) => {
7545
+ const tool = sessionContextAgentTool(providerId);
7546
+ if (tool === void 0 || !isSessionContextFileName(sessionId) || !path3.isAbsolute(dir)) {
7547
+ return void 0;
7548
+ }
7549
+ return path3.join(dir, tool, `${sessionId}.json`);
7550
+ };
7551
+ var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([
7552
+ "session.id",
7553
+ "trace_id",
7554
+ "span_id",
7555
+ "parent_span_id",
7556
+ "gen_ai.conversation.id",
7557
+ "factory.local"
7558
+ ]);
7559
+ var RESERVED_CONTEXT_PREFIXES = Object.freeze(["factory.local.", "otelhook."]);
7560
+ var isReservedSessionContextKey = (key) => RESERVED_CONTEXT_KEYS.has(key) || RESERVED_CONTEXT_PREFIXES.some((prefix) => key.startsWith(prefix));
7561
+ var sanitizeSessionContextAttributes = (attributes) => {
7562
+ const kept = {};
7563
+ let count = 0;
7564
+ for (const [key, value] of Object.entries(attributes)) {
7565
+ if (count >= MAX_RESOURCE_ATTRIBUTES) {
7566
+ break;
7567
+ }
7568
+ if (checkResourceAttributeKey(key) !== void 0 || isReservedSessionContextKey(key)) {
7569
+ continue;
7570
+ }
7571
+ if (typeof value === "string") {
7572
+ if (value.length > MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) {
7573
+ continue;
7574
+ }
7575
+ } else if (typeof value === "number") {
7576
+ if (!Number.isFinite(value)) {
7577
+ continue;
7578
+ }
7579
+ } else if (typeof value !== "boolean") {
7580
+ continue;
7581
+ }
7582
+ kept[key] = value;
7583
+ count += 1;
7584
+ }
7585
+ return kept;
7586
+ };
7587
+ 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})$/;
7588
+ var isoInstantSchema = z23.string().max(64).regex(ISO_INSTANT_PATTERN).transform((value, ctx) => {
7589
+ const millis = Date.parse(value);
7590
+ if (!Number.isFinite(millis)) {
7591
+ ctx.issues.push({ code: "custom", input: value, message: "not a valid instant" });
7592
+ return z23.NEVER;
7593
+ }
7594
+ return millis;
7595
+ });
7596
+ var segmentSchema = z23.object({
7597
+ from: isoInstantSchema,
7598
+ to: isoInstantSchema.nullable(),
7599
+ reason: z23.string().max(256).optional(),
7600
+ attributes: z23.record(z23.string(), z23.unknown())
7601
+ });
7602
+ var sessionContextFileSchema = z23.object({
7603
+ version: z23.literal(SESSION_CONTEXT_FILE_VERSION),
7604
+ agentTool: z23.string().max(64).optional(),
7605
+ sessionId: z23.string().max(256).optional(),
7606
+ segments: z23.array(segmentSchema).max(MAX_SESSION_CONTEXT_SEGMENTS)
7607
+ });
7608
+ var parseSessionContextFile = (value, expected) => {
7609
+ const parsed = sessionContextFileSchema.safeParse(value);
7610
+ if (!parsed.success) {
7611
+ return void 0;
7612
+ }
7613
+ const file = parsed.data;
7614
+ 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) {
7615
+ return void 0;
7616
+ }
7617
+ return file.segments.map((segment) => ({
7618
+ from: segment.from,
7619
+ to: segment.to,
7620
+ attributes: sanitizeSessionContextAttributes(segment.attributes)
7621
+ }));
7622
+ };
7623
+ var segmentInForce = (segments, at) => {
7624
+ let best;
7625
+ for (const segment of segments) {
7626
+ if (segment.from <= at && (segment.to === null || at < segment.to)) {
7627
+ if (best === void 0 || segment.from >= best.from) {
7628
+ best = segment;
7629
+ }
7630
+ }
7631
+ }
7632
+ return best;
7633
+ };
7634
+ var stampSessionContext = (events, segments) => events.map((event3) => {
7635
+ const { contextAttributes: _discarded, ...rest } = event3;
7636
+ const segment = segments === void 0 ? void 0 : segmentInForce(segments, event3.occurredAt);
7637
+ if (segment === void 0 || Object.keys(segment.attributes).length === 0) {
7638
+ return _discarded === void 0 ? event3 : rest;
7639
+ }
7640
+ return { ...rest, contextAttributes: { ...segment.attributes } };
7641
+ });
7642
+ var readBounded = async (file, maxBytes) => {
7643
+ let handle;
7644
+ try {
7645
+ handle = await open2(file, "r");
7646
+ } catch {
7647
+ return void 0;
7648
+ }
7649
+ try {
7650
+ const stats = await handle.stat();
7651
+ if (!stats.isFile() || stats.size > maxBytes) {
7652
+ return void 0;
7653
+ }
7654
+ const buffer = Buffer.alloc(maxBytes + 1);
7655
+ let length = 0;
7656
+ while (length < buffer.length) {
7657
+ const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
7658
+ if (bytesRead === 0) {
7659
+ break;
7660
+ }
7661
+ length += bytesRead;
7662
+ }
7663
+ if (length > maxBytes) {
7664
+ return void 0;
7665
+ }
7666
+ return buffer.subarray(0, length).toString("utf8");
7667
+ } catch {
7668
+ return void 0;
7669
+ } finally {
7670
+ await handle.close().catch(() => void 0);
7671
+ }
7672
+ };
7673
+ var createDirectorySessionContextReader = (options) => {
7674
+ const maxBytes = options.maxBytes ?? DEFAULT_SESSION_CONTEXT_MAX_BYTES;
7675
+ const budgetMillis = options.budgetMillis ?? DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS;
7676
+ const readOnce = async (providerId, sessionId) => {
7677
+ const file = sessionContextFilePath(options.dir, providerId, sessionId);
7678
+ if (file === void 0) {
7679
+ return void 0;
7680
+ }
7681
+ const text = await readBounded(file, maxBytes);
7682
+ if (text === void 0) {
7683
+ return void 0;
7684
+ }
7685
+ let decoded;
7686
+ try {
7687
+ decoded = JSON.parse(text);
7688
+ } catch {
7689
+ return void 0;
7690
+ }
7691
+ const agentTool = sessionContextAgentTool(providerId);
7692
+ return parseSessionContextFile(decoded, {
7693
+ ...agentTool === void 0 ? {} : { agentTool },
7694
+ sessionId
7695
+ });
7696
+ };
7697
+ return {
7698
+ read: async (request) => {
7699
+ let timer;
7700
+ const timeout = new Promise((resolve5) => {
7701
+ timer = setTimeout(() => resolve5(void 0), budgetMillis);
7702
+ timer.unref?.();
7703
+ });
7704
+ try {
7705
+ return await Promise.race([
7706
+ readOnce(request.providerId, request.sessionId).catch(() => void 0),
7707
+ timeout
7708
+ ]);
7709
+ } finally {
7710
+ if (timer !== void 0) {
7711
+ clearTimeout(timer);
7712
+ }
7713
+ }
7714
+ }
7715
+ };
7716
+ };
7717
+
7394
7718
  // src/runtime/hook.ts
7395
- var usageScopeSchema = z23.enum(["session", "generation", "subagent"]);
7719
+ var usageScopeSchema = z24.enum(["session", "generation", "subagent"]);
7396
7720
  var classifyDurability = (input) => {
7397
7721
  if (!input.attempted) {
7398
7722
  return "nothing-to-deliver";
@@ -8101,6 +8425,10 @@ var createOtelHook = (deps) => {
8101
8425
  });
8102
8426
  }
8103
8427
  }
8428
+ batch = stampSessionContext(
8429
+ batch,
8430
+ !suppress && batch.length > 0 && deps.sessionContext !== void 0 ? await readSessionContext(deps.sessionContext, detection.providerId, identity.sessionId) : void 0
8431
+ );
8104
8432
  let emitted = 0;
8105
8433
  let exportRejected = 0;
8106
8434
  if (!suppress && batch.length > 0) {
@@ -8216,6 +8544,13 @@ var createOtelHook = (deps) => {
8216
8544
  };
8217
8545
  return { resolveDelivery, ingest, flush, shutdown, config };
8218
8546
  };
8547
+ var readSessionContext = async (reader, providerId, sessionId) => {
8548
+ try {
8549
+ return await reader.read({ providerId, sessionId });
8550
+ } catch {
8551
+ return void 0;
8552
+ }
8553
+ };
8219
8554
  var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
8220
8555
  const events = [];
8221
8556
  for (const [index, info] of diagnostics.slice(0, MAX_ERROR_EVENTS).entries()) {
@@ -8250,8 +8585,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
8250
8585
  };
8251
8586
 
8252
8587
  // src/runtime/git-worktree.ts
8253
- import { lstat, open as open2, stat as stat2 } from "fs/promises";
8254
- import * as path3 from "path";
8588
+ import { lstat, open as open3, stat as stat2 } from "fs/promises";
8589
+ import * as path4 from "path";
8255
8590
  var MAX_WORKTREE_WALK_DEPTH = 128;
8256
8591
  var MAX_GIT_FILE_BYTES = 4096;
8257
8592
  var MAX_CACHE_ENTRIES = 1024;
@@ -8259,10 +8594,10 @@ var DEFAULT_WORKTREE_CACHE_TTL_MILLIS = 5e3;
8259
8594
  var MAX_BRANCH_NAME_LENGTH = 255;
8260
8595
  var ABSENT = Object.freeze({ kind: "absent" });
8261
8596
  var INVALID = Object.freeze({ kind: "invalid" });
8262
- var readBounded = async (filePath) => {
8597
+ var readBounded2 = async (filePath) => {
8263
8598
  let handle;
8264
8599
  try {
8265
- handle = await open2(filePath, "r");
8600
+ handle = await open3(filePath, "r");
8266
8601
  const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
8267
8602
  const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
8268
8603
  return buffer.subarray(0, bytesRead).toString("utf8");
@@ -8283,7 +8618,7 @@ var parseHeadBranch = (head) => {
8283
8618
  return branch;
8284
8619
  };
8285
8620
  var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
8286
- var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path3.resolve(base, target);
8621
+ var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path4.resolve(base, target);
8287
8622
  var parseGitDirFile = (content, worktreeRoot) => {
8288
8623
  const line = firstLine(content);
8289
8624
  return resolveGitPath(
@@ -8309,17 +8644,17 @@ var isDirectory = async (directory) => {
8309
8644
  }
8310
8645
  };
8311
8646
  var repositoryOf = async (worktreeRoot, gitDir) => {
8312
- const commonDirFile = path3.join(gitDir, "commondir");
8313
- const content = await readBounded(commonDirFile);
8647
+ const commonDirFile = path4.join(gitDir, "commondir");
8648
+ const content = await readBounded2(commonDirFile);
8314
8649
  if (content === void 0) {
8315
8650
  return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
8316
8651
  }
8317
8652
  const commonDir = parseCommonDirFile(content, gitDir);
8318
- const mainRoot = commonDir !== void 0 && path3.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path3.dirname(commonDir) : void 0;
8653
+ const mainRoot = commonDir !== void 0 && path4.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path4.dirname(commonDir) : void 0;
8319
8654
  return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
8320
8655
  };
8321
8656
  var probeDirectory = async (directory) => {
8322
- const dotGit = path3.join(directory, ".git");
8657
+ const dotGit = path4.join(directory, ".git");
8323
8658
  let info;
8324
8659
  try {
8325
8660
  info = await stat2(dotGit);
@@ -8330,13 +8665,13 @@ var probeDirectory = async (directory) => {
8330
8665
  if (info.isDirectory()) {
8331
8666
  gitDir = dotGit;
8332
8667
  } else if (info.isFile()) {
8333
- const content = await readBounded(dotGit);
8668
+ const content = await readBounded2(dotGit);
8334
8669
  gitDir = content === void 0 ? void 0 : parseGitDirFile(content, directory);
8335
8670
  }
8336
8671
  if (gitDir === void 0) {
8337
8672
  return INVALID;
8338
8673
  }
8339
- const head = await readBounded(path3.join(gitDir, "HEAD"));
8674
+ const head = await readBounded2(path4.join(gitDir, "HEAD"));
8340
8675
  if (head === void 0) {
8341
8676
  return INVALID;
8342
8677
  }
@@ -8366,10 +8701,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
8366
8701
  };
8367
8702
  const locate = async (absolutePath) => {
8368
8703
  try {
8369
- if (!path3.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
8704
+ if (!path4.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
8370
8705
  return void 0;
8371
8706
  }
8372
- let directory = path3.resolve(absolutePath);
8707
+ let directory = path4.resolve(absolutePath);
8373
8708
  for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
8374
8709
  const probe = await cachedProbe(directory);
8375
8710
  if (probe.kind === "worktree") {
@@ -8378,7 +8713,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
8378
8713
  if (probe.kind === "invalid") {
8379
8714
  return void 0;
8380
8715
  }
8381
- const parent = path3.dirname(directory);
8716
+ const parent = path4.dirname(directory);
8382
8717
  if (parent === directory) {
8383
8718
  return void 0;
8384
8719
  }
@@ -8418,6 +8753,8 @@ var rollupUsageKey = (sessionId, scope, scopeKey) => `${rollupScanPrefix(session
8418
8753
  var rollupEpochKey = (sessionId, scope, scopeKey) => `${rollupEpochScanPrefix(sessionId)}${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;
8419
8754
  var rollupScanPrefix = (sessionId) => sessionId === void 0 ? `${LIFECYCLE_PREFIX}:usage:` : `${LIFECYCLE_PREFIX}:usage:${encodeSegment(sessionId)}:`;
8420
8755
  var rollupEpochScanPrefix = (sessionId) => sessionId === void 0 ? `${LIFECYCLE_PREFIX}:epoch:` : `${LIFECYCLE_PREFIX}:epoch:${encodeSegment(sessionId)}:`;
8756
+ var metricSeriesKey = (sessionScope2, seriesDigest) => `${metricSeriesScanPrefix(sessionScope2)}${encodeSegment(seriesDigest)}`;
8757
+ var metricSeriesScanPrefix = (sessionScope2) => sessionScope2 === void 0 ? `${LIFECYCLE_PREFIX}:metric:v1:` : `${LIFECYCLE_PREFIX}:metric:v1:${encodeSegment(sessionScope2)}:`;
8421
8758
 
8422
8759
  // src/lifecycle/dedup.ts
8423
8760
  var DEFAULT_STALE_CLAIM_MILLIS = 6e4;
@@ -8607,7 +8944,7 @@ import {
8607
8944
  } from "@opentelemetry/semantic-conventions/incubating";
8608
8945
 
8609
8946
  // src/version.ts
8610
- var VERSION = "0.10.0";
8947
+ var VERSION = "0.12.0";
8611
8948
 
8612
8949
  // src/telemetry/export-identity.ts
8613
8950
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -8660,6 +8997,11 @@ var passthroughResourceAttributes = (resource) => {
8660
8997
  }
8661
8998
  return attributes;
8662
8999
  };
9000
+ var contextAttributesOf = (event3) => event3.contextAttributes === void 0 ? {} : { ...event3.contextAttributes };
9001
+ var profileAttributes = (event3, resource) => ({
9002
+ ...passthroughResourceAttributes(resource),
9003
+ ...contextAttributesOf(event3)
9004
+ });
8663
9005
  var resolveExportedSessionId = (eventSessionId, resource) => {
8664
9006
  for (const key of EXTERNAL_SESSION_KEY_ATTRIBUTES) {
8665
9007
  const supplied = resource.attributes[key];
@@ -8680,6 +9022,8 @@ var hexTraceAttributes = (ids) => ({
8680
9022
  var exportIdentityAttributes = (event3, resource, ids) => {
8681
9023
  const { sessionId, providerSessionId } = resolveExportedSessionId(event3.sessionId, resource);
8682
9024
  return {
9025
+ // First, so nothing in the profile layer can replace an identity attribute.
9026
+ ...profileAttributes(event3, resource),
8683
9027
  [ATTR_SESSION_ID]: sessionId,
8684
9028
  [ATTR_OTELHOOK_SESSION_ID]: providerSessionId,
8685
9029
  [ATTR_GEN_AI_CONVERSATION_ID]: providerSessionId,
@@ -8688,7 +9032,6 @@ var exportIdentityAttributes = (event3, resource, ids) => {
8688
9032
  ...event3.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event3.provenance.providerVersion },
8689
9033
  [ATTR_OTELHOOK_WORKSPACE_ID]: event3.workspace.workspaceId,
8690
9034
  ...event3.subagentId === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event3.subagentId },
8691
- ...passthroughResourceAttributes(resource),
8692
9035
  ...hexTraceAttributes(ids)
8693
9036
  };
8694
9037
  };
@@ -8839,12 +9182,12 @@ var pickTarget = (attributes) => {
8839
9182
  }
8840
9183
  return picked;
8841
9184
  };
8842
- var withoutTarget = (attributes, resource) => {
9185
+ var withoutTarget = (attributes, resource, event3) => {
8843
9186
  const rest = { ...attributes };
8844
9187
  for (const key of TARGET_KEYS) {
8845
9188
  delete rest[key];
8846
9189
  }
8847
- return { ...rest, ...pickTarget(passthroughResourceAttributes(resource)) };
9190
+ return { ...rest, ...pickTarget(profileAttributes(event3, resource)) };
8848
9191
  };
8849
9192
  var rankOf = (candidate) => {
8850
9193
  const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];
@@ -8949,7 +9292,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
8949
9292
  name = "session";
8950
9293
  kind = SpanKind.INTERNAL;
8951
9294
  attributes = {
8952
- ...withoutTarget(attributes, resource),
9295
+ ...withoutTarget(attributes, resource, anchor),
8953
9296
  ...strongestTarget([pickTarget(resolved.recovered), start === void 0 ? {} : targetAttributes(start)]),
8954
9297
  ...start?.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName },
8955
9298
  ...start?.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion },
@@ -8991,7 +9334,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
8991
9334
  kind = SpanKind.CLIENT;
8992
9335
  attributes = {
8993
9336
  // Target keys are re-chosen below as one unit, never mixed across edges.
8994
- ...withoutTarget(attributes, resource),
9337
+ ...withoutTarget(attributes, resource, anchor),
8995
9338
  [ATTR_GEN_AI_TOOL_NAME]: toolName,
8996
9339
  [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,
8997
9340
  ...start?.toolKind === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind },
@@ -9729,6 +10072,425 @@ var createUsageAccumulator = (deps) => {
9729
10072
  return { accumulateDelta, recordReset, read, cleanup };
9730
10073
  };
9731
10074
 
10075
+ // src/lifecycle/metric-series.ts
10076
+ import { createHash as createHash5 } from "crypto";
10077
+
10078
+ // src/telemetry/metric-model.ts
10079
+ var TOKEN_USAGE_BUCKETS = Object.freeze([
10080
+ 1,
10081
+ 4,
10082
+ 16,
10083
+ 64,
10084
+ 256,
10085
+ 1024,
10086
+ 4096,
10087
+ 16384,
10088
+ 65536,
10089
+ 262144,
10090
+ 1048576,
10091
+ 4194304,
10092
+ 16777216,
10093
+ 67108864
10094
+ ]);
10095
+ var OPERATION_DURATION_BUCKETS = Object.freeze([
10096
+ 0.01,
10097
+ 0.02,
10098
+ 0.04,
10099
+ 0.08,
10100
+ 0.16,
10101
+ 0.32,
10102
+ 0.64,
10103
+ 1.28,
10104
+ 2.56,
10105
+ 5.12,
10106
+ 10.24,
10107
+ 20.48,
10108
+ 40.96,
10109
+ 81.92
10110
+ ]);
10111
+ var METRIC_TOKEN_USAGE = "gen_ai.client.token.usage";
10112
+ var METRIC_OPERATION_DURATION = "gen_ai.client.operation.duration";
10113
+ var METRIC_SESSIONS = "otelhook.sessions";
10114
+ var METRIC_TOOL_CALLS = "otelhook.tool.calls";
10115
+ var METRIC_COST_USAGE = "otelhook.cost.usage";
10116
+ var METRIC_INSTRUMENTS = Object.freeze({
10117
+ [METRIC_TOKEN_USAGE]: {
10118
+ name: METRIC_TOKEN_USAGE,
10119
+ kind: "histogram",
10120
+ unit: "{token}",
10121
+ description: "Tokens used per generation, by token type (hook-derived)",
10122
+ valueType: "int",
10123
+ boundaries: TOKEN_USAGE_BUCKETS
10124
+ },
10125
+ [METRIC_OPERATION_DURATION]: {
10126
+ name: METRIC_OPERATION_DURATION,
10127
+ kind: "histogram",
10128
+ unit: "s",
10129
+ description: "Generation duration, from its start hook to its end hook (hook-derived)",
10130
+ valueType: "double",
10131
+ boundaries: OPERATION_DURATION_BUCKETS
10132
+ },
10133
+ [METRIC_SESSIONS]: {
10134
+ name: METRIC_SESSIONS,
10135
+ kind: "counter",
10136
+ unit: "{session}",
10137
+ description: "Agent sessions started",
10138
+ valueType: "int"
10139
+ },
10140
+ [METRIC_TOOL_CALLS]: {
10141
+ name: METRIC_TOOL_CALLS,
10142
+ kind: "counter",
10143
+ unit: "{call}",
10144
+ description: "Completed tool calls, by tool name and outcome",
10145
+ valueType: "int"
10146
+ },
10147
+ [METRIC_COST_USAGE]: {
10148
+ name: METRIC_COST_USAGE,
10149
+ kind: "counter",
10150
+ unit: "USD",
10151
+ description: "Cost reported by the provider; never estimated",
10152
+ valueType: "double"
10153
+ }
10154
+ });
10155
+ var isMetricInstrumentName = (value) => typeof value === "string" && Object.hasOwn(METRIC_INSTRUMENTS, value);
10156
+ var ATTR_GEN_AI_TOKEN_TYPE = "gen_ai.token.type";
10157
+ var ATTR_GEN_AI_PROVIDER_NAME = "gen_ai.provider.name";
10158
+ var ATTR_GEN_AI_OPERATION_NAME2 = "gen_ai.operation.name";
10159
+ var ATTR_GEN_AI_REQUEST_MODEL2 = "gen_ai.request.model";
10160
+ var ATTR_GEN_AI_RESPONSE_MODEL2 = "gen_ai.response.model";
10161
+ var ATTR_GEN_AI_TOOL_NAME2 = "gen_ai.tool.name";
10162
+ var ATTR_ERROR_TYPE2 = "error.type";
10163
+ var ATTR_SESSION_ID2 = "session.id";
10164
+ var ATTR_OTELHOOK_PROVIDER_ID2 = "otelhook.provider.id";
10165
+ var ATTR_OTELHOOK_OUTCOME2 = "otelhook.outcome";
10166
+ var ATTR_OTELHOOK_SESSION_KIND = "otelhook.session.kind";
10167
+ var commonAttributes = (event3, resource, includeSessionId) => ({
10168
+ // Session context first, so the metric's own attributes always win; and never
10169
+ // anything account-shaped, whatever the context says.
10170
+ ...event3.contextAttributes === void 0 ? {} : withoutAccountIdentity(event3.contextAttributes),
10171
+ [ATTR_OTELHOOK_PROVIDER_ID2]: event3.provenance.providerId,
10172
+ ...includeSessionId ? { [ATTR_SESSION_ID2]: resolveExportedSessionId(event3.sessionId, resource).sessionId } : {}
10173
+ });
10174
+ var generationAttributes = (end, requestModel) => ({
10175
+ [ATTR_GEN_AI_OPERATION_NAME2]: "chat",
10176
+ ...end.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_PROVIDER_NAME]: end.model.vendor },
10177
+ [ATTR_GEN_AI_REQUEST_MODEL2]: requestModel ?? end.model.modelId,
10178
+ [ATTR_GEN_AI_RESPONSE_MODEL2]: end.model.modelId
10179
+ });
10180
+ var TOKEN_FIELDS = [
10181
+ ["input", (usage) => usage.inputTokens],
10182
+ ["output", (usage) => usage.outputTokens],
10183
+ ["cache_read", (usage) => usage.cachedInputTokens],
10184
+ ["cache_creation", (usage) => usage.cacheCreationInputTokens]
10185
+ ];
10186
+ var isFailedOutcome = (outcome) => outcome !== "ok" && outcome !== "unknown" && outcome !== "cancelled";
10187
+ var deriveMetricObservations = (input) => {
10188
+ const includeSessionId = input.includeSessionId ?? true;
10189
+ const observations = [];
10190
+ const byId = /* @__PURE__ */ new Map();
10191
+ const startsInBatch = /* @__PURE__ */ new Map();
10192
+ for (const event3 of input.events) {
10193
+ byId.set(event3.eventId, event3);
10194
+ if (event3.type === "generation.start") {
10195
+ startsInBatch.set(event3.generationId, {
10196
+ startMillis: event3.occurredAt,
10197
+ requestModel: event3.model.modelId
10198
+ });
10199
+ }
10200
+ }
10201
+ const requestModelOf = (generationId) => startsInBatch.get(generationId)?.requestModel ?? input.generationStarts?.(generationId)?.requestModel;
10202
+ let lastPromptInBatch;
10203
+ for (const event3 of input.events) {
10204
+ if (event3.type === "prompt.submitted") {
10205
+ lastPromptInBatch ??= /* @__PURE__ */ new Map();
10206
+ lastPromptInBatch.set(event3.sessionId, Math.max(lastPromptInBatch.get(event3.sessionId) ?? 0, event3.occurredAt));
10207
+ }
10208
+ }
10209
+ const measuredDurationOf = (end) => {
10210
+ if (end.durationMillis !== void 0) {
10211
+ return end.durationMillis;
10212
+ }
10213
+ const recovered = startsInBatch.has(end.generationId) ? void 0 : input.generationStarts?.(end.generationId);
10214
+ if (recovered !== void 0) {
10215
+ return end.occurredAt - recovered.startMillis;
10216
+ }
10217
+ const turn = lastPromptInBatch?.get(end.sessionId) ?? input.turnStart?.(end.sessionId);
10218
+ return turn === void 0 || turn > end.occurredAt ? void 0 : end.occurredAt - turn;
10219
+ };
10220
+ const push = (event3, instrument, value, attributes) => {
10221
+ if (!Number.isFinite(value) || value < 0) {
10222
+ return;
10223
+ }
10224
+ observations.push({
10225
+ instrument,
10226
+ value,
10227
+ attributes: { ...commonAttributes(event3, input.resource, includeSessionId), ...attributes },
10228
+ timeMillis: event3.occurredAt,
10229
+ sessionId: event3.sessionId
10230
+ });
10231
+ };
10232
+ for (const event3 of input.events) {
10233
+ switch (event3.type) {
10234
+ case "session.start":
10235
+ push(event3, METRIC_SESSIONS, 1, { [ATTR_OTELHOOK_SESSION_KIND]: event3.sessionKind });
10236
+ break;
10237
+ case "tool.end":
10238
+ push(event3, METRIC_TOOL_CALLS, 1, {
10239
+ [ATTR_GEN_AI_TOOL_NAME2]: event3.toolName,
10240
+ [ATTR_OTELHOOK_OUTCOME2]: event3.outcome
10241
+ });
10242
+ break;
10243
+ case "generation.end": {
10244
+ const attributes = generationAttributes(event3, requestModelOf(event3.generationId));
10245
+ const durationMillis = measuredDurationOf(event3);
10246
+ if (durationMillis !== void 0 && durationMillis >= 0) {
10247
+ push(event3, METRIC_OPERATION_DURATION, durationMillis / 1e3, {
10248
+ ...attributes,
10249
+ ...isFailedOutcome(event3.outcome) ? { [ATTR_ERROR_TYPE2]: event3.outcome } : {}
10250
+ });
10251
+ }
10252
+ if (event3.cost !== void 0 && event3.cost.source === "provider-reported" && event3.cost.currency === "USD") {
10253
+ push(event3, METRIC_COST_USAGE, event3.cost.amount, attributes);
10254
+ }
10255
+ break;
10256
+ }
10257
+ default:
10258
+ break;
10259
+ }
10260
+ }
10261
+ for (const observation of input.usage) {
10262
+ if (observation.scope !== "generation") {
10263
+ continue;
10264
+ }
10265
+ const event3 = byId.get(observation.eventId);
10266
+ if (event3?.type !== "generation.end") {
10267
+ continue;
10268
+ }
10269
+ const attributes = generationAttributes(event3, requestModelOf(event3.generationId));
10270
+ for (const [tokenType, read] of TOKEN_FIELDS) {
10271
+ const value = read(observation.delta);
10272
+ if (value === 0 && (tokenType === "cache_read" || tokenType === "cache_creation")) {
10273
+ continue;
10274
+ }
10275
+ push(event3, METRIC_TOKEN_USAGE, value, { ...attributes, [ATTR_GEN_AI_TOKEN_TYPE]: tokenType });
10276
+ }
10277
+ }
10278
+ return observations;
10279
+ };
10280
+ var emptyHistogram = (boundaries) => ({
10281
+ count: 0,
10282
+ sum: 0,
10283
+ min: Number.POSITIVE_INFINITY,
10284
+ max: Number.NEGATIVE_INFINITY,
10285
+ bucketCounts: new Array(boundaries.length + 1).fill(0)
10286
+ });
10287
+ var bucketIndex = (boundaries, value) => {
10288
+ for (let index = 0; index < boundaries.length; index += 1) {
10289
+ const bound = boundaries[index];
10290
+ if (bound !== void 0 && value <= bound) {
10291
+ return index;
10292
+ }
10293
+ }
10294
+ return boundaries.length;
10295
+ };
10296
+ var recordIntoHistogram = (state, boundaries, value) => {
10297
+ const bucketCounts = [...state.bucketCounts];
10298
+ const index = bucketIndex(boundaries, value);
10299
+ bucketCounts[index] = (bucketCounts[index] ?? 0) + 1;
10300
+ return {
10301
+ count: state.count + 1,
10302
+ sum: state.sum + value,
10303
+ min: Math.min(state.min, value),
10304
+ max: Math.max(state.max, value),
10305
+ bucketCounts
10306
+ };
10307
+ };
10308
+ var seriesIdentity = (instrument, attributes) => JSON.stringify([
10309
+ instrument,
10310
+ Object.entries(attributes).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
10311
+ ]);
10312
+ var aggregateDeltaPoints = (observations, nowMillis) => {
10313
+ const series = /* @__PURE__ */ new Map();
10314
+ for (const observation of observations) {
10315
+ const instrument = METRIC_INSTRUMENTS[observation.instrument];
10316
+ const key = seriesIdentity(observation.instrument, observation.attributes);
10317
+ const existing = series.get(key) ?? {
10318
+ observation,
10319
+ start: observation.timeMillis,
10320
+ value: 0,
10321
+ ...instrument.boundaries === void 0 ? {} : { histogram: emptyHistogram(instrument.boundaries) }
10322
+ };
10323
+ existing.start = Math.min(existing.start, observation.timeMillis);
10324
+ if (existing.histogram !== void 0 && instrument.boundaries !== void 0) {
10325
+ existing.histogram = recordIntoHistogram(existing.histogram, instrument.boundaries, observation.value);
10326
+ } else {
10327
+ existing.value += observation.value;
10328
+ }
10329
+ series.set(key, existing);
10330
+ }
10331
+ return [...series.values()].map((entry) => ({
10332
+ instrument: entry.observation.instrument,
10333
+ temporality: "delta",
10334
+ attributes: entry.observation.attributes,
10335
+ startTimeMillis: Math.min(entry.start, nowMillis),
10336
+ timeMillis: Math.max(nowMillis, entry.start),
10337
+ ...entry.histogram === void 0 ? { value: entry.value } : { histogram: entry.histogram }
10338
+ }));
10339
+ };
10340
+ var FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES = Object.freeze([
10341
+ "user.",
10342
+ "enduser.",
10343
+ "organization."
10344
+ ]);
10345
+ var withoutAccountIdentity = (attributes) => Object.fromEntries(
10346
+ Object.entries(attributes).filter(
10347
+ ([key]) => !FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES.some((prefix) => key.startsWith(prefix))
10348
+ )
10349
+ );
10350
+
10351
+ // src/lifecycle/metric-series.ts
10352
+ var TURN_START_SEGMENT = "turn-start";
10353
+ var SHARED_SCOPE = "all";
10354
+ var SHARED_LOCK = "otelhook.metrics.shared";
10355
+ var sessionScope = (sessionId) => `s=${sessionId}`;
10356
+ var digest2 = (identity) => createHash5("sha256").update(identity).digest("base64url").slice(0, 43);
10357
+ var toStoredHistogram = (histogram) => ({
10358
+ count: histogram.count,
10359
+ sum: histogram.sum,
10360
+ // An empty histogram has infinite min/max, which JSON cannot hold. A stored
10361
+ // histogram always has at least one value, so these are finite in practice.
10362
+ min: Number.isFinite(histogram.min) ? histogram.min : 0,
10363
+ max: Number.isFinite(histogram.max) ? histogram.max : 0,
10364
+ bucketCounts: [...histogram.bucketCounts]
10365
+ });
10366
+ var createMetricSeriesStore = (deps) => {
10367
+ const { stateStore, clock } = deps;
10368
+ const readSeries = async (key) => {
10369
+ const record = await stateStore.read(key);
10370
+ if (record?.value.kind !== "metric-series") {
10371
+ return void 0;
10372
+ }
10373
+ return record.value;
10374
+ };
10375
+ const recordGroup = async (scope, observations, deliveryToken) => {
10376
+ const bySeries = /* @__PURE__ */ new Map();
10377
+ for (const observation of observations) {
10378
+ const identity = seriesIdentity(observation.instrument, observation.attributes);
10379
+ const group = bySeries.get(identity) ?? [];
10380
+ group.push(observation);
10381
+ bySeries.set(identity, group);
10382
+ }
10383
+ const now = clock.now();
10384
+ const points = [];
10385
+ for (const [identity, group] of bySeries) {
10386
+ const first = group[0];
10387
+ if (first === void 0) {
10388
+ continue;
10389
+ }
10390
+ const instrument = METRIC_INSTRUMENTS[first.instrument];
10391
+ const key = metricSeriesKey(scope, digest2(identity));
10392
+ const existing = await readSeries(key);
10393
+ const boundaries = instrument.boundaries;
10394
+ const compatible = existing !== void 0 && (boundaries === void 0 ? existing.value !== void 0 : existing.histogram?.bucketCounts.length === boundaries.length + 1);
10395
+ const base = compatible ? existing : void 0;
10396
+ const replay = deliveryToken !== void 0 && base?.appliedDelivery === deliveryToken;
10397
+ const earliest = Math.min(...group.map((observation) => observation.timeMillis));
10398
+ const startTimeMillis = base?.startTimeMillis ?? Math.min(earliest, now);
10399
+ let value = base?.value ?? 0;
10400
+ let histogram = boundaries === void 0 ? void 0 : base?.histogram === void 0 ? emptyHistogram(boundaries) : base.histogram;
10401
+ if (!replay) {
10402
+ for (const observation of group) {
10403
+ if (histogram !== void 0 && boundaries !== void 0) {
10404
+ histogram = recordIntoHistogram(histogram, boundaries, observation.value);
10405
+ } else {
10406
+ value += observation.value;
10407
+ }
10408
+ }
10409
+ await stateStore.write(key, {
10410
+ kind: "metric-series",
10411
+ startTimeMillis,
10412
+ ...histogram === void 0 ? { value } : { histogram: toStoredHistogram(histogram) },
10413
+ ...deliveryToken === void 0 ? {} : { appliedDelivery: deliveryToken }
10414
+ });
10415
+ }
10416
+ points.push({
10417
+ instrument: first.instrument,
10418
+ temporality: "cumulative",
10419
+ attributes: first.attributes,
10420
+ startTimeMillis,
10421
+ timeMillis: Math.max(now, startTimeMillis),
10422
+ ...histogram === void 0 ? { value } : { histogram }
10423
+ });
10424
+ }
10425
+ return points;
10426
+ };
10427
+ const recordCumulative = async (observations, options) => {
10428
+ if (observations.length === 0) {
10429
+ return [];
10430
+ }
10431
+ if (options?.perSession === false) {
10432
+ return withOptionalSessionLock(
10433
+ stateStore,
10434
+ SHARED_LOCK,
10435
+ () => recordGroup(SHARED_SCOPE, observations, options.deliveryToken)
10436
+ );
10437
+ }
10438
+ const bySession = /* @__PURE__ */ new Map();
10439
+ for (const observation of observations) {
10440
+ const group = bySession.get(observation.sessionId) ?? [];
10441
+ group.push(observation);
10442
+ bySession.set(observation.sessionId, group);
10443
+ }
10444
+ const points = [];
10445
+ for (const [sessionId, group] of bySession) {
10446
+ points.push(
10447
+ ...await withOptionalSessionLock(
10448
+ stateStore,
10449
+ sessionId,
10450
+ () => recordGroup(sessionScope(sessionId), group, options?.deliveryToken)
10451
+ )
10452
+ );
10453
+ }
10454
+ return points;
10455
+ };
10456
+ const cleanup = async (maxAgeMillis, options) => {
10457
+ const cap = options?.maxEntries ?? 1e3;
10458
+ const now = clock.now();
10459
+ let removed = 0;
10460
+ let scanned = 0;
10461
+ const prefix = metricSeriesScanPrefix(
10462
+ options?.sessionId === void 0 ? void 0 : sessionScope(options.sessionId)
10463
+ );
10464
+ for (const key of await stateStore.keys(prefix)) {
10465
+ if (scanned >= cap) {
10466
+ break;
10467
+ }
10468
+ scanned += 1;
10469
+ const record = await stateStore.read(key);
10470
+ if (record !== void 0 && now - record.updatedAt > maxAgeMillis) {
10471
+ await stateStore.delete(key);
10472
+ removed += 1;
10473
+ }
10474
+ }
10475
+ return { removed, scanned };
10476
+ };
10477
+ const turnKey = (sessionId) => metricSeriesKey(sessionScope(sessionId), TURN_START_SEGMENT);
10478
+ const recordTurnStart = (sessionId, startMillis) => withOptionalSessionLock(stateStore, sessionId, async () => {
10479
+ const existing = await stateStore.read(turnKey(sessionId));
10480
+ const previous = existing?.value.kind === "attributes" && typeof existing.value.attributes.startMillis === "number" ? existing.value.attributes.startMillis : void 0;
10481
+ if (previous !== void 0 && previous >= startMillis) {
10482
+ return;
10483
+ }
10484
+ await stateStore.write(turnKey(sessionId), { kind: "attributes", attributes: { startMillis } });
10485
+ });
10486
+ const readTurnStart = async (sessionId) => {
10487
+ const record = await stateStore.read(turnKey(sessionId));
10488
+ const value = record?.value.kind === "attributes" ? record.value.attributes.startMillis : void 0;
10489
+ return typeof value === "number" ? value : void 0;
10490
+ };
10491
+ return { recordCumulative, recordTurnStart, readTurnStart, cleanup };
10492
+ };
10493
+
9732
10494
  // src/lifecycle/janitor.ts
9733
10495
  var DEFAULT_MAX_AGE_MILLIS = 24 * 60 * 60 * 1e3;
9734
10496
  var DEFAULT_MAX_ENTRIES_PER_COMPONENT = 1e3;
@@ -9739,7 +10501,7 @@ var createLifecycleJanitor = (options) => {
9739
10501
  const usageMaxAge = options.usageMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
9740
10502
  const runOnce = async (sessionId) => {
9741
10503
  const scope = { maxEntries, ...sessionId === void 0 ? {} : { sessionId } };
9742
- const [span, dedup, usage] = await Promise.all([
10504
+ const [span, dedup, usage, metrics] = await Promise.all([
9743
10505
  options.spanCorrelator?.cleanup(spanMaxAge, scope),
9744
10506
  // Deduplication is deliberately swept across every scope rather than the
9745
10507
  // ending session's: a delivery scope is a host-chosen namespace or a
@@ -9750,12 +10512,14 @@ var createLifecycleJanitor = (options) => {
9750
10512
  maxEntries,
9751
10513
  ...options.dedupStaleClaimMillis === void 0 ? {} : { staleClaimMillis: options.dedupStaleClaimMillis }
9752
10514
  }),
9753
- options.usageAccumulator?.cleanup(usageMaxAge, scope)
10515
+ options.usageAccumulator?.cleanup(usageMaxAge, scope),
10516
+ options.metricSeries?.cleanup(usageMaxAge, scope)
9754
10517
  ]);
9755
10518
  return {
9756
10519
  ...span === void 0 ? {} : { span },
9757
10520
  ...dedup === void 0 ? {} : { dedup },
9758
- ...usage === void 0 ? {} : { usage }
10521
+ ...usage === void 0 ? {} : { usage },
10522
+ ...metrics === void 0 ? {} : { metrics }
9759
10523
  };
9760
10524
  };
9761
10525
  return { runOnce };
@@ -9831,24 +10595,24 @@ var createBoundedMemoryStateStore = (options) => {
9831
10595
 
9832
10596
  // src/state/filesystem-store.ts
9833
10597
  import { randomBytes as randomBytes2 } from "crypto";
9834
- import { mkdir, open as open3, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
9835
- import * as path4 from "path";
10598
+ import { mkdir, open as open4, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
10599
+ import * as path5 from "path";
9836
10600
 
9837
10601
  // src/state/keys.ts
9838
- import { createHash as createHash5 } from "crypto";
10602
+ import { createHash as createHash6 } from "crypto";
9839
10603
  var SAFE_SEGMENT_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
9840
10604
  var isSafeSegment = (segment) => SAFE_SEGMENT_PATTERN.test(segment);
9841
10605
  var sanitizeSegment = (segment) => {
9842
10606
  if (isSafeSegment(segment)) {
9843
10607
  return segment;
9844
10608
  }
9845
- return `h_${createHash5("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
10609
+ return `h_${createHash6("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
9846
10610
  };
9847
10611
  var namespaceSegments = (namespace) => [
9848
10612
  sanitizeSegment(namespace.providerId),
9849
10613
  sanitizeSegment(namespace.installationId)
9850
10614
  ];
9851
- var keyDigest = (key) => createHash5("sha256").update(key, "utf8").digest("hex");
10615
+ var keyDigest = (key) => createHash6("sha256").update(key, "utf8").digest("hex");
9852
10616
 
9853
10617
  // src/state/filesystem-store.ts
9854
10618
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
@@ -9864,10 +10628,10 @@ var wrapFsError = (thrown, operation) => {
9864
10628
  };
9865
10629
  var createFilesystemStateStore = (options) => {
9866
10630
  const [providerSegment, installationSegment] = namespaceSegments(options);
9867
- const baseDir = path4.join(options.rootDir, providerSegment, installationSegment);
9868
- const recordsDir = path4.join(baseDir, "records");
9869
- const quarantineDir = path4.join(baseDir, "quarantine");
9870
- const locksDir = path4.join(baseDir, "locks");
10631
+ const baseDir = path5.join(options.rootDir, providerSegment, installationSegment);
10632
+ const recordsDir = path5.join(baseDir, "records");
10633
+ const quarantineDir = path5.join(baseDir, "quarantine");
10634
+ const locksDir = path5.join(baseDir, "locks");
9871
10635
  const lockTimeoutMillis = options.lockTimeoutMillis ?? 5e3;
9872
10636
  const lockStaleMillis = options.lockStaleMillis ?? 3e4;
9873
10637
  const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;
@@ -9891,11 +10655,11 @@ var createFilesystemStateStore = (options) => {
9891
10655
  throw wrapFsError(thrown, "ensure-dirs");
9892
10656
  }
9893
10657
  };
9894
- const recordPath = (key) => path4.join(recordsDir, `${keyDigest(key)}.json`);
9895
- const tempPath = (key) => path4.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
9896
- const lockPath = (sessionId) => path4.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
10658
+ const recordPath = (key) => path5.join(recordsDir, `${keyDigest(key)}.json`);
10659
+ const tempPath = (key) => path5.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
10660
+ const lockPath = (sessionId) => path5.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
9897
10661
  const quarantine = async (filePath, key, reason) => {
9898
- const dest = path4.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
10662
+ const dest = path5.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
9899
10663
  try {
9900
10664
  await rename(filePath, dest);
9901
10665
  } catch {
@@ -9959,7 +10723,7 @@ var createFilesystemStateStore = (options) => {
9959
10723
  const startedAt = options.clock.monotonicMillis();
9960
10724
  for (; ; ) {
9961
10725
  try {
9962
- const handle = await open3(filePath, "wx");
10726
+ const handle = await open4(filePath, "wx");
9963
10727
  try {
9964
10728
  await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));
9965
10729
  } finally {
@@ -10027,7 +10791,7 @@ var createFilesystemStateStore = (options) => {
10027
10791
  }
10028
10792
  let raw;
10029
10793
  try {
10030
- raw = await readFile(path4.join(recordsDir, entry), "utf8");
10794
+ raw = await readFile(path5.join(recordsDir, entry), "utf8");
10031
10795
  } catch {
10032
10796
  continue;
10033
10797
  }
@@ -10080,7 +10844,7 @@ var createFilesystemStateStore = (options) => {
10080
10844
  continue;
10081
10845
  }
10082
10846
  scanned += 1;
10083
- const filePath = path4.join(recordsDir, entry);
10847
+ const filePath = path5.join(recordsDir, entry);
10084
10848
  try {
10085
10849
  const raw = await readFile(filePath, "utf8");
10086
10850
  const envelope = JSON.parse(raw);
@@ -10100,7 +10864,7 @@ var createFilesystemStateStore = (options) => {
10100
10864
  lockEntries = [];
10101
10865
  }
10102
10866
  for (const entry of lockEntries) {
10103
- const filePath = path4.join(locksDir, entry);
10867
+ const filePath = path5.join(locksDir, entry);
10104
10868
  try {
10105
10869
  const raw = await readFile(filePath, "utf8");
10106
10870
  const parsed = JSON.parse(raw);
@@ -10119,7 +10883,7 @@ var createFilesystemStateStore = (options) => {
10119
10883
  // src/telemetry/spool-queue.ts
10120
10884
  import { randomBytes as randomBytes3 } from "crypto";
10121
10885
  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";
10122
- import * as path5 from "path";
10886
+ import * as path6 from "path";
10123
10887
  var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
10124
10888
  total: 0,
10125
10889
  age: 0,
@@ -10135,7 +10899,7 @@ var enqueuedAtOf = (fileName) => {
10135
10899
  var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
10136
10900
  var readSpoolDropCounts = async (queueDir) => {
10137
10901
  try {
10138
- const parsed = JSON.parse(await readFile2(path5.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
10902
+ const parsed = JSON.parse(await readFile2(path6.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
10139
10903
  if (typeof parsed !== "object" || parsed === null) {
10140
10904
  return EMPTY_SPOOL_DROP_COUNTS;
10141
10905
  }
@@ -10164,7 +10928,7 @@ var readSpoolQueueStats = async (queueDir) => {
10164
10928
  let bytes = 0;
10165
10929
  for (const file of files) {
10166
10930
  try {
10167
- bytes += (await stat3(path5.join(queueDir, file))).size;
10931
+ bytes += (await stat3(path6.join(queueDir, file))).size;
10168
10932
  } catch {
10169
10933
  }
10170
10934
  }
@@ -10180,8 +10944,8 @@ var DEFAULT_DRAIN_MAX_BATCHES = 20;
10180
10944
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
10181
10945
  var createSpoolQueue = (options) => {
10182
10946
  const [providerSegment, installationSegment] = namespaceSegments(options);
10183
- const queueDir = path5.join(options.rootDir, providerSegment, installationSegment, options.queueName);
10184
- const corruptDir = path5.join(
10947
+ const queueDir = path6.join(options.rootDir, providerSegment, installationSegment, options.queueName);
10948
+ const corruptDir = path6.join(
10185
10949
  options.rootDir,
10186
10950
  providerSegment,
10187
10951
  installationSegment,
@@ -10228,9 +10992,9 @@ var createSpoolQueue = (options) => {
10228
10992
  [reason]: current[reason] + dropped,
10229
10993
  lastDroppedAt: options.clock.now()
10230
10994
  };
10231
- const tmp = path5.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
10995
+ const tmp = path6.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
10232
10996
  await writeFile2(tmp, JSON.stringify(next), "utf8");
10233
- await rename2(tmp, path5.join(queueDir, SPOOL_DROPS_FILE));
10997
+ await rename2(tmp, path6.join(queueDir, SPOOL_DROPS_FILE));
10234
10998
  } catch {
10235
10999
  }
10236
11000
  options.logger?.warn("durable spool dropped batches", {
@@ -10246,7 +11010,7 @@ var createSpoolQueue = (options) => {
10246
11010
  let bytes = 0;
10247
11011
  if (options.maxBytes !== void 0) {
10248
11012
  try {
10249
- bytes = (await stat3(path5.join(queueDir, name))).size;
11013
+ bytes = (await stat3(path6.join(queueDir, name))).size;
10250
11014
  } catch {
10251
11015
  continue;
10252
11016
  }
@@ -10260,7 +11024,7 @@ var createSpoolQueue = (options) => {
10260
11024
  let removed = 0;
10261
11025
  for (const file of files) {
10262
11026
  try {
10263
- await unlink2(path5.join(queueDir, file.name));
11027
+ await unlink2(path6.join(queueDir, file.name));
10264
11028
  removed += 1;
10265
11029
  } catch {
10266
11030
  }
@@ -10320,8 +11084,8 @@ var createSpoolQueue = (options) => {
10320
11084
  }
10321
11085
  }
10322
11086
  const fileName = `${String(now).padStart(16, "0")}-${randomBytes3(6).toString("hex")}.json`;
10323
- const target = path5.join(queueDir, fileName);
10324
- const tmp = path5.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
11087
+ const target = path6.join(queueDir, fileName);
11088
+ const tmp = path6.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
10325
11089
  await writeFile2(tmp, serialized, "utf8");
10326
11090
  await rename2(tmp, target);
10327
11091
  return { spooled: true };
@@ -10351,7 +11115,7 @@ var createSpoolQueue = (options) => {
10351
11115
  if (fileName === void 0) {
10352
11116
  break;
10353
11117
  }
10354
- const filePath = path5.join(queueDir, fileName);
11118
+ const filePath = path6.join(queueDir, fileName);
10355
11119
  const quarantine = async (rejection) => {
10356
11120
  quarantined += 1;
10357
11121
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -10360,7 +11124,7 @@ var createSpoolQueue = (options) => {
10360
11124
  "spool.queue": options.queueName
10361
11125
  });
10362
11126
  try {
10363
- await rename2(filePath, path5.join(corruptDir, fileName));
11127
+ await rename2(filePath, path6.join(corruptDir, fileName));
10364
11128
  } catch {
10365
11129
  await unlink2(filePath).catch(() => void 0);
10366
11130
  }
@@ -10597,6 +11361,33 @@ var replayResource = (attributes, policy) => {
10597
11361
  }
10598
11362
  return resourceFromAttributes(safe);
10599
11363
  };
11364
+ var agreedContextAttributes = (events) => {
11365
+ const [first, ...rest] = events;
11366
+ if (first?.contextAttributes === void 0) {
11367
+ return {};
11368
+ }
11369
+ const agreed = { ...first.contextAttributes };
11370
+ for (const event3 of rest) {
11371
+ for (const key of Object.keys(agreed)) {
11372
+ if (event3.contextAttributes?.[key] !== agreed[key]) {
11373
+ delete agreed[key];
11374
+ }
11375
+ }
11376
+ }
11377
+ return agreed;
11378
+ };
11379
+ var resourceWithContext = (resource, context) => {
11380
+ const overrides = {};
11381
+ for (const [key, value] of Object.entries(context)) {
11382
+ if (Object.hasOwn(resource.attributes, key) && !isReservedResourceAttributeKey(key) && resource.attributes[key] !== value) {
11383
+ overrides[key] = value;
11384
+ }
11385
+ }
11386
+ if (Object.keys(overrides).length === 0) {
11387
+ return resource;
11388
+ }
11389
+ return resourceFromAttributes({ ...resource.attributes, ...overrides });
11390
+ };
10600
11391
 
10601
11392
  // src/telemetry/otlp-sink.ts
10602
11393
  var chunk = (items, size) => {
@@ -10681,10 +11472,10 @@ var createOtlpTraceSink = (options) => {
10681
11472
  const exportSpans = (spans) => new Promise((resolve5) => {
10682
11473
  exporter.export([...spans], (result) => resolve5(result));
10683
11474
  });
10684
- const toSpoolBatch = (spans) => ({
11475
+ const toSpoolBatch = (spans, batchResource) => ({
10685
11476
  providerId: options.providerId,
10686
11477
  installationId: options.installationId,
10687
- resourceAttributes: { ...resource.attributes },
11478
+ resourceAttributes: { ...batchResource.attributes },
10688
11479
  instrumentationScope: { name: scope.name, ...scope.version === void 0 ? {} : { version: scope.version } },
10689
11480
  spans: spans.map(serializeSpan),
10690
11481
  enqueuedAt: options.clock.now()
@@ -10714,8 +11505,9 @@ var createOtlpTraceSink = (options) => {
10714
11505
  return { accepted: 0, rejected: 0, errors: [] };
10715
11506
  }
10716
11507
  const resolved = await resolveCorrelations(events);
11508
+ const batchResource = resourceWithContext(resource, agreedContextAttributes(events));
10717
11509
  const spans = canonicalEventsToReadableSpans(events, {
10718
- resource,
11510
+ resource: batchResource,
10719
11511
  instrumentationScope: scope,
10720
11512
  correlations: resolved.correlations,
10721
11513
  ...resolved.available === void 0 ? {} : { correlationAvailable: resolved.available }
@@ -10741,7 +11533,7 @@ var createOtlpTraceSink = (options) => {
10741
11533
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
10742
11534
  const permanent = isPermanentExportFailure(result);
10743
11535
  if (options.spool !== void 0 && !permanent) {
10744
- const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
11536
+ const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({
10745
11537
  spooled: false,
10746
11538
  reason: "capacity-exceeded"
10747
11539
  }));
@@ -10807,13 +11599,13 @@ var createOtlpTraceSink = (options) => {
10807
11599
  import { SeverityNumber, TraceFlags as TraceFlags2 } from "@opentelemetry/api";
10808
11600
  import { millisToHrTime as millisToHrTime2 } from "@opentelemetry/core";
10809
11601
  import {
10810
- ATTR_ERROR_TYPE as ATTR_ERROR_TYPE2,
10811
- ATTR_GEN_AI_OPERATION_NAME as ATTR_GEN_AI_OPERATION_NAME2,
10812
- ATTR_GEN_AI_REQUEST_MODEL as ATTR_GEN_AI_REQUEST_MODEL2,
10813
- ATTR_GEN_AI_RESPONSE_MODEL as ATTR_GEN_AI_RESPONSE_MODEL2,
11602
+ ATTR_ERROR_TYPE as ATTR_ERROR_TYPE3,
11603
+ ATTR_GEN_AI_OPERATION_NAME as ATTR_GEN_AI_OPERATION_NAME3,
11604
+ ATTR_GEN_AI_REQUEST_MODEL as ATTR_GEN_AI_REQUEST_MODEL3,
11605
+ ATTR_GEN_AI_RESPONSE_MODEL as ATTR_GEN_AI_RESPONSE_MODEL3,
10814
11606
  ATTR_GEN_AI_SYSTEM as ATTR_GEN_AI_SYSTEM2,
10815
11607
  ATTR_GEN_AI_TOOL_CALL_ID as ATTR_GEN_AI_TOOL_CALL_ID2,
10816
- ATTR_GEN_AI_TOOL_NAME as ATTR_GEN_AI_TOOL_NAME2,
11608
+ ATTR_GEN_AI_TOOL_NAME as ATTR_GEN_AI_TOOL_NAME3,
10817
11609
  ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS as ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS2,
10818
11610
  ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS as ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS2,
10819
11611
  ATTR_GEN_AI_USAGE_INPUT_TOKENS as ATTR_GEN_AI_USAGE_INPUT_TOKENS2,
@@ -10842,14 +11634,14 @@ var ATTR_OTELHOOK_EVENT_ID = "otelhook.event.id";
10842
11634
  var ATTR_OTELHOOK_EVENT_SEQUENCE = "otelhook.event.sequence";
10843
11635
  var ATTR_OTELHOOK_LOG_SIGNAL = "otelhook.log.signal";
10844
11636
  var ATTR_OTELHOOK_LOG_MAPPING_VERSION = "otelhook.log.mapping_version";
10845
- var ATTR_OTELHOOK_OUTCOME2 = "otelhook.outcome";
11637
+ var ATTR_OTELHOOK_OUTCOME3 = "otelhook.outcome";
10846
11638
  var ATTR_OTELHOOK_TOOL_KIND2 = "otelhook.tool.kind";
10847
11639
  var ATTR_OTELHOOK_TOOL_PERMISSION = "otelhook.tool.permission_decision";
10848
11640
  var ATTR_OTELHOOK_DELEGATION_DEPTH2 = "otelhook.delegation_depth";
10849
11641
  var ATTR_OTELHOOK_SUBAGENT_TYPE = "otelhook.subagent.type";
10850
11642
  var ATTR_OTELHOOK_AGENT_NAME2 = "otelhook.agent.name";
10851
11643
  var ATTR_OTELHOOK_AGENT_VERSION2 = "otelhook.agent.version";
10852
- var ATTR_OTELHOOK_SESSION_KIND = "otelhook.session.kind";
11644
+ var ATTR_OTELHOOK_SESSION_KIND2 = "otelhook.session.kind";
10853
11645
  var ATTR_OTELHOOK_PROMPT_SOURCE = "otelhook.prompt.source";
10854
11646
  var ATTR_OTELHOOK_PROMPT_TURN_INDEX = "otelhook.prompt.turn_index";
10855
11647
  var ATTR_OTELHOOK_GENERATION_ID2 = "otelhook.generation.id";
@@ -10993,15 +11785,15 @@ var eventAttributes = (event3) => {
10993
11785
  switch (event3.type) {
10994
11786
  case "session.start":
10995
11787
  return {
10996
- [ATTR_OTELHOOK_SESSION_KIND]: event3.sessionKind,
11788
+ [ATTR_OTELHOOK_SESSION_KIND2]: event3.sessionKind,
10997
11789
  ...event3.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME2]: event3.agentName },
10998
11790
  ...event3.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION2]: event3.agentVersion },
10999
- ...event3.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL2]: event3.model.modelId },
11791
+ ...event3.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL3]: event3.model.modelId },
11000
11792
  ...targetAttributes(event3)
11001
11793
  };
11002
11794
  case "session.end":
11003
11795
  return {
11004
- [ATTR_OTELHOOK_OUTCOME2]: event3.reason,
11796
+ [ATTR_OTELHOOK_OUTCOME3]: event3.reason,
11005
11797
  ...usageAttributes2(event3.usage)
11006
11798
  };
11007
11799
  case "prompt.submitted":
@@ -11012,25 +11804,25 @@ var eventAttributes = (event3) => {
11012
11804
  };
11013
11805
  case "generation.start":
11014
11806
  return {
11015
- [ATTR_GEN_AI_OPERATION_NAME2]: "chat",
11807
+ [ATTR_GEN_AI_OPERATION_NAME3]: "chat",
11016
11808
  [ATTR_OTELHOOK_GENERATION_ID2]: event3.generationId,
11017
- [ATTR_GEN_AI_REQUEST_MODEL2]: event3.model.modelId,
11809
+ [ATTR_GEN_AI_REQUEST_MODEL3]: event3.model.modelId,
11018
11810
  ...event3.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event3.model.vendor }
11019
11811
  };
11020
11812
  case "generation.end":
11021
11813
  return {
11022
- [ATTR_GEN_AI_OPERATION_NAME2]: "chat",
11814
+ [ATTR_GEN_AI_OPERATION_NAME3]: "chat",
11023
11815
  [ATTR_OTELHOOK_GENERATION_ID2]: event3.generationId,
11024
- [ATTR_GEN_AI_RESPONSE_MODEL2]: event3.model.modelId,
11816
+ [ATTR_GEN_AI_RESPONSE_MODEL3]: event3.model.modelId,
11025
11817
  ...event3.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event3.model.vendor },
11026
- [ATTR_OTELHOOK_OUTCOME2]: event3.outcome,
11818
+ [ATTR_OTELHOOK_OUTCOME3]: event3.outcome,
11027
11819
  ...event3.stopReason === void 0 ? {} : { [ATTR_OTELHOOK_STOP_REASON]: event3.stopReason },
11028
11820
  ...usageAttributes2(event3.usage),
11029
11821
  ...event3.usage === void 0 || event3.usagePartial === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_PARTIAL]: event3.usagePartial }
11030
11822
  };
11031
11823
  case "tool.start":
11032
11824
  return {
11033
- [ATTR_GEN_AI_TOOL_NAME2]: event3.toolName,
11825
+ [ATTR_GEN_AI_TOOL_NAME3]: event3.toolName,
11034
11826
  [ATTR_GEN_AI_TOOL_CALL_ID2]: event3.toolCallId,
11035
11827
  [ATTR_OTELHOOK_TOOL_KIND2]: event3.toolKind,
11036
11828
  ...event3.generationId === void 0 ? {} : { [ATTR_OTELHOOK_GENERATION_ID2]: event3.generationId },
@@ -11038,9 +11830,9 @@ var eventAttributes = (event3) => {
11038
11830
  };
11039
11831
  case "tool.end":
11040
11832
  return {
11041
- [ATTR_GEN_AI_TOOL_NAME2]: event3.toolName,
11833
+ [ATTR_GEN_AI_TOOL_NAME3]: event3.toolName,
11042
11834
  [ATTR_GEN_AI_TOOL_CALL_ID2]: event3.toolCallId,
11043
- [ATTR_OTELHOOK_OUTCOME2]: event3.outcome,
11835
+ [ATTR_OTELHOOK_OUTCOME3]: event3.outcome,
11044
11836
  ...event3.permissionDecision === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_PERMISSION]: event3.permissionDecision },
11045
11837
  ...targetAttributes(event3)
11046
11838
  };
@@ -11048,11 +11840,11 @@ var eventAttributes = (event3) => {
11048
11840
  return {
11049
11841
  [ATTR_OTELHOOK_DELEGATION_DEPTH2]: event3.delegationDepth,
11050
11842
  ...event3.subagentType === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_TYPE]: event3.subagentType },
11051
- ...event3.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL2]: event3.model.modelId }
11843
+ ...event3.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL3]: event3.model.modelId }
11052
11844
  };
11053
11845
  case "subagent.end":
11054
11846
  return {
11055
- [ATTR_OTELHOOK_OUTCOME2]: event3.outcome,
11847
+ [ATTR_OTELHOOK_OUTCOME3]: event3.outcome,
11056
11848
  ...usageAttributes2(event3.usage)
11057
11849
  };
11058
11850
  case "compaction.performed":
@@ -11065,7 +11857,7 @@ var eventAttributes = (event3) => {
11065
11857
  };
11066
11858
  case "error.raised":
11067
11859
  return {
11068
- [ATTR_ERROR_TYPE2]: event3.errorCode,
11860
+ [ATTR_ERROR_TYPE3]: event3.errorCode,
11069
11861
  [ATTR_OTELHOOK_ERROR_PHASE]: event3.phase,
11070
11862
  [ATTR_OTELHOOK_ERROR_RETRYABLE]: event3.retryable,
11071
11863
  [ATTR_OTELHOOK_ERROR_SEVERITY]: event3.severity
@@ -11476,10 +12268,10 @@ var createOtlpLogSink = (options) => {
11476
12268
  const exportRecords = (records) => new Promise((resolve5) => {
11477
12269
  exporter.export([...records], (result) => resolve5(result));
11478
12270
  });
11479
- const toSpoolBatch = (records) => ({
12271
+ const toSpoolBatch = (records, batchResource) => ({
11480
12272
  providerId: options.providerId,
11481
12273
  installationId: options.installationId,
11482
- resourceAttributes: { ...resource.attributes },
12274
+ resourceAttributes: { ...batchResource.attributes },
11483
12275
  instrumentationScope: {
11484
12276
  name: scope.name,
11485
12277
  ...scope.version === void 0 ? {} : { version: scope.version }
@@ -11514,8 +12306,9 @@ var createOtlpLogSink = (options) => {
11514
12306
  return { accepted: 0, rejected: 0, errors: [] };
11515
12307
  }
11516
12308
  const resolved = await resolveCorrelations(events);
12309
+ const batchResource = resourceWithContext(resource, agreedContextAttributes(events));
11517
12310
  const mapped = canonicalEventsToLogRecords(events, {
11518
- resource,
12311
+ resource: batchResource,
11519
12312
  instrumentationScope: scope,
11520
12313
  content,
11521
12314
  correlations: resolved.correlations,
@@ -11550,7 +12343,7 @@ var createOtlpLogSink = (options) => {
11550
12343
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
11551
12344
  const permanent = isPermanentExportFailure(result);
11552
12345
  if (options.spool !== void 0 && !permanent) {
11553
- const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
12346
+ const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({
11554
12347
  spooled: false,
11555
12348
  reason: "capacity-exceeded"
11556
12349
  }));
@@ -11660,8 +12453,357 @@ var shareCorrelationPerBatch = (correlate) => {
11660
12453
  };
11661
12454
  };
11662
12455
 
12456
+ // src/telemetry/durable-metric-spool.ts
12457
+ var MAX_SPOOLED_METRIC_POINTS_PER_BATCH = 4096;
12458
+ var MAX_STRING_LENGTH = 8192;
12459
+ var MAX_ATTRIBUTES_PER_POINT = 64;
12460
+ var MAX_BUCKETS = 64;
12461
+ var isPlainObject5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
12462
+ var isFiniteNonNegative3 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
12463
+ var isBoundedString3 = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_STRING_LENGTH;
12464
+ var isPrimitiveAttribute2 = (value) => typeof value === "string" && value.length <= MAX_STRING_LENGTH || typeof value === "number" && Number.isFinite(value) || typeof value === "boolean";
12465
+ var isReplayablePoint = (value) => {
12466
+ if (!isPlainObject5(value) || !isMetricInstrumentName(value.instrument)) {
12467
+ return false;
12468
+ }
12469
+ if (value.temporality !== "cumulative" && value.temporality !== "delta") {
12470
+ return false;
12471
+ }
12472
+ if (!isFiniteNonNegative3(value.startTimeMillis) || !isFiniteNonNegative3(value.timeMillis)) {
12473
+ return false;
12474
+ }
12475
+ if (!isPlainObject5(value.attributes)) {
12476
+ return false;
12477
+ }
12478
+ const entries = Object.entries(value.attributes);
12479
+ if (entries.length > MAX_ATTRIBUTES_PER_POINT || !entries.every(([, item]) => isPrimitiveAttribute2(item))) {
12480
+ return false;
12481
+ }
12482
+ const instrument = METRIC_INSTRUMENTS[value.instrument];
12483
+ if (instrument.kind === "counter") {
12484
+ return isFiniteNonNegative3(value.value) && value.histogram === void 0;
12485
+ }
12486
+ const histogram = value.histogram;
12487
+ if (!isPlainObject5(histogram) || value.value !== void 0) {
12488
+ return false;
12489
+ }
12490
+ const buckets = histogram.bucketCounts;
12491
+ return isFiniteNonNegative3(histogram.count) && Number.isInteger(histogram.count) && isFiniteNonNegative3(histogram.sum) && typeof histogram.min === "number" && typeof histogram.max === "number" && Array.isArray(buckets) && buckets.length <= MAX_BUCKETS && buckets.length === (instrument.boundaries?.length ?? 0) + 1 && buckets.every((count) => isFiniteNonNegative3(count) && Number.isInteger(count));
12492
+ };
12493
+ var validateMetricSpoolBatch = (value, identity) => {
12494
+ if (!isPlainObject5(value)) {
12495
+ return { rejection: "not-an-object" };
12496
+ }
12497
+ if (value.providerId !== identity.providerId || value.installationId !== identity.installationId) {
12498
+ return { rejection: "identity-mismatch" };
12499
+ }
12500
+ if (!isPlainObject5(value.resourceAttributes)) {
12501
+ return { rejection: "resource-attributes-invalid" };
12502
+ }
12503
+ if (!isPlainObject5(value.instrumentationScope) || !isBoundedString3(value.instrumentationScope.name)) {
12504
+ return { rejection: "instrumentation-scope-invalid" };
12505
+ }
12506
+ if (value.instrumentationScope.version !== void 0 && typeof value.instrumentationScope.version !== "string") {
12507
+ return { rejection: "instrumentation-scope-invalid" };
12508
+ }
12509
+ if (!Array.isArray(value.points) || value.points.length === 0 || value.points.length > MAX_SPOOLED_METRIC_POINTS_PER_BATCH) {
12510
+ return { rejection: "points-invalid" };
12511
+ }
12512
+ if (!value.points.every(isReplayablePoint)) {
12513
+ return { rejection: "point-field-invalid" };
12514
+ }
12515
+ if (!isFiniteNonNegative3(value.enqueuedAt)) {
12516
+ return { rejection: "not-an-object" };
12517
+ }
12518
+ return { batch: value };
12519
+ };
12520
+ var DEFAULT_MAX_METRIC_SPOOL_FILES = 500;
12521
+ var createFileDurableMetricSpool = (options) => createSpoolQueue({
12522
+ rootDir: options.rootDir,
12523
+ providerId: options.providerId,
12524
+ installationId: options.installationId,
12525
+ clock: options.clock,
12526
+ ...options.logger === void 0 ? {} : { logger: options.logger },
12527
+ maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_METRIC_SPOOL_FILES,
12528
+ queueName: options.queueName ?? "spool-metrics",
12529
+ ...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
12530
+ ...options.maxAgeMillis === void 0 ? {} : { maxAgeMillis: options.maxAgeMillis },
12531
+ ...options.overflow === void 0 ? {} : { overflow: options.overflow },
12532
+ validate: validateMetricSpoolBatch
12533
+ });
12534
+
12535
+ // src/telemetry/otlp-metric-sink.ts
12536
+ import { ValueType } from "@opentelemetry/api";
12537
+ import { ExportResultCode as ExportResultCode3, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
12538
+ import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
12539
+ import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
12540
+ import {
12541
+ AggregationTemporality,
12542
+ DataPointType
12543
+ } from "@opentelemetry/sdk-metrics";
12544
+ var resolveMetricsEndpoint = (exporter) => {
12545
+ const stated = exporter.metrics?.endpoint;
12546
+ if (stated !== void 0) {
12547
+ return { endpoint: stated, derived: false };
12548
+ }
12549
+ if (exporter.endpoint === void 0) {
12550
+ return { unresolvable: "no-endpoint" };
12551
+ }
12552
+ return { endpoint: siblingSignalEndpoint(exporter.endpoint, "metrics"), derived: true };
12553
+ };
12554
+ var describeMetricsDeliverability = (exporter) => {
12555
+ if (exporter.metrics?.enabled !== true) {
12556
+ return { status: "disabled", reason: "metrics-disabled" };
12557
+ }
12558
+ if (!exporter.enabled) {
12559
+ return { status: "disabled", reason: "exporter-disabled" };
12560
+ }
12561
+ if (exporter.protocol === "none") {
12562
+ return { status: "disabled", reason: "protocol-none" };
12563
+ }
12564
+ if (exporter.protocol !== "http/protobuf") {
12565
+ return { status: "disabled", reason: "protocol-unsupported" };
12566
+ }
12567
+ const resolved = resolveMetricsEndpoint(exporter);
12568
+ if ("unresolvable" in resolved) {
12569
+ return { status: "disabled", reason: "no-endpoint" };
12570
+ }
12571
+ return { status: "configured", endpoint: resolved.endpoint, derivedEndpoint: resolved.derived };
12572
+ };
12573
+ var DISABLED_DETAIL2 = Object.freeze({
12574
+ "exporter-disabled": "otlp metric sink disabled: the exporter is disabled",
12575
+ "protocol-none": "otlp metric sink disabled: protocol is none",
12576
+ "protocol-unsupported": "otlp metric sink disabled: protocol not supported by this build",
12577
+ "no-endpoint": "otlp metric sink disabled: no metrics endpoint configured and none could be derived"
12578
+ });
12579
+ var createDisabledMetricSink = (destination) => {
12580
+ const health = createHealthTracker(
12581
+ "telemetry-metric-sink",
12582
+ destination === void 0 ? {} : { destination }
12583
+ );
12584
+ return {
12585
+ enabled: false,
12586
+ exportPoints: () => Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),
12587
+ flush: () => Promise.resolve(),
12588
+ shutdown: () => Promise.resolve(),
12589
+ health: () => health.snapshot(),
12590
+ drainSpool: () => Promise.resolve({ drained: 0, remaining: 0, failed: 0 })
12591
+ };
12592
+ };
12593
+ var createDisabledOtlpMetricSink = createDisabledMetricSink;
12594
+ var toMetricData = (points) => {
12595
+ const byInstrument = /* @__PURE__ */ new Map();
12596
+ for (const point of points) {
12597
+ const key = `${point.instrument}|${point.temporality}`;
12598
+ const group = byInstrument.get(key) ?? [];
12599
+ group.push(point);
12600
+ byInstrument.set(key, group);
12601
+ }
12602
+ const metrics = [];
12603
+ for (const group of byInstrument.values()) {
12604
+ const first = group[0];
12605
+ if (first === void 0) {
12606
+ continue;
12607
+ }
12608
+ const instrument = METRIC_INSTRUMENTS[first.instrument];
12609
+ const descriptor = {
12610
+ name: instrument.name,
12611
+ description: instrument.description,
12612
+ unit: instrument.unit,
12613
+ valueType: instrument.valueType === "int" ? ValueType.INT : ValueType.DOUBLE
12614
+ };
12615
+ const aggregationTemporality = first.temporality === "cumulative" ? AggregationTemporality.CUMULATIVE : AggregationTemporality.DELTA;
12616
+ const times = (point) => ({
12617
+ startTime: millisToHrTime4(point.startTimeMillis),
12618
+ endTime: millisToHrTime4(point.timeMillis)
12619
+ });
12620
+ if (instrument.kind === "counter") {
12621
+ metrics.push({
12622
+ descriptor,
12623
+ aggregationTemporality,
12624
+ dataPointType: DataPointType.SUM,
12625
+ isMonotonic: true,
12626
+ dataPoints: group.map((point) => ({
12627
+ ...times(point),
12628
+ attributes: { ...point.attributes },
12629
+ value: point.value ?? 0
12630
+ }))
12631
+ });
12632
+ continue;
12633
+ }
12634
+ metrics.push({
12635
+ descriptor,
12636
+ aggregationTemporality,
12637
+ dataPointType: DataPointType.HISTOGRAM,
12638
+ dataPoints: group.map((point) => {
12639
+ const histogram = point.histogram;
12640
+ return {
12641
+ ...times(point),
12642
+ attributes: { ...point.attributes },
12643
+ value: {
12644
+ buckets: {
12645
+ boundaries: [...instrument.boundaries ?? []],
12646
+ counts: [...histogram?.bucketCounts ?? []]
12647
+ },
12648
+ count: histogram?.count ?? 0,
12649
+ sum: histogram?.sum ?? 0,
12650
+ ...histogram === void 0 || histogram.count === 0 ? {} : { min: histogram.min, max: histogram.max }
12651
+ }
12652
+ };
12653
+ })
12654
+ });
12655
+ }
12656
+ return metrics;
12657
+ };
12658
+ var createOtlpMetricSink = (options) => {
12659
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
12660
+ const deliverability = describeMetricsDeliverability(options.exporter);
12661
+ if (deliverability.status === "disabled") {
12662
+ if (deliverability.reason !== "metrics-disabled") {
12663
+ options.logger?.warn(DISABLED_DETAIL2[deliverability.reason], {
12664
+ "exporter.protocol": options.exporter.protocol,
12665
+ ...destinationFields
12666
+ });
12667
+ }
12668
+ return createDisabledMetricSink(options.destination);
12669
+ }
12670
+ const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
12671
+ const resource = resourceFromAttributes2(
12672
+ withoutAccountIdentity(resourceFromExporterPolicy(options.exporter).attributes)
12673
+ );
12674
+ const health = createHealthTracker(
12675
+ "telemetry-metric-sink",
12676
+ options.destination === void 0 ? {} : { destination: options.destination }
12677
+ );
12678
+ const exporter = new OTLPMetricExporter({
12679
+ url: deliverability.endpoint,
12680
+ headers: { ...options.headers },
12681
+ timeoutMillis: options.exporter.timeoutMillis
12682
+ });
12683
+ let shutdownCompleted = false;
12684
+ const exportResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve5) => {
12685
+ const payload = {
12686
+ resource: batchResource,
12687
+ scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }]
12688
+ };
12689
+ try {
12690
+ exporter.export(payload, (result) => resolve5(result));
12691
+ } catch (thrown) {
12692
+ resolve5({
12693
+ code: ExportResultCode3.FAILED,
12694
+ error: thrown instanceof Error ? thrown : new Error("export threw")
12695
+ });
12696
+ }
12697
+ });
12698
+ const toSpoolBatch = (points, batchResource) => ({
12699
+ providerId: options.providerId,
12700
+ installationId: options.installationId,
12701
+ resourceAttributes: { ...batchResource.attributes },
12702
+ instrumentationScope: {
12703
+ name: scope.name,
12704
+ ...scope.version === void 0 ? {} : { version: scope.version }
12705
+ },
12706
+ points: points.map((point) => ({ ...point })),
12707
+ enqueuedAt: options.clock.now()
12708
+ });
12709
+ const sendSerializedBatch = async (batch) => {
12710
+ const batchResource = resourceFromAttributes2(
12711
+ withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes)
12712
+ );
12713
+ const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);
12714
+ if (result.code === ExportResultCode3.SUCCESS) {
12715
+ return true;
12716
+ }
12717
+ return isPermanentExportFailure(result) ? "discard" : false;
12718
+ };
12719
+ const exportPoints = async (points, context) => {
12720
+ if (points.length === 0) {
12721
+ return { accepted: 0, rejected: 0, errors: [] };
12722
+ }
12723
+ const batchResource = context === void 0 ? resource : resourceWithContext(resource, context);
12724
+ const result = await exportResourceMetrics(points, batchResource, scope);
12725
+ if (result.code === ExportResultCode3.SUCCESS) {
12726
+ health.recordSuccess(points.length, options.clock.now());
12727
+ return { accepted: points.length, rejected: 0, errors: [] };
12728
+ }
12729
+ health.recordFailure("telemetry-export-failure", points.length, options.clock.now());
12730
+ const permanent = isPermanentExportFailure(result);
12731
+ if (options.spool !== void 0 && !permanent) {
12732
+ const spooled = await options.spool.enqueue(toSpoolBatch(points, batchResource)).catch(() => ({
12733
+ spooled: false,
12734
+ reason: "capacity-exceeded"
12735
+ }));
12736
+ if (spooled.spooled) {
12737
+ options.logger?.warn("metric batch not delivered; spooled for the next invocation", {
12738
+ "export.batch_size": points.length,
12739
+ ...destinationFields
12740
+ });
12741
+ return { accepted: points.length, rejected: 0, errors: [] };
12742
+ }
12743
+ }
12744
+ return {
12745
+ accepted: 0,
12746
+ rejected: points.length,
12747
+ errors: [
12748
+ createErrorInfo({
12749
+ code: "telemetry-export-failure",
12750
+ phase: "export",
12751
+ detail: permanent ? "collector refused a metric batch with a non-retryable status" : "collector rejected or was unreachable for a metric batch",
12752
+ details: {
12753
+ "export.batch_size": points.length,
12754
+ "export.signal": "metrics",
12755
+ ...destinationFields
12756
+ }
12757
+ })
12758
+ ]
12759
+ };
12760
+ };
12761
+ const drainSpool = async (maxBatches) => {
12762
+ if (options.spool === void 0) {
12763
+ return { drained: 0, remaining: 0, failed: 0 };
12764
+ }
12765
+ const result = await options.spool.drain(sendSerializedBatch, {
12766
+ ...maxBatches === void 0 ? {} : { maxBatches }
12767
+ });
12768
+ if (result.drained > 0) {
12769
+ health.recordSuccess(result.drained, options.clock.now());
12770
+ }
12771
+ return result;
12772
+ };
12773
+ const flush = async () => {
12774
+ try {
12775
+ await exporter.forceFlush();
12776
+ } catch {
12777
+ }
12778
+ await drainSpool().catch(() => void 0);
12779
+ };
12780
+ const shutdown = async () => {
12781
+ if (shutdownCompleted) {
12782
+ return;
12783
+ }
12784
+ shutdownCompleted = true;
12785
+ await flush();
12786
+ try {
12787
+ await exporter.shutdown();
12788
+ } catch {
12789
+ }
12790
+ };
12791
+ return {
12792
+ enabled: true,
12793
+ exportPoints,
12794
+ flush,
12795
+ shutdown,
12796
+ health: () => health.snapshot(),
12797
+ drainSpool
12798
+ };
12799
+ };
12800
+
11663
12801
  // src/telemetry/export-destinations.ts
11664
- var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs" } : { traces: `destinations/${destination}/spool`, logs: `destinations/${destination}/spool-logs` };
12802
+ var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs", metrics: "spool-metrics" } : {
12803
+ traces: `destinations/${destination}/spool`,
12804
+ logs: `destinations/${destination}/spool-logs`,
12805
+ metrics: `destinations/${destination}/spool-metrics`
12806
+ };
11665
12807
  var exporterPolicyForDestination = (exporter, destination) => {
11666
12808
  if (destination.source === "exporter") {
11667
12809
  return exporter;
@@ -11678,8 +12820,10 @@ var exporterPolicyForDestination = (exporter, destination) => {
11678
12820
  });
11679
12821
  return "endpoint" in derived ? derived.endpoint : void 0;
11680
12822
  })());
12823
+ const { metrics: sharedMetrics, ...rest } = shared;
12824
+ const derivedMetrics = destination.metricsEndpoint ?? (destination.endpoint === void 0 ? void 0 : siblingSignalEndpoint(destination.endpoint, "metrics"));
11681
12825
  return {
11682
- ...shared,
12826
+ ...rest,
11683
12827
  protocol: destination.protocol,
11684
12828
  ...tracesEndpoint === void 0 ? {} : { endpoint: tracesEndpoint },
11685
12829
  headerNames: Object.keys(destination.headers).sort(),
@@ -11687,6 +12831,11 @@ var exporterPolicyForDestination = (exporter, destination) => {
11687
12831
  ...logs,
11688
12832
  enabled: destination.signals.logs,
11689
12833
  ...derivedLogs === void 0 ? {} : { endpoint: derivedLogs }
12834
+ },
12835
+ metrics: {
12836
+ ...effectiveMetricsPolicy({ ...exporter, metrics: sharedMetrics }),
12837
+ enabled: destination.signals.metrics,
12838
+ ...derivedMetrics === void 0 ? {} : { endpoint: derivedMetrics }
11690
12839
  }
11691
12840
  };
11692
12841
  };
@@ -11758,6 +12907,12 @@ var createExportDestinationSinks = (options) => {
11758
12907
  ...bounds,
11759
12908
  queueName: queues.logs
11760
12909
  });
12910
+ const metricSpool = options.spoolRootDir === void 0 || !destination.signals.metrics ? void 0 : createFileDurableMetricSpool({
12911
+ rootDir: options.spoolRootDir,
12912
+ ...shared,
12913
+ ...bounds,
12914
+ queueName: queues.metrics
12915
+ });
11761
12916
  const sinkShared = {
11762
12917
  exporter: policy,
11763
12918
  ...shared,
@@ -11775,12 +12930,21 @@ var createExportDestinationSinks = (options) => {
11775
12930
  ...logSpool === void 0 ? {} : { spool: logSpool },
11776
12931
  content: options.logContent
11777
12932
  });
12933
+ const metrics = destination.signals.metrics ? createOtlpMetricSink({
12934
+ exporter: policy,
12935
+ ...shared,
12936
+ ...label === void 0 ? {} : { destination: label },
12937
+ ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
12938
+ ...metricSpool === void 0 ? {} : { spool: metricSpool }
12939
+ }) : createDisabledOtlpMetricSink(label);
11778
12940
  destinations.push({
11779
12941
  name: destination.name,
11780
12942
  traces,
11781
12943
  logs,
12944
+ metrics,
11782
12945
  ...spool === void 0 ? {} : { spool },
11783
- ...logSpool === void 0 ? {} : { logSpool }
12946
+ ...logSpool === void 0 ? {} : { logSpool },
12947
+ ...metricSpool === void 0 ? {} : { metricSpool }
11784
12948
  });
11785
12949
  }
11786
12950
  return { destinations, skipped };
@@ -11939,6 +13103,16 @@ var createHookRuntime = (options) => {
11939
13103
  logger,
11940
13104
  installationId: options.installationId,
11941
13105
  payloadEnrichers: options.payloadEnrichers ?? (readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : []),
13106
+ ...(() => {
13107
+ if (options.sessionContextReader === null) {
13108
+ return {};
13109
+ }
13110
+ if (options.sessionContextReader !== void 0) {
13111
+ return { sessionContext: options.sessionContextReader };
13112
+ }
13113
+ const dir = sessionContextDir(options.config);
13114
+ return dir === void 0 ? {} : { sessionContext: createDirectorySessionContextReader({ dir }) };
13115
+ })(),
11942
13116
  ...options.worktreeLocator === null ? {} : {
11943
13117
  worktreeLocator: options.worktreeLocator ?? createFilesystemWorktreeLocator({ monotonicMillis: () => clock.monotonicMillis() })
11944
13118
  }
@@ -11946,6 +13120,12 @@ var createHookRuntime = (options) => {
11946
13120
  const hook = createOtelHook({ ...hookDeps, sink });
11947
13121
  const deduplicator = createCallbackDeduplicator({ stateStore, clock });
11948
13122
  const usageAccumulator = createUsageAccumulator({ stateStore, clock });
13123
+ const metricSeries = createMetricSeriesStore({ stateStore, clock });
13124
+ const metricsPolicy = effectiveMetricsPolicy(options.config.exporter);
13125
+ const metricDestinations = exportDestinations.destinations.filter(
13126
+ (destination) => destination.metrics.enabled
13127
+ );
13128
+ const metricResource = resourceFromExporterPolicy(options.config.exporter);
11949
13129
  const deliveryRetentionMillis = options.deliveryRetentionMillis ?? lifecycleMaxAge;
11950
13130
  if (deliveryRetentionMillis < staleClaimMillis) {
11951
13131
  logger.warn("delivery retention is shorter than the stale-claim window", {
@@ -11957,6 +13137,7 @@ var createHookRuntime = (options) => {
11957
13137
  spanCorrelator,
11958
13138
  deduplicator,
11959
13139
  usageAccumulator,
13140
+ metricSeries,
11960
13141
  spanMaxAgeMillis: lifecycleMaxAge,
11961
13142
  dedupMaxAgeMillis: deliveryRetentionMillis,
11962
13143
  // The *effective* window, not the requested one: a sweep that considered a
@@ -11967,6 +13148,87 @@ var createHookRuntime = (options) => {
11967
13148
  });
11968
13149
  const deliveryLock = createAsyncLock();
11969
13150
  const stateDiagnostic = (thrown) => errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() });
13151
+ const generationStartsFor = async (events) => {
13152
+ const needed = events.some(
13153
+ (event3) => event3.type === "generation.end" && event3.durationMillis === void 0 && !events.some(
13154
+ (other) => other.type === "generation.start" && other.generationId === event3.generationId
13155
+ )
13156
+ );
13157
+ if (!needed) {
13158
+ return void 0;
13159
+ }
13160
+ try {
13161
+ const starts = /* @__PURE__ */ new Map();
13162
+ for (const correlation of await correlate(events)) {
13163
+ if (correlation.ref.family !== "generation" || correlation.startMillis === void 0) {
13164
+ continue;
13165
+ }
13166
+ const requestModel = correlation.attributes?.["gen_ai.request.model"];
13167
+ starts.set(correlation.ref.scopeKey, {
13168
+ startMillis: correlation.startMillis,
13169
+ ...typeof requestModel === "string" ? { requestModel } : {}
13170
+ });
13171
+ }
13172
+ return (generationId) => starts.get(generationId);
13173
+ } catch {
13174
+ return void 0;
13175
+ }
13176
+ };
13177
+ const recordMetrics = async (ingest, deliveryToken, diagnostics) => {
13178
+ if (metricDestinations.length === 0 || ingest.events.length === 0) {
13179
+ return void 0;
13180
+ }
13181
+ try {
13182
+ for (const event3 of ingest.events) {
13183
+ if (event3.type === "prompt.submitted") {
13184
+ await metricSeries.recordTurnStart(event3.sessionId, event3.occurredAt);
13185
+ }
13186
+ }
13187
+ const generationStarts = await generationStartsFor(ingest.events);
13188
+ const turnStarts = /* @__PURE__ */ new Map();
13189
+ for (const event3 of ingest.events) {
13190
+ if (event3.type === "generation.end" && !turnStarts.has(event3.sessionId)) {
13191
+ turnStarts.set(event3.sessionId, await metricSeries.readTurnStart(event3.sessionId));
13192
+ }
13193
+ }
13194
+ const observations = deriveMetricObservations({
13195
+ events: ingest.events,
13196
+ usage: ingest.usageObservations,
13197
+ resource: metricResource,
13198
+ includeSessionId: metricsPolicy.includeSessionId,
13199
+ ...generationStarts === void 0 ? {} : { generationStarts },
13200
+ turnStart: (sessionId) => turnStarts.get(sessionId)
13201
+ });
13202
+ if (observations.length === 0) {
13203
+ return void 0;
13204
+ }
13205
+ const points = metricsPolicy.temporality === "delta" ? aggregateDeltaPoints(observations, clock.now()) : await metricSeries.recordCumulative(observations, {
13206
+ perSession: metricsPolicy.includeSessionId,
13207
+ ...deliveryToken === void 0 ? {} : { deliveryToken }
13208
+ });
13209
+ const context = agreedContextAttributes(ingest.events);
13210
+ const results = await Promise.all(
13211
+ metricDestinations.map(async (destination) => {
13212
+ const result = await destination.metrics.exportPoints(points, context).catch(
13213
+ (thrown) => ({
13214
+ accepted: 0,
13215
+ rejected: points.length,
13216
+ errors: [
13217
+ errorInfoFromThrown(thrown, { code: "telemetry-export-failure", phase: "export" })
13218
+ ]
13219
+ })
13220
+ );
13221
+ diagnostics.push(...result.errors);
13222
+ return { name: destination.name, accepted: result.accepted, rejected: result.rejected };
13223
+ })
13224
+ );
13225
+ return { points: points.length, destinations: results };
13226
+ } catch (thrown) {
13227
+ diagnostics.push(stateDiagnostic(thrown));
13228
+ logger.warn("hook-derived metrics could not be recorded for this callback", {});
13229
+ return void 0;
13230
+ }
13231
+ };
11970
13232
  const rollupDeliveryToken = (identity) => {
11971
13233
  const token = ids.newOpaqueId(["usage-delivery", identity.scope, identity.callbackId]).replace(/[^A-Za-z0-9_-]/g, "").slice(0, 128);
11972
13234
  return token.length === 0 ? void 0 : token;
@@ -12087,6 +13349,11 @@ var createHookRuntime = (options) => {
12087
13349
  identity === void 0 ? void 0 : rollupDeliveryToken(identity)
12088
13350
  );
12089
13351
  }
13352
+ const metrics = !duplicateDelivery && ingest.identity !== void 0 && isCommittable(ingest.durability) ? await recordMetrics(
13353
+ ingest,
13354
+ identity === void 0 ? void 0 : rollupDeliveryToken(identity),
13355
+ diagnostics
13356
+ ) : void 0;
12090
13357
  if (owned && identity !== void 0) {
12091
13358
  try {
12092
13359
  if (isCommittable(ingest.durability)) {
@@ -12153,6 +13420,7 @@ var createHookRuntime = (options) => {
12153
13420
  duplicateDelivery,
12154
13421
  delivery,
12155
13422
  usageRollups,
13423
+ ...metrics === void 0 ? {} : { metrics },
12156
13424
  ...cleanup === void 0 ? {} : { cleanup },
12157
13425
  diagnostics
12158
13426
  };
@@ -12169,12 +13437,20 @@ var createHookRuntime = (options) => {
12169
13437
  () => runProcess(input, identified.identity, report, diagnostics)
12170
13438
  );
12171
13439
  };
12172
- const snapshots = () => sink.health();
13440
+ const snapshots = () => [
13441
+ ...sink.health(),
13442
+ ...metricDestinations.map((destination) => destination.metrics.health())
13443
+ ];
12173
13444
  let shutdownReport;
12174
13445
  const shutdown = () => {
12175
13446
  shutdownReport ??= (async () => {
12176
13447
  const raced = await Promise.race([
12177
- hook.shutdown().then(() => "completed"),
13448
+ Promise.all([
13449
+ hook.shutdown(),
13450
+ // Metric sinks are not behind the hook's sink: they replay their own
13451
+ // spools here, inside the same bounded window.
13452
+ ...metricDestinations.map((destination) => destination.metrics.shutdown().catch(() => void 0))
13453
+ ]).then(() => "completed"),
12178
13454
  delay(flushTimeoutMillis)
12179
13455
  ]);
12180
13456
  if (raced === "timeout") {
@@ -12204,6 +13480,7 @@ var createHookRuntime = (options) => {
12204
13480
  deduplicator,
12205
13481
  usageAccumulator,
12206
13482
  spanCorrelator,
13483
+ metricSeries,
12207
13484
  janitor,
12208
13485
  process: process_,
12209
13486
  shutdown,
@@ -12212,12 +13489,12 @@ var createHookRuntime = (options) => {
12212
13489
  };
12213
13490
 
12214
13491
  // src/providers/antigravity/registration.ts
12215
- var isPlainObject5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
13492
+ var isPlainObject6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
12216
13493
  var mergeAntigravityHookRegistration = (input) => {
12217
13494
  const events = input.events ?? ANTIGRAVITY_HOOK_EVENT_NAMES;
12218
- const base = isPlainObject5(input.existing) ? input.existing : {};
12219
- const existingHooks = isPlainObject5(base.hooks) ? base.hooks : {};
12220
- let changed = !isPlainObject5(input.existing) || !isPlainObject5(base.hooks);
13495
+ const base = isPlainObject6(input.existing) ? input.existing : {};
13496
+ const existingHooks = isPlainObject6(base.hooks) ? base.hooks : {};
13497
+ let changed = !isPlainObject6(input.existing) || !isPlainObject6(base.hooks);
12221
13498
  const nextHooks = { ...existingHooks };
12222
13499
  const identifies = input.identifies ?? ((entry) => entry.command === input.command);
12223
13500
  const desired = {
@@ -12226,7 +13503,7 @@ var mergeAntigravityHookRegistration = (input) => {
12226
13503
  };
12227
13504
  for (const event3 of events) {
12228
13505
  const currentList = Array.isArray(existingHooks[event3]) ? [...existingHooks[event3]] : [];
12229
- const managedIndex = currentList.findIndex((entry) => isPlainObject5(entry) && identifies(entry));
13506
+ const managedIndex = currentList.findIndex((entry) => isPlainObject6(entry) && identifies(entry));
12230
13507
  if (managedIndex === -1) {
12231
13508
  changed = true;
12232
13509
  nextHooks[event3] = [...currentList, desired];
@@ -12235,7 +13512,7 @@ var mergeAntigravityHookRegistration = (input) => {
12235
13512
  const managed = currentList[managedIndex];
12236
13513
  const updated = { ...managed, ...desired };
12237
13514
  const next = currentList.filter(
12238
- (entry, index) => index === managedIndex || !(isPlainObject5(entry) && identifies(entry))
13515
+ (entry, index) => index === managedIndex || !(isPlainObject6(entry) && identifies(entry))
12239
13516
  );
12240
13517
  next[next.indexOf(managed)] = updated;
12241
13518
  const rewritten = Object.entries(desired).some(([key, value]) => managed[key] !== value);
@@ -12250,8 +13527,8 @@ var mergeAntigravityHookRegistration = (input) => {
12250
13527
  };
12251
13528
  };
12252
13529
  var removeAntigravityHookRegistration = (input) => {
12253
- const base = isPlainObject5(input.existing) ? { ...input.existing } : {};
12254
- if (!isPlainObject5(base.hooks)) {
13530
+ const base = isPlainObject6(input.existing) ? { ...input.existing } : {};
13531
+ if (!isPlainObject6(base.hooks)) {
12255
13532
  return { config: base, changed: false };
12256
13533
  }
12257
13534
  const nextHooks = { ...base.hooks };
@@ -12263,7 +13540,7 @@ var removeAntigravityHookRegistration = (input) => {
12263
13540
  continue;
12264
13541
  }
12265
13542
  const kept = currentList.filter(
12266
- (entry) => !(isPlainObject5(entry) && input.identifies(entry))
13543
+ (entry) => !(isPlainObject6(entry) && input.identifies(entry))
12267
13544
  );
12268
13545
  if (kept.length === currentList.length) {
12269
13546
  continue;
@@ -12288,7 +13565,7 @@ var removeAntigravityHookRegistration = (input) => {
12288
13565
  };
12289
13566
  var readAntigravityHookRegistrations = (existing, identifies) => {
12290
13567
  const found = /* @__PURE__ */ new Map();
12291
- if (!isPlainObject5(existing) || !isPlainObject5(existing.hooks)) {
13568
+ if (!isPlainObject6(existing) || !isPlainObject6(existing.hooks)) {
12292
13569
  return found;
12293
13570
  }
12294
13571
  for (const [event3, list] of Object.entries(existing.hooks)) {
@@ -12296,7 +13573,7 @@ var readAntigravityHookRegistrations = (existing, identifies) => {
12296
13573
  continue;
12297
13574
  }
12298
13575
  const commands = list.filter(
12299
- (entry) => isPlainObject5(entry) && typeof entry.command === "string" && identifies(entry)
13576
+ (entry) => isPlainObject6(entry) && typeof entry.command === "string" && identifies(entry)
12300
13577
  ).map((entry) => entry.command);
12301
13578
  if (commands.length > 0) {
12302
13579
  found.set(event3, commands);
@@ -12306,10 +13583,10 @@ var readAntigravityHookRegistrations = (existing, identifies) => {
12306
13583
  };
12307
13584
 
12308
13585
  // src/providers/hook-document.ts
12309
- var isPlainObject6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
13586
+ var isPlainObject7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
12310
13587
  var normalizeMatcher = (value) => typeof value === "string" && value !== "" && value !== "*" ? value : void 0;
12311
- var isManaged = (value, identifies) => isPlainObject6(value) && identifies(value);
12312
- var cloneGroup = (value) => isPlainObject6(value) && Array.isArray(value.hooks) ? { ...value, hooks: [...value.hooks] } : void 0;
13588
+ var isManaged = (value, identifies) => isPlainObject7(value) && identifies(value);
13589
+ var cloneGroup = (value) => isPlainObject7(value) && Array.isArray(value.hooks) ? { ...value, hooks: [...value.hooks] } : void 0;
12313
13590
  var matchesDesired = (existing, desired) => {
12314
13591
  for (const [key, value] of Object.entries(desired)) {
12315
13592
  if (existing[key] !== value) {
@@ -12337,7 +13614,7 @@ var readHooksObject = (base, conflicts) => {
12337
13614
  if (raw === void 0) {
12338
13615
  return {};
12339
13616
  }
12340
- if (!isPlainObject6(raw)) {
13617
+ if (!isPlainObject7(raw)) {
12341
13618
  conflicts.push({
12342
13619
  location: "hooks",
12343
13620
  detail: `expected an object keyed by hook event name, found ${Array.isArray(raw) ? "an array" : raw === null ? "null" : typeof raw}`
@@ -12346,7 +13623,7 @@ var readHooksObject = (base, conflicts) => {
12346
13623
  }
12347
13624
  return { ...raw };
12348
13625
  };
12349
- var pruneEventList = (list) => list.filter((group) => !(isPlainObject6(group) && Array.isArray(group.hooks) && group.hooks.length === 0));
13626
+ var pruneEventList = (list) => list.filter((group) => !(isPlainObject7(group) && Array.isArray(group.hooks) && group.hooks.length === 0));
12350
13627
  var finalize = (base, hooks) => {
12351
13628
  const next = { ...base };
12352
13629
  if (Object.keys(hooks).length === 0) {
@@ -12357,7 +13634,7 @@ var finalize = (base, hooks) => {
12357
13634
  return next;
12358
13635
  };
12359
13636
  var mergeNestedHookRegistration = (input) => {
12360
- const base = isPlainObject6(input.existing) ? { ...input.existing } : {};
13637
+ const base = isPlainObject7(input.existing) ? { ...input.existing } : {};
12361
13638
  const conflicts = [];
12362
13639
  const hooks = readHooksObject(base, conflicts);
12363
13640
  if (hooks === void 0) {
@@ -12373,7 +13650,7 @@ var mergeNestedHookRegistration = (input) => {
12373
13650
  }
12374
13651
  const groups = list.map((group) => cloneGroup(group) ?? group);
12375
13652
  const usableGroups = groups.filter(
12376
- (group) => isPlainObject6(group) && Array.isArray(group.hooks)
13653
+ (group) => isPlainObject7(group) && Array.isArray(group.hooks)
12377
13654
  );
12378
13655
  let ownHandler;
12379
13656
  let ownGroup;
@@ -12438,7 +13715,7 @@ var mergeNestedHookRegistration = (input) => {
12438
13715
  return { document: finalize(base, hooks), changed, changes, conflicts };
12439
13716
  };
12440
13717
  var removeNestedHookRegistrations = (input) => {
12441
- const base = isPlainObject6(input.existing) ? { ...input.existing } : {};
13718
+ const base = isPlainObject7(input.existing) ? { ...input.existing } : {};
12442
13719
  const conflicts = [];
12443
13720
  const hooks = readHooksObject(base, conflicts);
12444
13721
  if (hooks === void 0) {
@@ -12491,7 +13768,7 @@ var removeNestedHookRegistrations = (input) => {
12491
13768
  };
12492
13769
  var readNestedHookRegistrations = (existing, identifies) => {
12493
13770
  const found = /* @__PURE__ */ new Map();
12494
- if (!isPlainObject6(existing) || !isPlainObject6(existing.hooks)) {
13771
+ if (!isPlainObject7(existing) || !isPlainObject7(existing.hooks)) {
12495
13772
  return found;
12496
13773
  }
12497
13774
  for (const [event3, list] of Object.entries(existing.hooks)) {
@@ -12500,7 +13777,7 @@ var readNestedHookRegistrations = (existing, identifies) => {
12500
13777
  }
12501
13778
  const commands = [];
12502
13779
  for (const group of list) {
12503
- if (!isPlainObject6(group) || !Array.isArray(group.hooks)) {
13780
+ if (!isPlainObject7(group) || !Array.isArray(group.hooks)) {
12504
13781
  continue;
12505
13782
  }
12506
13783
  for (const handler of group.hooks) {
@@ -12640,7 +13917,7 @@ var CURSOR_UNREGISTERED_HOOK_EVENTS = Object.freeze({
12640
13917
  workspaceOpen: "an app-lifecycle hook that carries no conversation_id, so it has no session to attribute telemetry to"
12641
13918
  });
12642
13919
  var CURSOR_HOOKS_DOCUMENT_VERSION = 1;
12643
- var isPlainObject7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
13920
+ var isPlainObject8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
12644
13921
  var buildEntry3 = (input) => ({
12645
13922
  type: "command",
12646
13923
  command: input.command,
@@ -12649,8 +13926,8 @@ var buildEntry3 = (input) => ({
12649
13926
  });
12650
13927
  var mergeCursorHookRegistration = (input) => {
12651
13928
  const events = input.events ?? CURSOR_REGISTRABLE_HOOK_EVENTS;
12652
- const base = isPlainObject7(input.existing) ? { ...input.existing } : {};
12653
- const existingHooks = isPlainObject7(base.hooks) ? base.hooks : {};
13929
+ const base = isPlainObject8(input.existing) ? { ...input.existing } : {};
13930
+ const existingHooks = isPlainObject8(base.hooks) ? base.hooks : {};
12654
13931
  const nextHooks = { ...existingHooks };
12655
13932
  const desired = buildEntry3(input);
12656
13933
  let changed = false;
@@ -12661,7 +13938,7 @@ var mergeCursorHookRegistration = (input) => {
12661
13938
  for (const event3 of events) {
12662
13939
  const currentList = Array.isArray(existingHooks[event3]) ? [...existingHooks[event3]] : [];
12663
13940
  const managed = currentList.filter(
12664
- (entry) => isPlainObject7(entry) && input.identifies(entry)
13941
+ (entry) => isPlainObject8(entry) && input.identifies(entry)
12665
13942
  );
12666
13943
  const [ours] = managed;
12667
13944
  if (ours === void 0) {
@@ -12670,7 +13947,7 @@ var mergeCursorHookRegistration = (input) => {
12670
13947
  continue;
12671
13948
  }
12672
13949
  const rewritten = { ...ours, ...desired };
12673
- const next = currentList.filter((entry) => entry === ours || !(isPlainObject7(entry) && input.identifies(entry))).map((entry) => entry === ours ? rewritten : entry);
13950
+ const next = currentList.filter((entry) => entry === ours || !(isPlainObject8(entry) && input.identifies(entry))).map((entry) => entry === ours ? rewritten : entry);
12674
13951
  const entryChanged = Object.entries(desired).some(([key, value]) => ours[key] !== value);
12675
13952
  if (entryChanged || managed.length > 1) {
12676
13953
  changed = true;
@@ -12680,8 +13957,8 @@ var mergeCursorHookRegistration = (input) => {
12680
13957
  return { config: { ...base, hooks: nextHooks }, changed };
12681
13958
  };
12682
13959
  var removeCursorHookRegistration = (input) => {
12683
- const base = isPlainObject7(input.existing) ? { ...input.existing } : {};
12684
- if (!isPlainObject7(base.hooks)) {
13960
+ const base = isPlainObject8(input.existing) ? { ...input.existing } : {};
13961
+ if (!isPlainObject8(base.hooks)) {
12685
13962
  return { config: base, changed: false };
12686
13963
  }
12687
13964
  const nextHooks = { ...base.hooks };
@@ -12693,7 +13970,7 @@ var removeCursorHookRegistration = (input) => {
12693
13970
  continue;
12694
13971
  }
12695
13972
  const kept = currentList.filter(
12696
- (entry) => !(isPlainObject7(entry) && input.identifies(entry))
13973
+ (entry) => !(isPlainObject8(entry) && input.identifies(entry))
12697
13974
  );
12698
13975
  if (kept.length === currentList.length) {
12699
13976
  continue;
@@ -12721,7 +13998,7 @@ var removeCursorHookRegistration = (input) => {
12721
13998
  };
12722
13999
  var readCursorHookRegistrations = (existing, identifies) => {
12723
14000
  const found = /* @__PURE__ */ new Map();
12724
- if (!isPlainObject7(existing) || !isPlainObject7(existing.hooks)) {
14001
+ if (!isPlainObject8(existing) || !isPlainObject8(existing.hooks)) {
12725
14002
  return found;
12726
14003
  }
12727
14004
  for (const [event3, list] of Object.entries(existing.hooks)) {
@@ -12729,7 +14006,7 @@ var readCursorHookRegistrations = (existing, identifies) => {
12729
14006
  continue;
12730
14007
  }
12731
14008
  const commands = list.filter(
12732
- (entry) => isPlainObject7(entry) && typeof entry.command === "string" && identifies(entry)
14009
+ (entry) => isPlainObject8(entry) && typeof entry.command === "string" && identifies(entry)
12733
14010
  ).map((entry) => entry.command);
12734
14011
  if (commands.length > 0) {
12735
14012
  found.set(event3, commands);
@@ -12829,7 +14106,7 @@ var managedHookPredicate = (marker) => {
12829
14106
  }
12830
14107
  return (handler) => handler.name === MANAGED_HOOK_NAME || typeof handler.command === "string" && handler.command.includes(marker);
12831
14108
  };
12832
- var isPlainObject8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
14109
+ var isPlainObject9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
12833
14110
  var adaptFlatResult = (read, existing, events, identifies, result, removal) => {
12834
14111
  const before = read(existing, identifies);
12835
14112
  const after = read(result.config, identifies);
@@ -12853,10 +14130,10 @@ var adaptFlatResult = (read, existing, events, identifies, result, removal) => {
12853
14130
  return { document: result.config, changed: result.changed, changes, conflicts: [] };
12854
14131
  };
12855
14132
  var flatHookConflicts = (existing) => {
12856
- if (!isPlainObject8(existing) || existing.hooks === void 0) {
14133
+ if (!isPlainObject9(existing) || existing.hooks === void 0) {
12857
14134
  return [];
12858
14135
  }
12859
- if (!isPlainObject8(existing.hooks)) {
14136
+ if (!isPlainObject9(existing.hooks)) {
12860
14137
  return [
12861
14138
  {
12862
14139
  location: "hooks",
@@ -12876,7 +14153,7 @@ var flatHookConflicts = (existing) => {
12876
14153
  return conflicts;
12877
14154
  };
12878
14155
  var asAntigravityEvents = (events) => events;
12879
- var documentEventNames = (existing) => isPlainObject8(existing) && isPlainObject8(existing.hooks) ? Object.keys(existing.hooks) : [];
14156
+ var documentEventNames = (existing) => isPlainObject9(existing) && isPlainObject9(existing.hooks) ? Object.keys(existing.hooks) : [];
12880
14157
  var PLANNERS = Object.freeze([
12881
14158
  Object.freeze({
12882
14159
  providerId: ANTIGRAVITY_PROVIDER_ID,
@@ -12885,7 +14162,7 @@ var PLANNERS = Object.freeze([
12885
14162
  const conflicts = flatHookConflicts(input.existing);
12886
14163
  if (conflicts.length > 0) {
12887
14164
  return {
12888
- document: isPlainObject8(input.existing) ? input.existing : {},
14165
+ document: isPlainObject9(input.existing) ? input.existing : {},
12889
14166
  changed: false,
12890
14167
  changes: [],
12891
14168
  conflicts
@@ -12911,7 +14188,7 @@ var PLANNERS = Object.freeze([
12911
14188
  const conflicts = flatHookConflicts(input.existing);
12912
14189
  if (conflicts.length > 0) {
12913
14190
  return {
12914
- document: isPlainObject8(input.existing) ? input.existing : {},
14191
+ document: isPlainObject9(input.existing) ? input.existing : {},
12915
14192
  changed: false,
12916
14193
  changes: [],
12917
14194
  conflicts
@@ -12954,7 +14231,7 @@ var PLANNERS = Object.freeze([
12954
14231
  const conflicts = flatHookConflicts(input.existing);
12955
14232
  if (conflicts.length > 0) {
12956
14233
  return {
12957
- document: isPlainObject8(input.existing) ? input.existing : {},
14234
+ document: isPlainObject9(input.existing) ? input.existing : {},
12958
14235
  changed: false,
12959
14236
  changes: [],
12960
14237
  conflicts
@@ -12981,7 +14258,7 @@ var PLANNERS = Object.freeze([
12981
14258
  const conflicts = flatHookConflicts(input.existing);
12982
14259
  if (conflicts.length > 0) {
12983
14260
  return {
12984
- document: isPlainObject8(input.existing) ? input.existing : {},
14261
+ document: isPlainObject9(input.existing) ? input.existing : {},
12985
14262
  changed: false,
12986
14263
  changes: [],
12987
14264
  conflicts
@@ -13072,7 +14349,7 @@ var SUPPORTED_REGISTRATION_PROVIDER_IDS = Object.freeze(
13072
14349
  );
13073
14350
 
13074
14351
  // src/install/scopes.ts
13075
- import * as path6 from "path";
14352
+ import * as path7 from "path";
13076
14353
  var REGISTRATION_SCOPES = Object.freeze([
13077
14354
  "global",
13078
14355
  "project"
@@ -13140,15 +14417,15 @@ var PROVIDERS_WITH_VERIFIED_LOCATION = Object.freeze([
13140
14417
  var findInstallLocation = (providerId, scope) => PROVIDER_INSTALL_LOCATIONS.find(
13141
14418
  (entry) => entry.providerId === providerId && entry.scope === scope
13142
14419
  );
13143
- var resolveInstallPath = (location, roots) => path6.resolve(
14420
+ var resolveInstallPath = (location, roots) => path7.resolve(
13144
14421
  location.scope === "global" ? roots.homeDir : roots.projectDir,
13145
14422
  ...location.segments
13146
14423
  );
13147
14424
 
13148
14425
  // src/install/document.ts
13149
14426
  import { randomBytes as randomBytes4 } from "crypto";
13150
- import { chmod, mkdir as mkdir3, open as open4, readFile as readFile3, rename as rename3, stat as stat4, unlink as unlink3 } from "fs/promises";
13151
- import * as path7 from "path";
14427
+ import { chmod, mkdir as mkdir3, open as open5, readFile as readFile3, rename as rename3, stat as stat4, unlink as unlink3 } from "fs/promises";
14428
+ import * as path8 from "path";
13152
14429
  var DEFAULT_DOCUMENT_FORMAT = Object.freeze({
13153
14430
  indent: " ",
13154
14431
  eol: "\n",
@@ -13219,11 +14496,11 @@ var renameWithRetry = async (from, to) => {
13219
14496
  var NEW_DOCUMENT_MODE = 384;
13220
14497
  var TEMPORARY_DOCUMENT_MODE = 384;
13221
14498
  var writeDocumentAtomically = async (filePath, contents) => {
13222
- const directory = path7.dirname(filePath);
14499
+ const directory = path8.dirname(filePath);
13223
14500
  await mkdir3(directory, { recursive: true });
13224
- const temporary = path7.join(
14501
+ const temporary = path8.join(
13225
14502
  directory,
13226
- `.${path7.basename(filePath)}.${randomBytes4(6).toString("hex")}.tmp`
14503
+ `.${path8.basename(filePath)}.${randomBytes4(6).toString("hex")}.tmp`
13227
14504
  );
13228
14505
  let existingMode;
13229
14506
  try {
@@ -13235,7 +14512,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
13235
14512
  }
13236
14513
  const targetMode = existingMode ?? NEW_DOCUMENT_MODE;
13237
14514
  try {
13238
- const handle = await open4(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
14515
+ const handle = await open5(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
13239
14516
  try {
13240
14517
  await handle.writeFile(contents, "utf8");
13241
14518
  await handle.sync();
@@ -13252,12 +14529,12 @@ var writeDocumentAtomically = async (filePath, contents) => {
13252
14529
 
13253
14530
  // src/install/file-lock.ts
13254
14531
  import { randomBytes as randomBytes5 } from "crypto";
13255
- import { mkdir as mkdir4, open as open5, readFile as readFile4, rename as rename4, stat as stat5, unlink as unlink4 } from "fs/promises";
13256
- import * as path8 from "path";
14532
+ import { mkdir as mkdir4, open as open6, readFile as readFile4, rename as rename4, stat as stat5, unlink as unlink4 } from "fs/promises";
14533
+ import * as path9 from "path";
13257
14534
  var FileLockTimeoutError = class extends Error {
13258
14535
  constructor(lockPath, timeoutMillis) {
13259
14536
  super(
13260
- `timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path8.basename(lockPath)}`
14537
+ `timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path9.basename(lockPath)}`
13261
14538
  );
13262
14539
  this.name = "FileLockTimeoutError";
13263
14540
  }
@@ -13329,12 +14606,12 @@ var withFileLock = async (filePath, options, fn) => {
13329
14606
  const pollIntervalMillis = options.pollIntervalMillis ?? 25;
13330
14607
  const lockPath = lockPathFor(filePath);
13331
14608
  const startedAt = options.clock.monotonicMillis();
13332
- await mkdir4(path8.dirname(filePath), { recursive: true });
14609
+ await mkdir4(path9.dirname(filePath), { recursive: true });
13333
14610
  for (; ; ) {
13334
14611
  const token = randomBytes5(16).toString("hex");
13335
14612
  let acquired = false;
13336
14613
  try {
13337
- const handle = await open5(lockPath, "wx", 384);
14614
+ const handle = await open6(lockPath, "wx", 384);
13338
14615
  try {
13339
14616
  const contents = {
13340
14617
  token,
@@ -13377,7 +14654,7 @@ var withFileLock = async (filePath, options, fn) => {
13377
14654
 
13378
14655
  // src/install/lifecycle.ts
13379
14656
  import { readFile as readFile5 } from "fs/promises";
13380
- import * as path9 from "path";
14657
+ import * as path10 from "path";
13381
14658
  var defaultHookCommand = (providerId) => `otel-hook run --provider ${providerId}`;
13382
14659
  var unsupportedOutcome = (providerId, scope, reason) => ({
13383
14660
  providerId,
@@ -13394,7 +14671,7 @@ var unsupportedOutcome = (providerId, scope, reason) => ({
13394
14671
  var resolveTarget = (providerId, scope, request) => {
13395
14672
  if (request.configFile !== void 0) {
13396
14673
  return {
13397
- configPath: path9.resolve(request.configFile),
14674
+ configPath: path10.resolve(request.configFile),
13398
14675
  evidence: "path supplied by the caller with --settings-file"
13399
14676
  };
13400
14677
  }
@@ -13411,14 +14688,14 @@ var resolveTarget = (providerId, scope, request) => {
13411
14688
  };
13412
14689
  };
13413
14690
  var codexFeatureNote = async (configPath) => {
13414
- const tomlPath = path9.join(path9.dirname(configPath), "config.toml");
14691
+ const tomlPath = path10.join(path10.dirname(configPath), "config.toml");
13415
14692
  let raw;
13416
14693
  try {
13417
14694
  raw = await readFile5(tomlPath, "utf8");
13418
14695
  } catch {
13419
14696
  return void 0;
13420
14697
  }
13421
- return readCodexHooksFeatureFlag(raw) === "disabled" ? `${path9.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed` : void 0;
14698
+ return readCodexHooksFeatureFlag(raw) === "disabled" ? `${path10.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed` : void 0;
13422
14699
  };
13423
14700
  var readState = async (configPath) => {
13424
14701
  const read = await readJsonDocument(configPath);
@@ -13430,12 +14707,12 @@ var readState = async (configPath) => {
13430
14707
  case "unparseable":
13431
14708
  return {
13432
14709
  status: "blocked",
13433
- problem: `${path9.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`
14710
+ problem: `${path10.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`
13434
14711
  };
13435
14712
  case "unreadable":
13436
14713
  return {
13437
14714
  status: "failed",
13438
- problem: `${path9.basename(configPath)} could not be read (${read.detail})`
14715
+ problem: `${path10.basename(configPath)} could not be read (${read.detail})`
13439
14716
  };
13440
14717
  }
13441
14718
  };
@@ -13547,7 +14824,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
13547
14824
  missingEvents: [],
13548
14825
  notes,
13549
14826
  problems: planned.conflicts.map(
13550
- (conflict) => `${path9.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`
14827
+ (conflict) => `${path10.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`
13551
14828
  )
13552
14829
  };
13553
14830
  }
@@ -13558,7 +14835,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
13558
14835
  changed: false,
13559
14836
  registeredEvents: [],
13560
14837
  missingEvents: [],
13561
- notes: [...notes, `${path9.basename(configPath)} does not exist; nothing to remove`],
14838
+ notes: [...notes, `${path10.basename(configPath)} does not exist; nothing to remove`],
13562
14839
  problems: []
13563
14840
  };
13564
14841
  }
@@ -13601,7 +14878,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
13601
14878
  missingEvents: [],
13602
14879
  notes,
13603
14880
  problems: [
13604
- `could not write ${path9.basename(configPath)} (${thrown instanceof Error ? thrown.name : typeof thrown})`
14881
+ `could not write ${path10.basename(configPath)} (${thrown instanceof Error ? thrown.name : typeof thrown})`
13605
14882
  ]
13606
14883
  };
13607
14884
  }
@@ -13628,7 +14905,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
13628
14905
  missingEvents: [],
13629
14906
  notes,
13630
14907
  problems: [
13631
- thrown instanceof Error ? `${path9.basename(configPath)}: ${thrown.message}` : `${path9.basename(configPath)}: the configuration file could not be locked`
14908
+ thrown instanceof Error ? `${path10.basename(configPath)}: ${thrown.message}` : `${path10.basename(configPath)}: the configuration file could not be locked`
13632
14909
  ]
13633
14910
  };
13634
14911
  }
@@ -13749,6 +15026,7 @@ export {
13749
15026
  DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS,
13750
15027
  DEFAULT_CONFIG,
13751
15028
  DEFAULT_DESTINATION_NAME,
15029
+ DEFAULT_DESTINATION_SIGNALS,
13752
15030
  DEFAULT_DETECTION_POLICY,
13753
15031
  DEFAULT_DIAGNOSTICS_POLICY,
13754
15032
  DEFAULT_DOCUMENT_FORMAT,
@@ -13757,11 +15035,14 @@ export {
13757
15035
  DEFAULT_INSTRUMENTATION_SCOPE,
13758
15036
  DEFAULT_LOGS_POLICY,
13759
15037
  DEFAULT_MANAGED_COMMAND_MARKER,
15038
+ DEFAULT_METRICS_POLICY,
13760
15039
  DEFAULT_PRIVACY_LIMITS,
13761
15040
  DEFAULT_PRIVACY_POLICY,
13762
15041
  DEFAULT_PROVIDERS_POLICY,
13763
15042
  DEFAULT_SECRET_KEY_PATTERNS,
13764
15043
  DEFAULT_SECRET_VALUE_PATTERNS,
15044
+ DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS,
15045
+ DEFAULT_SESSION_CONTEXT_MAX_BYTES,
13765
15046
  DEFAULT_SPOOL_POLICY,
13766
15047
  DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS,
13767
15048
  DEFAULT_WORKTREE_CACHE_TTL_MILLIS,
@@ -13804,11 +15085,19 @@ export {
13804
15085
  MAX_RESOURCE_ATTRIBUTES,
13805
15086
  MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH,
13806
15087
  MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH,
15088
+ MAX_SESSION_CONTEXT_SEGMENTS,
13807
15089
  MAX_TARGET_HINT_PATHS,
13808
15090
  MAX_TARGET_PATH_LENGTH,
13809
15091
  MAX_WORKTREE_WALK_DEPTH,
13810
15092
  MCP_TOOL_NAME_PATTERN,
15093
+ METRIC_COST_USAGE,
15094
+ METRIC_INSTRUMENTS,
15095
+ METRIC_OPERATION_DURATION,
15096
+ METRIC_SESSIONS,
15097
+ METRIC_TOKEN_USAGE,
15098
+ METRIC_TOOL_CALLS,
13811
15099
  NO_LOG_CONTENT,
15100
+ OPERATION_DURATION_BUCKETS,
13812
15101
  OTLP_ENDPOINT_VARIABLES,
13813
15102
  OTLP_HEADER_VARIABLES,
13814
15103
  OtelHookError,
@@ -13824,11 +15113,14 @@ export {
13824
15113
  RESERVED_RESOURCE_ATTRIBUTE_KEYS,
13825
15114
  RESOURCE_ATTRIBUTE_KEY_PATTERN,
13826
15115
  RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL,
15116
+ SESSION_CONTEXT_AGENT_TOOLS,
15117
+ SESSION_CONTEXT_FILE_VERSION,
13827
15118
  SILENT_HOOK_RESPONSE,
13828
15119
  SPAN_RECORD_VERSION,
13829
15120
  SUBAGENT_ID_PATTERN,
13830
15121
  SUPPORTED_REGISTRATION_PROVIDER_IDS,
13831
15122
  TARGETED_EVENT_TYPES,
15123
+ TOKEN_USAGE_BUCKETS,
13832
15124
  UNKNOWN_PROVIDER_ID,
13833
15125
  UNKNOWN_WORKSPACE_ID,
13834
15126
  UsageNormalizationError,
@@ -13836,6 +15128,7 @@ export {
13836
15128
  WORKSPACE_ID_PATTERN,
13837
15129
  adapterSupports,
13838
15130
  addUsage,
15131
+ aggregateDeltaPoints,
13839
15132
  appliedDeliverySchema,
13840
15133
  asProviderId,
13841
15134
  attachClaudeTranscriptTurn,
@@ -13878,10 +15171,12 @@ export {
13878
15171
  createDefaultProviderRegistry,
13879
15172
  createDestinationFanout,
13880
15173
  createDeterministicIdGenerator,
15174
+ createDirectorySessionContextReader,
13881
15175
  createErrorInfo,
13882
15176
  createEventFactory,
13883
15177
  createExportDestinationSinks,
13884
15178
  createFileDurableLogSpool,
15179
+ createFileDurableMetricSpool,
13885
15180
  createFileDurableSpool,
13886
15181
  createFilesystemStateStore,
13887
15182
  createFilesystemWorktreeLocator,
@@ -13891,10 +15186,12 @@ export {
13891
15186
  createHookRuntime,
13892
15187
  createInMemoryStateStore,
13893
15188
  createLifecycleJanitor,
15189
+ createMetricSeriesStore,
13894
15190
  createNullLogger,
13895
15191
  createNullTelemetrySink,
13896
15192
  createOtelHook,
13897
15193
  createOtlpLogSink,
15194
+ createOtlpMetricSink,
13898
15195
  createOtlpTraceSink,
13899
15196
  createPrivacyService,
13900
15197
  createProviderRegistry,
@@ -13911,11 +15208,13 @@ export {
13911
15208
  deliveryComponentSchema,
13912
15209
  deliveryGapReasonSchema,
13913
15210
  deliveryIdentifierSupportSchema,
15211
+ deriveMetricObservations,
13914
15212
  deriveWorkspaceIdentity,
13915
15213
  describeAdapter,
13916
15214
  describeErrorCode,
13917
15215
  describeExportDestinations,
13918
15216
  describeLogsDeliverability,
15217
+ describeMetricsDeliverability,
13919
15218
  describeOtlpHeaderNames,
13920
15219
  describeProviderCatalog,
13921
15220
  describeResolvedConfig,
@@ -13926,6 +15225,7 @@ export {
13926
15225
  detectionPolicySchema,
13927
15226
  diagnosticsPolicySchema,
13928
15227
  durationMillisSchema,
15228
+ effectiveMetricsPolicy,
13929
15229
  effectiveSpoolPolicy,
13930
15230
  emptyExtensions,
13931
15231
  endpointOrigin,
@@ -13964,7 +15264,9 @@ export {
13964
15264
  isPermanentExportFailure,
13965
15265
  isReservedExtensionNamespace,
13966
15266
  isReservedResourceAttributeKey,
15267
+ isReservedSessionContextKey,
13967
15268
  isSecretResourceAttributeKey,
15269
+ isSessionContextFileName,
13968
15270
  isTargetedEvent,
13969
15271
  isUnavailableContentFact,
13970
15272
  isUnknownProvider,
@@ -13982,6 +15284,7 @@ export {
13982
15284
  mergeGeminiHookRegistration,
13983
15285
  mergeNestedHookRegistration,
13984
15286
  mergeOtlpHeaders,
15287
+ metricsPolicySchema,
13985
15288
  minimumStaleClaimMillis,
13986
15289
  modelDescriptorSchema,
13987
15290
  nonEmptyStringSchema,
@@ -14001,6 +15304,7 @@ export {
14001
15304
  parseHeaderValueReference,
14002
15305
  parseOtlpHeadersValue,
14003
15306
  parseResourceAttributesValue,
15307
+ parseSessionContextFile,
14004
15308
  planProviderRegistration,
14005
15309
  privacyLimitsSchema,
14006
15310
  privacyPolicySchema,
@@ -14041,6 +15345,7 @@ export {
14041
15345
  resolveInstallPath,
14042
15346
  resolveInvocationIdentity,
14043
15347
  resolveLogsEndpoint,
15348
+ resolveMetricsEndpoint,
14044
15349
  resolveOtlpHeaders,
14045
15350
  resolvePrivacyPolicy,
14046
15351
  resolvedProviderIdSchema,
@@ -14048,7 +15353,13 @@ export {
14048
15353
  resourceAttributesSchema,
14049
15354
  runRegistrationLifecycle,
14050
15355
  sanitizeResourceAttributes,
15356
+ sanitizeSessionContextAttributes,
15357
+ segmentInForce,
14051
15358
  sequenceNumberSchema,
15359
+ sessionContextAgentTool,
15360
+ sessionContextDir,
15361
+ sessionContextFilePath,
15362
+ sessionContextPolicySchema,
14052
15363
  sessionCwdHint,
14053
15364
  sessionEndEventSchema,
14054
15365
  sessionIdSchema,
@@ -14059,6 +15370,7 @@ export {
14059
15370
  spanScopeRefOf,
14060
15371
  spoolPolicySchema,
14061
15372
  spoolQueueNamesFor,
15373
+ stampSessionContext,
14062
15374
  startOnlySpanAttributes,
14063
15375
  stateRecordSchema,
14064
15376
  stateValueSchema,
@@ -14080,6 +15392,7 @@ export {
14080
15392
  usageScopeSchema,
14081
15393
  usageTemporalitySchema,
14082
15394
  validateCanonicalEvent,
15395
+ validateMetricSpoolBatch,
14083
15396
  withFileLock,
14084
15397
  withOptionalSessionLock,
14085
15398
  workspaceIdSchema,