@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/telemetry.js CHANGED
@@ -18,7 +18,7 @@ import {
18
18
  } from "@opentelemetry/semantic-conventions/incubating";
19
19
 
20
20
  // src/version.ts
21
- var VERSION = "0.10.0";
21
+ var VERSION = "0.12.0";
22
22
 
23
23
  // src/telemetry/export-identity.ts
24
24
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -663,7 +663,15 @@ var baseEventFields = {
663
663
  * factory, never by hand.
664
664
  */
665
665
  subagentId: subagentIdSchema.optional(),
666
- extensions: extensionsSchema.default(emptyExtensions)
666
+ extensions: extensionsSchema.default(emptyExtensions),
667
+ /**
668
+ * Attributes of the session context segment in force when the event
669
+ * occurred (`docs/session-context.md`), stamped by the core from a file a
670
+ * harness wrote. Exported on every record of the event, over the same keys
671
+ * from the Resource. Absent when no context applies. Set by the core only,
672
+ * never by an adapter.
673
+ */
674
+ contextAttributes: z9.record(z9.string().min(1).max(255), z9.union([z9.string(), z9.number(), z9.boolean()])).optional()
667
675
  };
668
676
  var event = (shape) => z9.strictObject({ ...baseEventFields, ...shape });
669
677
  var sessionStartEventSchema = event({
@@ -850,6 +858,11 @@ var passthroughResourceAttributes = (resource) => {
850
858
  }
851
859
  return attributes;
852
860
  };
861
+ var contextAttributesOf = (event2) => event2.contextAttributes === void 0 ? {} : { ...event2.contextAttributes };
862
+ var profileAttributes = (event2, resource) => ({
863
+ ...passthroughResourceAttributes(resource),
864
+ ...contextAttributesOf(event2)
865
+ });
853
866
  var resolveExportedSessionId = (eventSessionId, resource) => {
854
867
  for (const key of EXTERNAL_SESSION_KEY_ATTRIBUTES) {
855
868
  const supplied = resource.attributes[key];
@@ -870,6 +883,8 @@ var hexTraceAttributes = (ids) => ({
870
883
  var exportIdentityAttributes = (event2, resource, ids) => {
871
884
  const { sessionId, providerSessionId } = resolveExportedSessionId(event2.sessionId, resource);
872
885
  return {
886
+ // First, so nothing in the profile layer can replace an identity attribute.
887
+ ...profileAttributes(event2, resource),
873
888
  [ATTR_SESSION_ID]: sessionId,
874
889
  [ATTR_OTELHOOK_SESSION_ID]: providerSessionId,
875
890
  [ATTR_GEN_AI_CONVERSATION_ID]: providerSessionId,
@@ -878,7 +893,6 @@ var exportIdentityAttributes = (event2, resource, ids) => {
878
893
  ...event2.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event2.provenance.providerVersion },
879
894
  [ATTR_OTELHOOK_WORKSPACE_ID]: event2.workspace.workspaceId,
880
895
  ...event2.subagentId === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event2.subagentId },
881
- ...passthroughResourceAttributes(resource),
882
896
  ...hexTraceAttributes(ids)
883
897
  };
884
898
  };
@@ -1029,12 +1043,12 @@ var pickTarget = (attributes) => {
1029
1043
  }
1030
1044
  return picked;
1031
1045
  };
1032
- var withoutTarget = (attributes, resource) => {
1046
+ var withoutTarget = (attributes, resource, event2) => {
1033
1047
  const rest = { ...attributes };
1034
1048
  for (const key of TARGET_KEYS) {
1035
1049
  delete rest[key];
1036
1050
  }
1037
- return { ...rest, ...pickTarget(passthroughResourceAttributes(resource)) };
1051
+ return { ...rest, ...pickTarget(profileAttributes(event2, resource)) };
1038
1052
  };
1039
1053
  var rankOf = (candidate) => {
1040
1054
  const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];
@@ -1139,7 +1153,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
1139
1153
  name = "session";
1140
1154
  kind = SpanKind.INTERNAL;
1141
1155
  attributes = {
1142
- ...withoutTarget(attributes, resource),
1156
+ ...withoutTarget(attributes, resource, anchor),
1143
1157
  ...strongestTarget([pickTarget(resolved.recovered), start === void 0 ? {} : targetAttributes(start)]),
1144
1158
  ...start?.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName },
1145
1159
  ...start?.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion },
@@ -1181,7 +1195,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
1181
1195
  kind = SpanKind.CLIENT;
1182
1196
  attributes = {
1183
1197
  // Target keys are re-chosen below as one unit, never mixed across edges.
1184
- ...withoutTarget(attributes, resource),
1198
+ ...withoutTarget(attributes, resource, anchor),
1185
1199
  [ATTR_GEN_AI_TOOL_NAME]: toolName,
1186
1200
  [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,
1187
1201
  ...start?.toolKind === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind },
@@ -2133,6 +2147,33 @@ var replayResource = (attributes, policy) => {
2133
2147
  }
2134
2148
  return resourceFromAttributes(safe);
2135
2149
  };
2150
+ var agreedContextAttributes = (events) => {
2151
+ const [first, ...rest] = events;
2152
+ if (first?.contextAttributes === void 0) {
2153
+ return {};
2154
+ }
2155
+ const agreed = { ...first.contextAttributes };
2156
+ for (const event2 of rest) {
2157
+ for (const key of Object.keys(agreed)) {
2158
+ if (event2.contextAttributes?.[key] !== agreed[key]) {
2159
+ delete agreed[key];
2160
+ }
2161
+ }
2162
+ }
2163
+ return agreed;
2164
+ };
2165
+ var resourceWithContext = (resource, context) => {
2166
+ const overrides = {};
2167
+ for (const [key, value] of Object.entries(context)) {
2168
+ if (Object.hasOwn(resource.attributes, key) && !isReservedResourceAttributeKey(key) && resource.attributes[key] !== value) {
2169
+ overrides[key] = value;
2170
+ }
2171
+ }
2172
+ if (Object.keys(overrides).length === 0) {
2173
+ return resource;
2174
+ }
2175
+ return resourceFromAttributes({ ...resource.attributes, ...overrides });
2176
+ };
2136
2177
 
2137
2178
  // src/telemetry/otlp-sink.ts
2138
2179
  var chunk = (items, size) => {
@@ -2217,10 +2258,10 @@ var createOtlpTraceSink = (options) => {
2217
2258
  const exportSpans = (spans) => new Promise((resolve) => {
2218
2259
  exporter.export([...spans], (result) => resolve(result));
2219
2260
  });
2220
- const toSpoolBatch = (spans) => ({
2261
+ const toSpoolBatch = (spans, batchResource) => ({
2221
2262
  providerId: options.providerId,
2222
2263
  installationId: options.installationId,
2223
- resourceAttributes: { ...resource.attributes },
2264
+ resourceAttributes: { ...batchResource.attributes },
2224
2265
  instrumentationScope: { name: scope.name, ...scope.version === void 0 ? {} : { version: scope.version } },
2225
2266
  spans: spans.map(serializeSpan),
2226
2267
  enqueuedAt: options.clock.now()
@@ -2250,8 +2291,9 @@ var createOtlpTraceSink = (options) => {
2250
2291
  return { accepted: 0, rejected: 0, errors: [] };
2251
2292
  }
2252
2293
  const resolved = await resolveCorrelations(events);
2294
+ const batchResource = resourceWithContext(resource, agreedContextAttributes(events));
2253
2295
  const spans = canonicalEventsToReadableSpans(events, {
2254
- resource,
2296
+ resource: batchResource,
2255
2297
  instrumentationScope: scope,
2256
2298
  correlations: resolved.correlations,
2257
2299
  ...resolved.available === void 0 ? {} : { correlationAvailable: resolved.available }
@@ -2277,7 +2319,7 @@ var createOtlpTraceSink = (options) => {
2277
2319
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
2278
2320
  const permanent = isPermanentExportFailure(result);
2279
2321
  if (options.spool !== void 0 && !permanent) {
2280
- const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
2322
+ const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({
2281
2323
  spooled: false,
2282
2324
  reason: "capacity-exceeded"
2283
2325
  }));
@@ -2871,10 +2913,17 @@ import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
2871
2913
  var OTLP_ENDPOINT_VARIABLES = Object.freeze({
2872
2914
  generic: "OTEL_EXPORTER_OTLP_ENDPOINT",
2873
2915
  traces: "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
2874
- logs: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT"
2916
+ logs: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
2917
+ metrics: "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"
2875
2918
  });
2876
2919
  var OTLP_TRACES_PATH = "/v1/traces";
2877
2920
  var OTLP_LOGS_PATH = "/v1/logs";
2921
+ var OTLP_METRICS_PATH = "/v1/metrics";
2922
+ var SIGNAL_PATHS = Object.freeze({
2923
+ traces: OTLP_TRACES_PATH,
2924
+ logs: OTLP_LOGS_PATH,
2925
+ metrics: OTLP_METRICS_PATH
2926
+ });
2878
2927
  var withoutTrailingSlashes = (value) => {
2879
2928
  let end = value.length;
2880
2929
  while (end > 0 && value.charCodeAt(end - 1) === 47) {
@@ -2882,6 +2931,17 @@ var withoutTrailingSlashes = (value) => {
2882
2931
  }
2883
2932
  return value.slice(0, end);
2884
2933
  };
2934
+ var siblingSignalEndpoint = (tracesEndpoint, signal) => {
2935
+ const trimmed = withoutTrailingSlashes(tracesEndpoint);
2936
+ const target = SIGNAL_PATHS[signal];
2937
+ if (trimmed.endsWith(target)) {
2938
+ return trimmed;
2939
+ }
2940
+ if (trimmed.endsWith(OTLP_TRACES_PATH)) {
2941
+ return `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${target}`;
2942
+ }
2943
+ return `${trimmed}${target}`;
2944
+ };
2885
2945
 
2886
2946
  // src/telemetry/otlp-log-sink.ts
2887
2947
  var resolveLogsEndpoint = (exporter) => {
@@ -3030,10 +3090,10 @@ var createOtlpLogSink = (options) => {
3030
3090
  const exportRecords = (records) => new Promise((resolve) => {
3031
3091
  exporter.export([...records], (result) => resolve(result));
3032
3092
  });
3033
- const toSpoolBatch = (records) => ({
3093
+ const toSpoolBatch = (records, batchResource) => ({
3034
3094
  providerId: options.providerId,
3035
3095
  installationId: options.installationId,
3036
- resourceAttributes: { ...resource.attributes },
3096
+ resourceAttributes: { ...batchResource.attributes },
3037
3097
  instrumentationScope: {
3038
3098
  name: scope.name,
3039
3099
  ...scope.version === void 0 ? {} : { version: scope.version }
@@ -3068,8 +3128,9 @@ var createOtlpLogSink = (options) => {
3068
3128
  return { accepted: 0, rejected: 0, errors: [] };
3069
3129
  }
3070
3130
  const resolved = await resolveCorrelations(events);
3131
+ const batchResource = resourceWithContext(resource, agreedContextAttributes(events));
3071
3132
  const mapped = canonicalEventsToLogRecords(events, {
3072
- resource,
3133
+ resource: batchResource,
3073
3134
  instrumentationScope: scope,
3074
3135
  content,
3075
3136
  correlations: resolved.correlations,
@@ -3104,7 +3165,7 @@ var createOtlpLogSink = (options) => {
3104
3165
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
3105
3166
  const permanent = isPermanentExportFailure(result);
3106
3167
  if (options.spool !== void 0 && !permanent) {
3107
- const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
3168
+ const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({
3108
3169
  spooled: false,
3109
3170
  reason: "capacity-exceeded"
3110
3171
  }));
@@ -3240,7 +3301,7 @@ var HEADER_ENV_REFERENCE_PREFIX = "env:";
3240
3301
  var HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
3241
3302
  var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
3242
3303
  var MAX_HEADER_VALUE_LENGTH = 8192;
3243
- var exportSignalSchema = z13.enum(["traces", "logs"]);
3304
+ var exportSignalSchema = z13.enum(["traces", "logs", "metrics"]);
3244
3305
  var headerValueSchema = z13.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
3245
3306
  (value) => !isUnsafeHeaderValue(value),
3246
3307
  "header values may not contain line breaks, control characters, or characters beyond Latin-1"
@@ -3263,6 +3324,8 @@ var exportDestinationSchema = z13.strictObject({
3263
3324
  tracesEndpoint: endpointSchema.optional(),
3264
3325
  /** Per-signal override of the derived logs URL. */
3265
3326
  logsEndpoint: endpointSchema.optional(),
3327
+ /** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */
3328
+ metricsEndpoint: endpointSchema.optional(),
3266
3329
  /** Defaults to `exporter.protocol`. */
3267
3330
  protocol: z13.enum(["http/protobuf", "http/json", "none"]).optional(),
3268
3331
  /**
@@ -3275,15 +3338,17 @@ var exportDestinationSchema = z13.strictObject({
3275
3338
  `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
3276
3339
  ).optional(),
3277
3340
  /**
3278
- * Which signals this destination receives. Default: both. The logs signal is
3279
- * still governed by `exporter.logs.enabled`, which stays the one opt-in for a
3280
- * second stream leaving the host.
3341
+ * Which signals this destination receives. Default: traces and logs. The logs
3342
+ * signal is still governed by `exporter.logs.enabled`, which stays the one
3343
+ * opt-in for content-bearing records leaving the host. `metrics` is never on by
3344
+ * default: a destination receives hook-derived metrics only when it lists them.
3281
3345
  */
3282
- signals: z13.array(exportSignalSchema).min(1).max(2).readonly().optional()
3346
+ signals: z13.array(exportSignalSchema).min(1).max(3).readonly().optional()
3283
3347
  }).refine(
3284
- (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0,
3285
- "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint"
3348
+ (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
3349
+ "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
3286
3350
  );
3351
+ var DEFAULT_DESTINATION_SIGNALS = Object.freeze(["traces", "logs"]);
3287
3352
  var exportDestinationsSchema = z13.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
3288
3353
  const seen = /* @__PURE__ */ new Set();
3289
3354
  destinations.forEach((destination, index) => {
@@ -3328,7 +3393,8 @@ var legacyDestination = (exporter) => ({
3328
3393
  protocol: exporter.protocol,
3329
3394
  ...exporter.endpoint === void 0 ? {} : { endpoint: exporter.endpoint },
3330
3395
  ...exporter.logs.endpoint === void 0 ? {} : { logsEndpoint: exporter.logs.endpoint },
3331
- signals: { traces: true, logs: exporter.logs.enabled },
3396
+ ...exporter.metrics?.endpoint === void 0 ? {} : { metricsEndpoint: exporter.metrics.endpoint },
3397
+ signals: { traces: true, logs: exporter.logs.enabled, metrics: exporter.metrics?.enabled === true },
3332
3398
  headers: {}
3333
3399
  });
3334
3400
  var hasConfiguredDestinations = (exporter) => exporter.destinations !== void 0 && exporter.destinations.length > 0;
@@ -3337,14 +3403,14 @@ var resolveExportDestinations = (exporter) => {
3337
3403
  return [legacyDestination(exporter)];
3338
3404
  }
3339
3405
  const resolved = [];
3340
- if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0) {
3406
+ if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0 || exporter.metrics?.endpoint !== void 0) {
3341
3407
  resolved.push(legacyDestination(exporter));
3342
3408
  }
3343
3409
  for (const destination of exporter.destinations ?? []) {
3344
3410
  if (destination.enabled === false) {
3345
3411
  continue;
3346
3412
  }
3347
- const signals = destination.signals ?? exportSignalSchema.options;
3413
+ const signals = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;
3348
3414
  resolved.push({
3349
3415
  name: destination.name,
3350
3416
  source: "destinations",
@@ -3352,9 +3418,11 @@ var resolveExportDestinations = (exporter) => {
3352
3418
  ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
3353
3419
  ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
3354
3420
  ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
3421
+ ...destination.metricsEndpoint === void 0 ? {} : { metricsEndpoint: destination.metricsEndpoint },
3355
3422
  signals: {
3356
3423
  traces: signals.includes("traces"),
3357
- logs: exporter.logs.enabled && signals.includes("logs")
3424
+ logs: exporter.logs.enabled && signals.includes("logs"),
3425
+ metrics: signals.includes("metrics")
3358
3426
  },
3359
3427
  headers: { ...destination.headers ?? {} }
3360
3428
  });
@@ -3381,8 +3449,801 @@ var resolveDestinationHeaders = (headers, environment) => {
3381
3449
  return { values, missingVariables: [...new Set(missing)].sort() };
3382
3450
  };
3383
3451
 
3452
+ // src/config/schema.ts
3453
+ import { isAbsolute } from "path";
3454
+ import { z as z14 } from "zod";
3455
+ var logsPolicySchema = z14.strictObject({
3456
+ enabled: z14.boolean(),
3457
+ /**
3458
+ * Full URL for the logs signal.
3459
+ *
3460
+ * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes
3461
+ * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.
3462
+ */
3463
+ endpoint: z14.string().url().max(2048).optional(),
3464
+ includeContent: z14.boolean(),
3465
+ maxBatchSize: z14.number().int().min(1).max(4096)
3466
+ });
3467
+ var DEFAULT_LOGS_POLICY = Object.freeze({
3468
+ enabled: false,
3469
+ includeContent: false,
3470
+ maxBatchSize: 128
3471
+ });
3472
+ var metricsPolicySchema = z14.strictObject({
3473
+ enabled: z14.boolean(),
3474
+ /** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */
3475
+ endpoint: z14.string().url().max(2048).optional(),
3476
+ temporality: z14.enum(["cumulative", "delta"]),
3477
+ includeSessionId: z14.boolean()
3478
+ });
3479
+ var DEFAULT_METRICS_POLICY = Object.freeze({
3480
+ enabled: false,
3481
+ temporality: "cumulative",
3482
+ includeSessionId: true
3483
+ });
3484
+ var exporterPolicySchema = z14.strictObject({
3485
+ enabled: z14.boolean(),
3486
+ protocol: z14.enum(["http/protobuf", "http/json", "none"]),
3487
+ endpoint: z14.string().url().max(2048).optional(),
3488
+ /**
3489
+ * Header names only. Values are supplied separately at construction time and
3490
+ * are never part of a resolved-config snapshot, which is logged and exported.
3491
+ */
3492
+ headerNames: z14.array(nonEmptyStringSchema).max(32).readonly(),
3493
+ timeoutMillis: z14.number().int().min(1).max(6e5),
3494
+ maxBatchSize: z14.number().int().min(1).max(4096),
3495
+ maxQueueSize: z14.number().int().min(1).max(65536),
3496
+ maxRetryAttempts: z14.number().int().min(0).max(10),
3497
+ serviceName: nonEmptyStringSchema,
3498
+ serviceNamespace: nonEmptyStringSchema.optional(),
3499
+ /**
3500
+ * Custom attributes merged into the exported OTLP Resource.
3501
+ *
3502
+ * Bounded and validated, and refusing `service.name`/`service.namespace`,
3503
+ * which are the two fields above. Distinct from an invocation's
3504
+ * `consumerAttributes`: this describes the emitting deployment, carries no
3505
+ * identity, and is the same for every span this process exports.
3506
+ */
3507
+ resourceAttributes: resourceAttributesSchema,
3508
+ /**
3509
+ * The logs signal. Nested under the exporter because it shares the endpoint,
3510
+ * headers, timeout, protocol, service identity, and resource attributes above —
3511
+ * a second top-level section would invite two of each to drift apart.
3512
+ */
3513
+ logs: logsPolicySchema,
3514
+ /**
3515
+ * Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before
3516
+ * metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.
3517
+ */
3518
+ metrics: metricsPolicySchema.optional(),
3519
+ /**
3520
+ * Additional OTLP destinations, each sent every batch in parallel.
3521
+ *
3522
+ * Absent (the default), the exporter has exactly one destination — the
3523
+ * single-endpoint settings above, named `default` — and behaves exactly as it
3524
+ * did before this list existed. See `destinations.ts`.
3525
+ *
3526
+ * Merged as one leaf: a higher layer that sets the list replaces it whole,
3527
+ * because "the union of two partial lists" has no answer an operator could
3528
+ * predict.
3529
+ */
3530
+ destinations: exportDestinationsSchema.optional(),
3531
+ /**
3532
+ * Per-destination retry spool bounds, each optional and merged per leaf; any
3533
+ * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.
3534
+ */
3535
+ spool: spoolPolicySchema.partial().optional()
3536
+ });
3537
+ var detectionPolicySchema = z14.strictObject({
3538
+ /** Detections below this confidence resolve to the unknown provider. */
3539
+ minimumConfidence: detectionConfidenceSchema,
3540
+ /** When false, an ambiguous detection is an error rather than unknown. */
3541
+ allowAmbiguousFallback: z14.boolean(),
3542
+ /** Optional allow-list of provider ids; empty means "any registered". */
3543
+ allowedProviderIds: z14.array(nonEmptyStringSchema).max(32).readonly()
3544
+ });
3545
+ var diagnosticsPolicySchema = z14.strictObject({
3546
+ logLevel: z14.enum(["silent", "error", "warn", "info", "debug"]),
3547
+ /** Emit `error.raised` events for contained failures. */
3548
+ emitErrorEvents: z14.boolean()
3549
+ });
3550
+ var providersPolicySchema = z14.strictObject({
3551
+ claudeCode: z14.strictObject({
3552
+ readTranscriptUsage: z14.boolean()
3553
+ }).optional()
3554
+ });
3555
+ var sessionContextPolicySchema = z14.strictObject({
3556
+ /** Absolute path of the context directory. */
3557
+ dir: z14.string().min(1).max(4096).refine((value) => isAbsolute(value), { message: "must be an absolute path" })
3558
+ });
3559
+ var otelHookConfigSchema = z14.strictObject({
3560
+ exporter: exporterPolicySchema,
3561
+ privacy: privacyPolicySchema,
3562
+ detection: detectionPolicySchema,
3563
+ diagnostics: diagnosticsPolicySchema,
3564
+ /** Optional so a hand-built configuration from before it existed stays valid. */
3565
+ providers: providersPolicySchema.optional(),
3566
+ /** Optional: absent means no session context is read. */
3567
+ sessionContext: sessionContextPolicySchema.optional()
3568
+ });
3569
+ var otelHookConfigPatchSchema = z14.strictObject({
3570
+ // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
3571
+ // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
3572
+ // without also restating the endpoint and the batch size.
3573
+ exporter: exporterPolicySchema.omit({ logs: true, metrics: true, spool: true }).partial().extend({
3574
+ logs: logsPolicySchema.partial().optional(),
3575
+ metrics: metricsPolicySchema.partial().optional(),
3576
+ spool: spoolPolicySchema.partial().optional()
3577
+ }).optional(),
3578
+ privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
3579
+ detection: detectionPolicySchema.partial().optional(),
3580
+ diagnostics: diagnosticsPolicySchema.partial().optional(),
3581
+ providers: z14.strictObject({
3582
+ claudeCode: z14.strictObject({ readTranscriptUsage: z14.boolean() }).partial().optional()
3583
+ }).partial().optional(),
3584
+ sessionContext: sessionContextPolicySchema.partial().optional()
3585
+ });
3586
+ var DEFAULT_EXPORTER_POLICY = Object.freeze({
3587
+ enabled: true,
3588
+ protocol: "http/protobuf",
3589
+ headerNames: Object.freeze([]),
3590
+ timeoutMillis: 1e4,
3591
+ maxBatchSize: 128,
3592
+ maxQueueSize: 2048,
3593
+ maxRetryAttempts: 2,
3594
+ serviceName: "coding-agent",
3595
+ resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
3596
+ logs: DEFAULT_LOGS_POLICY,
3597
+ metrics: DEFAULT_METRICS_POLICY
3598
+ });
3599
+ var DEFAULT_DETECTION_POLICY = Object.freeze({
3600
+ minimumConfidence: "strong",
3601
+ allowAmbiguousFallback: true,
3602
+ allowedProviderIds: Object.freeze([])
3603
+ });
3604
+ var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
3605
+ logLevel: "warn",
3606
+ emitErrorEvents: true
3607
+ });
3608
+ var DEFAULT_PROVIDERS_POLICY = Object.freeze({
3609
+ claudeCode: Object.freeze({ readTranscriptUsage: false })
3610
+ });
3611
+ var DEFAULT_CONFIG = Object.freeze({
3612
+ exporter: DEFAULT_EXPORTER_POLICY,
3613
+ privacy: DEFAULT_PRIVACY_POLICY,
3614
+ detection: DEFAULT_DETECTION_POLICY,
3615
+ diagnostics: DEFAULT_DIAGNOSTICS_POLICY,
3616
+ providers: DEFAULT_PROVIDERS_POLICY
3617
+ });
3618
+ var effectiveMetricsPolicy = (exporter) => ({
3619
+ ...DEFAULT_METRICS_POLICY,
3620
+ ...exporter.metrics ?? {}
3621
+ });
3622
+
3623
+ // src/telemetry/metric-model.ts
3624
+ var TOKEN_USAGE_BUCKETS = Object.freeze([
3625
+ 1,
3626
+ 4,
3627
+ 16,
3628
+ 64,
3629
+ 256,
3630
+ 1024,
3631
+ 4096,
3632
+ 16384,
3633
+ 65536,
3634
+ 262144,
3635
+ 1048576,
3636
+ 4194304,
3637
+ 16777216,
3638
+ 67108864
3639
+ ]);
3640
+ var OPERATION_DURATION_BUCKETS = Object.freeze([
3641
+ 0.01,
3642
+ 0.02,
3643
+ 0.04,
3644
+ 0.08,
3645
+ 0.16,
3646
+ 0.32,
3647
+ 0.64,
3648
+ 1.28,
3649
+ 2.56,
3650
+ 5.12,
3651
+ 10.24,
3652
+ 20.48,
3653
+ 40.96,
3654
+ 81.92
3655
+ ]);
3656
+ var METRIC_TOKEN_USAGE = "gen_ai.client.token.usage";
3657
+ var METRIC_OPERATION_DURATION = "gen_ai.client.operation.duration";
3658
+ var METRIC_SESSIONS = "otelhook.sessions";
3659
+ var METRIC_TOOL_CALLS = "otelhook.tool.calls";
3660
+ var METRIC_COST_USAGE = "otelhook.cost.usage";
3661
+ var METRIC_INSTRUMENTS = Object.freeze({
3662
+ [METRIC_TOKEN_USAGE]: {
3663
+ name: METRIC_TOKEN_USAGE,
3664
+ kind: "histogram",
3665
+ unit: "{token}",
3666
+ description: "Tokens used per generation, by token type (hook-derived)",
3667
+ valueType: "int",
3668
+ boundaries: TOKEN_USAGE_BUCKETS
3669
+ },
3670
+ [METRIC_OPERATION_DURATION]: {
3671
+ name: METRIC_OPERATION_DURATION,
3672
+ kind: "histogram",
3673
+ unit: "s",
3674
+ description: "Generation duration, from its start hook to its end hook (hook-derived)",
3675
+ valueType: "double",
3676
+ boundaries: OPERATION_DURATION_BUCKETS
3677
+ },
3678
+ [METRIC_SESSIONS]: {
3679
+ name: METRIC_SESSIONS,
3680
+ kind: "counter",
3681
+ unit: "{session}",
3682
+ description: "Agent sessions started",
3683
+ valueType: "int"
3684
+ },
3685
+ [METRIC_TOOL_CALLS]: {
3686
+ name: METRIC_TOOL_CALLS,
3687
+ kind: "counter",
3688
+ unit: "{call}",
3689
+ description: "Completed tool calls, by tool name and outcome",
3690
+ valueType: "int"
3691
+ },
3692
+ [METRIC_COST_USAGE]: {
3693
+ name: METRIC_COST_USAGE,
3694
+ kind: "counter",
3695
+ unit: "USD",
3696
+ description: "Cost reported by the provider; never estimated",
3697
+ valueType: "double"
3698
+ }
3699
+ });
3700
+ var isMetricInstrumentName = (value) => typeof value === "string" && Object.hasOwn(METRIC_INSTRUMENTS, value);
3701
+ var ATTR_GEN_AI_TOKEN_TYPE = "gen_ai.token.type";
3702
+ var ATTR_GEN_AI_PROVIDER_NAME = "gen_ai.provider.name";
3703
+ var ATTR_GEN_AI_OPERATION_NAME3 = "gen_ai.operation.name";
3704
+ var ATTR_GEN_AI_REQUEST_MODEL3 = "gen_ai.request.model";
3705
+ var ATTR_GEN_AI_RESPONSE_MODEL3 = "gen_ai.response.model";
3706
+ var ATTR_GEN_AI_TOOL_NAME3 = "gen_ai.tool.name";
3707
+ var ATTR_ERROR_TYPE3 = "error.type";
3708
+ var ATTR_SESSION_ID2 = "session.id";
3709
+ var ATTR_OTELHOOK_PROVIDER_ID2 = "otelhook.provider.id";
3710
+ var ATTR_OTELHOOK_OUTCOME3 = "otelhook.outcome";
3711
+ var ATTR_OTELHOOK_SESSION_KIND2 = "otelhook.session.kind";
3712
+ var commonAttributes = (event2, resource, includeSessionId) => ({
3713
+ // Session context first, so the metric's own attributes always win; and never
3714
+ // anything account-shaped, whatever the context says.
3715
+ ...event2.contextAttributes === void 0 ? {} : withoutAccountIdentity(event2.contextAttributes),
3716
+ [ATTR_OTELHOOK_PROVIDER_ID2]: event2.provenance.providerId,
3717
+ ...includeSessionId ? { [ATTR_SESSION_ID2]: resolveExportedSessionId(event2.sessionId, resource).sessionId } : {}
3718
+ });
3719
+ var generationAttributes = (end, requestModel) => ({
3720
+ [ATTR_GEN_AI_OPERATION_NAME3]: "chat",
3721
+ ...end.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_PROVIDER_NAME]: end.model.vendor },
3722
+ [ATTR_GEN_AI_REQUEST_MODEL3]: requestModel ?? end.model.modelId,
3723
+ [ATTR_GEN_AI_RESPONSE_MODEL3]: end.model.modelId
3724
+ });
3725
+ var TOKEN_FIELDS = [
3726
+ ["input", (usage) => usage.inputTokens],
3727
+ ["output", (usage) => usage.outputTokens],
3728
+ ["cache_read", (usage) => usage.cachedInputTokens],
3729
+ ["cache_creation", (usage) => usage.cacheCreationInputTokens]
3730
+ ];
3731
+ var isFailedOutcome = (outcome) => outcome !== "ok" && outcome !== "unknown" && outcome !== "cancelled";
3732
+ var deriveMetricObservations = (input) => {
3733
+ const includeSessionId = input.includeSessionId ?? true;
3734
+ const observations = [];
3735
+ const byId = /* @__PURE__ */ new Map();
3736
+ const startsInBatch = /* @__PURE__ */ new Map();
3737
+ for (const event2 of input.events) {
3738
+ byId.set(event2.eventId, event2);
3739
+ if (event2.type === "generation.start") {
3740
+ startsInBatch.set(event2.generationId, {
3741
+ startMillis: event2.occurredAt,
3742
+ requestModel: event2.model.modelId
3743
+ });
3744
+ }
3745
+ }
3746
+ const requestModelOf = (generationId) => startsInBatch.get(generationId)?.requestModel ?? input.generationStarts?.(generationId)?.requestModel;
3747
+ let lastPromptInBatch;
3748
+ for (const event2 of input.events) {
3749
+ if (event2.type === "prompt.submitted") {
3750
+ lastPromptInBatch ??= /* @__PURE__ */ new Map();
3751
+ lastPromptInBatch.set(event2.sessionId, Math.max(lastPromptInBatch.get(event2.sessionId) ?? 0, event2.occurredAt));
3752
+ }
3753
+ }
3754
+ const measuredDurationOf = (end) => {
3755
+ if (end.durationMillis !== void 0) {
3756
+ return end.durationMillis;
3757
+ }
3758
+ const recovered = startsInBatch.has(end.generationId) ? void 0 : input.generationStarts?.(end.generationId);
3759
+ if (recovered !== void 0) {
3760
+ return end.occurredAt - recovered.startMillis;
3761
+ }
3762
+ const turn = lastPromptInBatch?.get(end.sessionId) ?? input.turnStart?.(end.sessionId);
3763
+ return turn === void 0 || turn > end.occurredAt ? void 0 : end.occurredAt - turn;
3764
+ };
3765
+ const push = (event2, instrument, value, attributes) => {
3766
+ if (!Number.isFinite(value) || value < 0) {
3767
+ return;
3768
+ }
3769
+ observations.push({
3770
+ instrument,
3771
+ value,
3772
+ attributes: { ...commonAttributes(event2, input.resource, includeSessionId), ...attributes },
3773
+ timeMillis: event2.occurredAt,
3774
+ sessionId: event2.sessionId
3775
+ });
3776
+ };
3777
+ for (const event2 of input.events) {
3778
+ switch (event2.type) {
3779
+ case "session.start":
3780
+ push(event2, METRIC_SESSIONS, 1, { [ATTR_OTELHOOK_SESSION_KIND2]: event2.sessionKind });
3781
+ break;
3782
+ case "tool.end":
3783
+ push(event2, METRIC_TOOL_CALLS, 1, {
3784
+ [ATTR_GEN_AI_TOOL_NAME3]: event2.toolName,
3785
+ [ATTR_OTELHOOK_OUTCOME3]: event2.outcome
3786
+ });
3787
+ break;
3788
+ case "generation.end": {
3789
+ const attributes = generationAttributes(event2, requestModelOf(event2.generationId));
3790
+ const durationMillis = measuredDurationOf(event2);
3791
+ if (durationMillis !== void 0 && durationMillis >= 0) {
3792
+ push(event2, METRIC_OPERATION_DURATION, durationMillis / 1e3, {
3793
+ ...attributes,
3794
+ ...isFailedOutcome(event2.outcome) ? { [ATTR_ERROR_TYPE3]: event2.outcome } : {}
3795
+ });
3796
+ }
3797
+ if (event2.cost !== void 0 && event2.cost.source === "provider-reported" && event2.cost.currency === "USD") {
3798
+ push(event2, METRIC_COST_USAGE, event2.cost.amount, attributes);
3799
+ }
3800
+ break;
3801
+ }
3802
+ default:
3803
+ break;
3804
+ }
3805
+ }
3806
+ for (const observation of input.usage) {
3807
+ if (observation.scope !== "generation") {
3808
+ continue;
3809
+ }
3810
+ const event2 = byId.get(observation.eventId);
3811
+ if (event2?.type !== "generation.end") {
3812
+ continue;
3813
+ }
3814
+ const attributes = generationAttributes(event2, requestModelOf(event2.generationId));
3815
+ for (const [tokenType, read] of TOKEN_FIELDS) {
3816
+ const value = read(observation.delta);
3817
+ if (value === 0 && (tokenType === "cache_read" || tokenType === "cache_creation")) {
3818
+ continue;
3819
+ }
3820
+ push(event2, METRIC_TOKEN_USAGE, value, { ...attributes, [ATTR_GEN_AI_TOKEN_TYPE]: tokenType });
3821
+ }
3822
+ }
3823
+ return observations;
3824
+ };
3825
+ var emptyHistogram = (boundaries) => ({
3826
+ count: 0,
3827
+ sum: 0,
3828
+ min: Number.POSITIVE_INFINITY,
3829
+ max: Number.NEGATIVE_INFINITY,
3830
+ bucketCounts: new Array(boundaries.length + 1).fill(0)
3831
+ });
3832
+ var bucketIndex = (boundaries, value) => {
3833
+ for (let index = 0; index < boundaries.length; index += 1) {
3834
+ const bound = boundaries[index];
3835
+ if (bound !== void 0 && value <= bound) {
3836
+ return index;
3837
+ }
3838
+ }
3839
+ return boundaries.length;
3840
+ };
3841
+ var recordIntoHistogram = (state, boundaries, value) => {
3842
+ const bucketCounts = [...state.bucketCounts];
3843
+ const index = bucketIndex(boundaries, value);
3844
+ bucketCounts[index] = (bucketCounts[index] ?? 0) + 1;
3845
+ return {
3846
+ count: state.count + 1,
3847
+ sum: state.sum + value,
3848
+ min: Math.min(state.min, value),
3849
+ max: Math.max(state.max, value),
3850
+ bucketCounts
3851
+ };
3852
+ };
3853
+ var seriesIdentity = (instrument, attributes) => JSON.stringify([
3854
+ instrument,
3855
+ Object.entries(attributes).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
3856
+ ]);
3857
+ var aggregateDeltaPoints = (observations, nowMillis) => {
3858
+ const series = /* @__PURE__ */ new Map();
3859
+ for (const observation of observations) {
3860
+ const instrument = METRIC_INSTRUMENTS[observation.instrument];
3861
+ const key = seriesIdentity(observation.instrument, observation.attributes);
3862
+ const existing = series.get(key) ?? {
3863
+ observation,
3864
+ start: observation.timeMillis,
3865
+ value: 0,
3866
+ ...instrument.boundaries === void 0 ? {} : { histogram: emptyHistogram(instrument.boundaries) }
3867
+ };
3868
+ existing.start = Math.min(existing.start, observation.timeMillis);
3869
+ if (existing.histogram !== void 0 && instrument.boundaries !== void 0) {
3870
+ existing.histogram = recordIntoHistogram(existing.histogram, instrument.boundaries, observation.value);
3871
+ } else {
3872
+ existing.value += observation.value;
3873
+ }
3874
+ series.set(key, existing);
3875
+ }
3876
+ return [...series.values()].map((entry) => ({
3877
+ instrument: entry.observation.instrument,
3878
+ temporality: "delta",
3879
+ attributes: entry.observation.attributes,
3880
+ startTimeMillis: Math.min(entry.start, nowMillis),
3881
+ timeMillis: Math.max(nowMillis, entry.start),
3882
+ ...entry.histogram === void 0 ? { value: entry.value } : { histogram: entry.histogram }
3883
+ }));
3884
+ };
3885
+ var FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES = Object.freeze([
3886
+ "user.",
3887
+ "enduser.",
3888
+ "organization."
3889
+ ]);
3890
+ var withoutAccountIdentity = (attributes) => Object.fromEntries(
3891
+ Object.entries(attributes).filter(
3892
+ ([key]) => !FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES.some((prefix) => key.startsWith(prefix))
3893
+ )
3894
+ );
3895
+
3896
+ // src/telemetry/durable-metric-spool.ts
3897
+ var MAX_SPOOLED_METRIC_POINTS_PER_BATCH = 4096;
3898
+ var MAX_STRING_LENGTH = 8192;
3899
+ var MAX_ATTRIBUTES_PER_POINT = 64;
3900
+ var MAX_BUCKETS = 64;
3901
+ var isPlainObject3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3902
+ var isFiniteNonNegative3 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
3903
+ var isBoundedString3 = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_STRING_LENGTH;
3904
+ var isPrimitiveAttribute2 = (value) => typeof value === "string" && value.length <= MAX_STRING_LENGTH || typeof value === "number" && Number.isFinite(value) || typeof value === "boolean";
3905
+ var isReplayablePoint = (value) => {
3906
+ if (!isPlainObject3(value) || !isMetricInstrumentName(value.instrument)) {
3907
+ return false;
3908
+ }
3909
+ if (value.temporality !== "cumulative" && value.temporality !== "delta") {
3910
+ return false;
3911
+ }
3912
+ if (!isFiniteNonNegative3(value.startTimeMillis) || !isFiniteNonNegative3(value.timeMillis)) {
3913
+ return false;
3914
+ }
3915
+ if (!isPlainObject3(value.attributes)) {
3916
+ return false;
3917
+ }
3918
+ const entries = Object.entries(value.attributes);
3919
+ if (entries.length > MAX_ATTRIBUTES_PER_POINT || !entries.every(([, item]) => isPrimitiveAttribute2(item))) {
3920
+ return false;
3921
+ }
3922
+ const instrument = METRIC_INSTRUMENTS[value.instrument];
3923
+ if (instrument.kind === "counter") {
3924
+ return isFiniteNonNegative3(value.value) && value.histogram === void 0;
3925
+ }
3926
+ const histogram = value.histogram;
3927
+ if (!isPlainObject3(histogram) || value.value !== void 0) {
3928
+ return false;
3929
+ }
3930
+ const buckets = histogram.bucketCounts;
3931
+ 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));
3932
+ };
3933
+ var validateMetricSpoolBatch = (value, identity) => {
3934
+ if (!isPlainObject3(value)) {
3935
+ return { rejection: "not-an-object" };
3936
+ }
3937
+ if (value.providerId !== identity.providerId || value.installationId !== identity.installationId) {
3938
+ return { rejection: "identity-mismatch" };
3939
+ }
3940
+ if (!isPlainObject3(value.resourceAttributes)) {
3941
+ return { rejection: "resource-attributes-invalid" };
3942
+ }
3943
+ if (!isPlainObject3(value.instrumentationScope) || !isBoundedString3(value.instrumentationScope.name)) {
3944
+ return { rejection: "instrumentation-scope-invalid" };
3945
+ }
3946
+ if (value.instrumentationScope.version !== void 0 && typeof value.instrumentationScope.version !== "string") {
3947
+ return { rejection: "instrumentation-scope-invalid" };
3948
+ }
3949
+ if (!Array.isArray(value.points) || value.points.length === 0 || value.points.length > MAX_SPOOLED_METRIC_POINTS_PER_BATCH) {
3950
+ return { rejection: "points-invalid" };
3951
+ }
3952
+ if (!value.points.every(isReplayablePoint)) {
3953
+ return { rejection: "point-field-invalid" };
3954
+ }
3955
+ if (!isFiniteNonNegative3(value.enqueuedAt)) {
3956
+ return { rejection: "not-an-object" };
3957
+ }
3958
+ return { batch: value };
3959
+ };
3960
+ var DEFAULT_MAX_METRIC_SPOOL_FILES = 500;
3961
+ var createFileDurableMetricSpool = (options) => createSpoolQueue({
3962
+ rootDir: options.rootDir,
3963
+ providerId: options.providerId,
3964
+ installationId: options.installationId,
3965
+ clock: options.clock,
3966
+ ...options.logger === void 0 ? {} : { logger: options.logger },
3967
+ maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_METRIC_SPOOL_FILES,
3968
+ queueName: options.queueName ?? "spool-metrics",
3969
+ ...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
3970
+ ...options.maxAgeMillis === void 0 ? {} : { maxAgeMillis: options.maxAgeMillis },
3971
+ ...options.overflow === void 0 ? {} : { overflow: options.overflow },
3972
+ validate: validateMetricSpoolBatch
3973
+ });
3974
+
3975
+ // src/telemetry/otlp-metric-sink.ts
3976
+ import { ValueType } from "@opentelemetry/api";
3977
+ import { ExportResultCode as ExportResultCode3, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
3978
+ import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
3979
+ import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
3980
+ import {
3981
+ AggregationTemporality,
3982
+ DataPointType
3983
+ } from "@opentelemetry/sdk-metrics";
3984
+ var resolveMetricsEndpoint = (exporter) => {
3985
+ const stated = exporter.metrics?.endpoint;
3986
+ if (stated !== void 0) {
3987
+ return { endpoint: stated, derived: false };
3988
+ }
3989
+ if (exporter.endpoint === void 0) {
3990
+ return { unresolvable: "no-endpoint" };
3991
+ }
3992
+ return { endpoint: siblingSignalEndpoint(exporter.endpoint, "metrics"), derived: true };
3993
+ };
3994
+ var describeMetricsDeliverability = (exporter) => {
3995
+ if (exporter.metrics?.enabled !== true) {
3996
+ return { status: "disabled", reason: "metrics-disabled" };
3997
+ }
3998
+ if (!exporter.enabled) {
3999
+ return { status: "disabled", reason: "exporter-disabled" };
4000
+ }
4001
+ if (exporter.protocol === "none") {
4002
+ return { status: "disabled", reason: "protocol-none" };
4003
+ }
4004
+ if (exporter.protocol !== "http/protobuf") {
4005
+ return { status: "disabled", reason: "protocol-unsupported" };
4006
+ }
4007
+ const resolved = resolveMetricsEndpoint(exporter);
4008
+ if ("unresolvable" in resolved) {
4009
+ return { status: "disabled", reason: "no-endpoint" };
4010
+ }
4011
+ return { status: "configured", endpoint: resolved.endpoint, derivedEndpoint: resolved.derived };
4012
+ };
4013
+ var DISABLED_DETAIL2 = Object.freeze({
4014
+ "exporter-disabled": "otlp metric sink disabled: the exporter is disabled",
4015
+ "protocol-none": "otlp metric sink disabled: protocol is none",
4016
+ "protocol-unsupported": "otlp metric sink disabled: protocol not supported by this build",
4017
+ "no-endpoint": "otlp metric sink disabled: no metrics endpoint configured and none could be derived"
4018
+ });
4019
+ var createDisabledMetricSink = (destination) => {
4020
+ const health = createHealthTracker(
4021
+ "telemetry-metric-sink",
4022
+ destination === void 0 ? {} : { destination }
4023
+ );
4024
+ return {
4025
+ enabled: false,
4026
+ exportPoints: () => Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),
4027
+ flush: () => Promise.resolve(),
4028
+ shutdown: () => Promise.resolve(),
4029
+ health: () => health.snapshot(),
4030
+ drainSpool: () => Promise.resolve({ drained: 0, remaining: 0, failed: 0 })
4031
+ };
4032
+ };
4033
+ var createDisabledOtlpMetricSink = createDisabledMetricSink;
4034
+ var toMetricData = (points) => {
4035
+ const byInstrument = /* @__PURE__ */ new Map();
4036
+ for (const point of points) {
4037
+ const key = `${point.instrument}|${point.temporality}`;
4038
+ const group = byInstrument.get(key) ?? [];
4039
+ group.push(point);
4040
+ byInstrument.set(key, group);
4041
+ }
4042
+ const metrics = [];
4043
+ for (const group of byInstrument.values()) {
4044
+ const first = group[0];
4045
+ if (first === void 0) {
4046
+ continue;
4047
+ }
4048
+ const instrument = METRIC_INSTRUMENTS[first.instrument];
4049
+ const descriptor = {
4050
+ name: instrument.name,
4051
+ description: instrument.description,
4052
+ unit: instrument.unit,
4053
+ valueType: instrument.valueType === "int" ? ValueType.INT : ValueType.DOUBLE
4054
+ };
4055
+ const aggregationTemporality = first.temporality === "cumulative" ? AggregationTemporality.CUMULATIVE : AggregationTemporality.DELTA;
4056
+ const times = (point) => ({
4057
+ startTime: millisToHrTime4(point.startTimeMillis),
4058
+ endTime: millisToHrTime4(point.timeMillis)
4059
+ });
4060
+ if (instrument.kind === "counter") {
4061
+ metrics.push({
4062
+ descriptor,
4063
+ aggregationTemporality,
4064
+ dataPointType: DataPointType.SUM,
4065
+ isMonotonic: true,
4066
+ dataPoints: group.map((point) => ({
4067
+ ...times(point),
4068
+ attributes: { ...point.attributes },
4069
+ value: point.value ?? 0
4070
+ }))
4071
+ });
4072
+ continue;
4073
+ }
4074
+ metrics.push({
4075
+ descriptor,
4076
+ aggregationTemporality,
4077
+ dataPointType: DataPointType.HISTOGRAM,
4078
+ dataPoints: group.map((point) => {
4079
+ const histogram = point.histogram;
4080
+ return {
4081
+ ...times(point),
4082
+ attributes: { ...point.attributes },
4083
+ value: {
4084
+ buckets: {
4085
+ boundaries: [...instrument.boundaries ?? []],
4086
+ counts: [...histogram?.bucketCounts ?? []]
4087
+ },
4088
+ count: histogram?.count ?? 0,
4089
+ sum: histogram?.sum ?? 0,
4090
+ ...histogram === void 0 || histogram.count === 0 ? {} : { min: histogram.min, max: histogram.max }
4091
+ }
4092
+ };
4093
+ })
4094
+ });
4095
+ }
4096
+ return metrics;
4097
+ };
4098
+ var createOtlpMetricSink = (options) => {
4099
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
4100
+ const deliverability = describeMetricsDeliverability(options.exporter);
4101
+ if (deliverability.status === "disabled") {
4102
+ if (deliverability.reason !== "metrics-disabled") {
4103
+ options.logger?.warn(DISABLED_DETAIL2[deliverability.reason], {
4104
+ "exporter.protocol": options.exporter.protocol,
4105
+ ...destinationFields
4106
+ });
4107
+ }
4108
+ return createDisabledMetricSink(options.destination);
4109
+ }
4110
+ const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
4111
+ const resource = resourceFromAttributes2(
4112
+ withoutAccountIdentity(resourceFromExporterPolicy(options.exporter).attributes)
4113
+ );
4114
+ const health = createHealthTracker(
4115
+ "telemetry-metric-sink",
4116
+ options.destination === void 0 ? {} : { destination: options.destination }
4117
+ );
4118
+ const exporter = new OTLPMetricExporter({
4119
+ url: deliverability.endpoint,
4120
+ headers: { ...options.headers },
4121
+ timeoutMillis: options.exporter.timeoutMillis
4122
+ });
4123
+ let shutdownCompleted = false;
4124
+ const exportResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve) => {
4125
+ const payload = {
4126
+ resource: batchResource,
4127
+ scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }]
4128
+ };
4129
+ try {
4130
+ exporter.export(payload, (result) => resolve(result));
4131
+ } catch (thrown) {
4132
+ resolve({
4133
+ code: ExportResultCode3.FAILED,
4134
+ error: thrown instanceof Error ? thrown : new Error("export threw")
4135
+ });
4136
+ }
4137
+ });
4138
+ const toSpoolBatch = (points, batchResource) => ({
4139
+ providerId: options.providerId,
4140
+ installationId: options.installationId,
4141
+ resourceAttributes: { ...batchResource.attributes },
4142
+ instrumentationScope: {
4143
+ name: scope.name,
4144
+ ...scope.version === void 0 ? {} : { version: scope.version }
4145
+ },
4146
+ points: points.map((point) => ({ ...point })),
4147
+ enqueuedAt: options.clock.now()
4148
+ });
4149
+ const sendSerializedBatch = async (batch) => {
4150
+ const batchResource = resourceFromAttributes2(
4151
+ withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes)
4152
+ );
4153
+ const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);
4154
+ if (result.code === ExportResultCode3.SUCCESS) {
4155
+ return true;
4156
+ }
4157
+ return isPermanentExportFailure(result) ? "discard" : false;
4158
+ };
4159
+ const exportPoints = async (points, context) => {
4160
+ if (points.length === 0) {
4161
+ return { accepted: 0, rejected: 0, errors: [] };
4162
+ }
4163
+ const batchResource = context === void 0 ? resource : resourceWithContext(resource, context);
4164
+ const result = await exportResourceMetrics(points, batchResource, scope);
4165
+ if (result.code === ExportResultCode3.SUCCESS) {
4166
+ health.recordSuccess(points.length, options.clock.now());
4167
+ return { accepted: points.length, rejected: 0, errors: [] };
4168
+ }
4169
+ health.recordFailure("telemetry-export-failure", points.length, options.clock.now());
4170
+ const permanent = isPermanentExportFailure(result);
4171
+ if (options.spool !== void 0 && !permanent) {
4172
+ const spooled = await options.spool.enqueue(toSpoolBatch(points, batchResource)).catch(() => ({
4173
+ spooled: false,
4174
+ reason: "capacity-exceeded"
4175
+ }));
4176
+ if (spooled.spooled) {
4177
+ options.logger?.warn("metric batch not delivered; spooled for the next invocation", {
4178
+ "export.batch_size": points.length,
4179
+ ...destinationFields
4180
+ });
4181
+ return { accepted: points.length, rejected: 0, errors: [] };
4182
+ }
4183
+ }
4184
+ return {
4185
+ accepted: 0,
4186
+ rejected: points.length,
4187
+ errors: [
4188
+ createErrorInfo({
4189
+ code: "telemetry-export-failure",
4190
+ phase: "export",
4191
+ detail: permanent ? "collector refused a metric batch with a non-retryable status" : "collector rejected or was unreachable for a metric batch",
4192
+ details: {
4193
+ "export.batch_size": points.length,
4194
+ "export.signal": "metrics",
4195
+ ...destinationFields
4196
+ }
4197
+ })
4198
+ ]
4199
+ };
4200
+ };
4201
+ const drainSpool = async (maxBatches) => {
4202
+ if (options.spool === void 0) {
4203
+ return { drained: 0, remaining: 0, failed: 0 };
4204
+ }
4205
+ const result = await options.spool.drain(sendSerializedBatch, {
4206
+ ...maxBatches === void 0 ? {} : { maxBatches }
4207
+ });
4208
+ if (result.drained > 0) {
4209
+ health.recordSuccess(result.drained, options.clock.now());
4210
+ }
4211
+ return result;
4212
+ };
4213
+ const flush = async () => {
4214
+ try {
4215
+ await exporter.forceFlush();
4216
+ } catch {
4217
+ }
4218
+ await drainSpool().catch(() => void 0);
4219
+ };
4220
+ const shutdown = async () => {
4221
+ if (shutdownCompleted) {
4222
+ return;
4223
+ }
4224
+ shutdownCompleted = true;
4225
+ await flush();
4226
+ try {
4227
+ await exporter.shutdown();
4228
+ } catch {
4229
+ }
4230
+ };
4231
+ return {
4232
+ enabled: true,
4233
+ exportPoints,
4234
+ flush,
4235
+ shutdown,
4236
+ health: () => health.snapshot(),
4237
+ drainSpool
4238
+ };
4239
+ };
4240
+
3384
4241
  // src/telemetry/export-destinations.ts
3385
- var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs" } : { traces: `destinations/${destination}/spool`, logs: `destinations/${destination}/spool-logs` };
4242
+ var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs", metrics: "spool-metrics" } : {
4243
+ traces: `destinations/${destination}/spool`,
4244
+ logs: `destinations/${destination}/spool-logs`,
4245
+ metrics: `destinations/${destination}/spool-metrics`
4246
+ };
3386
4247
  var exporterPolicyForDestination = (exporter, destination) => {
3387
4248
  if (destination.source === "exporter") {
3388
4249
  return exporter;
@@ -3399,8 +4260,10 @@ var exporterPolicyForDestination = (exporter, destination) => {
3399
4260
  });
3400
4261
  return "endpoint" in derived ? derived.endpoint : void 0;
3401
4262
  })());
4263
+ const { metrics: sharedMetrics, ...rest } = shared;
4264
+ const derivedMetrics = destination.metricsEndpoint ?? (destination.endpoint === void 0 ? void 0 : siblingSignalEndpoint(destination.endpoint, "metrics"));
3402
4265
  return {
3403
- ...shared,
4266
+ ...rest,
3404
4267
  protocol: destination.protocol,
3405
4268
  ...tracesEndpoint === void 0 ? {} : { endpoint: tracesEndpoint },
3406
4269
  headerNames: Object.keys(destination.headers).sort(),
@@ -3408,6 +4271,11 @@ var exporterPolicyForDestination = (exporter, destination) => {
3408
4271
  ...logs,
3409
4272
  enabled: destination.signals.logs,
3410
4273
  ...derivedLogs === void 0 ? {} : { endpoint: derivedLogs }
4274
+ },
4275
+ metrics: {
4276
+ ...effectiveMetricsPolicy({ ...exporter, metrics: sharedMetrics }),
4277
+ enabled: destination.signals.metrics,
4278
+ ...derivedMetrics === void 0 ? {} : { endpoint: derivedMetrics }
3411
4279
  }
3412
4280
  };
3413
4281
  };
@@ -3479,6 +4347,12 @@ var createExportDestinationSinks = (options) => {
3479
4347
  ...bounds,
3480
4348
  queueName: queues.logs
3481
4349
  });
4350
+ const metricSpool = options.spoolRootDir === void 0 || !destination.signals.metrics ? void 0 : createFileDurableMetricSpool({
4351
+ rootDir: options.spoolRootDir,
4352
+ ...shared,
4353
+ ...bounds,
4354
+ queueName: queues.metrics
4355
+ });
3482
4356
  const sinkShared = {
3483
4357
  exporter: policy,
3484
4358
  ...shared,
@@ -3496,12 +4370,21 @@ var createExportDestinationSinks = (options) => {
3496
4370
  ...logSpool === void 0 ? {} : { spool: logSpool },
3497
4371
  content: options.logContent
3498
4372
  });
4373
+ const metrics = destination.signals.metrics ? createOtlpMetricSink({
4374
+ exporter: policy,
4375
+ ...shared,
4376
+ ...label === void 0 ? {} : { destination: label },
4377
+ ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
4378
+ ...metricSpool === void 0 ? {} : { spool: metricSpool }
4379
+ }) : createDisabledOtlpMetricSink(label);
3499
4380
  destinations.push({
3500
4381
  name: destination.name,
3501
4382
  traces,
3502
4383
  logs,
4384
+ metrics,
3503
4385
  ...spool === void 0 ? {} : { spool },
3504
- ...logSpool === void 0 ? {} : { logSpool }
4386
+ ...logSpool === void 0 ? {} : { logSpool },
4387
+ ...metricSpool === void 0 ? {} : { metricSpool }
3505
4388
  });
3506
4389
  }
3507
4390
  return { destinations, skipped };
@@ -3555,27 +4438,42 @@ export {
3555
4438
  MAX_LOG_RECORDS_PER_EVENT,
3556
4439
  MAX_RECOVERED_START_ATTRIBUTES,
3557
4440
  MCP_TOOL_NAME_PATTERN,
4441
+ METRIC_COST_USAGE,
4442
+ METRIC_INSTRUMENTS,
4443
+ METRIC_OPERATION_DURATION,
4444
+ METRIC_SESSIONS,
4445
+ METRIC_TOKEN_USAGE,
4446
+ METRIC_TOOL_CALLS,
3558
4447
  NO_LOG_CONTENT,
4448
+ OPERATION_DURATION_BUCKETS,
4449
+ TOKEN_USAGE_BUCKETS,
4450
+ aggregateDeltaPoints,
3559
4451
  canonicalEventTraceIdentities,
3560
4452
  canonicalEventsToLogRecords,
3561
4453
  canonicalEventsToReadableSpans,
3562
4454
  createDestinationFanout,
3563
4455
  createExportDestinationSinks,
3564
4456
  createFileDurableLogSpool,
4457
+ createFileDurableMetricSpool,
3565
4458
  createFileDurableSpool,
3566
4459
  createOtlpLogSink,
4460
+ createOtlpMetricSink,
3567
4461
  createOtlpTraceSink,
3568
4462
  createSignalFanout,
4463
+ deriveMetricObservations,
3569
4464
  describeLogsDeliverability,
4465
+ describeMetricsDeliverability,
3570
4466
  exporterPolicyForDestination,
3571
4467
  isPermanentExportFailure,
3572
4468
  logSignalOf,
3573
4469
  logSignalsForLifecycleEvents,
3574
4470
  parentScopeRefOf,
3575
4471
  resolveLogsEndpoint,
4472
+ resolveMetricsEndpoint,
3576
4473
  shareCorrelationPerBatch,
3577
4474
  spanScopeRefOf,
3578
4475
  spoolQueueNamesFor,
3579
- startOnlySpanAttributes
4476
+ startOnlySpanAttributes,
4477
+ validateMetricSpoolBatch
3580
4478
  };
3581
4479
  //# sourceMappingURL=telemetry.js.map