@osfactory/otel-hook 0.8.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
  };
@@ -672,7 +673,7 @@ import {
672
673
  } from "@opentelemetry/semantic-conventions/incubating";
673
674
 
674
675
  // src/version.ts
675
- var VERSION = "0.8.0";
676
+ var VERSION = "0.9.0";
676
677
 
677
678
  // src/telemetry/export-identity.ts
678
679
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -2925,13 +2926,180 @@ var createSystemClock = () => ({
2925
2926
  });
2926
2927
 
2927
2928
  // src/runtime/hook.ts
2928
- import { z as z16 } from "zod";
2929
+ import { z as z17 } from "zod";
2929
2930
 
2930
2931
  // src/config/schema.ts
2931
- import { z as z13 } from "zod";
2932
+ import { z as z14 } from "zod";
2932
2933
 
2933
- // src/config/resource-attributes.ts
2934
+ // src/config/destinations.ts
2934
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";
2935
3103
  var MAX_RESOURCE_ATTRIBUTES = 64;
2936
3104
  var MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH = 255;
2937
3105
  var MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH = 2048;
@@ -2976,12 +3144,12 @@ var checkResourceAttributeKey = (key) => {
2976
3144
  }
2977
3145
  return void 0;
2978
3146
  };
2979
- var resourceAttributeValueSchema = z12.union([
2980
- z12.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),
2981
- z12.number().finite(),
2982
- z12.boolean()
3147
+ var resourceAttributeValueSchema = z13.union([
3148
+ z13.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),
3149
+ z13.number().finite(),
3150
+ z13.boolean()
2983
3151
  ]);
2984
- var resourceAttributesSchema = z12.record(z12.string(), resourceAttributeValueSchema).superRefine((value, ctx) => {
3152
+ var resourceAttributesSchema = z13.record(z13.string(), resourceAttributeValueSchema).superRefine((value, ctx) => {
2985
3153
  const keys = Object.keys(value);
2986
3154
  if (keys.length > MAX_RESOURCE_ATTRIBUTES) {
2987
3155
  ctx.addIssue({
@@ -3016,36 +3184,36 @@ var sanitizeResourceAttributes = (attributes) => {
3016
3184
  };
3017
3185
 
3018
3186
  // src/config/schema.ts
3019
- var logsPolicySchema = z13.strictObject({
3020
- enabled: z13.boolean(),
3187
+ var logsPolicySchema = z14.strictObject({
3188
+ enabled: z14.boolean(),
3021
3189
  /**
3022
3190
  * Full URL for the logs signal.
3023
3191
  *
3024
3192
  * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes
3025
3193
  * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.
3026
3194
  */
3027
- endpoint: z13.string().url().max(2048).optional(),
3028
- includeContent: z13.boolean(),
3029
- 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)
3030
3198
  });
3031
3199
  var DEFAULT_LOGS_POLICY = Object.freeze({
3032
3200
  enabled: false,
3033
3201
  includeContent: false,
3034
3202
  maxBatchSize: 128
3035
3203
  });
3036
- var exporterPolicySchema = z13.strictObject({
3037
- enabled: z13.boolean(),
3038
- protocol: z13.enum(["http/protobuf", "http/json", "none"]),
3039
- 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(),
3040
3208
  /**
3041
3209
  * Header names only. Values are supplied separately at construction time and
3042
3210
  * are never part of a resolved-config snapshot, which is logged and exported.
3043
3211
  */
3044
- headerNames: z13.array(nonEmptyStringSchema).max(32).readonly(),
3045
- timeoutMillis: z13.number().int().min(1).max(6e5),
3046
- maxBatchSize: z13.number().int().min(1).max(4096),
3047
- maxQueueSize: z13.number().int().min(1).max(65536),
3048
- 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),
3049
3217
  serviceName: nonEmptyStringSchema,
3050
3218
  serviceNamespace: nonEmptyStringSchema.optional(),
3051
3219
  /**
@@ -3062,32 +3230,52 @@ var exporterPolicySchema = z13.strictObject({
3062
3230
  * headers, timeout, protocol, service identity, and resource attributes above —
3063
3231
  * a second top-level section would invite two of each to drift apart.
3064
3232
  */
3065
- 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()
3066
3251
  });
3067
- var detectionPolicySchema = z13.strictObject({
3252
+ var detectionPolicySchema = z14.strictObject({
3068
3253
  /** Detections below this confidence resolve to the unknown provider. */
3069
3254
  minimumConfidence: detectionConfidenceSchema,
3070
3255
  /** When false, an ambiguous detection is an error rather than unknown. */
3071
- allowAmbiguousFallback: z13.boolean(),
3256
+ allowAmbiguousFallback: z14.boolean(),
3072
3257
  /** Optional allow-list of provider ids; empty means "any registered". */
3073
- allowedProviderIds: z13.array(nonEmptyStringSchema).max(32).readonly()
3258
+ allowedProviderIds: z14.array(nonEmptyStringSchema).max(32).readonly()
3074
3259
  });
3075
- var diagnosticsPolicySchema = z13.strictObject({
3076
- logLevel: z13.enum(["silent", "error", "warn", "info", "debug"]),
3260
+ var diagnosticsPolicySchema = z14.strictObject({
3261
+ logLevel: z14.enum(["silent", "error", "warn", "info", "debug"]),
3077
3262
  /** Emit `error.raised` events for contained failures. */
3078
- emitErrorEvents: z13.boolean()
3263
+ emitErrorEvents: z14.boolean()
3079
3264
  });
3080
- var otelHookConfigSchema = z13.strictObject({
3265
+ var otelHookConfigSchema = z14.strictObject({
3081
3266
  exporter: exporterPolicySchema,
3082
3267
  privacy: privacyPolicySchema,
3083
3268
  detection: detectionPolicySchema,
3084
3269
  diagnostics: diagnosticsPolicySchema
3085
3270
  });
3086
- var otelHookConfigPatchSchema = z13.strictObject({
3271
+ var otelHookConfigPatchSchema = z14.strictObject({
3087
3272
  // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
3088
3273
  // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
3089
3274
  // without also restating the endpoint and the batch size.
3090
- 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(),
3091
3279
  privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
3092
3280
  detection: detectionPolicySchema.partial().optional(),
3093
3281
  diagnostics: diagnosticsPolicySchema.partial().optional()
@@ -3121,27 +3309,27 @@ var DEFAULT_CONFIG = Object.freeze({
3121
3309
  });
3122
3310
 
3123
3311
  // src/providers/adapter.ts
3124
- import { z as z14 } from "zod";
3125
- var providerDetectionSchema = z14.strictObject({
3312
+ import { z as z15 } from "zod";
3313
+ var providerDetectionSchema = z15.strictObject({
3126
3314
  providerId: resolvedProviderIdSchema,
3127
3315
  confidence: detectionConfidenceSchema,
3128
3316
  /**
3129
3317
  * Short, non-sensitive justifications, e.g. `"payload.hook_event_name present"`.
3130
3318
  * Reasons are exported in diagnostics, so they must not quote payload values.
3131
3319
  */
3132
- reasons: z14.array(z14.string().min(1).max(160)).max(8),
3320
+ reasons: z15.array(z15.string().min(1).max(160)).max(8),
3133
3321
  providerVersion: nonEmptyStringSchema.optional(),
3134
3322
  /** The provider's own name for this event, when the payload states one. */
3135
3323
  sourceEventName: nonEmptyStringSchema.optional()
3136
3324
  });
3137
- var deliveryIdentifierSupportSchema = z14.enum(["none", "partial", "all"]);
3325
+ var deliveryIdentifierSupportSchema = z15.enum(["none", "partial", "all"]);
3138
3326
  var DELIVERY_COMPONENT_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
3139
- var deliveryComponentSchema = z14.string().regex(
3327
+ var deliveryComponentSchema = z15.string().regex(
3140
3328
  DELIVERY_COMPONENT_PATTERN,
3141
3329
  "delivery component must be identifier-shaped: no whitespace, no path separators"
3142
3330
  );
3143
3331
  var MAX_DELIVERY_COMPONENTS = 8;
3144
- var providerDeliveryClaimSchema = z14.strictObject({
3332
+ var providerDeliveryClaimSchema = z15.strictObject({
3145
3333
  /**
3146
3334
  * The provider's own session/conversation id. Scopes the callback identity, so
3147
3335
  * two sessions reusing one tool-call id never collide.
@@ -3153,26 +3341,26 @@ var providerDeliveryClaimSchema = z14.strictObject({
3153
3341
  * Identifier-shaped payload fields that, together with `sourceEventName`,
3154
3342
  * name this callback within the session exactly once.
3155
3343
  */
3156
- components: z14.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),
3344
+ components: z15.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),
3157
3345
  /**
3158
3346
  * Short, non-sensitive justifications, e.g. `"payload.tool_use_id names one
3159
3347
  * tool call"`. Evidence reaches diagnostics, so it must name fields, never
3160
3348
  * quote their values.
3161
3349
  */
3162
- 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()
3163
3351
  });
3164
3352
  var DELIVERY_GAP_REASON_PATTERN = /^[^\n\r\t\\/]{1,240}$/;
3165
- var deliveryGapReasonSchema = z14.string().regex(
3353
+ var deliveryGapReasonSchema = z15.string().regex(
3166
3354
  DELIVERY_GAP_REASON_PATTERN,
3167
3355
  "delivery gap reason must be one line of prose: no path separators, no control characters"
3168
3356
  );
3169
3357
  var MAX_DELIVERY_GAPS = 48;
3170
- 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, {
3171
3359
  message: `at most ${String(MAX_DELIVERY_GAPS)} delivery gaps may be declared`
3172
3360
  });
3173
- var providerCapabilitiesSchema = z14.strictObject({
3361
+ var providerCapabilitiesSchema = z15.strictObject({
3174
3362
  /** Event types the adapter can produce. */
3175
- lifecycleEvents: z14.array(canonicalEventTypeSchema).max(32).readonly(),
3363
+ lifecycleEvents: z15.array(canonicalEventTypeSchema).max(32).readonly(),
3176
3364
  usageTemporality: usageTemporalitySchema,
3177
3365
  /**
3178
3366
  * Which accumulator series a `cumulative` report continues — that is, which
@@ -3191,32 +3379,32 @@ var providerCapabilitiesSchema = z14.strictObject({
3191
3379
  * Subagent snapshots keep their own series regardless: a delegated agent's
3192
3380
  * counter is not a point on the parent session's curve.
3193
3381
  */
3194
- cumulativeUsageSeries: z14.enum(["event-scope", "session-lifetime"]).optional(),
3195
- reportsCachedInput: z14.boolean(),
3196
- reportsCacheCreation: z14.boolean(),
3382
+ cumulativeUsageSeries: z15.enum(["event-scope", "session-lifetime"]).optional(),
3383
+ reportsCachedInput: z15.boolean(),
3384
+ reportsCacheCreation: z15.boolean(),
3197
3385
  cacheCreationAccounting: cacheCreationAccountingSchema,
3198
- reportsReasoningOutput: z14.boolean(),
3199
- reportsProviderTotal: z14.boolean(),
3200
- reportsCost: z14.boolean(),
3201
- emitsSubagentEvents: z14.boolean(),
3202
- emitsCompactionEvents: z14.boolean(),
3386
+ reportsReasoningOutput: z15.boolean(),
3387
+ reportsProviderTotal: z15.boolean(),
3388
+ reportsCost: z15.boolean(),
3389
+ emitsSubagentEvents: z15.boolean(),
3390
+ emitsCompactionEvents: z15.boolean(),
3203
3391
  /** True when the provider reads a structured response from stdout. */
3204
- requiresHookResponse: z14.boolean(),
3392
+ requiresHookResponse: z15.boolean(),
3205
3393
  /** How much of this provider's hook traffic is replay-identifiable. */
3206
3394
  deliveryIdentifier: deliveryIdentifierSupportSchema
3207
3395
  });
3208
- var providerHookResponseSchema = z14.strictObject({
3396
+ var providerHookResponseSchema = z15.strictObject({
3209
3397
  /**
3210
3398
  * Always 0. A telemetry hook that can fail the host agent is a liability, so
3211
3399
  * the type forbids expressing anything else (ADR 0004).
3212
3400
  */
3213
- exitCode: z14.literal(0),
3401
+ exitCode: z15.literal(0),
3214
3402
  /** Protocol response text. Omit to write nothing at all. */
3215
- stdout: z14.string().max(8192).optional(),
3403
+ stdout: z15.string().max(8192).optional(),
3216
3404
  /** Non-sensitive diagnostic text for stderr. */
3217
- stderr: z14.string().max(8192).optional(),
3405
+ stderr: z15.string().max(8192).optional(),
3218
3406
  /** Declares which of the two stdout contracts this response follows. */
3219
- contract: z14.enum(["silent", "provider-protocol"])
3407
+ contract: z15.enum(["silent", "provider-protocol"])
3220
3408
  });
3221
3409
  var SILENT_HOOK_RESPONSE = Object.freeze({
3222
3410
  exitCode: 0,
@@ -3453,15 +3641,15 @@ var createDeterministicIdGenerator = (options = {}) => {
3453
3641
  };
3454
3642
 
3455
3643
  // src/runtime/ports.ts
3456
- import { z as z15 } from "zod";
3457
- var appliedDeliverySchema = z15.strictObject({
3458
- 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}$/),
3459
3647
  /** How many of that delivery's observations are folded in, counted from one. */
3460
- applications: z15.number().int().min(1).max(4096)
3648
+ applications: z16.number().int().min(1).max(4096)
3461
3649
  });
3462
- var stateValueSchema = z15.discriminatedUnion("kind", [
3463
- z15.strictObject({
3464
- kind: z15.literal("usage-cumulative"),
3650
+ var stateValueSchema = z16.discriminatedUnion("kind", [
3651
+ z16.strictObject({
3652
+ kind: z16.literal("usage-cumulative"),
3465
3653
  usage: canonicalUsageSchema,
3466
3654
  /**
3467
3655
  * Optional: absent on every record written before this field existed, which
@@ -3470,22 +3658,22 @@ var stateValueSchema = z15.discriminatedUnion("kind", [
3470
3658
  */
3471
3659
  appliedDelivery: appliedDeliverySchema.optional()
3472
3660
  }),
3473
- z15.strictObject({
3474
- kind: z15.literal("sequence"),
3661
+ z16.strictObject({
3662
+ kind: z16.literal("sequence"),
3475
3663
  next: sequenceNumberSchema
3476
3664
  }),
3477
- z15.strictObject({
3478
- kind: z15.literal("attributes"),
3665
+ z16.strictObject({
3666
+ kind: z16.literal("attributes"),
3479
3667
  attributes: attributesSchema
3480
3668
  })
3481
3669
  ]);
3482
- var stateRecordSchema = z15.strictObject({
3670
+ var stateRecordSchema = z16.strictObject({
3483
3671
  /** Incremented on each write; lets callers detect lost updates. */
3484
- revision: z15.number().int().min(0),
3672
+ revision: z16.number().int().min(0),
3485
3673
  updatedAt: epochMillisSchema,
3486
3674
  value: stateValueSchema
3487
3675
  });
3488
- var logLevelSchema = z15.enum(["silent", "error", "warn", "info", "debug"]);
3676
+ var logLevelSchema = z16.enum(["silent", "error", "warn", "info", "debug"]);
3489
3677
  var LOG_LEVEL_RANK = Object.freeze({
3490
3678
  silent: 0,
3491
3679
  error: 1,
@@ -3640,7 +3828,7 @@ var resolveEventTargets = async (input) => {
3640
3828
  };
3641
3829
 
3642
3830
  // src/runtime/hook.ts
3643
- var usageScopeSchema = z16.enum(["session", "generation", "subagent"]);
3831
+ var usageScopeSchema = z17.enum(["session", "generation", "subagent"]);
3644
3832
  var classifyDurability = (input) => {
3645
3833
  if (!input.attempted) {
3646
3834
  return "nothing-to-deliver";
@@ -4827,8 +5015,64 @@ var createFilesystemStateStore = (options) => {
4827
5015
 
4828
5016
  // src/telemetry/spool-queue.ts
4829
5017
  import { randomBytes as randomBytes3 } from "crypto";
4830
- 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";
4831
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
+ };
4832
5076
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
4833
5077
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
4834
5078
  var createSpoolQueue = (options) => {
@@ -4869,27 +5113,132 @@ var createSpoolQueue = (options) => {
4869
5113
  }
4870
5114
  return entries.filter((entry) => entry.endsWith(".json") && !entry.startsWith(".tmp-")).sort();
4871
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;
4872
5168
  const enqueue = async (batch) => {
4873
5169
  await ensureDirs();
4874
- const existing = await listSorted();
4875
- if (existing.length >= options.maxFiles) {
5170
+ const serialized = JSON.stringify(batch);
5171
+ const bytes = Buffer.byteLength(serialized, "utf8");
5172
+ const refuse = async (reason) => {
4876
5173
  options.logger?.warn("durable spool at capacity; batch dropped", {
4877
5174
  "spool.max_files": options.maxFiles,
5175
+ ...options.maxBytes === void 0 ? {} : { "spool.max_bytes": options.maxBytes },
4878
5176
  "spool.queue": options.queueName
4879
5177
  });
5178
+ await recordDrops(reason, 1);
4880
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
+ }
4881
5218
  }
4882
- 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`;
4883
5220
  const target = path4.join(queueDir, fileName);
4884
5221
  const tmp = path4.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
4885
- await writeFile2(tmp, JSON.stringify(batch), "utf8");
5222
+ await writeFile2(tmp, serialized, "utf8");
4886
5223
  await rename2(tmp, target);
4887
5224
  return { spooled: true };
4888
5225
  };
4889
5226
  const drain = async (send, drainOptions) => {
4890
5227
  await ensureDirs();
4891
5228
  const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;
4892
- 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
+ }
4893
5242
  let drained = 0;
4894
5243
  let failed = 0;
4895
5244
  let quarantined = 0;
@@ -4934,6 +5283,12 @@ var createSpoolQueue = (options) => {
4934
5283
  } catch {
4935
5284
  delivered = false;
4936
5285
  }
5286
+ if (delivered === "discard") {
5287
+ if (await unlink2(filePath).then(() => true, () => false)) {
5288
+ await recordDrops("rejected", 1);
5289
+ }
5290
+ continue;
5291
+ }
4937
5292
  if (delivered) {
4938
5293
  await unlink2(filePath).catch(() => void 0);
4939
5294
  drained += 1;
@@ -4951,7 +5306,8 @@ var createSpoolQueue = (options) => {
4951
5306
  size: async () => {
4952
5307
  await ensureDirs();
4953
5308
  return (await listSorted()).length;
4954
- }
5309
+ },
5310
+ stats: () => readSpoolQueueStats(queueDir)
4955
5311
  };
4956
5312
  };
4957
5313
 
@@ -5050,7 +5406,10 @@ var createFileDurableLogSpool = (options) => createSpoolQueue({
5050
5406
  clock: options.clock,
5051
5407
  ...options.logger === void 0 ? {} : { logger: options.logger },
5052
5408
  maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_LOG_SPOOL_FILES,
5053
- 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 },
5054
5413
  validate: validateLogSpoolBatch
5055
5414
  });
5056
5415
 
@@ -5142,7 +5501,10 @@ var createFileDurableSpool = (options) => createSpoolQueue({
5142
5501
  clock: options.clock,
5143
5502
  ...options.logger === void 0 ? {} : { logger: options.logger },
5144
5503
  maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_SPOOL_FILES,
5145
- 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 },
5146
5508
  validate: validateSpoolBatch
5147
5509
  });
5148
5510
 
@@ -5168,6 +5530,13 @@ var withoutTrailingSlashes = (value) => {
5168
5530
  return value.slice(0, end);
5169
5531
  };
5170
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
+
5171
5540
  // src/telemetry/exporter-resource.ts
5172
5541
  import { resourceFromAttributes } from "@opentelemetry/resources";
5173
5542
  var resourceFromExporterPolicy = (policy) => resourceFromAttributes({
@@ -5646,8 +6015,11 @@ var chunk = (items, size) => {
5646
6015
  }
5647
6016
  return chunks;
5648
6017
  };
5649
- var createDisabledSink = () => {
5650
- const health = createHealthTracker("telemetry-log-sink");
6018
+ var createDisabledSink = (destination) => {
6019
+ const health = createHealthTracker(
6020
+ "telemetry-log-sink",
6021
+ destination === void 0 ? {} : { destination }
6022
+ );
5651
6023
  return {
5652
6024
  emit: (events) => {
5653
6025
  health.recordSuccess(events.length);
@@ -5686,19 +6058,24 @@ var DISABLED_DETAIL = Object.freeze({
5686
6058
  "no-endpoint": "otlp log sink disabled: no logs endpoint configured and none could be derived"
5687
6059
  });
5688
6060
  var createOtlpLogSink = (options) => {
6061
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
5689
6062
  const deliverability = describeLogsDeliverability(options.exporter);
5690
6063
  if (deliverability.status === "disabled") {
5691
6064
  if (deliverability.reason !== "logs-disabled") {
5692
6065
  options.logger?.warn(DISABLED_DETAIL[deliverability.reason], {
5693
- "exporter.protocol": options.exporter.protocol
6066
+ "exporter.protocol": options.exporter.protocol,
6067
+ ...destinationFields
5694
6068
  });
5695
6069
  }
5696
- return createDisabledSink();
6070
+ return createDisabledSink(options.destination);
5697
6071
  }
5698
6072
  const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
5699
6073
  const resource = resourceFromExporterPolicy(options.exporter);
5700
6074
  const content = options.content ?? NO_LOG_CONTENT;
5701
- const health = createHealthTracker("telemetry-log-sink");
6075
+ const health = createHealthTracker(
6076
+ "telemetry-log-sink",
6077
+ options.destination === void 0 ? {} : { destination: options.destination }
6078
+ );
5702
6079
  const exporter = new OTLPLogExporter({
5703
6080
  url: deliverability.endpoint,
5704
6081
  headers: { ...options.headers },
@@ -5725,7 +6102,10 @@ var createOtlpLogSink = (options) => {
5725
6102
  (record) => deserializeRecord(record, batchResource, batch.instrumentationScope)
5726
6103
  );
5727
6104
  const result = await exportRecords(records);
5728
- return result.code === ExportResultCode.SUCCESS;
6105
+ if (result.code === ExportResultCode.SUCCESS) {
6106
+ return true;
6107
+ }
6108
+ return isPermanentExportFailure(result) ? "discard" : false;
5729
6109
  };
5730
6110
  const resolveCorrelations = async (events) => {
5731
6111
  if (options.correlate === void 0) {
@@ -5777,13 +6157,18 @@ var createOtlpLogSink = (options) => {
5777
6157
  continue;
5778
6158
  }
5779
6159
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
5780
- if (options.spool !== void 0) {
6160
+ const permanent = isPermanentExportFailure(result);
6161
+ if (options.spool !== void 0 && !permanent) {
5781
6162
  const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
5782
6163
  spooled: false,
5783
6164
  reason: "capacity-exceeded"
5784
6165
  }));
5785
6166
  if (spoolResult.spooled) {
5786
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
+ });
5787
6172
  continue;
5788
6173
  }
5789
6174
  }
@@ -5792,8 +6177,12 @@ var createOtlpLogSink = (options) => {
5792
6177
  createErrorInfo({
5793
6178
  code: "telemetry-export-failure",
5794
6179
  phase: "export",
5795
- detail: "collector rejected or was unreachable for a log record batch",
5796
- 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
+ }
5797
6186
  })
5798
6187
  );
5799
6188
  }
@@ -5876,8 +6265,11 @@ var deserializeSpan = (serialized, resource, scope) => assembleReadableSpan({
5876
6265
  resource,
5877
6266
  instrumentationScope: scope
5878
6267
  });
5879
- var createDisabledSink2 = () => {
5880
- const health = createHealthTracker("telemetry-sink");
6268
+ var createDisabledSink2 = (destination) => {
6269
+ const health = createHealthTracker(
6270
+ "telemetry-sink",
6271
+ destination === void 0 ? {} : { destination }
6272
+ );
5881
6273
  return {
5882
6274
  emit: (events) => {
5883
6275
  health.recordSuccess(events.length);
@@ -5890,22 +6282,27 @@ var createDisabledSink2 = () => {
5890
6282
  };
5891
6283
  };
5892
6284
  var createOtlpTraceSink = (options) => {
6285
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
5893
6286
  if (!options.exporter.enabled || options.exporter.protocol === "none") {
5894
- return createDisabledSink2();
6287
+ return createDisabledSink2(options.destination);
5895
6288
  }
5896
6289
  if (options.exporter.endpoint === void 0) {
5897
- options.logger?.warn("otlp sink disabled: no endpoint configured", {});
5898
- return createDisabledSink2();
6290
+ options.logger?.warn("otlp sink disabled: no endpoint configured", destinationFields);
6291
+ return createDisabledSink2(options.destination);
5899
6292
  }
5900
6293
  if (options.exporter.protocol !== "http/protobuf") {
5901
6294
  options.logger?.warn("otlp sink: protocol not supported by this build, falling back to disabled", {
5902
- "exporter.protocol": options.exporter.protocol
6295
+ "exporter.protocol": options.exporter.protocol,
6296
+ ...destinationFields
5903
6297
  });
5904
- return createDisabledSink2();
6298
+ return createDisabledSink2(options.destination);
5905
6299
  }
5906
6300
  const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
5907
6301
  const resource = resourceFromExporterPolicy(options.exporter);
5908
- const health = createHealthTracker("telemetry-sink");
6302
+ const health = createHealthTracker(
6303
+ "telemetry-sink",
6304
+ options.destination === void 0 ? {} : { destination: options.destination }
6305
+ );
5909
6306
  const exporter = new OTLPTraceExporter({
5910
6307
  url: options.exporter.endpoint,
5911
6308
  headers: { ...options.headers },
@@ -5927,7 +6324,10 @@ var createOtlpTraceSink = (options) => {
5927
6324
  const batchResource = replayResource(batch.resourceAttributes, options.exporter);
5928
6325
  const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));
5929
6326
  const result = await exportSpans(spans);
5930
- return result.code === ExportResultCode2.SUCCESS;
6327
+ if (result.code === ExportResultCode2.SUCCESS) {
6328
+ return true;
6329
+ }
6330
+ return isPermanentExportFailure(result) ? "discard" : false;
5931
6331
  };
5932
6332
  const resolveCorrelations = async (events) => {
5933
6333
  if (options.correlate === void 0) {
@@ -5955,6 +6355,9 @@ var createOtlpTraceSink = (options) => {
5955
6355
  let accepted = 0;
5956
6356
  let rejected = 0;
5957
6357
  for (const batch of chunk2(spans, options.exporter.maxBatchSize)) {
6358
+ if (batch.length === 0) {
6359
+ continue;
6360
+ }
5958
6361
  let result;
5959
6362
  try {
5960
6363
  result = await exportSpans(batch);
@@ -5967,13 +6370,18 @@ var createOtlpTraceSink = (options) => {
5967
6370
  continue;
5968
6371
  }
5969
6372
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
5970
- if (options.spool !== void 0) {
6373
+ const permanent = isPermanentExportFailure(result);
6374
+ if (options.spool !== void 0 && !permanent) {
5971
6375
  const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
5972
6376
  spooled: false,
5973
6377
  reason: "capacity-exceeded"
5974
6378
  }));
5975
6379
  if (spoolResult.spooled) {
5976
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
+ });
5977
6385
  continue;
5978
6386
  }
5979
6387
  }
@@ -5982,8 +6390,8 @@ var createOtlpTraceSink = (options) => {
5982
6390
  createErrorInfo({
5983
6391
  code: "telemetry-export-failure",
5984
6392
  phase: "export",
5985
- detail: "collector rejected or was unreachable for a span batch",
5986
- 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 }
5987
6395
  })
5988
6396
  );
5989
6397
  }
@@ -6068,6 +6476,172 @@ var shareCorrelationPerBatch = (correlate) => {
6068
6476
  };
6069
6477
  };
6070
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
+
6071
6645
  // src/integration/hook-runtime.ts
6072
6646
  var DEFAULT_FLUSH_TIMEOUT_MILLIS = 2e3;
6073
6647
  var DEFAULT_STATE_LOCK_TIMEOUT_MILLIS = 1e3;
@@ -6130,46 +6704,23 @@ var createHookRuntime = (options) => {
6130
6704
  logger,
6131
6705
  lockTimeoutMillis: stateLockTimeoutMillis
6132
6706
  });
6133
- const spool = options.enableSpool === false ? void 0 : createFileDurableSpool({
6134
- rootDir: options.stateRootDir,
6135
- providerId: options.providerNamespace,
6136
- installationId: options.installationId,
6137
- clock,
6138
- logger
6139
- });
6140
- const logSpool = options.enableSpool === false || !options.config.exporter.logs.enabled ? void 0 : createFileDurableLogSpool({
6141
- rootDir: options.stateRootDir,
6142
- providerId: options.providerNamespace,
6143
- installationId: options.installationId,
6144
- clock,
6145
- logger
6146
- });
6147
6707
  const spanCorrelator = createSpanCorrelator({
6148
6708
  stateStore,
6149
6709
  clock,
6150
6710
  maxStartAgeMillis: lifecycleMaxAge
6151
6711
  });
6152
6712
  const correlate = shareCorrelationPerBatch((events) => spanCorrelator.correlateBatch(events));
6153
- const traceSink = createOtlpTraceSink({
6154
- exporter: options.config.exporter,
6155
- ...options.headers === void 0 ? {} : { headers: options.headers },
6156
- providerId: options.providerNamespace,
6157
- installationId: options.installationId,
6158
- clock,
6159
- logger,
6160
- ...spool === void 0 ? {} : { spool },
6161
- correlate
6162
- });
6163
- const logHeaders = options.logHeaders ?? options.headers;
6164
- const logSink = createOtlpLogSink({
6713
+ const exportDestinations = createExportDestinationSinks({
6165
6714
  exporter: options.config.exporter,
6166
- ...logHeaders === void 0 ? {} : { headers: logHeaders },
6715
+ ...options.headers === void 0 ? {} : { defaultHeaders: options.headers },
6716
+ ...options.logHeaders === void 0 ? {} : { defaultLogHeaders: options.logHeaders },
6717
+ ...options.headerEnvironment === void 0 ? {} : { headerEnvironment: options.headerEnvironment },
6167
6718
  providerId: options.providerNamespace,
6168
6719
  installationId: options.installationId,
6169
6720
  clock,
6170
6721
  logger,
6171
- ...logSpool === void 0 ? {} : { spool: logSpool },
6172
- content: {
6722
+ ...options.enableSpool === false ? {} : { spoolRootDir: options.stateRootDir },
6723
+ logContent: {
6173
6724
  includeContent: options.config.exporter.logs.includeContent,
6174
6725
  // The pre-existing verbatim-content opt-in, passed through rather than
6175
6726
  // re-derived: `raw` disclosure in a log body is governed by the same flag it
@@ -6178,7 +6729,22 @@ var createHookRuntime = (options) => {
6178
6729
  },
6179
6730
  correlate
6180
6731
  });
6181
- 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);
6182
6748
  const hookDeps = {
6183
6749
  stateStore,
6184
6750
  config: options.config,
@@ -6447,6 +7013,8 @@ var createHookRuntime = (options) => {
6447
7013
  logSink,
6448
7014
  ...spool === void 0 ? {} : { spool },
6449
7015
  ...logSpool === void 0 ? {} : { logSpool },
7016
+ destinations: exportDestinations.destinations,
7017
+ skippedDestinations: exportDestinations.skipped,
6450
7018
  privacy,
6451
7019
  deduplicator,
6452
7020
  usageAccumulator,