@osfactory/otel-hook 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +124 -4
  2. package/dist/{adapter-BJiz6lqM.d.ts → adapter-DiLknaTF.d.ts} +14 -2
  3. package/dist/cli.js +2272 -730
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +13 -4
  6. package/dist/config.js +128 -23
  7. package/dist/config.js.map +1 -1
  8. package/dist/{destinations-C6Bm89W6.d.ts → destinations-BIl3gGzx.d.ts} +12 -2
  9. package/dist/diagnostics.d.ts +1 -1
  10. package/dist/diagnostics.js.map +1 -1
  11. package/dist/{events-B3MHoJTD.d.ts → events-CSD_YiJ2.d.ts} +2 -0
  12. package/dist/{export-destinations-d8tZV0G4.d.ts → export-destinations-QWKGGEjk.d.ts} +131 -6
  13. package/dist/{filesystem-store-r-nNA3BA.d.ts → filesystem-store-D3SCNmbX.d.ts} +1 -1
  14. package/dist/{hook-zA1b4cWd.d.ts → hook-BOecWGSz.d.ts} +10 -5
  15. package/dist/index.d.ts +16 -16
  16. package/dist/index.js +1808 -251
  17. package/dist/index.js.map +1 -1
  18. package/dist/install.d.ts +4 -4
  19. package/dist/install.js +31 -2
  20. package/dist/install.js.map +1 -1
  21. package/dist/integration.d.ts +37 -12
  22. package/dist/integration.js +3271 -1551
  23. package/dist/integration.js.map +1 -1
  24. package/dist/lifecycle.d.ts +55 -4
  25. package/dist/lifecycle.js +277 -4
  26. package/dist/lifecycle.js.map +1 -1
  27. package/dist/{memory-Bl9ANVff.d.ts → memory-Cs51jyRk.d.ts} +2 -2
  28. package/dist/{semconv-fPRb-dpU.d.ts → metric-model-DDnWxL9d.d.ts} +154 -2
  29. package/dist/model.d.ts +1 -1
  30. package/dist/model.js +7 -0
  31. package/dist/model.js.map +1 -1
  32. package/dist/{payload-Ci8_ERm6.d.ts → payload-ChtrEX6A.d.ts} +41 -2
  33. package/dist/{ports-n7KFOpKo.d.ts → ports-CeqLq31i.d.ts} +87 -2
  34. package/dist/providers.d.ts +146 -10
  35. package/dist/providers.js +397 -13
  36. package/dist/providers.js.map +1 -1
  37. package/dist/{registry-B8ZHc2bc.d.ts → registry-CcJNF3WY.d.ts} +2 -2
  38. package/dist/runtime.d.ts +8 -8
  39. package/dist/runtime.js +1404 -1219
  40. package/dist/runtime.js.map +1 -1
  41. package/dist/{schema-BxiVsU-d.d.ts → schema-DMnoU1V_.d.ts} +93 -1
  42. package/dist/state.d.ts +4 -4
  43. package/dist/state.js +630 -39
  44. package/dist/state.js.map +1 -1
  45. package/dist/telemetry.d.ts +6 -6
  46. package/dist/telemetry.js +872 -19
  47. package/dist/telemetry.js.map +1 -1
  48. package/dist/testing.d.ts +11 -9
  49. package/dist/testing.js +264 -34
  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.9.0";
21
+ var VERSION = "0.11.0";
22
22
 
23
23
  // src/telemetry/export-identity.ts
24
24
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -706,6 +706,13 @@ var generationEndEventSchema = event({
706
706
  stopReason: nonEmptyStringSchema.optional(),
707
707
  durationMillis: durationMillisSchema.optional(),
708
708
  usage: canonicalUsageSchema.optional(),
709
+ /**
710
+ * True when `usage` is known to cover only part of the generation (for
711
+ * example the last model request of a multi-request turn); false when the
712
+ * provider or harness said it is the whole. Absent: not stated. Meaningless
713
+ * without `usage`.
714
+ */
715
+ usagePartial: z9.boolean().optional(),
709
716
  cost: costFactsSchema.optional(),
710
717
  outputContent: contentFactsSchema.optional()
711
718
  });
@@ -887,6 +894,7 @@ var ATTR_OTELHOOK_SPAN_PAIRING = "otelhook.span.pairing";
887
894
  var ATTR_OTELHOOK_SPAN_ORPHAN = "otelhook.span.orphan";
888
895
  var ATTR_OTELHOOK_OUTCOME = "otelhook.outcome";
889
896
  var ATTR_OTELHOOK_RESET_DETECTED = "otelhook.usage.reset_detected";
897
+ var ATTR_OTELHOOK_USAGE_PARTIAL = "otelhook.usage.partial";
890
898
  var ATTR_OTELHOOK_TOOL_KIND = "otelhook.tool.kind";
891
899
  var ATTR_OTELHOOK_DELEGATION_DEPTH = "otelhook.delegation_depth";
892
900
  var ATTR_OTELHOOK_COMPACTION_TRIGGER = "otelhook.compaction.trigger";
@@ -1159,7 +1167,8 @@ var buildLifecycleSpan = (plan, resource, scope) => {
1159
1167
  // Codex turn): the key a consumer stores a usage observation under.
1160
1168
  [ATTR_OTELHOOK_GENERATION_ID]: group.ref.scopeKey,
1161
1169
  ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
1162
- ...usageAttributes(end?.usage, false)
1170
+ ...usageAttributes(end?.usage, false),
1171
+ ...end?.usage === void 0 || end.usagePartial === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_PARTIAL]: end.usagePartial }
1163
1172
  };
1164
1173
  status = outcomeStatus(end?.outcome);
1165
1174
  break;
@@ -2552,7 +2561,8 @@ var eventAttributes = (event2) => {
2552
2561
  ...event2.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event2.model.vendor },
2553
2562
  [ATTR_OTELHOOK_OUTCOME2]: event2.outcome,
2554
2563
  ...event2.stopReason === void 0 ? {} : { [ATTR_OTELHOOK_STOP_REASON]: event2.stopReason },
2555
- ...usageAttributes2(event2.usage)
2564
+ ...usageAttributes2(event2.usage),
2565
+ ...event2.usage === void 0 || event2.usagePartial === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_PARTIAL]: event2.usagePartial }
2556
2566
  };
2557
2567
  case "tool.start":
2558
2568
  return {
@@ -2861,10 +2871,17 @@ import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
2861
2871
  var OTLP_ENDPOINT_VARIABLES = Object.freeze({
2862
2872
  generic: "OTEL_EXPORTER_OTLP_ENDPOINT",
2863
2873
  traces: "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
2864
- logs: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT"
2874
+ logs: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
2875
+ metrics: "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"
2865
2876
  });
2866
2877
  var OTLP_TRACES_PATH = "/v1/traces";
2867
2878
  var OTLP_LOGS_PATH = "/v1/logs";
2879
+ var OTLP_METRICS_PATH = "/v1/metrics";
2880
+ var SIGNAL_PATHS = Object.freeze({
2881
+ traces: OTLP_TRACES_PATH,
2882
+ logs: OTLP_LOGS_PATH,
2883
+ metrics: OTLP_METRICS_PATH
2884
+ });
2868
2885
  var withoutTrailingSlashes = (value) => {
2869
2886
  let end = value.length;
2870
2887
  while (end > 0 && value.charCodeAt(end - 1) === 47) {
@@ -2872,6 +2889,17 @@ var withoutTrailingSlashes = (value) => {
2872
2889
  }
2873
2890
  return value.slice(0, end);
2874
2891
  };
2892
+ var siblingSignalEndpoint = (tracesEndpoint, signal) => {
2893
+ const trimmed = withoutTrailingSlashes(tracesEndpoint);
2894
+ const target = SIGNAL_PATHS[signal];
2895
+ if (trimmed.endsWith(target)) {
2896
+ return trimmed;
2897
+ }
2898
+ if (trimmed.endsWith(OTLP_TRACES_PATH)) {
2899
+ return `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${target}`;
2900
+ }
2901
+ return `${trimmed}${target}`;
2902
+ };
2875
2903
 
2876
2904
  // src/telemetry/otlp-log-sink.ts
2877
2905
  var resolveLogsEndpoint = (exporter) => {
@@ -3230,7 +3258,7 @@ var HEADER_ENV_REFERENCE_PREFIX = "env:";
3230
3258
  var HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
3231
3259
  var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
3232
3260
  var MAX_HEADER_VALUE_LENGTH = 8192;
3233
- var exportSignalSchema = z13.enum(["traces", "logs"]);
3261
+ var exportSignalSchema = z13.enum(["traces", "logs", "metrics"]);
3234
3262
  var headerValueSchema = z13.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
3235
3263
  (value) => !isUnsafeHeaderValue(value),
3236
3264
  "header values may not contain line breaks, control characters, or characters beyond Latin-1"
@@ -3253,6 +3281,8 @@ var exportDestinationSchema = z13.strictObject({
3253
3281
  tracesEndpoint: endpointSchema.optional(),
3254
3282
  /** Per-signal override of the derived logs URL. */
3255
3283
  logsEndpoint: endpointSchema.optional(),
3284
+ /** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */
3285
+ metricsEndpoint: endpointSchema.optional(),
3256
3286
  /** Defaults to `exporter.protocol`. */
3257
3287
  protocol: z13.enum(["http/protobuf", "http/json", "none"]).optional(),
3258
3288
  /**
@@ -3265,15 +3295,17 @@ var exportDestinationSchema = z13.strictObject({
3265
3295
  `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
3266
3296
  ).optional(),
3267
3297
  /**
3268
- * Which signals this destination receives. Default: both. The logs signal is
3269
- * still governed by `exporter.logs.enabled`, which stays the one opt-in for a
3270
- * second stream leaving the host.
3298
+ * Which signals this destination receives. Default: traces and logs. The logs
3299
+ * signal is still governed by `exporter.logs.enabled`, which stays the one
3300
+ * opt-in for content-bearing records leaving the host. `metrics` is never on by
3301
+ * default: a destination receives hook-derived metrics only when it lists them.
3271
3302
  */
3272
- signals: z13.array(exportSignalSchema).min(1).max(2).readonly().optional()
3303
+ signals: z13.array(exportSignalSchema).min(1).max(3).readonly().optional()
3273
3304
  }).refine(
3274
- (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0,
3275
- "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint"
3305
+ (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
3306
+ "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
3276
3307
  );
3308
+ var DEFAULT_DESTINATION_SIGNALS = Object.freeze(["traces", "logs"]);
3277
3309
  var exportDestinationsSchema = z13.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
3278
3310
  const seen = /* @__PURE__ */ new Set();
3279
3311
  destinations.forEach((destination, index) => {
@@ -3318,7 +3350,8 @@ var legacyDestination = (exporter) => ({
3318
3350
  protocol: exporter.protocol,
3319
3351
  ...exporter.endpoint === void 0 ? {} : { endpoint: exporter.endpoint },
3320
3352
  ...exporter.logs.endpoint === void 0 ? {} : { logsEndpoint: exporter.logs.endpoint },
3321
- signals: { traces: true, logs: exporter.logs.enabled },
3353
+ ...exporter.metrics?.endpoint === void 0 ? {} : { metricsEndpoint: exporter.metrics.endpoint },
3354
+ signals: { traces: true, logs: exporter.logs.enabled, metrics: exporter.metrics?.enabled === true },
3322
3355
  headers: {}
3323
3356
  });
3324
3357
  var hasConfiguredDestinations = (exporter) => exporter.destinations !== void 0 && exporter.destinations.length > 0;
@@ -3327,14 +3360,14 @@ var resolveExportDestinations = (exporter) => {
3327
3360
  return [legacyDestination(exporter)];
3328
3361
  }
3329
3362
  const resolved = [];
3330
- if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0) {
3363
+ if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0 || exporter.metrics?.endpoint !== void 0) {
3331
3364
  resolved.push(legacyDestination(exporter));
3332
3365
  }
3333
3366
  for (const destination of exporter.destinations ?? []) {
3334
3367
  if (destination.enabled === false) {
3335
3368
  continue;
3336
3369
  }
3337
- const signals = destination.signals ?? exportSignalSchema.options;
3370
+ const signals = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;
3338
3371
  resolved.push({
3339
3372
  name: destination.name,
3340
3373
  source: "destinations",
@@ -3342,9 +3375,11 @@ var resolveExportDestinations = (exporter) => {
3342
3375
  ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
3343
3376
  ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
3344
3377
  ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
3378
+ ...destination.metricsEndpoint === void 0 ? {} : { metricsEndpoint: destination.metricsEndpoint },
3345
3379
  signals: {
3346
3380
  traces: signals.includes("traces"),
3347
- logs: exporter.logs.enabled && signals.includes("logs")
3381
+ logs: exporter.logs.enabled && signals.includes("logs"),
3382
+ metrics: signals.includes("metrics")
3348
3383
  },
3349
3384
  headers: { ...destination.headers ?? {} }
3350
3385
  });
@@ -3371,8 +3406,789 @@ var resolveDestinationHeaders = (headers, environment) => {
3371
3406
  return { values, missingVariables: [...new Set(missing)].sort() };
3372
3407
  };
3373
3408
 
3409
+ // src/config/schema.ts
3410
+ import { z as z14 } from "zod";
3411
+ var logsPolicySchema = z14.strictObject({
3412
+ enabled: z14.boolean(),
3413
+ /**
3414
+ * Full URL for the logs signal.
3415
+ *
3416
+ * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes
3417
+ * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.
3418
+ */
3419
+ endpoint: z14.string().url().max(2048).optional(),
3420
+ includeContent: z14.boolean(),
3421
+ maxBatchSize: z14.number().int().min(1).max(4096)
3422
+ });
3423
+ var DEFAULT_LOGS_POLICY = Object.freeze({
3424
+ enabled: false,
3425
+ includeContent: false,
3426
+ maxBatchSize: 128
3427
+ });
3428
+ var metricsPolicySchema = z14.strictObject({
3429
+ enabled: z14.boolean(),
3430
+ /** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */
3431
+ endpoint: z14.string().url().max(2048).optional(),
3432
+ temporality: z14.enum(["cumulative", "delta"]),
3433
+ includeSessionId: z14.boolean()
3434
+ });
3435
+ var DEFAULT_METRICS_POLICY = Object.freeze({
3436
+ enabled: false,
3437
+ temporality: "cumulative",
3438
+ includeSessionId: true
3439
+ });
3440
+ var exporterPolicySchema = z14.strictObject({
3441
+ enabled: z14.boolean(),
3442
+ protocol: z14.enum(["http/protobuf", "http/json", "none"]),
3443
+ endpoint: z14.string().url().max(2048).optional(),
3444
+ /**
3445
+ * Header names only. Values are supplied separately at construction time and
3446
+ * are never part of a resolved-config snapshot, which is logged and exported.
3447
+ */
3448
+ headerNames: z14.array(nonEmptyStringSchema).max(32).readonly(),
3449
+ timeoutMillis: z14.number().int().min(1).max(6e5),
3450
+ maxBatchSize: z14.number().int().min(1).max(4096),
3451
+ maxQueueSize: z14.number().int().min(1).max(65536),
3452
+ maxRetryAttempts: z14.number().int().min(0).max(10),
3453
+ serviceName: nonEmptyStringSchema,
3454
+ serviceNamespace: nonEmptyStringSchema.optional(),
3455
+ /**
3456
+ * Custom attributes merged into the exported OTLP Resource.
3457
+ *
3458
+ * Bounded and validated, and refusing `service.name`/`service.namespace`,
3459
+ * which are the two fields above. Distinct from an invocation's
3460
+ * `consumerAttributes`: this describes the emitting deployment, carries no
3461
+ * identity, and is the same for every span this process exports.
3462
+ */
3463
+ resourceAttributes: resourceAttributesSchema,
3464
+ /**
3465
+ * The logs signal. Nested under the exporter because it shares the endpoint,
3466
+ * headers, timeout, protocol, service identity, and resource attributes above —
3467
+ * a second top-level section would invite two of each to drift apart.
3468
+ */
3469
+ logs: logsPolicySchema,
3470
+ /**
3471
+ * Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before
3472
+ * metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.
3473
+ */
3474
+ metrics: metricsPolicySchema.optional(),
3475
+ /**
3476
+ * Additional OTLP destinations, each sent every batch in parallel.
3477
+ *
3478
+ * Absent (the default), the exporter has exactly one destination — the
3479
+ * single-endpoint settings above, named `default` — and behaves exactly as it
3480
+ * did before this list existed. See `destinations.ts`.
3481
+ *
3482
+ * Merged as one leaf: a higher layer that sets the list replaces it whole,
3483
+ * because "the union of two partial lists" has no answer an operator could
3484
+ * predict.
3485
+ */
3486
+ destinations: exportDestinationsSchema.optional(),
3487
+ /**
3488
+ * Per-destination retry spool bounds, each optional and merged per leaf; any
3489
+ * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.
3490
+ */
3491
+ spool: spoolPolicySchema.partial().optional()
3492
+ });
3493
+ var detectionPolicySchema = z14.strictObject({
3494
+ /** Detections below this confidence resolve to the unknown provider. */
3495
+ minimumConfidence: detectionConfidenceSchema,
3496
+ /** When false, an ambiguous detection is an error rather than unknown. */
3497
+ allowAmbiguousFallback: z14.boolean(),
3498
+ /** Optional allow-list of provider ids; empty means "any registered". */
3499
+ allowedProviderIds: z14.array(nonEmptyStringSchema).max(32).readonly()
3500
+ });
3501
+ var diagnosticsPolicySchema = z14.strictObject({
3502
+ logLevel: z14.enum(["silent", "error", "warn", "info", "debug"]),
3503
+ /** Emit `error.raised` events for contained failures. */
3504
+ emitErrorEvents: z14.boolean()
3505
+ });
3506
+ var providersPolicySchema = z14.strictObject({
3507
+ claudeCode: z14.strictObject({
3508
+ readTranscriptUsage: z14.boolean()
3509
+ }).optional()
3510
+ });
3511
+ var otelHookConfigSchema = z14.strictObject({
3512
+ exporter: exporterPolicySchema,
3513
+ privacy: privacyPolicySchema,
3514
+ detection: detectionPolicySchema,
3515
+ diagnostics: diagnosticsPolicySchema,
3516
+ /** Optional so a hand-built configuration from before it existed stays valid. */
3517
+ providers: providersPolicySchema.optional()
3518
+ });
3519
+ var otelHookConfigPatchSchema = z14.strictObject({
3520
+ // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
3521
+ // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
3522
+ // without also restating the endpoint and the batch size.
3523
+ exporter: exporterPolicySchema.omit({ logs: true, metrics: true, spool: true }).partial().extend({
3524
+ logs: logsPolicySchema.partial().optional(),
3525
+ metrics: metricsPolicySchema.partial().optional(),
3526
+ spool: spoolPolicySchema.partial().optional()
3527
+ }).optional(),
3528
+ privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
3529
+ detection: detectionPolicySchema.partial().optional(),
3530
+ diagnostics: diagnosticsPolicySchema.partial().optional(),
3531
+ providers: z14.strictObject({
3532
+ claudeCode: z14.strictObject({ readTranscriptUsage: z14.boolean() }).partial().optional()
3533
+ }).partial().optional()
3534
+ });
3535
+ var DEFAULT_EXPORTER_POLICY = Object.freeze({
3536
+ enabled: true,
3537
+ protocol: "http/protobuf",
3538
+ headerNames: Object.freeze([]),
3539
+ timeoutMillis: 1e4,
3540
+ maxBatchSize: 128,
3541
+ maxQueueSize: 2048,
3542
+ maxRetryAttempts: 2,
3543
+ serviceName: "coding-agent",
3544
+ resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
3545
+ logs: DEFAULT_LOGS_POLICY,
3546
+ metrics: DEFAULT_METRICS_POLICY
3547
+ });
3548
+ var DEFAULT_DETECTION_POLICY = Object.freeze({
3549
+ minimumConfidence: "strong",
3550
+ allowAmbiguousFallback: true,
3551
+ allowedProviderIds: Object.freeze([])
3552
+ });
3553
+ var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
3554
+ logLevel: "warn",
3555
+ emitErrorEvents: true
3556
+ });
3557
+ var DEFAULT_PROVIDERS_POLICY = Object.freeze({
3558
+ claudeCode: Object.freeze({ readTranscriptUsage: false })
3559
+ });
3560
+ var DEFAULT_CONFIG = Object.freeze({
3561
+ exporter: DEFAULT_EXPORTER_POLICY,
3562
+ privacy: DEFAULT_PRIVACY_POLICY,
3563
+ detection: DEFAULT_DETECTION_POLICY,
3564
+ diagnostics: DEFAULT_DIAGNOSTICS_POLICY,
3565
+ providers: DEFAULT_PROVIDERS_POLICY
3566
+ });
3567
+ var effectiveMetricsPolicy = (exporter) => ({
3568
+ ...DEFAULT_METRICS_POLICY,
3569
+ ...exporter.metrics ?? {}
3570
+ });
3571
+
3572
+ // src/telemetry/metric-model.ts
3573
+ var TOKEN_USAGE_BUCKETS = Object.freeze([
3574
+ 1,
3575
+ 4,
3576
+ 16,
3577
+ 64,
3578
+ 256,
3579
+ 1024,
3580
+ 4096,
3581
+ 16384,
3582
+ 65536,
3583
+ 262144,
3584
+ 1048576,
3585
+ 4194304,
3586
+ 16777216,
3587
+ 67108864
3588
+ ]);
3589
+ var OPERATION_DURATION_BUCKETS = Object.freeze([
3590
+ 0.01,
3591
+ 0.02,
3592
+ 0.04,
3593
+ 0.08,
3594
+ 0.16,
3595
+ 0.32,
3596
+ 0.64,
3597
+ 1.28,
3598
+ 2.56,
3599
+ 5.12,
3600
+ 10.24,
3601
+ 20.48,
3602
+ 40.96,
3603
+ 81.92
3604
+ ]);
3605
+ var METRIC_TOKEN_USAGE = "gen_ai.client.token.usage";
3606
+ var METRIC_OPERATION_DURATION = "gen_ai.client.operation.duration";
3607
+ var METRIC_SESSIONS = "otelhook.sessions";
3608
+ var METRIC_TOOL_CALLS = "otelhook.tool.calls";
3609
+ var METRIC_COST_USAGE = "otelhook.cost.usage";
3610
+ var METRIC_INSTRUMENTS = Object.freeze({
3611
+ [METRIC_TOKEN_USAGE]: {
3612
+ name: METRIC_TOKEN_USAGE,
3613
+ kind: "histogram",
3614
+ unit: "{token}",
3615
+ description: "Tokens used per generation, by token type (hook-derived)",
3616
+ valueType: "int",
3617
+ boundaries: TOKEN_USAGE_BUCKETS
3618
+ },
3619
+ [METRIC_OPERATION_DURATION]: {
3620
+ name: METRIC_OPERATION_DURATION,
3621
+ kind: "histogram",
3622
+ unit: "s",
3623
+ description: "Generation duration, from its start hook to its end hook (hook-derived)",
3624
+ valueType: "double",
3625
+ boundaries: OPERATION_DURATION_BUCKETS
3626
+ },
3627
+ [METRIC_SESSIONS]: {
3628
+ name: METRIC_SESSIONS,
3629
+ kind: "counter",
3630
+ unit: "{session}",
3631
+ description: "Agent sessions started",
3632
+ valueType: "int"
3633
+ },
3634
+ [METRIC_TOOL_CALLS]: {
3635
+ name: METRIC_TOOL_CALLS,
3636
+ kind: "counter",
3637
+ unit: "{call}",
3638
+ description: "Completed tool calls, by tool name and outcome",
3639
+ valueType: "int"
3640
+ },
3641
+ [METRIC_COST_USAGE]: {
3642
+ name: METRIC_COST_USAGE,
3643
+ kind: "counter",
3644
+ unit: "USD",
3645
+ description: "Cost reported by the provider; never estimated",
3646
+ valueType: "double"
3647
+ }
3648
+ });
3649
+ var isMetricInstrumentName = (value) => typeof value === "string" && Object.hasOwn(METRIC_INSTRUMENTS, value);
3650
+ var ATTR_GEN_AI_TOKEN_TYPE = "gen_ai.token.type";
3651
+ var ATTR_GEN_AI_PROVIDER_NAME = "gen_ai.provider.name";
3652
+ var ATTR_GEN_AI_OPERATION_NAME3 = "gen_ai.operation.name";
3653
+ var ATTR_GEN_AI_REQUEST_MODEL3 = "gen_ai.request.model";
3654
+ var ATTR_GEN_AI_RESPONSE_MODEL3 = "gen_ai.response.model";
3655
+ var ATTR_GEN_AI_TOOL_NAME3 = "gen_ai.tool.name";
3656
+ var ATTR_ERROR_TYPE3 = "error.type";
3657
+ var ATTR_SESSION_ID2 = "session.id";
3658
+ var ATTR_OTELHOOK_PROVIDER_ID2 = "otelhook.provider.id";
3659
+ var ATTR_OTELHOOK_OUTCOME3 = "otelhook.outcome";
3660
+ var ATTR_OTELHOOK_SESSION_KIND2 = "otelhook.session.kind";
3661
+ var commonAttributes = (event2, resource, includeSessionId) => ({
3662
+ [ATTR_OTELHOOK_PROVIDER_ID2]: event2.provenance.providerId,
3663
+ ...includeSessionId ? { [ATTR_SESSION_ID2]: resolveExportedSessionId(event2.sessionId, resource).sessionId } : {}
3664
+ });
3665
+ var generationAttributes = (end, requestModel) => ({
3666
+ [ATTR_GEN_AI_OPERATION_NAME3]: "chat",
3667
+ ...end.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_PROVIDER_NAME]: end.model.vendor },
3668
+ [ATTR_GEN_AI_REQUEST_MODEL3]: requestModel ?? end.model.modelId,
3669
+ [ATTR_GEN_AI_RESPONSE_MODEL3]: end.model.modelId
3670
+ });
3671
+ var TOKEN_FIELDS = [
3672
+ ["input", (usage) => usage.inputTokens],
3673
+ ["output", (usage) => usage.outputTokens],
3674
+ ["cache_read", (usage) => usage.cachedInputTokens],
3675
+ ["cache_creation", (usage) => usage.cacheCreationInputTokens]
3676
+ ];
3677
+ var isFailedOutcome = (outcome) => outcome !== "ok" && outcome !== "unknown" && outcome !== "cancelled";
3678
+ var deriveMetricObservations = (input) => {
3679
+ const includeSessionId = input.includeSessionId ?? true;
3680
+ const observations = [];
3681
+ const byId = /* @__PURE__ */ new Map();
3682
+ const startsInBatch = /* @__PURE__ */ new Map();
3683
+ for (const event2 of input.events) {
3684
+ byId.set(event2.eventId, event2);
3685
+ if (event2.type === "generation.start") {
3686
+ startsInBatch.set(event2.generationId, {
3687
+ startMillis: event2.occurredAt,
3688
+ requestModel: event2.model.modelId
3689
+ });
3690
+ }
3691
+ }
3692
+ const requestModelOf = (generationId) => startsInBatch.get(generationId)?.requestModel ?? input.generationStarts?.(generationId)?.requestModel;
3693
+ let lastPromptInBatch;
3694
+ for (const event2 of input.events) {
3695
+ if (event2.type === "prompt.submitted") {
3696
+ lastPromptInBatch ??= /* @__PURE__ */ new Map();
3697
+ lastPromptInBatch.set(event2.sessionId, Math.max(lastPromptInBatch.get(event2.sessionId) ?? 0, event2.occurredAt));
3698
+ }
3699
+ }
3700
+ const measuredDurationOf = (end) => {
3701
+ if (end.durationMillis !== void 0) {
3702
+ return end.durationMillis;
3703
+ }
3704
+ const recovered = startsInBatch.has(end.generationId) ? void 0 : input.generationStarts?.(end.generationId);
3705
+ if (recovered !== void 0) {
3706
+ return end.occurredAt - recovered.startMillis;
3707
+ }
3708
+ const turn = lastPromptInBatch?.get(end.sessionId) ?? input.turnStart?.(end.sessionId);
3709
+ return turn === void 0 || turn > end.occurredAt ? void 0 : end.occurredAt - turn;
3710
+ };
3711
+ const push = (event2, instrument, value, attributes) => {
3712
+ if (!Number.isFinite(value) || value < 0) {
3713
+ return;
3714
+ }
3715
+ observations.push({
3716
+ instrument,
3717
+ value,
3718
+ attributes: { ...commonAttributes(event2, input.resource, includeSessionId), ...attributes },
3719
+ timeMillis: event2.occurredAt,
3720
+ sessionId: event2.sessionId
3721
+ });
3722
+ };
3723
+ for (const event2 of input.events) {
3724
+ switch (event2.type) {
3725
+ case "session.start":
3726
+ push(event2, METRIC_SESSIONS, 1, { [ATTR_OTELHOOK_SESSION_KIND2]: event2.sessionKind });
3727
+ break;
3728
+ case "tool.end":
3729
+ push(event2, METRIC_TOOL_CALLS, 1, {
3730
+ [ATTR_GEN_AI_TOOL_NAME3]: event2.toolName,
3731
+ [ATTR_OTELHOOK_OUTCOME3]: event2.outcome
3732
+ });
3733
+ break;
3734
+ case "generation.end": {
3735
+ const attributes = generationAttributes(event2, requestModelOf(event2.generationId));
3736
+ const durationMillis = measuredDurationOf(event2);
3737
+ if (durationMillis !== void 0 && durationMillis >= 0) {
3738
+ push(event2, METRIC_OPERATION_DURATION, durationMillis / 1e3, {
3739
+ ...attributes,
3740
+ ...isFailedOutcome(event2.outcome) ? { [ATTR_ERROR_TYPE3]: event2.outcome } : {}
3741
+ });
3742
+ }
3743
+ if (event2.cost !== void 0 && event2.cost.source === "provider-reported" && event2.cost.currency === "USD") {
3744
+ push(event2, METRIC_COST_USAGE, event2.cost.amount, attributes);
3745
+ }
3746
+ break;
3747
+ }
3748
+ default:
3749
+ break;
3750
+ }
3751
+ }
3752
+ for (const observation of input.usage) {
3753
+ if (observation.scope !== "generation") {
3754
+ continue;
3755
+ }
3756
+ const event2 = byId.get(observation.eventId);
3757
+ if (event2?.type !== "generation.end") {
3758
+ continue;
3759
+ }
3760
+ const attributes = generationAttributes(event2, requestModelOf(event2.generationId));
3761
+ for (const [tokenType, read] of TOKEN_FIELDS) {
3762
+ const value = read(observation.delta);
3763
+ if (value === 0 && (tokenType === "cache_read" || tokenType === "cache_creation")) {
3764
+ continue;
3765
+ }
3766
+ push(event2, METRIC_TOKEN_USAGE, value, { ...attributes, [ATTR_GEN_AI_TOKEN_TYPE]: tokenType });
3767
+ }
3768
+ }
3769
+ return observations;
3770
+ };
3771
+ var emptyHistogram = (boundaries) => ({
3772
+ count: 0,
3773
+ sum: 0,
3774
+ min: Number.POSITIVE_INFINITY,
3775
+ max: Number.NEGATIVE_INFINITY,
3776
+ bucketCounts: new Array(boundaries.length + 1).fill(0)
3777
+ });
3778
+ var bucketIndex = (boundaries, value) => {
3779
+ for (let index = 0; index < boundaries.length; index += 1) {
3780
+ const bound = boundaries[index];
3781
+ if (bound !== void 0 && value <= bound) {
3782
+ return index;
3783
+ }
3784
+ }
3785
+ return boundaries.length;
3786
+ };
3787
+ var recordIntoHistogram = (state, boundaries, value) => {
3788
+ const bucketCounts = [...state.bucketCounts];
3789
+ const index = bucketIndex(boundaries, value);
3790
+ bucketCounts[index] = (bucketCounts[index] ?? 0) + 1;
3791
+ return {
3792
+ count: state.count + 1,
3793
+ sum: state.sum + value,
3794
+ min: Math.min(state.min, value),
3795
+ max: Math.max(state.max, value),
3796
+ bucketCounts
3797
+ };
3798
+ };
3799
+ var seriesIdentity = (instrument, attributes) => JSON.stringify([
3800
+ instrument,
3801
+ Object.entries(attributes).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
3802
+ ]);
3803
+ var aggregateDeltaPoints = (observations, nowMillis) => {
3804
+ const series = /* @__PURE__ */ new Map();
3805
+ for (const observation of observations) {
3806
+ const instrument = METRIC_INSTRUMENTS[observation.instrument];
3807
+ const key = seriesIdentity(observation.instrument, observation.attributes);
3808
+ const existing = series.get(key) ?? {
3809
+ observation,
3810
+ start: observation.timeMillis,
3811
+ value: 0,
3812
+ ...instrument.boundaries === void 0 ? {} : { histogram: emptyHistogram(instrument.boundaries) }
3813
+ };
3814
+ existing.start = Math.min(existing.start, observation.timeMillis);
3815
+ if (existing.histogram !== void 0 && instrument.boundaries !== void 0) {
3816
+ existing.histogram = recordIntoHistogram(existing.histogram, instrument.boundaries, observation.value);
3817
+ } else {
3818
+ existing.value += observation.value;
3819
+ }
3820
+ series.set(key, existing);
3821
+ }
3822
+ return [...series.values()].map((entry) => ({
3823
+ instrument: entry.observation.instrument,
3824
+ temporality: "delta",
3825
+ attributes: entry.observation.attributes,
3826
+ startTimeMillis: Math.min(entry.start, nowMillis),
3827
+ timeMillis: Math.max(nowMillis, entry.start),
3828
+ ...entry.histogram === void 0 ? { value: entry.value } : { histogram: entry.histogram }
3829
+ }));
3830
+ };
3831
+ var FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES = Object.freeze([
3832
+ "user.",
3833
+ "enduser.",
3834
+ "organization."
3835
+ ]);
3836
+ var withoutAccountIdentity = (attributes) => Object.fromEntries(
3837
+ Object.entries(attributes).filter(
3838
+ ([key]) => !FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES.some((prefix) => key.startsWith(prefix))
3839
+ )
3840
+ );
3841
+
3842
+ // src/telemetry/durable-metric-spool.ts
3843
+ var MAX_SPOOLED_METRIC_POINTS_PER_BATCH = 4096;
3844
+ var MAX_STRING_LENGTH = 8192;
3845
+ var MAX_ATTRIBUTES_PER_POINT = 64;
3846
+ var MAX_BUCKETS = 64;
3847
+ var isPlainObject3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3848
+ var isFiniteNonNegative3 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
3849
+ var isBoundedString3 = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_STRING_LENGTH;
3850
+ var isPrimitiveAttribute2 = (value) => typeof value === "string" && value.length <= MAX_STRING_LENGTH || typeof value === "number" && Number.isFinite(value) || typeof value === "boolean";
3851
+ var isReplayablePoint = (value) => {
3852
+ if (!isPlainObject3(value) || !isMetricInstrumentName(value.instrument)) {
3853
+ return false;
3854
+ }
3855
+ if (value.temporality !== "cumulative" && value.temporality !== "delta") {
3856
+ return false;
3857
+ }
3858
+ if (!isFiniteNonNegative3(value.startTimeMillis) || !isFiniteNonNegative3(value.timeMillis)) {
3859
+ return false;
3860
+ }
3861
+ if (!isPlainObject3(value.attributes)) {
3862
+ return false;
3863
+ }
3864
+ const entries = Object.entries(value.attributes);
3865
+ if (entries.length > MAX_ATTRIBUTES_PER_POINT || !entries.every(([, item]) => isPrimitiveAttribute2(item))) {
3866
+ return false;
3867
+ }
3868
+ const instrument = METRIC_INSTRUMENTS[value.instrument];
3869
+ if (instrument.kind === "counter") {
3870
+ return isFiniteNonNegative3(value.value) && value.histogram === void 0;
3871
+ }
3872
+ const histogram = value.histogram;
3873
+ if (!isPlainObject3(histogram) || value.value !== void 0) {
3874
+ return false;
3875
+ }
3876
+ const buckets = histogram.bucketCounts;
3877
+ 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));
3878
+ };
3879
+ var validateMetricSpoolBatch = (value, identity) => {
3880
+ if (!isPlainObject3(value)) {
3881
+ return { rejection: "not-an-object" };
3882
+ }
3883
+ if (value.providerId !== identity.providerId || value.installationId !== identity.installationId) {
3884
+ return { rejection: "identity-mismatch" };
3885
+ }
3886
+ if (!isPlainObject3(value.resourceAttributes)) {
3887
+ return { rejection: "resource-attributes-invalid" };
3888
+ }
3889
+ if (!isPlainObject3(value.instrumentationScope) || !isBoundedString3(value.instrumentationScope.name)) {
3890
+ return { rejection: "instrumentation-scope-invalid" };
3891
+ }
3892
+ if (value.instrumentationScope.version !== void 0 && typeof value.instrumentationScope.version !== "string") {
3893
+ return { rejection: "instrumentation-scope-invalid" };
3894
+ }
3895
+ if (!Array.isArray(value.points) || value.points.length === 0 || value.points.length > MAX_SPOOLED_METRIC_POINTS_PER_BATCH) {
3896
+ return { rejection: "points-invalid" };
3897
+ }
3898
+ if (!value.points.every(isReplayablePoint)) {
3899
+ return { rejection: "point-field-invalid" };
3900
+ }
3901
+ if (!isFiniteNonNegative3(value.enqueuedAt)) {
3902
+ return { rejection: "not-an-object" };
3903
+ }
3904
+ return { batch: value };
3905
+ };
3906
+ var DEFAULT_MAX_METRIC_SPOOL_FILES = 500;
3907
+ var createFileDurableMetricSpool = (options) => createSpoolQueue({
3908
+ rootDir: options.rootDir,
3909
+ providerId: options.providerId,
3910
+ installationId: options.installationId,
3911
+ clock: options.clock,
3912
+ ...options.logger === void 0 ? {} : { logger: options.logger },
3913
+ maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_METRIC_SPOOL_FILES,
3914
+ queueName: options.queueName ?? "spool-metrics",
3915
+ ...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
3916
+ ...options.maxAgeMillis === void 0 ? {} : { maxAgeMillis: options.maxAgeMillis },
3917
+ ...options.overflow === void 0 ? {} : { overflow: options.overflow },
3918
+ validate: validateMetricSpoolBatch
3919
+ });
3920
+
3921
+ // src/telemetry/otlp-metric-sink.ts
3922
+ import { ValueType } from "@opentelemetry/api";
3923
+ import { ExportResultCode as ExportResultCode3, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
3924
+ import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
3925
+ import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
3926
+ import {
3927
+ AggregationTemporality,
3928
+ DataPointType
3929
+ } from "@opentelemetry/sdk-metrics";
3930
+ var resolveMetricsEndpoint = (exporter) => {
3931
+ const stated = exporter.metrics?.endpoint;
3932
+ if (stated !== void 0) {
3933
+ return { endpoint: stated, derived: false };
3934
+ }
3935
+ if (exporter.endpoint === void 0) {
3936
+ return { unresolvable: "no-endpoint" };
3937
+ }
3938
+ return { endpoint: siblingSignalEndpoint(exporter.endpoint, "metrics"), derived: true };
3939
+ };
3940
+ var describeMetricsDeliverability = (exporter) => {
3941
+ if (exporter.metrics?.enabled !== true) {
3942
+ return { status: "disabled", reason: "metrics-disabled" };
3943
+ }
3944
+ if (!exporter.enabled) {
3945
+ return { status: "disabled", reason: "exporter-disabled" };
3946
+ }
3947
+ if (exporter.protocol === "none") {
3948
+ return { status: "disabled", reason: "protocol-none" };
3949
+ }
3950
+ if (exporter.protocol !== "http/protobuf") {
3951
+ return { status: "disabled", reason: "protocol-unsupported" };
3952
+ }
3953
+ const resolved = resolveMetricsEndpoint(exporter);
3954
+ if ("unresolvable" in resolved) {
3955
+ return { status: "disabled", reason: "no-endpoint" };
3956
+ }
3957
+ return { status: "configured", endpoint: resolved.endpoint, derivedEndpoint: resolved.derived };
3958
+ };
3959
+ var DISABLED_DETAIL2 = Object.freeze({
3960
+ "exporter-disabled": "otlp metric sink disabled: the exporter is disabled",
3961
+ "protocol-none": "otlp metric sink disabled: protocol is none",
3962
+ "protocol-unsupported": "otlp metric sink disabled: protocol not supported by this build",
3963
+ "no-endpoint": "otlp metric sink disabled: no metrics endpoint configured and none could be derived"
3964
+ });
3965
+ var createDisabledMetricSink = (destination) => {
3966
+ const health = createHealthTracker(
3967
+ "telemetry-metric-sink",
3968
+ destination === void 0 ? {} : { destination }
3969
+ );
3970
+ return {
3971
+ enabled: false,
3972
+ exportPoints: () => Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),
3973
+ flush: () => Promise.resolve(),
3974
+ shutdown: () => Promise.resolve(),
3975
+ health: () => health.snapshot(),
3976
+ drainSpool: () => Promise.resolve({ drained: 0, remaining: 0, failed: 0 })
3977
+ };
3978
+ };
3979
+ var createDisabledOtlpMetricSink = createDisabledMetricSink;
3980
+ var toMetricData = (points) => {
3981
+ const byInstrument = /* @__PURE__ */ new Map();
3982
+ for (const point of points) {
3983
+ const key = `${point.instrument}|${point.temporality}`;
3984
+ const group = byInstrument.get(key) ?? [];
3985
+ group.push(point);
3986
+ byInstrument.set(key, group);
3987
+ }
3988
+ const metrics = [];
3989
+ for (const group of byInstrument.values()) {
3990
+ const first = group[0];
3991
+ if (first === void 0) {
3992
+ continue;
3993
+ }
3994
+ const instrument = METRIC_INSTRUMENTS[first.instrument];
3995
+ const descriptor = {
3996
+ name: instrument.name,
3997
+ description: instrument.description,
3998
+ unit: instrument.unit,
3999
+ valueType: instrument.valueType === "int" ? ValueType.INT : ValueType.DOUBLE
4000
+ };
4001
+ const aggregationTemporality = first.temporality === "cumulative" ? AggregationTemporality.CUMULATIVE : AggregationTemporality.DELTA;
4002
+ const times = (point) => ({
4003
+ startTime: millisToHrTime4(point.startTimeMillis),
4004
+ endTime: millisToHrTime4(point.timeMillis)
4005
+ });
4006
+ if (instrument.kind === "counter") {
4007
+ metrics.push({
4008
+ descriptor,
4009
+ aggregationTemporality,
4010
+ dataPointType: DataPointType.SUM,
4011
+ isMonotonic: true,
4012
+ dataPoints: group.map((point) => ({
4013
+ ...times(point),
4014
+ attributes: { ...point.attributes },
4015
+ value: point.value ?? 0
4016
+ }))
4017
+ });
4018
+ continue;
4019
+ }
4020
+ metrics.push({
4021
+ descriptor,
4022
+ aggregationTemporality,
4023
+ dataPointType: DataPointType.HISTOGRAM,
4024
+ dataPoints: group.map((point) => {
4025
+ const histogram = point.histogram;
4026
+ return {
4027
+ ...times(point),
4028
+ attributes: { ...point.attributes },
4029
+ value: {
4030
+ buckets: {
4031
+ boundaries: [...instrument.boundaries ?? []],
4032
+ counts: [...histogram?.bucketCounts ?? []]
4033
+ },
4034
+ count: histogram?.count ?? 0,
4035
+ sum: histogram?.sum ?? 0,
4036
+ ...histogram === void 0 || histogram.count === 0 ? {} : { min: histogram.min, max: histogram.max }
4037
+ }
4038
+ };
4039
+ })
4040
+ });
4041
+ }
4042
+ return metrics;
4043
+ };
4044
+ var createOtlpMetricSink = (options) => {
4045
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
4046
+ const deliverability = describeMetricsDeliverability(options.exporter);
4047
+ if (deliverability.status === "disabled") {
4048
+ if (deliverability.reason !== "metrics-disabled") {
4049
+ options.logger?.warn(DISABLED_DETAIL2[deliverability.reason], {
4050
+ "exporter.protocol": options.exporter.protocol,
4051
+ ...destinationFields
4052
+ });
4053
+ }
4054
+ return createDisabledMetricSink(options.destination);
4055
+ }
4056
+ const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
4057
+ const resource = resourceFromAttributes2(
4058
+ withoutAccountIdentity(resourceFromExporterPolicy(options.exporter).attributes)
4059
+ );
4060
+ const health = createHealthTracker(
4061
+ "telemetry-metric-sink",
4062
+ options.destination === void 0 ? {} : { destination: options.destination }
4063
+ );
4064
+ const exporter = new OTLPMetricExporter({
4065
+ url: deliverability.endpoint,
4066
+ headers: { ...options.headers },
4067
+ timeoutMillis: options.exporter.timeoutMillis
4068
+ });
4069
+ let shutdownCompleted = false;
4070
+ const exportResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve) => {
4071
+ const payload = {
4072
+ resource: batchResource,
4073
+ scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }]
4074
+ };
4075
+ try {
4076
+ exporter.export(payload, (result) => resolve(result));
4077
+ } catch (thrown) {
4078
+ resolve({
4079
+ code: ExportResultCode3.FAILED,
4080
+ error: thrown instanceof Error ? thrown : new Error("export threw")
4081
+ });
4082
+ }
4083
+ });
4084
+ const toSpoolBatch = (points) => ({
4085
+ providerId: options.providerId,
4086
+ installationId: options.installationId,
4087
+ resourceAttributes: { ...resource.attributes },
4088
+ instrumentationScope: {
4089
+ name: scope.name,
4090
+ ...scope.version === void 0 ? {} : { version: scope.version }
4091
+ },
4092
+ points: points.map((point) => ({ ...point })),
4093
+ enqueuedAt: options.clock.now()
4094
+ });
4095
+ const sendSerializedBatch = async (batch) => {
4096
+ const batchResource = resourceFromAttributes2(
4097
+ withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes)
4098
+ );
4099
+ const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);
4100
+ if (result.code === ExportResultCode3.SUCCESS) {
4101
+ return true;
4102
+ }
4103
+ return isPermanentExportFailure(result) ? "discard" : false;
4104
+ };
4105
+ const exportPoints = async (points) => {
4106
+ if (points.length === 0) {
4107
+ return { accepted: 0, rejected: 0, errors: [] };
4108
+ }
4109
+ const result = await exportResourceMetrics(points, resource, scope);
4110
+ if (result.code === ExportResultCode3.SUCCESS) {
4111
+ health.recordSuccess(points.length, options.clock.now());
4112
+ return { accepted: points.length, rejected: 0, errors: [] };
4113
+ }
4114
+ health.recordFailure("telemetry-export-failure", points.length, options.clock.now());
4115
+ const permanent = isPermanentExportFailure(result);
4116
+ if (options.spool !== void 0 && !permanent) {
4117
+ const spooled = await options.spool.enqueue(toSpoolBatch(points)).catch(() => ({
4118
+ spooled: false,
4119
+ reason: "capacity-exceeded"
4120
+ }));
4121
+ if (spooled.spooled) {
4122
+ options.logger?.warn("metric batch not delivered; spooled for the next invocation", {
4123
+ "export.batch_size": points.length,
4124
+ ...destinationFields
4125
+ });
4126
+ return { accepted: points.length, rejected: 0, errors: [] };
4127
+ }
4128
+ }
4129
+ return {
4130
+ accepted: 0,
4131
+ rejected: points.length,
4132
+ errors: [
4133
+ createErrorInfo({
4134
+ code: "telemetry-export-failure",
4135
+ phase: "export",
4136
+ detail: permanent ? "collector refused a metric batch with a non-retryable status" : "collector rejected or was unreachable for a metric batch",
4137
+ details: {
4138
+ "export.batch_size": points.length,
4139
+ "export.signal": "metrics",
4140
+ ...destinationFields
4141
+ }
4142
+ })
4143
+ ]
4144
+ };
4145
+ };
4146
+ const drainSpool = async (maxBatches) => {
4147
+ if (options.spool === void 0) {
4148
+ return { drained: 0, remaining: 0, failed: 0 };
4149
+ }
4150
+ const result = await options.spool.drain(sendSerializedBatch, {
4151
+ ...maxBatches === void 0 ? {} : { maxBatches }
4152
+ });
4153
+ if (result.drained > 0) {
4154
+ health.recordSuccess(result.drained, options.clock.now());
4155
+ }
4156
+ return result;
4157
+ };
4158
+ const flush = async () => {
4159
+ try {
4160
+ await exporter.forceFlush();
4161
+ } catch {
4162
+ }
4163
+ await drainSpool().catch(() => void 0);
4164
+ };
4165
+ const shutdown = async () => {
4166
+ if (shutdownCompleted) {
4167
+ return;
4168
+ }
4169
+ shutdownCompleted = true;
4170
+ await flush();
4171
+ try {
4172
+ await exporter.shutdown();
4173
+ } catch {
4174
+ }
4175
+ };
4176
+ return {
4177
+ enabled: true,
4178
+ exportPoints,
4179
+ flush,
4180
+ shutdown,
4181
+ health: () => health.snapshot(),
4182
+ drainSpool
4183
+ };
4184
+ };
4185
+
3374
4186
  // src/telemetry/export-destinations.ts
3375
- var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs" } : { traces: `destinations/${destination}/spool`, logs: `destinations/${destination}/spool-logs` };
4187
+ var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs", metrics: "spool-metrics" } : {
4188
+ traces: `destinations/${destination}/spool`,
4189
+ logs: `destinations/${destination}/spool-logs`,
4190
+ metrics: `destinations/${destination}/spool-metrics`
4191
+ };
3376
4192
  var exporterPolicyForDestination = (exporter, destination) => {
3377
4193
  if (destination.source === "exporter") {
3378
4194
  return exporter;
@@ -3389,8 +4205,10 @@ var exporterPolicyForDestination = (exporter, destination) => {
3389
4205
  });
3390
4206
  return "endpoint" in derived ? derived.endpoint : void 0;
3391
4207
  })());
4208
+ const { metrics: sharedMetrics, ...rest } = shared;
4209
+ const derivedMetrics = destination.metricsEndpoint ?? (destination.endpoint === void 0 ? void 0 : siblingSignalEndpoint(destination.endpoint, "metrics"));
3392
4210
  return {
3393
- ...shared,
4211
+ ...rest,
3394
4212
  protocol: destination.protocol,
3395
4213
  ...tracesEndpoint === void 0 ? {} : { endpoint: tracesEndpoint },
3396
4214
  headerNames: Object.keys(destination.headers).sort(),
@@ -3398,6 +4216,11 @@ var exporterPolicyForDestination = (exporter, destination) => {
3398
4216
  ...logs,
3399
4217
  enabled: destination.signals.logs,
3400
4218
  ...derivedLogs === void 0 ? {} : { endpoint: derivedLogs }
4219
+ },
4220
+ metrics: {
4221
+ ...effectiveMetricsPolicy({ ...exporter, metrics: sharedMetrics }),
4222
+ enabled: destination.signals.metrics,
4223
+ ...derivedMetrics === void 0 ? {} : { endpoint: derivedMetrics }
3401
4224
  }
3402
4225
  };
3403
4226
  };
@@ -3469,6 +4292,12 @@ var createExportDestinationSinks = (options) => {
3469
4292
  ...bounds,
3470
4293
  queueName: queues.logs
3471
4294
  });
4295
+ const metricSpool = options.spoolRootDir === void 0 || !destination.signals.metrics ? void 0 : createFileDurableMetricSpool({
4296
+ rootDir: options.spoolRootDir,
4297
+ ...shared,
4298
+ ...bounds,
4299
+ queueName: queues.metrics
4300
+ });
3472
4301
  const sinkShared = {
3473
4302
  exporter: policy,
3474
4303
  ...shared,
@@ -3486,12 +4315,21 @@ var createExportDestinationSinks = (options) => {
3486
4315
  ...logSpool === void 0 ? {} : { spool: logSpool },
3487
4316
  content: options.logContent
3488
4317
  });
4318
+ const metrics = destination.signals.metrics ? createOtlpMetricSink({
4319
+ exporter: policy,
4320
+ ...shared,
4321
+ ...label === void 0 ? {} : { destination: label },
4322
+ ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
4323
+ ...metricSpool === void 0 ? {} : { spool: metricSpool }
4324
+ }) : createDisabledOtlpMetricSink(label);
3489
4325
  destinations.push({
3490
4326
  name: destination.name,
3491
4327
  traces,
3492
4328
  logs,
4329
+ metrics,
3493
4330
  ...spool === void 0 ? {} : { spool },
3494
- ...logSpool === void 0 ? {} : { logSpool }
4331
+ ...logSpool === void 0 ? {} : { logSpool },
4332
+ ...metricSpool === void 0 ? {} : { metricSpool }
3495
4333
  });
3496
4334
  }
3497
4335
  return { destinations, skipped };
@@ -3545,27 +4383,42 @@ export {
3545
4383
  MAX_LOG_RECORDS_PER_EVENT,
3546
4384
  MAX_RECOVERED_START_ATTRIBUTES,
3547
4385
  MCP_TOOL_NAME_PATTERN,
4386
+ METRIC_COST_USAGE,
4387
+ METRIC_INSTRUMENTS,
4388
+ METRIC_OPERATION_DURATION,
4389
+ METRIC_SESSIONS,
4390
+ METRIC_TOKEN_USAGE,
4391
+ METRIC_TOOL_CALLS,
3548
4392
  NO_LOG_CONTENT,
4393
+ OPERATION_DURATION_BUCKETS,
4394
+ TOKEN_USAGE_BUCKETS,
4395
+ aggregateDeltaPoints,
3549
4396
  canonicalEventTraceIdentities,
3550
4397
  canonicalEventsToLogRecords,
3551
4398
  canonicalEventsToReadableSpans,
3552
4399
  createDestinationFanout,
3553
4400
  createExportDestinationSinks,
3554
4401
  createFileDurableLogSpool,
4402
+ createFileDurableMetricSpool,
3555
4403
  createFileDurableSpool,
3556
4404
  createOtlpLogSink,
4405
+ createOtlpMetricSink,
3557
4406
  createOtlpTraceSink,
3558
4407
  createSignalFanout,
4408
+ deriveMetricObservations,
3559
4409
  describeLogsDeliverability,
4410
+ describeMetricsDeliverability,
3560
4411
  exporterPolicyForDestination,
3561
4412
  isPermanentExportFailure,
3562
4413
  logSignalOf,
3563
4414
  logSignalsForLifecycleEvents,
3564
4415
  parentScopeRefOf,
3565
4416
  resolveLogsEndpoint,
4417
+ resolveMetricsEndpoint,
3566
4418
  shareCorrelationPerBatch,
3567
4419
  spanScopeRefOf,
3568
4420
  spoolQueueNamesFor,
3569
- startOnlySpanAttributes
4421
+ startOnlySpanAttributes,
4422
+ validateMetricSpoolBatch
3570
4423
  };
3571
4424
  //# sourceMappingURL=telemetry.js.map