@osfactory/otel-hook 0.7.0 → 0.9.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.
@@ -31,7 +31,8 @@ var createHealthTracker = (subsystem, options = {}) => {
31
31
  consecutiveFailures,
32
32
  ...lastSuccessAt === void 0 ? {} : { lastSuccessAt },
33
33
  ...lastFailureAt === void 0 ? {} : { lastFailureAt },
34
- ...lastErrorCode === void 0 ? {} : { lastErrorCode }
34
+ ...lastErrorCode === void 0 ? {} : { lastErrorCode },
35
+ ...options.destination === void 0 ? {} : { destination: options.destination }
35
36
  })
36
37
  };
37
38
  };
@@ -655,27 +656,7 @@ var createLifecycleJanitor = (options) => {
655
656
  // src/telemetry/semconv.ts
656
657
  import { createHash } from "crypto";
657
658
  import { SpanKind, SpanStatusCode, TraceFlags } from "@opentelemetry/api";
658
-
659
- // node_modules/@opentelemetry/core/build/esm/common/time.js
660
- var NANOSECOND_DIGITS = 9;
661
- var NANOSECOND_DIGITS_IN_MILLIS = 6;
662
- var MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);
663
- var SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);
664
- function millisToHrTime(epochMillis) {
665
- const epochSeconds = epochMillis / 1e3;
666
- const seconds = Math.trunc(epochSeconds);
667
- const nanos = Math.round(epochMillis % 1e3 * MILLISECONDS_TO_NANOSECONDS);
668
- return [seconds, nanos];
669
- }
670
-
671
- // node_modules/@opentelemetry/core/build/esm/ExportResult.js
672
- var ExportResultCode;
673
- (function(ExportResultCode2) {
674
- ExportResultCode2[ExportResultCode2["SUCCESS"] = 0] = "SUCCESS";
675
- ExportResultCode2[ExportResultCode2["FAILED"] = 1] = "FAILED";
676
- })(ExportResultCode || (ExportResultCode = {}));
677
-
678
- // src/telemetry/semconv.ts
659
+ import { millisToHrTime } from "@opentelemetry/core";
679
660
  import {
680
661
  ATTR_ERROR_TYPE,
681
662
  ATTR_GEN_AI_OPERATION_NAME,
@@ -692,7 +673,7 @@ import {
692
673
  } from "@opentelemetry/semantic-conventions/incubating";
693
674
 
694
675
  // src/version.ts
695
- var VERSION = "0.7.0";
676
+ var VERSION = "0.9.0";
696
677
 
697
678
  // src/telemetry/export-identity.ts
698
679
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -1427,10 +1408,13 @@ var targetAttributes = (event2) => {
1427
1408
  };
1428
1409
  var usageTemporalityAttributes = (usage) => usage === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_TEMPORALITY]: usage.temporality };
1429
1410
  var isPrimitiveAttribute = (value) => typeof value === "string" || typeof value === "number" || typeof value === "boolean";
1430
- var passthroughHarAttributes = (resource) => {
1411
+ var PASSTHROUGH_RESOURCE_PREFIXES = Object.freeze(["har.", "factory.", "vcs."]);
1412
+ var LOCAL_ONLY_RESOURCE_PREFIX = "factory.local.";
1413
+ var isPassthroughKey = (key) => PASSTHROUGH_RESOURCE_PREFIXES.some((prefix) => key.startsWith(prefix)) && !key.startsWith(LOCAL_ONLY_RESOURCE_PREFIX) && key !== "factory.local";
1414
+ var passthroughResourceAttributes = (resource) => {
1431
1415
  const attributes = {};
1432
1416
  for (const [key, value] of Object.entries(resource.attributes)) {
1433
- if (key.startsWith("har.") && isPrimitiveAttribute(value)) {
1417
+ if (isPassthroughKey(key) && isPrimitiveAttribute(value)) {
1434
1418
  attributes[key] = value;
1435
1419
  }
1436
1420
  }
@@ -1464,7 +1448,7 @@ var exportIdentityAttributes = (event2, resource, ids) => {
1464
1448
  ...event2.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event2.provenance.providerVersion },
1465
1449
  [ATTR_OTELHOOK_WORKSPACE_ID]: event2.workspace.workspaceId,
1466
1450
  ...event2.subagentId === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event2.subagentId },
1467
- ...passthroughHarAttributes(resource),
1451
+ ...passthroughResourceAttributes(resource),
1468
1452
  ...hexTraceAttributes(ids)
1469
1453
  };
1470
1454
  };
@@ -1614,12 +1598,12 @@ var pickTarget = (attributes) => {
1614
1598
  }
1615
1599
  return picked;
1616
1600
  };
1617
- var withoutTarget = (attributes) => {
1601
+ var withoutTarget = (attributes, resource) => {
1618
1602
  const rest = { ...attributes };
1619
1603
  for (const key of TARGET_KEYS) {
1620
1604
  delete rest[key];
1621
1605
  }
1622
- return rest;
1606
+ return { ...rest, ...pickTarget(passthroughResourceAttributes(resource)) };
1623
1607
  };
1624
1608
  var rankOf = (candidate) => {
1625
1609
  const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];
@@ -1724,7 +1708,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
1724
1708
  name = "session";
1725
1709
  kind = SpanKind.INTERNAL;
1726
1710
  attributes = {
1727
- ...withoutTarget(attributes),
1711
+ ...withoutTarget(attributes, resource),
1728
1712
  ...strongestTarget([pickTarget(resolved.recovered), start === void 0 ? {} : targetAttributes(start)]),
1729
1713
  ...start?.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName },
1730
1714
  ...start?.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion },
@@ -1765,7 +1749,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
1765
1749
  kind = SpanKind.CLIENT;
1766
1750
  attributes = {
1767
1751
  // Target keys are re-chosen below as one unit, never mixed across edges.
1768
- ...withoutTarget(attributes),
1752
+ ...withoutTarget(attributes, resource),
1769
1753
  [ATTR_GEN_AI_TOOL_NAME]: toolName,
1770
1754
  [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,
1771
1755
  ...start?.toolKind === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind },
@@ -2942,13 +2926,180 @@ var createSystemClock = () => ({
2942
2926
  });
2943
2927
 
2944
2928
  // src/runtime/hook.ts
2945
- import { z as z16 } from "zod";
2929
+ import { z as z17 } from "zod";
2946
2930
 
2947
2931
  // src/config/schema.ts
2948
- import { z as z13 } from "zod";
2932
+ import { z as z14 } from "zod";
2949
2933
 
2950
- // src/config/resource-attributes.ts
2934
+ // src/config/destinations.ts
2951
2935
  import { z as z12 } from "zod";
2936
+
2937
+ // src/config/header-value.ts
2938
+ var isUnsafeHeaderValue = (value) => [...value].some((char) => {
2939
+ const code = char.codePointAt(0) ?? 0;
2940
+ return code < 32 && code !== 9 || code === 127 || code > 255;
2941
+ });
2942
+
2943
+ // src/config/otlp-headers.ts
2944
+ var MAX_OTLP_HEADERS = 32;
2945
+ var OTLP_HEADER_VARIABLES = Object.freeze({
2946
+ generic: "OTEL_EXPORTER_OTLP_HEADERS",
2947
+ traces: "OTEL_EXPORTER_OTLP_TRACES_HEADERS",
2948
+ logs: "OTEL_EXPORTER_OTLP_LOGS_HEADERS"
2949
+ });
2950
+
2951
+ // src/config/destinations.ts
2952
+ var DEFAULT_DESTINATION_NAME = "default";
2953
+ var DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;
2954
+ var MAX_EXPORT_DESTINATIONS = 16;
2955
+ var MAX_DESTINATION_HEADERS = MAX_OTLP_HEADERS;
2956
+ var HEADER_ENV_REFERENCE_PREFIX = "env:";
2957
+ var HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
2958
+ var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
2959
+ var MAX_HEADER_VALUE_LENGTH = 8192;
2960
+ var exportSignalSchema = z12.enum(["traces", "logs"]);
2961
+ var headerValueSchema = z12.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
2962
+ (value) => !isUnsafeHeaderValue(value),
2963
+ "header values may not contain line breaks, control characters, or characters beyond Latin-1"
2964
+ ).refine(
2965
+ (value) => !value.startsWith(HEADER_ENV_REFERENCE_PREFIX) || ENV_VARIABLE_NAME_PATTERN.test(value.slice(HEADER_ENV_REFERENCE_PREFIX.length)),
2966
+ "an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN"
2967
+ );
2968
+ var endpointSchema = z12.string().url().max(2048);
2969
+ var exportDestinationSchema = z12.strictObject({
2970
+ /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */
2971
+ name: z12.string().regex(DESTINATION_NAME_PATTERN, "destination names are lowercase letters, digits, _ and -"),
2972
+ /** Default true. A disabled destination is neither sent to nor drained. */
2973
+ enabled: z12.boolean().optional(),
2974
+ /**
2975
+ * Traces URL, with the same meaning as `exporter.endpoint`: the logs URL is
2976
+ * derived from it (`/v1/traces` becomes `/v1/logs`) unless `logsEndpoint` is set.
2977
+ */
2978
+ endpoint: endpointSchema.optional(),
2979
+ /** Per-signal override of `endpoint` for traces. */
2980
+ tracesEndpoint: endpointSchema.optional(),
2981
+ /** Per-signal override of the derived logs URL. */
2982
+ logsEndpoint: endpointSchema.optional(),
2983
+ /** Defaults to `exporter.protocol`. */
2984
+ protocol: z12.enum(["http/protobuf", "http/json", "none"]).optional(),
2985
+ /**
2986
+ * Header name to value. A value of the form `env:NAME` is read from that
2987
+ * environment variable at send time, so a credential never has to be written
2988
+ * into the file. Values never appear in a snapshot, a diagnostic, or `doctor`.
2989
+ */
2990
+ headers: z12.record(z12.string().regex(HEADER_NAME_PATTERN, "not a valid header name"), headerValueSchema).refine(
2991
+ (headers) => Object.keys(headers).length <= MAX_DESTINATION_HEADERS,
2992
+ `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
2993
+ ).optional(),
2994
+ /**
2995
+ * Which signals this destination receives. Default: both. The logs signal is
2996
+ * still governed by `exporter.logs.enabled`, which stays the one opt-in for a
2997
+ * second stream leaving the host.
2998
+ */
2999
+ signals: z12.array(exportSignalSchema).min(1).max(2).readonly().optional()
3000
+ }).refine(
3001
+ (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0,
3002
+ "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint"
3003
+ );
3004
+ var exportDestinationsSchema = z12.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
3005
+ const seen = /* @__PURE__ */ new Set();
3006
+ destinations.forEach((destination, index) => {
3007
+ if (destination.name === DEFAULT_DESTINATION_NAME) {
3008
+ context.addIssue({
3009
+ code: "custom",
3010
+ path: [index, "name"],
3011
+ message: 'the name "default" is reserved for exporter.endpoint and the OTEL_EXPORTER_OTLP_* variables'
3012
+ });
3013
+ }
3014
+ if (seen.has(destination.name)) {
3015
+ context.addIssue({
3016
+ code: "custom",
3017
+ path: [index, "name"],
3018
+ message: `duplicate destination name "${destination.name}"`
3019
+ });
3020
+ }
3021
+ seen.add(destination.name);
3022
+ });
3023
+ });
3024
+ var spoolPolicySchema = z12.strictObject({
3025
+ /** Total bytes of queued batches. Default 16 MiB. */
3026
+ maxBytes: z12.number().int().min(1024).max(1073741824),
3027
+ /** A batch older than this is dropped instead of sent. Default 72 hours. */
3028
+ maxAgeMillis: z12.number().int().min(1e3).max(30 * 24 * 60 * 60 * 1e3),
3029
+ /** Number of queued batches. Default 500. */
3030
+ maxBatches: z12.number().int().min(1).max(65536)
3031
+ });
3032
+ var DEFAULT_SPOOL_POLICY = Object.freeze({
3033
+ maxBytes: 16 * 1024 * 1024,
3034
+ maxAgeMillis: 72 * 60 * 60 * 1e3,
3035
+ maxBatches: 500
3036
+ });
3037
+ var effectiveSpoolPolicy = (exporter) => ({
3038
+ maxBytes: exporter.spool?.maxBytes ?? DEFAULT_SPOOL_POLICY.maxBytes,
3039
+ maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,
3040
+ maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches
3041
+ });
3042
+ var legacyDestination = (exporter) => ({
3043
+ name: DEFAULT_DESTINATION_NAME,
3044
+ source: "exporter",
3045
+ protocol: exporter.protocol,
3046
+ ...exporter.endpoint === void 0 ? {} : { endpoint: exporter.endpoint },
3047
+ ...exporter.logs.endpoint === void 0 ? {} : { logsEndpoint: exporter.logs.endpoint },
3048
+ signals: { traces: true, logs: exporter.logs.enabled },
3049
+ headers: {}
3050
+ });
3051
+ var hasConfiguredDestinations = (exporter) => exporter.destinations !== void 0 && exporter.destinations.length > 0;
3052
+ var resolveExportDestinations = (exporter) => {
3053
+ if (!hasConfiguredDestinations(exporter)) {
3054
+ return [legacyDestination(exporter)];
3055
+ }
3056
+ const resolved = [];
3057
+ if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0) {
3058
+ resolved.push(legacyDestination(exporter));
3059
+ }
3060
+ for (const destination of exporter.destinations ?? []) {
3061
+ if (destination.enabled === false) {
3062
+ continue;
3063
+ }
3064
+ const signals = destination.signals ?? exportSignalSchema.options;
3065
+ resolved.push({
3066
+ name: destination.name,
3067
+ source: "destinations",
3068
+ protocol: destination.protocol ?? exporter.protocol,
3069
+ ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
3070
+ ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
3071
+ ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
3072
+ signals: {
3073
+ traces: signals.includes("traces"),
3074
+ logs: exporter.logs.enabled && signals.includes("logs")
3075
+ },
3076
+ headers: { ...destination.headers ?? {} }
3077
+ });
3078
+ }
3079
+ return resolved;
3080
+ };
3081
+ var parseHeaderValueReference = (value) => value.startsWith(HEADER_ENV_REFERENCE_PREFIX) ? { kind: "env", variable: value.slice(HEADER_ENV_REFERENCE_PREFIX.length) } : { kind: "literal" };
3082
+ var resolveDestinationHeaders = (headers, environment) => {
3083
+ const values = {};
3084
+ const missing = [];
3085
+ for (const [name, value] of Object.entries(headers)) {
3086
+ const reference = parseHeaderValueReference(value);
3087
+ if (reference.kind === "literal") {
3088
+ values[name] = value;
3089
+ continue;
3090
+ }
3091
+ const resolved = environment?.[reference.variable];
3092
+ if (resolved === void 0 || resolved === "") {
3093
+ missing.push(reference.variable);
3094
+ continue;
3095
+ }
3096
+ values[name] = resolved;
3097
+ }
3098
+ return { values, missingVariables: [...new Set(missing)].sort() };
3099
+ };
3100
+
3101
+ // src/config/resource-attributes.ts
3102
+ import { z as z13 } from "zod";
2952
3103
  var MAX_RESOURCE_ATTRIBUTES = 64;
2953
3104
  var MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH = 255;
2954
3105
  var MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH = 2048;
@@ -2993,12 +3144,12 @@ var checkResourceAttributeKey = (key) => {
2993
3144
  }
2994
3145
  return void 0;
2995
3146
  };
2996
- var resourceAttributeValueSchema = z12.union([
2997
- z12.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),
2998
- z12.number().finite(),
2999
- z12.boolean()
3147
+ var resourceAttributeValueSchema = z13.union([
3148
+ z13.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),
3149
+ z13.number().finite(),
3150
+ z13.boolean()
3000
3151
  ]);
3001
- var resourceAttributesSchema = z12.record(z12.string(), resourceAttributeValueSchema).superRefine((value, ctx) => {
3152
+ var resourceAttributesSchema = z13.record(z13.string(), resourceAttributeValueSchema).superRefine((value, ctx) => {
3002
3153
  const keys = Object.keys(value);
3003
3154
  if (keys.length > MAX_RESOURCE_ATTRIBUTES) {
3004
3155
  ctx.addIssue({
@@ -3033,36 +3184,36 @@ var sanitizeResourceAttributes = (attributes) => {
3033
3184
  };
3034
3185
 
3035
3186
  // src/config/schema.ts
3036
- var logsPolicySchema = z13.strictObject({
3037
- enabled: z13.boolean(),
3187
+ var logsPolicySchema = z14.strictObject({
3188
+ enabled: z14.boolean(),
3038
3189
  /**
3039
3190
  * Full URL for the logs signal.
3040
3191
  *
3041
3192
  * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes
3042
3193
  * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.
3043
3194
  */
3044
- endpoint: z13.string().url().max(2048).optional(),
3045
- includeContent: z13.boolean(),
3046
- maxBatchSize: z13.number().int().min(1).max(4096)
3195
+ endpoint: z14.string().url().max(2048).optional(),
3196
+ includeContent: z14.boolean(),
3197
+ maxBatchSize: z14.number().int().min(1).max(4096)
3047
3198
  });
3048
3199
  var DEFAULT_LOGS_POLICY = Object.freeze({
3049
3200
  enabled: false,
3050
3201
  includeContent: false,
3051
3202
  maxBatchSize: 128
3052
3203
  });
3053
- var exporterPolicySchema = z13.strictObject({
3054
- enabled: z13.boolean(),
3055
- protocol: z13.enum(["http/protobuf", "http/json", "none"]),
3056
- endpoint: z13.string().url().max(2048).optional(),
3204
+ var exporterPolicySchema = z14.strictObject({
3205
+ enabled: z14.boolean(),
3206
+ protocol: z14.enum(["http/protobuf", "http/json", "none"]),
3207
+ endpoint: z14.string().url().max(2048).optional(),
3057
3208
  /**
3058
3209
  * Header names only. Values are supplied separately at construction time and
3059
3210
  * are never part of a resolved-config snapshot, which is logged and exported.
3060
3211
  */
3061
- headerNames: z13.array(nonEmptyStringSchema).max(32).readonly(),
3062
- timeoutMillis: z13.number().int().min(1).max(6e5),
3063
- maxBatchSize: z13.number().int().min(1).max(4096),
3064
- maxQueueSize: z13.number().int().min(1).max(65536),
3065
- maxRetryAttempts: z13.number().int().min(0).max(10),
3212
+ headerNames: z14.array(nonEmptyStringSchema).max(32).readonly(),
3213
+ timeoutMillis: z14.number().int().min(1).max(6e5),
3214
+ maxBatchSize: z14.number().int().min(1).max(4096),
3215
+ maxQueueSize: z14.number().int().min(1).max(65536),
3216
+ maxRetryAttempts: z14.number().int().min(0).max(10),
3066
3217
  serviceName: nonEmptyStringSchema,
3067
3218
  serviceNamespace: nonEmptyStringSchema.optional(),
3068
3219
  /**
@@ -3079,32 +3230,52 @@ var exporterPolicySchema = z13.strictObject({
3079
3230
  * headers, timeout, protocol, service identity, and resource attributes above —
3080
3231
  * a second top-level section would invite two of each to drift apart.
3081
3232
  */
3082
- logs: logsPolicySchema
3233
+ logs: logsPolicySchema,
3234
+ /**
3235
+ * Additional OTLP destinations, each sent every batch in parallel.
3236
+ *
3237
+ * Absent (the default), the exporter has exactly one destination — the
3238
+ * single-endpoint settings above, named `default` — and behaves exactly as it
3239
+ * did before this list existed. See `destinations.ts`.
3240
+ *
3241
+ * Merged as one leaf: a higher layer that sets the list replaces it whole,
3242
+ * because "the union of two partial lists" has no answer an operator could
3243
+ * predict.
3244
+ */
3245
+ destinations: exportDestinationsSchema.optional(),
3246
+ /**
3247
+ * Per-destination retry spool bounds, each optional and merged per leaf; any
3248
+ * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.
3249
+ */
3250
+ spool: spoolPolicySchema.partial().optional()
3083
3251
  });
3084
- var detectionPolicySchema = z13.strictObject({
3252
+ var detectionPolicySchema = z14.strictObject({
3085
3253
  /** Detections below this confidence resolve to the unknown provider. */
3086
3254
  minimumConfidence: detectionConfidenceSchema,
3087
3255
  /** When false, an ambiguous detection is an error rather than unknown. */
3088
- allowAmbiguousFallback: z13.boolean(),
3256
+ allowAmbiguousFallback: z14.boolean(),
3089
3257
  /** Optional allow-list of provider ids; empty means "any registered". */
3090
- allowedProviderIds: z13.array(nonEmptyStringSchema).max(32).readonly()
3258
+ allowedProviderIds: z14.array(nonEmptyStringSchema).max(32).readonly()
3091
3259
  });
3092
- var diagnosticsPolicySchema = z13.strictObject({
3093
- logLevel: z13.enum(["silent", "error", "warn", "info", "debug"]),
3260
+ var diagnosticsPolicySchema = z14.strictObject({
3261
+ logLevel: z14.enum(["silent", "error", "warn", "info", "debug"]),
3094
3262
  /** Emit `error.raised` events for contained failures. */
3095
- emitErrorEvents: z13.boolean()
3263
+ emitErrorEvents: z14.boolean()
3096
3264
  });
3097
- var otelHookConfigSchema = z13.strictObject({
3265
+ var otelHookConfigSchema = z14.strictObject({
3098
3266
  exporter: exporterPolicySchema,
3099
3267
  privacy: privacyPolicySchema,
3100
3268
  detection: detectionPolicySchema,
3101
3269
  diagnostics: diagnosticsPolicySchema
3102
3270
  });
3103
- var otelHookConfigPatchSchema = z13.strictObject({
3271
+ var otelHookConfigPatchSchema = z14.strictObject({
3104
3272
  // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
3105
3273
  // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
3106
3274
  // without also restating the endpoint and the batch size.
3107
- exporter: exporterPolicySchema.omit({ logs: true }).partial().extend({ logs: logsPolicySchema.partial().optional() }).optional(),
3275
+ exporter: exporterPolicySchema.omit({ logs: true, spool: true }).partial().extend({
3276
+ logs: logsPolicySchema.partial().optional(),
3277
+ spool: spoolPolicySchema.partial().optional()
3278
+ }).optional(),
3108
3279
  privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
3109
3280
  detection: detectionPolicySchema.partial().optional(),
3110
3281
  diagnostics: diagnosticsPolicySchema.partial().optional()
@@ -3138,27 +3309,27 @@ var DEFAULT_CONFIG = Object.freeze({
3138
3309
  });
3139
3310
 
3140
3311
  // src/providers/adapter.ts
3141
- import { z as z14 } from "zod";
3142
- var providerDetectionSchema = z14.strictObject({
3312
+ import { z as z15 } from "zod";
3313
+ var providerDetectionSchema = z15.strictObject({
3143
3314
  providerId: resolvedProviderIdSchema,
3144
3315
  confidence: detectionConfidenceSchema,
3145
3316
  /**
3146
3317
  * Short, non-sensitive justifications, e.g. `"payload.hook_event_name present"`.
3147
3318
  * Reasons are exported in diagnostics, so they must not quote payload values.
3148
3319
  */
3149
- reasons: z14.array(z14.string().min(1).max(160)).max(8),
3320
+ reasons: z15.array(z15.string().min(1).max(160)).max(8),
3150
3321
  providerVersion: nonEmptyStringSchema.optional(),
3151
3322
  /** The provider's own name for this event, when the payload states one. */
3152
3323
  sourceEventName: nonEmptyStringSchema.optional()
3153
3324
  });
3154
- var deliveryIdentifierSupportSchema = z14.enum(["none", "partial", "all"]);
3325
+ var deliveryIdentifierSupportSchema = z15.enum(["none", "partial", "all"]);
3155
3326
  var DELIVERY_COMPONENT_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
3156
- var deliveryComponentSchema = z14.string().regex(
3327
+ var deliveryComponentSchema = z15.string().regex(
3157
3328
  DELIVERY_COMPONENT_PATTERN,
3158
3329
  "delivery component must be identifier-shaped: no whitespace, no path separators"
3159
3330
  );
3160
3331
  var MAX_DELIVERY_COMPONENTS = 8;
3161
- var providerDeliveryClaimSchema = z14.strictObject({
3332
+ var providerDeliveryClaimSchema = z15.strictObject({
3162
3333
  /**
3163
3334
  * The provider's own session/conversation id. Scopes the callback identity, so
3164
3335
  * two sessions reusing one tool-call id never collide.
@@ -3170,26 +3341,26 @@ var providerDeliveryClaimSchema = z14.strictObject({
3170
3341
  * Identifier-shaped payload fields that, together with `sourceEventName`,
3171
3342
  * name this callback within the session exactly once.
3172
3343
  */
3173
- components: z14.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),
3344
+ components: z15.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),
3174
3345
  /**
3175
3346
  * Short, non-sensitive justifications, e.g. `"payload.tool_use_id names one
3176
3347
  * tool call"`. Evidence reaches diagnostics, so it must name fields, never
3177
3348
  * quote their values.
3178
3349
  */
3179
- evidence: z14.array(z14.string().min(1).max(160)).min(1).max(4).readonly()
3350
+ evidence: z15.array(z15.string().min(1).max(160)).min(1).max(4).readonly()
3180
3351
  });
3181
3352
  var DELIVERY_GAP_REASON_PATTERN = /^[^\n\r\t\\/]{1,240}$/;
3182
- var deliveryGapReasonSchema = z14.string().regex(
3353
+ var deliveryGapReasonSchema = z15.string().regex(
3183
3354
  DELIVERY_GAP_REASON_PATTERN,
3184
3355
  "delivery gap reason must be one line of prose: no path separators, no control characters"
3185
3356
  );
3186
3357
  var MAX_DELIVERY_GAPS = 48;
3187
- var providerDeliveryGapsSchema = z14.record(deliveryComponentSchema, deliveryGapReasonSchema).refine((gaps) => Object.keys(gaps).length <= MAX_DELIVERY_GAPS, {
3358
+ var providerDeliveryGapsSchema = z15.record(deliveryComponentSchema, deliveryGapReasonSchema).refine((gaps) => Object.keys(gaps).length <= MAX_DELIVERY_GAPS, {
3188
3359
  message: `at most ${String(MAX_DELIVERY_GAPS)} delivery gaps may be declared`
3189
3360
  });
3190
- var providerCapabilitiesSchema = z14.strictObject({
3361
+ var providerCapabilitiesSchema = z15.strictObject({
3191
3362
  /** Event types the adapter can produce. */
3192
- lifecycleEvents: z14.array(canonicalEventTypeSchema).max(32).readonly(),
3363
+ lifecycleEvents: z15.array(canonicalEventTypeSchema).max(32).readonly(),
3193
3364
  usageTemporality: usageTemporalitySchema,
3194
3365
  /**
3195
3366
  * Which accumulator series a `cumulative` report continues — that is, which
@@ -3208,32 +3379,32 @@ var providerCapabilitiesSchema = z14.strictObject({
3208
3379
  * Subagent snapshots keep their own series regardless: a delegated agent's
3209
3380
  * counter is not a point on the parent session's curve.
3210
3381
  */
3211
- cumulativeUsageSeries: z14.enum(["event-scope", "session-lifetime"]).optional(),
3212
- reportsCachedInput: z14.boolean(),
3213
- reportsCacheCreation: z14.boolean(),
3382
+ cumulativeUsageSeries: z15.enum(["event-scope", "session-lifetime"]).optional(),
3383
+ reportsCachedInput: z15.boolean(),
3384
+ reportsCacheCreation: z15.boolean(),
3214
3385
  cacheCreationAccounting: cacheCreationAccountingSchema,
3215
- reportsReasoningOutput: z14.boolean(),
3216
- reportsProviderTotal: z14.boolean(),
3217
- reportsCost: z14.boolean(),
3218
- emitsSubagentEvents: z14.boolean(),
3219
- emitsCompactionEvents: z14.boolean(),
3386
+ reportsReasoningOutput: z15.boolean(),
3387
+ reportsProviderTotal: z15.boolean(),
3388
+ reportsCost: z15.boolean(),
3389
+ emitsSubagentEvents: z15.boolean(),
3390
+ emitsCompactionEvents: z15.boolean(),
3220
3391
  /** True when the provider reads a structured response from stdout. */
3221
- requiresHookResponse: z14.boolean(),
3392
+ requiresHookResponse: z15.boolean(),
3222
3393
  /** How much of this provider's hook traffic is replay-identifiable. */
3223
3394
  deliveryIdentifier: deliveryIdentifierSupportSchema
3224
3395
  });
3225
- var providerHookResponseSchema = z14.strictObject({
3396
+ var providerHookResponseSchema = z15.strictObject({
3226
3397
  /**
3227
3398
  * Always 0. A telemetry hook that can fail the host agent is a liability, so
3228
3399
  * the type forbids expressing anything else (ADR 0004).
3229
3400
  */
3230
- exitCode: z14.literal(0),
3401
+ exitCode: z15.literal(0),
3231
3402
  /** Protocol response text. Omit to write nothing at all. */
3232
- stdout: z14.string().max(8192).optional(),
3403
+ stdout: z15.string().max(8192).optional(),
3233
3404
  /** Non-sensitive diagnostic text for stderr. */
3234
- stderr: z14.string().max(8192).optional(),
3405
+ stderr: z15.string().max(8192).optional(),
3235
3406
  /** Declares which of the two stdout contracts this response follows. */
3236
- contract: z14.enum(["silent", "provider-protocol"])
3407
+ contract: z15.enum(["silent", "provider-protocol"])
3237
3408
  });
3238
3409
  var SILENT_HOOK_RESPONSE = Object.freeze({
3239
3410
  exitCode: 0,
@@ -3470,15 +3641,15 @@ var createDeterministicIdGenerator = (options = {}) => {
3470
3641
  };
3471
3642
 
3472
3643
  // src/runtime/ports.ts
3473
- import { z as z15 } from "zod";
3474
- var appliedDeliverySchema = z15.strictObject({
3475
- callbackId: z15.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
3644
+ import { z as z16 } from "zod";
3645
+ var appliedDeliverySchema = z16.strictObject({
3646
+ callbackId: z16.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
3476
3647
  /** How many of that delivery's observations are folded in, counted from one. */
3477
- applications: z15.number().int().min(1).max(4096)
3648
+ applications: z16.number().int().min(1).max(4096)
3478
3649
  });
3479
- var stateValueSchema = z15.discriminatedUnion("kind", [
3480
- z15.strictObject({
3481
- kind: z15.literal("usage-cumulative"),
3650
+ var stateValueSchema = z16.discriminatedUnion("kind", [
3651
+ z16.strictObject({
3652
+ kind: z16.literal("usage-cumulative"),
3482
3653
  usage: canonicalUsageSchema,
3483
3654
  /**
3484
3655
  * Optional: absent on every record written before this field existed, which
@@ -3487,22 +3658,22 @@ var stateValueSchema = z15.discriminatedUnion("kind", [
3487
3658
  */
3488
3659
  appliedDelivery: appliedDeliverySchema.optional()
3489
3660
  }),
3490
- z15.strictObject({
3491
- kind: z15.literal("sequence"),
3661
+ z16.strictObject({
3662
+ kind: z16.literal("sequence"),
3492
3663
  next: sequenceNumberSchema
3493
3664
  }),
3494
- z15.strictObject({
3495
- kind: z15.literal("attributes"),
3665
+ z16.strictObject({
3666
+ kind: z16.literal("attributes"),
3496
3667
  attributes: attributesSchema
3497
3668
  })
3498
3669
  ]);
3499
- var stateRecordSchema = z15.strictObject({
3670
+ var stateRecordSchema = z16.strictObject({
3500
3671
  /** Incremented on each write; lets callers detect lost updates. */
3501
- revision: z15.number().int().min(0),
3672
+ revision: z16.number().int().min(0),
3502
3673
  updatedAt: epochMillisSchema,
3503
3674
  value: stateValueSchema
3504
3675
  });
3505
- var logLevelSchema = z15.enum(["silent", "error", "warn", "info", "debug"]);
3676
+ var logLevelSchema = z16.enum(["silent", "error", "warn", "info", "debug"]);
3506
3677
  var LOG_LEVEL_RANK = Object.freeze({
3507
3678
  silent: 0,
3508
3679
  error: 1,
@@ -3657,7 +3828,7 @@ var resolveEventTargets = async (input) => {
3657
3828
  };
3658
3829
 
3659
3830
  // src/runtime/hook.ts
3660
- var usageScopeSchema = z16.enum(["session", "generation", "subagent"]);
3831
+ var usageScopeSchema = z17.enum(["session", "generation", "subagent"]);
3661
3832
  var classifyDurability = (input) => {
3662
3833
  if (!input.attempted) {
3663
3834
  return "nothing-to-deliver";
@@ -4844,8 +5015,64 @@ var createFilesystemStateStore = (options) => {
4844
5015
 
4845
5016
  // src/telemetry/spool-queue.ts
4846
5017
  import { randomBytes as randomBytes3 } from "crypto";
4847
- import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, rename as rename2, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
5018
+ import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, rename as rename2, stat as stat2, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
4848
5019
  import * as path4 from "path";
5020
+ var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
5021
+ total: 0,
5022
+ age: 0,
5023
+ size: 0,
5024
+ count: 0,
5025
+ rejected: 0
5026
+ });
5027
+ var SPOOL_DROPS_FILE = ".drops";
5028
+ var enqueuedAtOf = (fileName) => {
5029
+ const match = /^(\d{16})-/.exec(fileName);
5030
+ return match?.[1] === void 0 ? void 0 : Number(match[1]);
5031
+ };
5032
+ var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
5033
+ var readSpoolDropCounts = async (queueDir) => {
5034
+ try {
5035
+ const parsed = JSON.parse(await readFile2(path4.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
5036
+ if (typeof parsed !== "object" || parsed === null) {
5037
+ return EMPTY_SPOOL_DROP_COUNTS;
5038
+ }
5039
+ const record = parsed;
5040
+ const field = (name) => isCount(record[name]) ? record[name] : 0;
5041
+ return {
5042
+ total: field("total"),
5043
+ age: field("age"),
5044
+ size: field("size"),
5045
+ count: field("count"),
5046
+ rejected: field("rejected"),
5047
+ ...isCount(record.lastDroppedAt) ? { lastDroppedAt: record.lastDroppedAt } : {}
5048
+ };
5049
+ } catch {
5050
+ return EMPTY_SPOOL_DROP_COUNTS;
5051
+ }
5052
+ };
5053
+ var readSpoolQueueStats = async (queueDir) => {
5054
+ let entries;
5055
+ try {
5056
+ entries = await readdir2(queueDir);
5057
+ } catch {
5058
+ return { batches: 0, bytes: 0, dropped: await readSpoolDropCounts(queueDir) };
5059
+ }
5060
+ const files = entries.filter((entry) => entry.endsWith(".json") && !entry.startsWith(".tmp-")).sort();
5061
+ let bytes = 0;
5062
+ for (const file of files) {
5063
+ try {
5064
+ bytes += (await stat2(path4.join(queueDir, file))).size;
5065
+ } catch {
5066
+ }
5067
+ }
5068
+ const oldest = files[0] === void 0 ? void 0 : enqueuedAtOf(files[0]);
5069
+ return {
5070
+ batches: files.length,
5071
+ bytes,
5072
+ ...oldest === void 0 ? {} : { oldestEnqueuedAt: oldest },
5073
+ dropped: await readSpoolDropCounts(queueDir)
5074
+ };
5075
+ };
4849
5076
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
4850
5077
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
4851
5078
  var createSpoolQueue = (options) => {
@@ -4886,27 +5113,132 @@ var createSpoolQueue = (options) => {
4886
5113
  }
4887
5114
  return entries.filter((entry) => entry.endsWith(".json") && !entry.startsWith(".tmp-")).sort();
4888
5115
  };
5116
+ const recordDrops = async (reason, dropped) => {
5117
+ if (dropped <= 0) {
5118
+ return;
5119
+ }
5120
+ try {
5121
+ const current = await readSpoolDropCounts(queueDir);
5122
+ const next = {
5123
+ ...current,
5124
+ total: current.total + dropped,
5125
+ [reason]: current[reason] + dropped,
5126
+ lastDroppedAt: options.clock.now()
5127
+ };
5128
+ const tmp = path4.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
5129
+ await writeFile2(tmp, JSON.stringify(next), "utf8");
5130
+ await rename2(tmp, path4.join(queueDir, SPOOL_DROPS_FILE));
5131
+ } catch {
5132
+ }
5133
+ options.logger?.warn("durable spool dropped batches", {
5134
+ "spool.queue": options.queueName,
5135
+ "spool.drop_reason": reason,
5136
+ "spool.dropped": dropped
5137
+ });
5138
+ };
5139
+ const listWithSizes = async () => {
5140
+ const names = await listSorted();
5141
+ const files = [];
5142
+ for (const name of names) {
5143
+ let bytes = 0;
5144
+ if (options.maxBytes !== void 0) {
5145
+ try {
5146
+ bytes = (await stat2(path4.join(queueDir, name))).size;
5147
+ } catch {
5148
+ continue;
5149
+ }
5150
+ }
5151
+ const enqueuedAt = enqueuedAtOf(name);
5152
+ files.push({ name, bytes, ...enqueuedAt === void 0 ? {} : { enqueuedAt } });
5153
+ }
5154
+ return files;
5155
+ };
5156
+ const evict = async (files) => {
5157
+ let removed = 0;
5158
+ for (const file of files) {
5159
+ try {
5160
+ await unlink2(path4.join(queueDir, file.name));
5161
+ removed += 1;
5162
+ } catch {
5163
+ }
5164
+ }
5165
+ return removed;
5166
+ };
5167
+ const isExpired = (file, now) => options.maxAgeMillis !== void 0 && file.enqueuedAt !== void 0 && now - file.enqueuedAt > options.maxAgeMillis;
4889
5168
  const enqueue = async (batch) => {
4890
5169
  await ensureDirs();
4891
- const existing = await listSorted();
4892
- if (existing.length >= options.maxFiles) {
5170
+ const serialized = JSON.stringify(batch);
5171
+ const bytes = Buffer.byteLength(serialized, "utf8");
5172
+ const refuse = async (reason) => {
4893
5173
  options.logger?.warn("durable spool at capacity; batch dropped", {
4894
5174
  "spool.max_files": options.maxFiles,
5175
+ ...options.maxBytes === void 0 ? {} : { "spool.max_bytes": options.maxBytes },
4895
5176
  "spool.queue": options.queueName
4896
5177
  });
5178
+ await recordDrops(reason, 1);
4897
5179
  return { spooled: false, reason: "capacity-exceeded" };
5180
+ };
5181
+ if (options.maxBytes !== void 0 && bytes > options.maxBytes) {
5182
+ return refuse("size");
5183
+ }
5184
+ let queued = await listWithSizes();
5185
+ const now = options.clock.now();
5186
+ const expired = queued.filter((file) => isExpired(file, now));
5187
+ if (expired.length > 0) {
5188
+ await recordDrops("age", await evict(expired));
5189
+ queued = queued.filter((file) => !isExpired(file, now));
5190
+ }
5191
+ const overflow = options.overflow ?? "refuse-new";
5192
+ const totalBytes = () => queued.reduce((sum, file) => sum + file.bytes, 0);
5193
+ if (overflow === "refuse-new") {
5194
+ if (queued.length >= options.maxFiles) {
5195
+ return refuse("count");
5196
+ }
5197
+ if (options.maxBytes !== void 0 && totalBytes() + bytes > options.maxBytes) {
5198
+ return refuse("size");
5199
+ }
5200
+ } else {
5201
+ const overCount = Math.max(0, queued.length + 1 - options.maxFiles);
5202
+ if (overCount > 0) {
5203
+ await recordDrops("count", await evict(queued.slice(0, overCount)));
5204
+ queued = queued.slice(overCount);
5205
+ }
5206
+ if (options.maxBytes !== void 0) {
5207
+ let excess = totalBytes() + bytes - options.maxBytes;
5208
+ let cut = 0;
5209
+ while (excess > 0 && cut < queued.length) {
5210
+ excess -= queued[cut]?.bytes ?? 0;
5211
+ cut += 1;
5212
+ }
5213
+ if (cut > 0) {
5214
+ await recordDrops("size", await evict(queued.slice(0, cut)));
5215
+ queued = queued.slice(cut);
5216
+ }
5217
+ }
4898
5218
  }
4899
- const fileName = `${String(options.clock.now()).padStart(16, "0")}-${randomBytes3(6).toString("hex")}.json`;
5219
+ const fileName = `${String(now).padStart(16, "0")}-${randomBytes3(6).toString("hex")}.json`;
4900
5220
  const target = path4.join(queueDir, fileName);
4901
5221
  const tmp = path4.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
4902
- await writeFile2(tmp, JSON.stringify(batch), "utf8");
5222
+ await writeFile2(tmp, serialized, "utf8");
4903
5223
  await rename2(tmp, target);
4904
5224
  return { spooled: true };
4905
5225
  };
4906
5226
  const drain = async (send, drainOptions) => {
4907
5227
  await ensureDirs();
4908
5228
  const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;
4909
- const files = await listSorted();
5229
+ let files = await listSorted();
5230
+ if (options.maxAgeMillis !== void 0) {
5231
+ const now = options.clock.now();
5232
+ const expired = files.map((name) => {
5233
+ const enqueuedAt = enqueuedAtOf(name);
5234
+ return { name, bytes: 0, ...enqueuedAt === void 0 ? {} : { enqueuedAt } };
5235
+ }).filter((file) => isExpired(file, now));
5236
+ if (expired.length > 0) {
5237
+ await recordDrops("age", await evict(expired));
5238
+ const gone = new Set(expired.map((file) => file.name));
5239
+ files = files.filter((name) => !gone.has(name));
5240
+ }
5241
+ }
4910
5242
  let drained = 0;
4911
5243
  let failed = 0;
4912
5244
  let quarantined = 0;
@@ -4951,6 +5283,12 @@ var createSpoolQueue = (options) => {
4951
5283
  } catch {
4952
5284
  delivered = false;
4953
5285
  }
5286
+ if (delivered === "discard") {
5287
+ if (await unlink2(filePath).then(() => true, () => false)) {
5288
+ await recordDrops("rejected", 1);
5289
+ }
5290
+ continue;
5291
+ }
4954
5292
  if (delivered) {
4955
5293
  await unlink2(filePath).catch(() => void 0);
4956
5294
  drained += 1;
@@ -4968,7 +5306,8 @@ var createSpoolQueue = (options) => {
4968
5306
  size: async () => {
4969
5307
  await ensureDirs();
4970
5308
  return (await listSorted()).length;
4971
- }
5309
+ },
5310
+ stats: () => readSpoolQueueStats(queueDir)
4972
5311
  };
4973
5312
  };
4974
5313
 
@@ -5067,7 +5406,10 @@ var createFileDurableLogSpool = (options) => createSpoolQueue({
5067
5406
  clock: options.clock,
5068
5407
  ...options.logger === void 0 ? {} : { logger: options.logger },
5069
5408
  maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_LOG_SPOOL_FILES,
5070
- queueName: "spool-logs",
5409
+ queueName: options.queueName ?? "spool-logs",
5410
+ ...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
5411
+ ...options.maxAgeMillis === void 0 ? {} : { maxAgeMillis: options.maxAgeMillis },
5412
+ ...options.overflow === void 0 ? {} : { overflow: options.overflow },
5071
5413
  validate: validateLogSpoolBatch
5072
5414
  });
5073
5415
 
@@ -5159,14 +5501,42 @@ var createFileDurableSpool = (options) => createSpoolQueue({
5159
5501
  clock: options.clock,
5160
5502
  ...options.logger === void 0 ? {} : { logger: options.logger },
5161
5503
  maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_SPOOL_FILES,
5162
- queueName: "spool",
5504
+ queueName: options.queueName ?? "spool",
5505
+ ...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
5506
+ ...options.maxAgeMillis === void 0 ? {} : { maxAgeMillis: options.maxAgeMillis },
5507
+ ...options.overflow === void 0 ? {} : { overflow: options.overflow },
5163
5508
  validate: validateSpoolBatch
5164
5509
  });
5165
5510
 
5166
5511
  // src/telemetry/otlp-log-sink.ts
5167
5512
  import { TraceFlags as TraceFlags3 } from "@opentelemetry/api";
5513
+ import { ExportResultCode } from "@opentelemetry/core";
5514
+ import { millisToHrTime as millisToHrTime3 } from "@opentelemetry/core";
5168
5515
  import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
5169
5516
 
5517
+ // src/config/otlp-endpoint.ts
5518
+ var OTLP_ENDPOINT_VARIABLES = Object.freeze({
5519
+ generic: "OTEL_EXPORTER_OTLP_ENDPOINT",
5520
+ traces: "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
5521
+ logs: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT"
5522
+ });
5523
+ var OTLP_TRACES_PATH = "/v1/traces";
5524
+ var OTLP_LOGS_PATH = "/v1/logs";
5525
+ var withoutTrailingSlashes = (value) => {
5526
+ let end = value.length;
5527
+ while (end > 0 && value.charCodeAt(end - 1) === 47) {
5528
+ end -= 1;
5529
+ }
5530
+ return value.slice(0, end);
5531
+ };
5532
+
5533
+ // src/telemetry/export-failure.ts
5534
+ var RETRYABLE_HTTP_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
5535
+ var isPermanentExportFailure = (result) => {
5536
+ const code = result.error?.code;
5537
+ return typeof code === "number" && Number.isInteger(code) && code >= 400 && code < 600 && !RETRYABLE_HTTP_STATUSES.has(code);
5538
+ };
5539
+
5170
5540
  // src/telemetry/exporter-resource.ts
5171
5541
  import { resourceFromAttributes } from "@opentelemetry/resources";
5172
5542
  var resourceFromExporterPolicy = (policy) => resourceFromAttributes({
@@ -5203,8 +5573,8 @@ var replayResource = (attributes, policy) => {
5203
5573
  };
5204
5574
 
5205
5575
  // src/telemetry/log-records.ts
5206
- import { TraceFlags as TraceFlags2 } from "@opentelemetry/api";
5207
- import { SeverityNumber } from "@opentelemetry/api-logs";
5576
+ import { SeverityNumber, TraceFlags as TraceFlags2 } from "@opentelemetry/api";
5577
+ import { millisToHrTime as millisToHrTime2 } from "@opentelemetry/core";
5208
5578
  import {
5209
5579
  ATTR_ERROR_TYPE as ATTR_ERROR_TYPE2,
5210
5580
  ATTR_GEN_AI_OPERATION_NAME as ATTR_GEN_AI_OPERATION_NAME2,
@@ -5472,14 +5842,14 @@ var contentAttributes = (fact, body) => ({
5472
5842
  });
5473
5843
  var buildRecord = (input) => {
5474
5844
  const severityNumber = severityFor(input.event);
5475
- const hrTime2 = millisToHrTime(input.event.occurredAt);
5845
+ const hrTime = millisToHrTime2(input.event.occurredAt);
5476
5846
  return {
5477
- hrTime: hrTime2,
5847
+ hrTime,
5478
5848
  // A hook observes an event that already happened, and this mapping is pure —
5479
5849
  // there is no clock here to read a real observation time from. Reporting the
5480
5850
  // occurrence time for both is the honest answer: it says "this is when it
5481
5851
  // happened" twice rather than inventing a second, wrong timestamp.
5482
- hrTimeObserved: hrTime2,
5852
+ hrTimeObserved: hrTime,
5483
5853
  spanContext: input.spanContext,
5484
5854
  severityNumber,
5485
5855
  severityText: SEVERITY_TEXT[severityNumber] ?? "INFO",
@@ -5569,15 +5939,6 @@ var canonicalEventsToLogRecords = (events, options) => {
5569
5939
  };
5570
5940
 
5571
5941
  // src/telemetry/otlp-log-sink.ts
5572
- var OTLP_TRACES_PATH = "/v1/traces";
5573
- var OTLP_LOGS_PATH = "/v1/logs";
5574
- var withoutTrailingSlashes = (value) => {
5575
- let end = value.length;
5576
- while (end > 0 && value.charCodeAt(end - 1) === 47) {
5577
- end -= 1;
5578
- }
5579
- return value.slice(0, end);
5580
- };
5581
5942
  var resolveLogsEndpoint = (exporter) => {
5582
5943
  if (exporter.logs.endpoint !== void 0) {
5583
5944
  return { endpoint: exporter.logs.endpoint, derived: false };
@@ -5631,8 +5992,8 @@ var deserializeRecord = (serialized, resource, scope) => {
5631
5992
  isRemote: false
5632
5993
  };
5633
5994
  return {
5634
- hrTime: millisToHrTime(serialized.timeMillis),
5635
- hrTimeObserved: millisToHrTime(serialized.observedTimeMillis),
5995
+ hrTime: millisToHrTime3(serialized.timeMillis),
5996
+ hrTimeObserved: millisToHrTime3(serialized.observedTimeMillis),
5636
5997
  ...spanContext === void 0 ? {} : { spanContext },
5637
5998
  severityNumber: serialized.severityNumber,
5638
5999
  ...serialized.severityText === void 0 ? {} : { severityText: serialized.severityText },
@@ -5654,8 +6015,11 @@ var chunk = (items, size) => {
5654
6015
  }
5655
6016
  return chunks;
5656
6017
  };
5657
- var createDisabledSink = () => {
5658
- const health = createHealthTracker("telemetry-log-sink");
6018
+ var createDisabledSink = (destination) => {
6019
+ const health = createHealthTracker(
6020
+ "telemetry-log-sink",
6021
+ destination === void 0 ? {} : { destination }
6022
+ );
5659
6023
  return {
5660
6024
  emit: (events) => {
5661
6025
  health.recordSuccess(events.length);
@@ -5694,19 +6058,24 @@ var DISABLED_DETAIL = Object.freeze({
5694
6058
  "no-endpoint": "otlp log sink disabled: no logs endpoint configured and none could be derived"
5695
6059
  });
5696
6060
  var createOtlpLogSink = (options) => {
6061
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
5697
6062
  const deliverability = describeLogsDeliverability(options.exporter);
5698
6063
  if (deliverability.status === "disabled") {
5699
6064
  if (deliverability.reason !== "logs-disabled") {
5700
6065
  options.logger?.warn(DISABLED_DETAIL[deliverability.reason], {
5701
- "exporter.protocol": options.exporter.protocol
6066
+ "exporter.protocol": options.exporter.protocol,
6067
+ ...destinationFields
5702
6068
  });
5703
6069
  }
5704
- return createDisabledSink();
6070
+ return createDisabledSink(options.destination);
5705
6071
  }
5706
6072
  const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
5707
6073
  const resource = resourceFromExporterPolicy(options.exporter);
5708
6074
  const content = options.content ?? NO_LOG_CONTENT;
5709
- const health = createHealthTracker("telemetry-log-sink");
6075
+ const health = createHealthTracker(
6076
+ "telemetry-log-sink",
6077
+ options.destination === void 0 ? {} : { destination: options.destination }
6078
+ );
5710
6079
  const exporter = new OTLPLogExporter({
5711
6080
  url: deliverability.endpoint,
5712
6081
  headers: { ...options.headers },
@@ -5733,7 +6102,10 @@ var createOtlpLogSink = (options) => {
5733
6102
  (record) => deserializeRecord(record, batchResource, batch.instrumentationScope)
5734
6103
  );
5735
6104
  const result = await exportRecords(records);
5736
- return result.code === ExportResultCode.SUCCESS;
6105
+ if (result.code === ExportResultCode.SUCCESS) {
6106
+ return true;
6107
+ }
6108
+ return isPermanentExportFailure(result) ? "discard" : false;
5737
6109
  };
5738
6110
  const resolveCorrelations = async (events) => {
5739
6111
  if (options.correlate === void 0) {
@@ -5785,13 +6157,18 @@ var createOtlpLogSink = (options) => {
5785
6157
  continue;
5786
6158
  }
5787
6159
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
5788
- if (options.spool !== void 0) {
6160
+ const permanent = isPermanentExportFailure(result);
6161
+ if (options.spool !== void 0 && !permanent) {
5789
6162
  const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
5790
6163
  spooled: false,
5791
6164
  reason: "capacity-exceeded"
5792
6165
  }));
5793
6166
  if (spoolResult.spooled) {
5794
6167
  accepted += batch.length;
6168
+ options.logger?.warn("log record batch not delivered; spooled for the next invocation", {
6169
+ "export.batch_size": batch.length,
6170
+ ...destinationFields
6171
+ });
5795
6172
  continue;
5796
6173
  }
5797
6174
  }
@@ -5800,8 +6177,12 @@ var createOtlpLogSink = (options) => {
5800
6177
  createErrorInfo({
5801
6178
  code: "telemetry-export-failure",
5802
6179
  phase: "export",
5803
- detail: "collector rejected or was unreachable for a log record batch",
5804
- details: { "export.batch_size": batch.length, "export.signal": "logs" }
6180
+ detail: permanent ? "collector refused a log record batch with a non-retryable status" : "collector rejected or was unreachable for a log record batch",
6181
+ details: {
6182
+ "export.batch_size": batch.length,
6183
+ "export.signal": "logs",
6184
+ ...destinationFields
6185
+ }
5805
6186
  })
5806
6187
  );
5807
6188
  }
@@ -5847,6 +6228,7 @@ var createOtlpLogSink = (options) => {
5847
6228
  };
5848
6229
 
5849
6230
  // src/telemetry/otlp-sink.ts
6231
+ import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
5850
6232
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
5851
6233
  var chunk2 = (items, size) => {
5852
6234
  if (size <= 0 || items.length <= size) {
@@ -5883,8 +6265,11 @@ var deserializeSpan = (serialized, resource, scope) => assembleReadableSpan({
5883
6265
  resource,
5884
6266
  instrumentationScope: scope
5885
6267
  });
5886
- var createDisabledSink2 = () => {
5887
- const health = createHealthTracker("telemetry-sink");
6268
+ var createDisabledSink2 = (destination) => {
6269
+ const health = createHealthTracker(
6270
+ "telemetry-sink",
6271
+ destination === void 0 ? {} : { destination }
6272
+ );
5888
6273
  return {
5889
6274
  emit: (events) => {
5890
6275
  health.recordSuccess(events.length);
@@ -5897,22 +6282,27 @@ var createDisabledSink2 = () => {
5897
6282
  };
5898
6283
  };
5899
6284
  var createOtlpTraceSink = (options) => {
6285
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
5900
6286
  if (!options.exporter.enabled || options.exporter.protocol === "none") {
5901
- return createDisabledSink2();
6287
+ return createDisabledSink2(options.destination);
5902
6288
  }
5903
6289
  if (options.exporter.endpoint === void 0) {
5904
- options.logger?.warn("otlp sink disabled: no endpoint configured", {});
5905
- return createDisabledSink2();
6290
+ options.logger?.warn("otlp sink disabled: no endpoint configured", destinationFields);
6291
+ return createDisabledSink2(options.destination);
5906
6292
  }
5907
6293
  if (options.exporter.protocol !== "http/protobuf") {
5908
6294
  options.logger?.warn("otlp sink: protocol not supported by this build, falling back to disabled", {
5909
- "exporter.protocol": options.exporter.protocol
6295
+ "exporter.protocol": options.exporter.protocol,
6296
+ ...destinationFields
5910
6297
  });
5911
- return createDisabledSink2();
6298
+ return createDisabledSink2(options.destination);
5912
6299
  }
5913
6300
  const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
5914
6301
  const resource = resourceFromExporterPolicy(options.exporter);
5915
- const health = createHealthTracker("telemetry-sink");
6302
+ const health = createHealthTracker(
6303
+ "telemetry-sink",
6304
+ options.destination === void 0 ? {} : { destination: options.destination }
6305
+ );
5916
6306
  const exporter = new OTLPTraceExporter({
5917
6307
  url: options.exporter.endpoint,
5918
6308
  headers: { ...options.headers },
@@ -5934,7 +6324,10 @@ var createOtlpTraceSink = (options) => {
5934
6324
  const batchResource = replayResource(batch.resourceAttributes, options.exporter);
5935
6325
  const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));
5936
6326
  const result = await exportSpans(spans);
5937
- return result.code === ExportResultCode.SUCCESS;
6327
+ if (result.code === ExportResultCode2.SUCCESS) {
6328
+ return true;
6329
+ }
6330
+ return isPermanentExportFailure(result) ? "discard" : false;
5938
6331
  };
5939
6332
  const resolveCorrelations = async (events) => {
5940
6333
  if (options.correlate === void 0) {
@@ -5962,25 +6355,33 @@ var createOtlpTraceSink = (options) => {
5962
6355
  let accepted = 0;
5963
6356
  let rejected = 0;
5964
6357
  for (const batch of chunk2(spans, options.exporter.maxBatchSize)) {
6358
+ if (batch.length === 0) {
6359
+ continue;
6360
+ }
5965
6361
  let result;
5966
6362
  try {
5967
6363
  result = await exportSpans(batch);
5968
6364
  } catch (thrown) {
5969
- result = { code: ExportResultCode.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
6365
+ result = { code: ExportResultCode2.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
5970
6366
  }
5971
- if (result.code === ExportResultCode.SUCCESS) {
6367
+ if (result.code === ExportResultCode2.SUCCESS) {
5972
6368
  accepted += batch.length;
5973
6369
  health.recordSuccess(batch.length, options.clock.now());
5974
6370
  continue;
5975
6371
  }
5976
6372
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
5977
- if (options.spool !== void 0) {
6373
+ const permanent = isPermanentExportFailure(result);
6374
+ if (options.spool !== void 0 && !permanent) {
5978
6375
  const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
5979
6376
  spooled: false,
5980
6377
  reason: "capacity-exceeded"
5981
6378
  }));
5982
6379
  if (spoolResult.spooled) {
5983
6380
  accepted += batch.length;
6381
+ options.logger?.warn("span batch not delivered; spooled for the next invocation", {
6382
+ "export.batch_size": batch.length,
6383
+ ...destinationFields
6384
+ });
5984
6385
  continue;
5985
6386
  }
5986
6387
  }
@@ -5989,8 +6390,8 @@ var createOtlpTraceSink = (options) => {
5989
6390
  createErrorInfo({
5990
6391
  code: "telemetry-export-failure",
5991
6392
  phase: "export",
5992
- detail: "collector rejected or was unreachable for a span batch",
5993
- details: { "export.batch_size": batch.length }
6393
+ detail: permanent ? "collector refused a span batch with a non-retryable status" : "collector rejected or was unreachable for a span batch",
6394
+ details: { "export.batch_size": batch.length, ...destinationFields }
5994
6395
  })
5995
6396
  );
5996
6397
  }
@@ -6075,6 +6476,172 @@ var shareCorrelationPerBatch = (correlate) => {
6075
6476
  };
6076
6477
  };
6077
6478
 
6479
+ // src/telemetry/export-destinations.ts
6480
+ var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs" } : { traces: `destinations/${destination}/spool`, logs: `destinations/${destination}/spool-logs` };
6481
+ var exporterPolicyForDestination = (exporter, destination) => {
6482
+ if (destination.source === "exporter") {
6483
+ return exporter;
6484
+ }
6485
+ const { destinations, endpoint, logs, ...shared } = exporter;
6486
+ void destinations;
6487
+ void endpoint;
6488
+ const tracesEndpoint = destination.tracesEndpoint ?? destination.endpoint;
6489
+ const derivedLogs = destination.logsEndpoint ?? (destination.endpoint === void 0 ? void 0 : (() => {
6490
+ const derived = resolveLogsEndpoint({
6491
+ ...exporter,
6492
+ endpoint: destination.endpoint,
6493
+ logs: { enabled: true, includeContent: false, maxBatchSize: logs.maxBatchSize }
6494
+ });
6495
+ return "endpoint" in derived ? derived.endpoint : void 0;
6496
+ })());
6497
+ return {
6498
+ ...shared,
6499
+ protocol: destination.protocol,
6500
+ ...tracesEndpoint === void 0 ? {} : { endpoint: tracesEndpoint },
6501
+ headerNames: Object.keys(destination.headers).sort(),
6502
+ logs: {
6503
+ ...logs,
6504
+ enabled: destination.signals.logs,
6505
+ ...derivedLogs === void 0 ? {} : { endpoint: derivedLogs }
6506
+ }
6507
+ };
6508
+ };
6509
+ var createOptedOutTraceSink = (destination) => {
6510
+ const health = createHealthTracker(
6511
+ "telemetry-sink",
6512
+ destination === void 0 ? {} : { destination }
6513
+ );
6514
+ return {
6515
+ emit: () => Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),
6516
+ flush: () => Promise.resolve(),
6517
+ shutdown: () => Promise.resolve(),
6518
+ health: () => health.snapshot(),
6519
+ drainSpool: () => Promise.resolve({ drained: 0, remaining: 0, failed: 0 })
6520
+ };
6521
+ };
6522
+ var createExportDestinationSinks = (options) => {
6523
+ const labelled = hasConfiguredDestinations(options.exporter);
6524
+ const spoolPolicy = effectiveSpoolPolicy(options.exporter);
6525
+ const destinations = [];
6526
+ const skipped = [];
6527
+ for (const destination of resolveExportDestinations(options.exporter)) {
6528
+ let headers;
6529
+ let logHeaders;
6530
+ if (destination.source === "exporter") {
6531
+ headers = options.defaultHeaders;
6532
+ logHeaders = options.defaultLogHeaders ?? options.defaultHeaders;
6533
+ } else {
6534
+ const resolved = resolveDestinationHeaders(destination.headers, options.headerEnvironment);
6535
+ if (resolved.missingVariables.length > 0) {
6536
+ options.logger?.warn("export destination skipped: a header references an unset environment variable", {
6537
+ "export.destination": destination.name,
6538
+ "config.variables": [...resolved.missingVariables]
6539
+ });
6540
+ skipped.push({
6541
+ name: destination.name,
6542
+ reason: "header-variable-missing",
6543
+ missingVariables: resolved.missingVariables
6544
+ });
6545
+ continue;
6546
+ }
6547
+ headers = resolved.values;
6548
+ logHeaders = resolved.values;
6549
+ }
6550
+ const label = labelled ? destination.name : void 0;
6551
+ const policy = exporterPolicyForDestination(options.exporter, destination);
6552
+ const queues = spoolQueueNamesFor(destination.name);
6553
+ const bounds = {
6554
+ maxSpoolFiles: spoolPolicy.maxBatches,
6555
+ maxBytes: spoolPolicy.maxBytes,
6556
+ maxAgeMillis: spoolPolicy.maxAgeMillis,
6557
+ overflow: "drop-oldest"
6558
+ };
6559
+ const shared = {
6560
+ providerId: options.providerId,
6561
+ installationId: options.installationId,
6562
+ clock: options.clock,
6563
+ ...options.logger === void 0 ? {} : { logger: options.logger }
6564
+ };
6565
+ const spool = options.spoolRootDir === void 0 || !destination.signals.traces ? void 0 : createFileDurableSpool({
6566
+ rootDir: options.spoolRootDir,
6567
+ ...shared,
6568
+ ...bounds,
6569
+ queueName: queues.traces
6570
+ });
6571
+ const logSpool = options.spoolRootDir === void 0 || !destination.signals.logs ? void 0 : createFileDurableLogSpool({
6572
+ rootDir: options.spoolRootDir,
6573
+ ...shared,
6574
+ ...bounds,
6575
+ queueName: queues.logs
6576
+ });
6577
+ const sinkShared = {
6578
+ exporter: policy,
6579
+ ...shared,
6580
+ ...options.correlate === void 0 ? {} : { correlate: options.correlate },
6581
+ ...label === void 0 ? {} : { destination: label }
6582
+ };
6583
+ const traces = destination.signals.traces ? createOtlpTraceSink({
6584
+ ...sinkShared,
6585
+ ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
6586
+ ...spool === void 0 ? {} : { spool }
6587
+ }) : createOptedOutTraceSink(label);
6588
+ const logs = createOtlpLogSink({
6589
+ ...sinkShared,
6590
+ ...logHeaders === void 0 || Object.keys(logHeaders).length === 0 ? {} : { headers: logHeaders },
6591
+ ...logSpool === void 0 ? {} : { spool: logSpool },
6592
+ content: options.logContent
6593
+ });
6594
+ destinations.push({
6595
+ name: destination.name,
6596
+ traces,
6597
+ logs,
6598
+ ...spool === void 0 ? {} : { spool },
6599
+ ...logSpool === void 0 ? {} : { logSpool }
6600
+ });
6601
+ }
6602
+ return { destinations, skipped };
6603
+ };
6604
+ var createDestinationFanout = (destinations) => {
6605
+ const fanouts = destinations.map((destination) => ({
6606
+ name: destination.name,
6607
+ sink: createSignalFanout({ traces: destination.traces, logs: destination.logs })
6608
+ }));
6609
+ const only = fanouts.length === 1 ? fanouts[0] : void 0;
6610
+ if (only !== void 0) {
6611
+ return only.sink;
6612
+ }
6613
+ const emit = async (events) => {
6614
+ const results = await Promise.all(
6615
+ fanouts.map(
6616
+ (fanout) => fanout.sink.emit(events).catch(
6617
+ (thrown) => ({
6618
+ accepted: 0,
6619
+ rejected: events.length,
6620
+ errors: [errorInfoFromThrown(thrown, { code: "telemetry-export-failure", phase: "export" })]
6621
+ })
6622
+ )
6623
+ )
6624
+ );
6625
+ const errors = results.flatMap((result) => result.errors);
6626
+ return {
6627
+ accepted: results.reduce((sum, result) => sum + result.accepted, 0),
6628
+ rejected: results.reduce((sum, result) => sum + result.rejected, 0),
6629
+ errors
6630
+ };
6631
+ };
6632
+ const settleAll = async (run) => {
6633
+ await Promise.all(fanouts.map((fanout) => run(fanout.sink).catch(() => void 0)));
6634
+ };
6635
+ return {
6636
+ emit,
6637
+ // Each destination drains its own spool in its flush; in parallel, so one
6638
+ // unreachable destination's drain cannot use up the others' flush window.
6639
+ flush: () => settleAll((sink) => sink.flush()),
6640
+ shutdown: () => settleAll((sink) => sink.shutdown()),
6641
+ health: () => fanouts.flatMap((fanout) => fanout.sink.health())
6642
+ };
6643
+ };
6644
+
6078
6645
  // src/integration/hook-runtime.ts
6079
6646
  var DEFAULT_FLUSH_TIMEOUT_MILLIS = 2e3;
6080
6647
  var DEFAULT_STATE_LOCK_TIMEOUT_MILLIS = 1e3;
@@ -6137,46 +6704,23 @@ var createHookRuntime = (options) => {
6137
6704
  logger,
6138
6705
  lockTimeoutMillis: stateLockTimeoutMillis
6139
6706
  });
6140
- const spool = options.enableSpool === false ? void 0 : createFileDurableSpool({
6141
- rootDir: options.stateRootDir,
6142
- providerId: options.providerNamespace,
6143
- installationId: options.installationId,
6144
- clock,
6145
- logger
6146
- });
6147
- const logSpool = options.enableSpool === false || !options.config.exporter.logs.enabled ? void 0 : createFileDurableLogSpool({
6148
- rootDir: options.stateRootDir,
6149
- providerId: options.providerNamespace,
6150
- installationId: options.installationId,
6151
- clock,
6152
- logger
6153
- });
6154
6707
  const spanCorrelator = createSpanCorrelator({
6155
6708
  stateStore,
6156
6709
  clock,
6157
6710
  maxStartAgeMillis: lifecycleMaxAge
6158
6711
  });
6159
6712
  const correlate = shareCorrelationPerBatch((events) => spanCorrelator.correlateBatch(events));
6160
- const traceSink = createOtlpTraceSink({
6713
+ const exportDestinations = createExportDestinationSinks({
6161
6714
  exporter: options.config.exporter,
6162
- ...options.headers === void 0 ? {} : { headers: options.headers },
6715
+ ...options.headers === void 0 ? {} : { defaultHeaders: options.headers },
6716
+ ...options.logHeaders === void 0 ? {} : { defaultLogHeaders: options.logHeaders },
6717
+ ...options.headerEnvironment === void 0 ? {} : { headerEnvironment: options.headerEnvironment },
6163
6718
  providerId: options.providerNamespace,
6164
6719
  installationId: options.installationId,
6165
6720
  clock,
6166
6721
  logger,
6167
- ...spool === void 0 ? {} : { spool },
6168
- correlate
6169
- });
6170
- const logHeaders = options.logHeaders ?? options.headers;
6171
- const logSink = createOtlpLogSink({
6172
- exporter: options.config.exporter,
6173
- ...logHeaders === void 0 ? {} : { headers: logHeaders },
6174
- providerId: options.providerNamespace,
6175
- installationId: options.installationId,
6176
- clock,
6177
- logger,
6178
- ...logSpool === void 0 ? {} : { spool: logSpool },
6179
- content: {
6722
+ ...options.enableSpool === false ? {} : { spoolRootDir: options.stateRootDir },
6723
+ logContent: {
6180
6724
  includeContent: options.config.exporter.logs.includeContent,
6181
6725
  // The pre-existing verbatim-content opt-in, passed through rather than
6182
6726
  // re-derived: `raw` disclosure in a log body is governed by the same flag it
@@ -6185,7 +6729,22 @@ var createHookRuntime = (options) => {
6185
6729
  },
6186
6730
  correlate
6187
6731
  });
6188
- const sink = createSignalFanout({ traces: traceSink, logs: logSink });
6732
+ const primary = exportDestinations.destinations[0];
6733
+ const traceSink = primary?.traces ?? createOtlpTraceSink({
6734
+ exporter: { ...options.config.exporter, enabled: false },
6735
+ providerId: options.providerNamespace,
6736
+ installationId: options.installationId,
6737
+ clock
6738
+ });
6739
+ const logSink = primary?.logs ?? createOtlpLogSink({
6740
+ exporter: { ...options.config.exporter, logs: { ...options.config.exporter.logs, enabled: false } },
6741
+ providerId: options.providerNamespace,
6742
+ installationId: options.installationId,
6743
+ clock
6744
+ });
6745
+ const spool = primary?.spool;
6746
+ const logSpool = primary?.logSpool;
6747
+ const sink = createDestinationFanout(exportDestinations.destinations);
6189
6748
  const hookDeps = {
6190
6749
  stateStore,
6191
6750
  config: options.config,
@@ -6454,6 +7013,8 @@ var createHookRuntime = (options) => {
6454
7013
  logSink,
6455
7014
  ...spool === void 0 ? {} : { spool },
6456
7015
  ...logSpool === void 0 ? {} : { logSpool },
7016
+ destinations: exportDestinations.destinations,
7017
+ skippedDestinations: exportDestinations.skipped,
6457
7018
  privacy,
6458
7019
  deduplicator,
6459
7020
  usageAccumulator,