@osfactory/otel-hook 0.13.2 → 0.14.1
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.
- package/README.md +57 -0
- package/dist/{adapter-DyCb7y1N.d.ts → adapter-But5fFCk.d.ts} +9 -2
- package/dist/cli.js +628 -73
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +30 -4
- package/dist/config.js +161 -9
- package/dist/config.js.map +1 -1
- package/dist/{destinations-C4sSKjDO.d.ts → destinations-2KrcRslo.d.ts} +92 -2
- package/dist/{export-destinations-BjRXDots.d.ts → export-destinations-8tNkIC8a.d.ts} +110 -10
- package/dist/{filesystem-store-B3CpiIRl.d.ts → filesystem-store-Z8XgDtFj.d.ts} +1 -1
- package/dist/{hook-CKLpgrYP.d.ts → hook-D7XABd4f.d.ts} +19 -5
- package/dist/index.d.ts +14 -14
- package/dist/index.js +626 -72
- package/dist/index.js.map +1 -1
- package/dist/install.d.ts +4 -4
- package/dist/install.js.map +1 -1
- package/dist/integration.d.ts +9 -9
- package/dist/integration.js +555 -65
- package/dist/integration.js.map +1 -1
- package/dist/lifecycle.d.ts +1 -1
- package/dist/lifecycle.js +1 -1
- package/dist/lifecycle.js.map +1 -1
- package/dist/{memory-B3r6sZtC.d.ts → memory-gipZUiXP.d.ts} +1 -1
- package/dist/{payload-DLK7QaBB.d.ts → payload-DWdx9yk3.d.ts} +1 -1
- package/dist/{ports-DhpSDIkp.d.ts → ports-qZTwK-z2.d.ts} +22 -2
- package/dist/privacy.d.ts +2 -2
- package/dist/privacy.js +42 -1
- package/dist/privacy.js.map +1 -1
- package/dist/providers.d.ts +9 -9
- package/dist/providers.js +22 -5
- package/dist/providers.js.map +1 -1
- package/dist/{registry-DM-4YvIA.d.ts → registry-D9rmMYxw.d.ts} +2 -2
- package/dist/runtime.d.ts +24 -9
- package/dist/runtime.js +282 -30
- package/dist/runtime.js.map +1 -1
- package/dist/{schema-CD61uW99.d.ts → schema-oRsbo7WO.d.ts} +45 -0
- package/dist/{service-CbI9CObT.d.ts → service-DySC7KQM.d.ts} +6 -1
- package/dist/state.d.ts +3 -3
- package/dist/state.js.map +1 -1
- package/dist/telemetry.d.ts +6 -5
- package/dist/telemetry.js +304 -17
- package/dist/telemetry.js.map +1 -1
- package/dist/testing.d.ts +8 -8
- package/dist/testing.js +185 -10
- package/dist/testing.js.map +1 -1
- package/package.json +1 -1
package/dist/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/config/resource-attributes.ts","../src/model/primitives.ts","../src/privacy/policy.ts","../src/config/schema.ts","../src/config/destinations.ts","../src/config/header-value.ts","../src/config/otlp-headers.ts","../src/config/resolve.ts","../src/errors/index.ts","../src/errors/taxonomy.ts","../src/config/otlp-endpoint.ts","../src/config/environment.ts"],"sourcesContent":["import { z } from \"zod\";\n\nimport { MAX_IDENTIFIER_LENGTH } from \"../model/primitives.js\";\nimport { DEFAULT_SECRET_KEY_PATTERNS } from \"../privacy/policy.js\";\n\n/**\n * Custom OTLP **resource** attributes: facts about the emitting deployment\n * (`deployment.environment`, `service.instance.id`, a tenant label) that belong\n * on every span this installation exports.\n *\n * These are deliberately *not* {@link ConsumerAttributes}. Consumer attributes\n * are opaque per-invocation metadata that travels with one observation's\n * identity and is sanitized by the privacy service; resource attributes are\n * per-process exporter policy, resolved from configuration layers, and describe\n * the producer rather than the observation. The two never share a field name, a\n * flag, or a code path — see ADR 0001 on keeping identity out of configuration.\n */\n\n/** Upper bound on how many custom resource attributes one installation may set. */\nexport const MAX_RESOURCE_ATTRIBUTES = 64;\n/** Upper bound on a resource attribute key, matching the OpenTelemetry guidance. */\nexport const MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH = 255;\n/** Upper bound on a resource attribute value; values are repeated on every export. */\nexport const MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH = 2048;\n\n/**\n * Accepted shape of a resource attribute key.\n *\n * Deliberately narrower than \"any string\": a key becomes an attribute name on\n * the wire, so restricting it to the OpenTelemetry naming vocabulary keeps\n * newlines, control characters, and arbitrary binary out of the exported\n * resource by construction.\n */\nexport const RESOURCE_ATTRIBUTE_KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_./-]*$/;\n\n/**\n * Keys that resource attributes may never set directly.\n *\n * `service.name` and `service.namespace` are typed exporter policy with their\n * own precedence chain and their own diagnostics. If a resource-attribute map\n * could also write them, the winner would depend on merge order inside the\n * exporter rather than on the documented configuration precedence — which is\n * exactly the silent override this reservation prevents. Supplying either one\n * through `OTEL_RESOURCE_ATTRIBUTES` still works: the environment parser routes\n * it to the policy field at a defined precedence instead of smuggling it into\n * the resource map.\n */\nexport const RESERVED_RESOURCE_ATTRIBUTE_KEYS: readonly string[] = Object.freeze([\n \"service.name\",\n \"service.namespace\",\n]);\n\n/** Case-insensitive: `Service.Name` is the same reservation, spelled differently. */\nexport const isReservedResourceAttributeKey = (key: string): boolean =>\n RESERVED_RESOURCE_ATTRIBUTE_KEYS.includes(key.toLowerCase());\n\nconst SECRET_KEY_MATCHERS: readonly RegExp[] = Object.freeze(\n DEFAULT_SECRET_KEY_PATTERNS.flatMap((source) => {\n try {\n return [new RegExp(source, \"i\")];\n } catch {\n return [];\n }\n }),\n);\n\n/**\n * Whether a key names something that should never be exported.\n *\n * A resource attribute is attached to *every* span, so `api_key=...` in a\n * config file or a shell profile would be the most durable possible leak. The\n * central privacy policy's key patterns are reused rather than re-invented, so\n * one list governs both content sanitization and this boundary.\n */\nexport const isSecretResourceAttributeKey = (key: string): boolean =>\n SECRET_KEY_MATCHERS.some((pattern) => pattern.test(key));\n\nexport type ResourceAttributeKeyRejection =\n | \"empty\"\n | \"too-long\"\n | \"malformed\"\n | \"reserved\"\n | \"secret-like\";\n\n/** Non-sensitive explanations. None of these ever quotes an attribute *value*. */\nexport const RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL: Readonly<\n Record<ResourceAttributeKeyRejection, string>\n> = Object.freeze({\n empty: \"resource attribute key is empty\",\n \"too-long\": `resource attribute key exceeds ${String(MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH)} characters`,\n malformed:\n \"resource attribute key must start with a letter and use only letters, digits, and `_`, `.`, `-`, `/`\",\n reserved:\n \"service.name and service.namespace are exporter policy (--service-name / OTEL_HOOK_SERVICE_NAME), not resource attributes\",\n \"secret-like\":\n \"resource attribute key matches a secret-name pattern, so it is never exported\",\n});\n\n/** Returns why a key is unusable, or `undefined` when it is acceptable. */\nexport const checkResourceAttributeKey = (\n key: string,\n): ResourceAttributeKeyRejection | undefined => {\n if (key.length === 0) {\n return \"empty\";\n }\n if (key.length > MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH) {\n return \"too-long\";\n }\n if (!RESOURCE_ATTRIBUTE_KEY_PATTERN.test(key)) {\n return \"malformed\";\n }\n if (isReservedResourceAttributeKey(key)) {\n return \"reserved\";\n }\n if (isSecretResourceAttributeKey(key)) {\n return \"secret-like\";\n }\n return undefined;\n};\n\n/**\n * Resource attribute values are single primitives, never arrays.\n *\n * `OTEL_RESOURCE_ATTRIBUTES` cannot express an array, and allowing one only in\n * the file layer would make per-key precedence depend on which layer supplied a\n * key. A single primitive keeps the merge total and order-independent.\n */\nexport const resourceAttributeValueSchema = z.union([\n z.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),\n z.number().finite(),\n z.boolean(),\n]);\nexport type ResourceAttributeValue = z.infer<typeof resourceAttributeValueSchema>;\n\nexport const resourceAttributesSchema = z\n .record(z.string(), resourceAttributeValueSchema)\n .superRefine((value, ctx) => {\n const keys = Object.keys(value);\n if (keys.length > MAX_RESOURCE_ATTRIBUTES) {\n ctx.addIssue({\n code: \"custom\",\n message: `at most ${String(MAX_RESOURCE_ATTRIBUTES)} resource attributes are accepted`,\n });\n }\n for (const key of keys) {\n const rejection = checkResourceAttributeKey(key);\n if (rejection !== undefined) {\n ctx.addIssue({\n code: \"custom\",\n path: [key],\n message: RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL[rejection],\n });\n }\n }\n })\n .readonly();\nexport type ResourceAttributes = z.infer<typeof resourceAttributesSchema>;\n\nexport const EMPTY_RESOURCE_ATTRIBUTES: ResourceAttributes = Object.freeze({});\n\nexport type ParsedResourceAttributes = {\n readonly attributes: Readonly<Record<string, string>>;\n /** `service.name`, routed to exporter policy rather than into `attributes`. */\n readonly serviceName?: string;\n /** `service.namespace`, routed the same way. */\n readonly serviceNamespace?: string;\n /**\n * Why entries were skipped. Every message identifies an entry by its\n * *position*, never by quoting the entry — an ambient environment variable\n * may hold anything, and a diagnostic that echoes it would publish it.\n */\n readonly warnings: readonly string[];\n};\n\nconst stripSurroundingQuotes = (value: string): string =>\n value.length >= 2 && value.startsWith('\"') && value.endsWith('\"') ? value.slice(1, -1) : value;\n\n/**\n * Parse the standard `OTEL_RESOURCE_ATTRIBUTES` variable.\n *\n * The OpenTelemetry specification defines this as W3C Baggage: comma-separated\n * `key=value` pairs, optional whitespace around each part, an optional\n * `;`-delimited metadata suffix that carries no attribute meaning, and\n * **percent-encoded values**. Escaping is the part naive parsers get wrong, and\n * it is load-bearing here: without it `deployment.note=a%2Cb` silently becomes\n * two malformed entries, and `region=eu%2Dwest` keeps a literal `%2D`.\n *\n * Every rejection is reported and skipped rather than failing the whole\n * variable: a stale entry in a shell profile must not cost an operator the\n * attributes they got right, and must never disable telemetry (ADR 0004).\n */\nexport const parseResourceAttributesValue = (raw: string): ParsedResourceAttributes => {\n const attributes: Record<string, string> = {};\n const warnings: string[] = [];\n let serviceName: string | undefined;\n let serviceNamespace: string | undefined;\n let overflowed = false;\n\n const entries = raw.split(\",\");\n for (const [index, rawEntry] of entries.entries()) {\n const position = index + 1;\n // Baggage metadata (`key=value;prop=1`) carries no attribute meaning.\n const entry = (rawEntry.split(\";\")[0] ?? \"\").trim();\n if (entry === \"\") {\n continue;\n }\n\n const equals = entry.indexOf(\"=\");\n if (equals <= 0) {\n warnings.push(`entry ${String(position)} is not a key=value pair`);\n continue;\n }\n const key = entry.slice(0, equals).trim();\n // Split on the *first* `=` only: a percent-decoded value may legitimately\n // contain one, and re-joining would be lossy.\n const encoded = stripSurroundingQuotes(entry.slice(equals + 1).trim());\n let value: string;\n try {\n value = decodeURIComponent(encoded);\n } catch {\n warnings.push(`entry ${String(position)} has a malformed percent-encoded value`);\n continue;\n }\n\n if (isReservedResourceAttributeKey(key)) {\n if (value.length === 0 || value.length > MAX_IDENTIFIER_LENGTH) {\n warnings.push(\n `entry ${String(position)} sets ${key.toLowerCase()} to an empty or over-long value`,\n );\n continue;\n }\n if (key.toLowerCase() === \"service.name\") {\n serviceName = value;\n } else {\n serviceNamespace = value;\n }\n continue;\n }\n\n const rejection = checkResourceAttributeKey(key);\n if (rejection !== undefined) {\n warnings.push(\n `entry ${String(position)} was skipped: ${RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL[rejection]}`,\n );\n continue;\n }\n if (value.length > MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) {\n // Dropped rather than truncated: a silently shortened attribute value is\n // a wrong fact, which is worse than a missing one.\n warnings.push(\n `entry ${String(position)} has a value longer than ${String(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH)} characters`,\n );\n continue;\n }\n if (!(key in attributes) && Object.keys(attributes).length >= MAX_RESOURCE_ATTRIBUTES) {\n overflowed = true;\n continue;\n }\n // A repeated key takes its last value, matching every other layer here.\n attributes[key] = value;\n }\n\n if (overflowed) {\n warnings.push(\n `more than ${String(MAX_RESOURCE_ATTRIBUTES)} resource attributes were supplied; the excess was dropped`,\n );\n }\n\n return {\n attributes,\n ...(serviceName === undefined ? {} : { serviceName }),\n ...(serviceNamespace === undefined ? {} : { serviceNamespace }),\n warnings,\n };\n};\n\n/**\n * Drop anything that must not reach the exported resource.\n *\n * The schema already refuses these keys, but a {@link ExporterPolicy} can also\n * be hand-built by a library caller who never ran it through the schema. This\n * is the last gate before the wire, so it filters rather than trusts.\n */\nexport const sanitizeResourceAttributes = (\n attributes: ResourceAttributes,\n): Readonly<Record<string, ResourceAttributeValue>> => {\n const safe: Record<string, ResourceAttributeValue> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (checkResourceAttributeKey(key) !== undefined) {\n continue;\n }\n if (Object.keys(safe).length >= MAX_RESOURCE_ATTRIBUTES) {\n break;\n }\n safe[key] = value;\n }\n return safe;\n};\n\n/**\n * Attribute *names* only, for a logged or exported configuration snapshot.\n *\n * Names are safe to disclose because they are already part of every exported\n * resource; values are not disclosed, because a value is the half an operator\n * may have filled with something they would not want in a log line.\n */\nexport const describeResourceAttributeNames = (\n attributes: ResourceAttributes,\n): readonly string[] => Object.keys(attributes).sort();\n","import { z } from \"zod\";\n\n/** Maximum length accepted for short identifier-like strings. */\nexport const MAX_IDENTIFIER_LENGTH = 256;\n\n/** Maximum length accepted for a single string attribute value. */\nexport const MAX_ATTRIBUTE_STRING_LENGTH = 4096;\n\n/** Maximum number of entries accepted in an attribute array value. */\nexport const MAX_ATTRIBUTE_ARRAY_LENGTH = 128;\n\nexport const nonEmptyStringSchema = z.string().min(1).max(MAX_IDENTIFIER_LENGTH);\n\n/** Wall-clock time as whole milliseconds since the Unix epoch. */\nexport const epochMillisSchema = z.number().int().min(0).max(8_640_000_000_000_000);\nexport type EpochMillis = z.infer<typeof epochMillisSchema>;\n\n/** Non-negative duration in milliseconds; may be fractional. */\nexport const durationMillisSchema = z.number().min(0).finite();\n\n/** Token counts are always non-negative integers. */\nexport const tokenCountSchema = z.number().int().min(0);\n\n/** Monotonically increasing per-invocation ordering key. */\nexport const sequenceNumberSchema = z.number().int().min(0);\n\nconst brandedIdSchema = (): z.ZodString => z.string().min(1).max(MAX_IDENTIFIER_LENGTH);\n\nexport const invocationIdSchema = brandedIdSchema().brand<\"InvocationId\">();\nexport type InvocationId = z.infer<typeof invocationIdSchema>;\n\nexport const sessionIdSchema = brandedIdSchema().brand<\"SessionId\">();\nexport type SessionId = z.infer<typeof sessionIdSchema>;\n\nexport const eventIdSchema = brandedIdSchema().brand<\"EventId\">();\nexport type EventId = z.infer<typeof eventIdSchema>;\n\n/**\n * Workspace identifiers are opaque, privacy-safe handles of the form\n * `<scheme>:<token>`. Filesystem paths cannot satisfy this pattern, which keeps\n * home directories and repository paths out of telemetry by construction.\n */\nexport const WORKSPACE_ID_PATTERN = /^[a-z][a-z0-9]{0,15}:[A-Za-z0-9_-]{8,128}$/;\nexport const workspaceIdSchema = z\n .string()\n .regex(WORKSPACE_ID_PATTERN, \"workspace id must be an opaque `<scheme>:<token>` handle\")\n .brand<\"WorkspaceId\">();\nexport type WorkspaceId = z.infer<typeof workspaceIdSchema>;\n\n/** Provider ids are lowercase, hyphenated, and stable across releases. */\nexport const PROVIDER_ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\nexport const providerIdSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(PROVIDER_ID_PATTERN, \"provider id must be lowercase and hyphenated\")\n .brand<\"ProviderId\">();\nexport type ProviderId = z.infer<typeof providerIdSchema>;\n\n/** Sentinel used whenever the source provider could not be established. */\nexport const UNKNOWN_PROVIDER_ID = \"unknown\" as const;\nexport type UnknownProviderId = typeof UNKNOWN_PROVIDER_ID;\n\nexport const resolvedProviderIdSchema = z.union([\n providerIdSchema,\n z.literal(UNKNOWN_PROVIDER_ID),\n]);\nexport type ResolvedProviderId = z.infer<typeof resolvedProviderIdSchema>;\n\nexport const isUnknownProvider = (value: ResolvedProviderId): value is UnknownProviderId =>\n value === UNKNOWN_PROVIDER_ID;\n\n/**\n * Attribute values are restricted to OpenTelemetry-compatible primitives.\n *\n * This restriction is a containment boundary, not a convenience: because no\n * nested object can be represented, a raw provider payload cannot be smuggled\n * out of an adapter through attributes or extensions.\n */\nexport const attributePrimitiveSchema = z.union([\n z.string().max(MAX_ATTRIBUTE_STRING_LENGTH),\n z.number().finite(),\n z.boolean(),\n]);\nexport type AttributePrimitive = z.infer<typeof attributePrimitiveSchema>;\n\nexport const attributeValueSchema = z.union([\n attributePrimitiveSchema,\n z.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH),\n]);\nexport type AttributeValue = z.infer<typeof attributeValueSchema>;\n\nexport const attributesSchema = z.record(z.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);\nexport type Attributes = z.infer<typeof attributesSchema>;\n\n/** Ordered confidence ladder for provider detection. */\nexport const detectionConfidenceSchema = z.enum([\"none\", \"weak\", \"strong\", \"exact\"]);\nexport type DetectionConfidence = z.infer<typeof detectionConfidenceSchema>;\n\nexport const DETECTION_CONFIDENCE_RANK: Readonly<Record<DetectionConfidence, number>> =\n Object.freeze({\n none: 0,\n weak: 1,\n strong: 2,\n exact: 3,\n });\n\nexport const compareDetectionConfidence = (a: DetectionConfidence, b: DetectionConfidence): number =>\n DETECTION_CONFIDENCE_RANK[a] - DETECTION_CONFIDENCE_RANK[b];\n\n/** How the observed data reached this process. */\nexport const sourceTransportSchema = z.enum([\n \"hook-stdin\",\n \"cli-argument\",\n \"library-call\",\n \"test-fixture\",\n]);\nexport type SourceTransport = z.infer<typeof sourceTransportSchema>;\n","import { z } from \"zod\";\n\nimport type { ContentDisclosure } from \"../model/content.js\";\n\n/**\n * How much content the library is permitted to disclose.\n *\n * `omit` is the default and the only mode that requires no trust in the\n * downstream collector.\n */\nexport const contentModeSchema = z.enum([\"omit\", \"mask\", \"redact\", \"raw\"]);\nexport type ContentMode = z.infer<typeof contentModeSchema>;\n\nexport const CONTENT_MODE_DISCLOSURE: Readonly<Record<ContentMode, ContentDisclosure>> =\n Object.freeze({\n omit: \"omitted\",\n mask: \"masked\",\n redact: \"redacted\",\n raw: \"raw\",\n });\n\n/**\n * Default secret-key patterns, matched case-insensitively against object keys at\n * every depth. A key matching any of these has its value replaced before the\n * value itself is ever inspected.\n */\nexport const DEFAULT_SECRET_KEY_PATTERNS: readonly string[] = Object.freeze([\n \"(^|[._-])(secret|secrets)([._-]|$)\",\n \"(^|[._-])(token|tokens)([._-]|$)\",\n \"(^|[._-])(password|passwd|pwd)([._-]|$)\",\n \"(^|[._-])(credential|credentials)([._-]|$)\",\n \"(^|[._-])(api[._-]?key|apikey|access[._-]?key|secret[._-]?key|private[._-]?key)([._-]|$)\",\n \"(^|[._-])(authorization|auth[._-]?header|bearer)([._-]|$)\",\n \"(^|[._-])(cookie|set[._-]?cookie)([._-]|$)\",\n \"(^|[._-])(signature|sig)([._-]|$)\",\n]);\n\n/**\n * Default secret-value patterns applied to disclosed text in `redact` mode.\n * These are heuristics; they reduce accidental disclosure but are not a\n * substitute for `omit`.\n */\nexport const DEFAULT_SECRET_VALUE_PATTERNS: readonly string[] = Object.freeze([\n \"AKIA[0-9A-Z]{16}\",\n \"sk-[A-Za-z0-9_-]{16,}\",\n \"gh[pousr]_[A-Za-z0-9]{16,}\",\n \"xox[abprs]-[A-Za-z0-9-]{10,}\",\n \"-----BEGIN[A-Z ]*PRIVATE KEY-----\",\n \"eyJ[A-Za-z0-9_-]{10,}\\\\.[A-Za-z0-9_-]{10,}\\\\.[A-Za-z0-9_-]{10,}\",\n \"(?:Bearer|Basic)\\\\s+[A-Za-z0-9._~+/=-]{12,}\",\n]);\n\nexport const privacyLimitsSchema = z.strictObject({\n /** Maximum characters of disclosed text per content fact or string value. */\n maxStringLength: z.number().int().min(0).max(65_536),\n /** Maximum nesting depth walked when sanitizing structured values. */\n maxDepth: z.number().int().min(1).max(32),\n /** Maximum array entries retained when sanitizing structured values. */\n maxArrayLength: z.number().int().min(1).max(4096),\n /** Maximum canonical events emitted per invocation. */\n maxEventsPerInvocation: z.number().int().min(1).max(10_000),\n /** Maximum object keys retained per level when sanitizing. */\n maxObjectKeys: z.number().int().min(1).max(1024),\n});\nexport type PrivacyLimits = z.infer<typeof privacyLimitsSchema>;\n\nexport const privacyPolicySchema = z.strictObject({\n contentMode: contentModeSchema,\n /**\n * `raw` mode is refused unless this is also true, so a single mistyped\n * environment variable cannot start exporting prompts.\n */\n allowRawContent: z.boolean(),\n /**\n * Salt mixed into every hash. A per-deployment salt makes hashes\n * non-correlatable across deployments; an empty salt makes them globally\n * comparable. Both are legitimate; the choice is explicit.\n */\n hashSalt: z.string().max(256),\n maskCharacter: z.string().length(1),\n redactionPlaceholder: z.string().min(1).max(64),\n secretKeyPatterns: z.array(z.string().min(1)).max(128).readonly(),\n secretValuePatterns: z.array(z.string().min(1)).max(128).readonly(),\n limits: privacyLimitsSchema,\n});\nexport type PrivacyPolicy = z.infer<typeof privacyPolicySchema>;\n\nexport const DEFAULT_PRIVACY_LIMITS: PrivacyLimits = Object.freeze({\n maxStringLength: 1024,\n maxDepth: 6,\n maxArrayLength: 64,\n maxEventsPerInvocation: 512,\n maxObjectKeys: 128,\n});\n\nexport const DEFAULT_PRIVACY_POLICY: PrivacyPolicy = Object.freeze({\n contentMode: \"omit\",\n allowRawContent: false,\n hashSalt: \"\",\n maskCharacter: \"*\",\n redactionPlaceholder: \"[redacted]\",\n secretKeyPatterns: DEFAULT_SECRET_KEY_PATTERNS,\n secretValuePatterns: DEFAULT_SECRET_VALUE_PATTERNS,\n limits: DEFAULT_PRIVACY_LIMITS,\n});\n\nexport type PolicyResolution = {\n readonly policy: PrivacyPolicy;\n /** Non-sensitive notes about deterministic downgrades that were applied. */\n readonly notes: readonly string[];\n};\n\n/**\n * Validate a policy and apply the one deterministic downgrade the library\n * enforces: `raw` without `allowRawContent` becomes `omit`.\n */\nexport const resolvePrivacyPolicy = (policy: PrivacyPolicy): PolicyResolution => {\n const parsed = privacyPolicySchema.parse(policy);\n if (parsed.contentMode === \"raw\" && !parsed.allowRawContent) {\n return {\n policy: { ...parsed, contentMode: \"omit\" },\n notes: [\"contentMode=raw downgraded to omit because allowRawContent is false\"],\n };\n }\n return { policy: parsed, notes: [] };\n};\n","import { isAbsolute } from \"node:path\";\n\nimport { z } from \"zod\";\n\nimport { detectionConfidenceSchema, nonEmptyStringSchema } from \"../model/primitives.js\";\nimport {\n contentModeSchema,\n DEFAULT_PRIVACY_POLICY,\n privacyPolicySchema,\n} from \"../privacy/policy.js\";\nimport { exportDestinationsSchema, spoolPolicySchema } from \"./destinations.js\";\nimport { EMPTY_RESOURCE_ATTRIBUTES, resourceAttributesSchema } from \"./resource-attributes.js\";\n\n/**\n * Policy for the OTLP logs signal.\n *\n * Two switches rather than one, because they answer different questions and an\n * operator needs to be able to answer them differently:\n *\n * - `enabled` — whether a second signal leaves this host at all. Off by default:\n * an installation that upgrades must not silently start sending a new stream to a\n * collector whose receivers, quotas, and retention were sized for traces.\n * - `includeContent` — whether *disclosed* text may appear in a log body. Also off\n * by default, and deliberately not the same knob as `privacy.contentMode`: spans\n * carry no content in any content mode, so an installation that set\n * `contentMode` to get a hash and a length has never had content on the wire.\n * Reusing that setting to also mean \"publish prompts\" would change what an\n * existing configuration discloses without anybody editing it.\n *\n * `raw` content additionally requires the pre-existing `privacy.allowRawContent`\n * opt-in, which the privacy service enforces before a fact is ever built and the\n * log mapping re-checks at the wire.\n */\nexport const logsPolicySchema = z.strictObject({\n enabled: z.boolean(),\n /**\n * Full URL for the logs signal.\n *\n * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes\n * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.\n */\n endpoint: z.string().url().max(2048).optional(),\n includeContent: z.boolean(),\n maxBatchSize: z.number().int().min(1).max(4096),\n});\nexport type LogsPolicy = z.infer<typeof logsPolicySchema>;\n\nexport const DEFAULT_LOGS_POLICY: LogsPolicy = Object.freeze({\n enabled: false,\n includeContent: false,\n maxBatchSize: 128,\n});\n\n/**\n * Policy for hook-derived metrics (issue #69).\n *\n * Off by default, like logs: an upgrade must not start a new stream to a\n * collector nobody sized for it. `enabled` governs the `default` destination\n * (the single-endpoint settings); an `exporter.destinations[]` entry receives\n * metrics when its `signals` list names `metrics`. Metrics carry no content, so\n * listing the signal is the whole opt-in.\n *\n * - `temporality`: `cumulative` (default) exports running totals per series,\n * kept in the state store across hook processes, so a receiver that merges\n * counters by keeping the largest value stays correct. `delta` exports what one\n * callback observed and keeps no state.\n * - `includeSessionId`: put `session.id` on every data point (default true). Turn\n * it off where per-session series are too many for the backend.\n */\nexport const metricsPolicySchema = z.strictObject({\n enabled: z.boolean(),\n /** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */\n endpoint: z.string().url().max(2048).optional(),\n temporality: z.enum([\"cumulative\", \"delta\"]),\n includeSessionId: z.boolean(),\n});\nexport type MetricsPolicy = z.infer<typeof metricsPolicySchema>;\n\nexport const DEFAULT_METRICS_POLICY: MetricsPolicy = Object.freeze({\n enabled: false,\n temporality: \"cumulative\",\n includeSessionId: true,\n});\n\n/**\n * Runtime exporter policy.\n *\n * This describes *where and how* telemetry goes. It deliberately contains no\n * session, invocation, or workspace field: see ADR 0001. Mixing the two would\n * make identity globally reachable through configuration.\n */\nexport const exporterPolicySchema = z.strictObject({\n enabled: z.boolean(),\n protocol: z.enum([\"http/protobuf\", \"http/json\", \"none\"]),\n endpoint: z.string().url().max(2048).optional(),\n /**\n * Header names only. Values are supplied separately at construction time and\n * are never part of a resolved-config snapshot, which is logged and exported.\n */\n headerNames: z.array(nonEmptyStringSchema).max(32).readonly(),\n timeoutMillis: z.number().int().min(1).max(600_000),\n maxBatchSize: z.number().int().min(1).max(4096),\n maxQueueSize: z.number().int().min(1).max(65_536),\n maxRetryAttempts: z.number().int().min(0).max(10),\n serviceName: nonEmptyStringSchema,\n serviceNamespace: nonEmptyStringSchema.optional(),\n /**\n * Custom attributes merged into the exported OTLP Resource.\n *\n * Bounded and validated, and refusing `service.name`/`service.namespace`,\n * which are the two fields above. Distinct from an invocation's\n * `consumerAttributes`: this describes the emitting deployment, carries no\n * identity, and is the same for every span this process exports.\n */\n resourceAttributes: resourceAttributesSchema,\n /**\n * The logs signal. Nested under the exporter because it shares the endpoint,\n * headers, timeout, protocol, service identity, and resource attributes above —\n * a second top-level section would invite two of each to drift apart.\n */\n logs: logsPolicySchema,\n /**\n * Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before\n * metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.\n */\n metrics: metricsPolicySchema.optional(),\n /**\n * Additional OTLP destinations, each sent every batch in parallel.\n *\n * Absent (the default), the exporter has exactly one destination — the\n * single-endpoint settings above, named `default` — and behaves exactly as it\n * did before this list existed. See `destinations.ts`.\n *\n * Merged as one leaf: a higher layer that sets the list replaces it whole,\n * because \"the union of two partial lists\" has no answer an operator could\n * predict.\n */\n destinations: exportDestinationsSchema.optional(),\n /**\n * Per-destination retry spool bounds, each optional and merged per leaf; any\n * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.\n */\n spool: spoolPolicySchema.partial().optional(),\n /**\n * The most time one hook invocation spends trying to reach one endpoint, in\n * milliseconds: caps `timeoutMillis` for every OTLP request (connection setup\n * included) and the exporter's own retries inside it. A batch that does not\n * get through in time is spooled. Default {@link DEFAULT_EXPORT_BUDGET_MILLIS}:\n * the host agent waits for its hooks, so a down collector must not stall it.\n */\n exportBudgetMillis: z.number().int().min(50).max(600_000).optional(),\n /**\n * After an endpoint was unreachable (refused, timed out, or answered a\n * retryable status), every hook spools for it without trying for this long,\n * in milliseconds; then one hook probes it again. 0 disables the window.\n * Default {@link DEFAULT_ENDPOINT_DOWN_MILLIS}.\n */\n endpointDownMillis: z.number().int().min(0).max(3_600_000).optional(),\n});\nexport type ExporterPolicy = z.infer<typeof exporterPolicySchema>;\n\n/** Default `exporter.exportBudgetMillis`. */\nexport const DEFAULT_EXPORT_BUDGET_MILLIS = 1_500;\n/** Default `exporter.endpointDownMillis`. */\nexport const DEFAULT_ENDPOINT_DOWN_MILLIS = 30_000;\n\n/** The per-request OTLP timeout a hook uses: `timeoutMillis`, capped by the export budget. */\nexport const effectiveExportTimeoutMillis = (exporter: ExporterPolicy): number =>\n Math.min(exporter.timeoutMillis, exporter.exportBudgetMillis ?? DEFAULT_EXPORT_BUDGET_MILLIS);\n\nexport const detectionPolicySchema = z.strictObject({\n /** Detections below this confidence resolve to the unknown provider. */\n minimumConfidence: detectionConfidenceSchema,\n /** When false, an ambiguous detection is an error rather than unknown. */\n allowAmbiguousFallback: z.boolean(),\n /** Optional allow-list of provider ids; empty means \"any registered\". */\n allowedProviderIds: z.array(nonEmptyStringSchema).max(32).readonly(),\n});\nexport type DetectionPolicy = z.infer<typeof detectionPolicySchema>;\n\nexport const diagnosticsPolicySchema = z.strictObject({\n logLevel: z.enum([\"silent\", \"error\", \"warn\", \"info\", \"debug\"]),\n /** Emit `error.raised` events for contained failures. */\n emitErrorEvents: z.boolean(),\n});\nexport type DiagnosticsPolicy = z.infer<typeof diagnosticsPolicySchema>;\n\n/**\n * Per-provider behaviour that is not part of an adapter's parse.\n *\n * `claudeCode.readTranscriptUsage` is the one sanctioned exception to \"no\n * transcript reads in the hook\" (docs/claude-code-usage-contract.md, finding 8).\n * When true, the hook runtime — never the adapter — reads the session transcript\n * named by a Claude Code `Stop` / `StopFailure` payload, bounded, and attaches the\n * turn's model and summed token usage before the adapter parses it.\n *\n * `codex.readRolloutUsage` is the same exception for Codex, which puts no token\n * counters on any hook payload: at `Stop` the runtime reads the session's\n * rollout (`transcript_path`) from a per-session cursor, bounded, and attaches\n * the thread's running token total (docs/usage-semantics.md).\n *\n * Both off by default: without them, otel-hook reads no file a hook payload names.\n */\nexport const providersPolicySchema = z.strictObject({\n claudeCode: z\n .strictObject({\n readTranscriptUsage: z.boolean(),\n })\n .optional(),\n codex: z\n .strictObject({\n readRolloutUsage: z.boolean(),\n })\n .optional(),\n});\nexport type ProvidersPolicy = z.infer<typeof providersPolicySchema>;\n\n/**\n * Session context (`docs/session-context.md`): a directory a harness writes one\n * JSON file per agent session into, laid out `<dir>/<agent-tool>/<session-id>.json`.\n * With `dir` set, the hook reads that one file on every event and stamps the\n * attributes of the segment in force on every span, log record and metric point.\n * Absent (the default), nothing is read.\n *\n * Set in the configuration file or with `--session-context-dir`, never through\n * the environment: some agents (Claude Code) strip `OTEL_*` variables from the\n * hook processes they start.\n */\nexport const sessionContextPolicySchema = z.strictObject({\n /** Absolute path of the context directory. */\n dir: z\n .string()\n .min(1)\n .max(4096)\n .refine((value) => isAbsolute(value), { message: \"must be an absolute path\" }),\n});\nexport type SessionContextPolicy = z.infer<typeof sessionContextPolicySchema>;\n\nexport const otelHookConfigSchema = z.strictObject({\n exporter: exporterPolicySchema,\n privacy: privacyPolicySchema,\n detection: detectionPolicySchema,\n diagnostics: diagnosticsPolicySchema,\n /** Optional so a hand-built configuration from before it existed stays valid. */\n providers: providersPolicySchema.optional(),\n /** Optional: absent means no session context is read. */\n sessionContext: sessionContextPolicySchema.optional(),\n});\nexport type OtelHookConfig = z.infer<typeof otelHookConfigSchema>;\n\n/** Partial overlay accepted from a configuration layer. */\nexport const otelHookConfigPatchSchema = z.strictObject({\n // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:\n // merging happens per leaf, so a layer must be able to set `logs.enabled` alone\n // without also restating the endpoint and the batch size.\n exporter: exporterPolicySchema\n .omit({ logs: true, metrics: true, spool: true })\n .partial()\n .extend({\n logs: logsPolicySchema.partial().optional(),\n metrics: metricsPolicySchema.partial().optional(),\n spool: spoolPolicySchema.partial().optional(),\n })\n .optional(),\n privacy: privacyPolicySchema\n .omit({ limits: true })\n .partial()\n .extend({ limits: privacyPolicySchema.shape.limits.partial().optional() })\n .optional(),\n detection: detectionPolicySchema.partial().optional(),\n diagnostics: diagnosticsPolicySchema.partial().optional(),\n providers: z\n .strictObject({\n claudeCode: z.strictObject({ readTranscriptUsage: z.boolean() }).partial().optional(),\n codex: z.strictObject({ readRolloutUsage: z.boolean() }).partial().optional(),\n })\n .partial()\n .optional(),\n sessionContext: sessionContextPolicySchema.partial().optional(),\n});\nexport type OtelHookConfigPatch = z.infer<typeof otelHookConfigPatchSchema>;\n\nexport const DEFAULT_EXPORTER_POLICY: ExporterPolicy = Object.freeze({\n enabled: true,\n protocol: \"http/protobuf\",\n headerNames: Object.freeze([]),\n timeoutMillis: 10_000,\n maxBatchSize: 128,\n maxQueueSize: 2048,\n maxRetryAttempts: 2,\n serviceName: \"coding-agent\",\n resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,\n logs: DEFAULT_LOGS_POLICY,\n metrics: DEFAULT_METRICS_POLICY,\n});\n\nexport const DEFAULT_DETECTION_POLICY: DetectionPolicy = Object.freeze({\n minimumConfidence: \"strong\",\n allowAmbiguousFallback: true,\n allowedProviderIds: Object.freeze([]),\n});\n\nexport const DEFAULT_DIAGNOSTICS_POLICY: DiagnosticsPolicy = Object.freeze({\n logLevel: \"warn\",\n emitErrorEvents: true,\n});\n\nexport const DEFAULT_PROVIDERS_POLICY: ProvidersPolicy = Object.freeze({\n claudeCode: Object.freeze({ readTranscriptUsage: false }),\n codex: Object.freeze({ readRolloutUsage: false }),\n});\n\nexport const DEFAULT_CONFIG: OtelHookConfig = Object.freeze({\n exporter: DEFAULT_EXPORTER_POLICY,\n privacy: DEFAULT_PRIVACY_POLICY,\n detection: DEFAULT_DETECTION_POLICY,\n diagnostics: DEFAULT_DIAGNOSTICS_POLICY,\n providers: DEFAULT_PROVIDERS_POLICY,\n});\n\n/** Whether the runtime may read Claude Code transcripts at `Stop` (default false). */\nexport const readsClaudeTranscriptUsage = (config: OtelHookConfig): boolean =>\n config.providers?.claudeCode?.readTranscriptUsage === true;\n\n/** Whether the runtime may read Codex rollouts at `Stop` (default false). */\nexport const readsCodexRolloutUsage = (config: OtelHookConfig): boolean =>\n config.providers?.codex?.readRolloutUsage === true;\n\n/** The session context directory in force, or `undefined` when none is configured. */\nexport const sessionContextDir = (config: OtelHookConfig): string | undefined => config.sessionContext?.dir;\n\n/** Content mode is re-exported for callers building patches. */\nexport { contentModeSchema };\n\n/** The metrics policy in force, defaults filled in. */\nexport const effectiveMetricsPolicy = (exporter: ExporterPolicy): MetricsPolicy => ({\n ...DEFAULT_METRICS_POLICY,\n ...(exporter.metrics ?? {}),\n});\n","import { z } from \"zod\";\n\nimport { isUnsafeHeaderValue } from \"./header-value.js\";\nimport { MAX_OTLP_HEADERS } from \"./otlp-headers.js\";\nimport type { ExporterPolicy } from \"./schema.js\";\n\n/**\n * Export destinations: one batch, several OTLP endpoints.\n *\n * otel-hook is not a long-running process, so it cannot sit behind a proxy that\n * fans out for it. Instead every enabled destination is sent the same batch by the\n * same short-lived process, and what a destination could not take is kept in that\n * destination's own spool for the next invocation.\n *\n * ## The `default` destination\n *\n * The single-endpoint settings that predate this list — `exporter.endpoint`,\n * `exporter.logs.endpoint`, `exporter.protocol`, `--header`, and the standard\n * `OTEL_EXPORTER_OTLP_*` variables that feed them — describe one destination\n * named `default`. The name is therefore reserved: a `destinations[]` entry may\n * not take it, so there is exactly one place that destination is configured.\n *\n * A configuration with no `destinations` resolves to that one destination and\n * nothing else, exactly as before the list existed.\n */\n\nexport const DEFAULT_DESTINATION_NAME = \"default\";\n\n/**\n * Destination names become directory names (each destination spools on its own),\n * so they are held to a lowercase, filesystem-safe vocabulary rather than being\n * sanitized into something an operator would not recognize.\n */\nexport const DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;\n\nexport const MAX_EXPORT_DESTINATIONS = 16;\n/** The same bound `OTEL_EXPORTER_OTLP_*HEADERS` and `exporter.headerNames` have. */\nexport const MAX_DESTINATION_HEADERS = MAX_OTLP_HEADERS;\n\n/** Prefix of a header value that names an environment variable instead of holding a value. */\nexport const HEADER_ENV_REFERENCE_PREFIX = \"env:\";\n\n/** RFC 9110 `token`: the characters a header field name may use. */\nconst HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;\nconst ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;\nconst MAX_HEADER_VALUE_LENGTH = 8_192;\n\nexport const exportSignalSchema = z.enum([\"traces\", \"logs\", \"metrics\"]);\nexport type ExportSignal = z.infer<typeof exportSignalSchema>;\n\nconst headerValueSchema = z\n .string()\n .min(1)\n .max(MAX_HEADER_VALUE_LENGTH)\n // The rule `OTEL_EXPORTER_OTLP_*HEADERS` values are held to: a line break is a\n // request-splitting vector, and other controls or non-Latin-1 characters would\n // only make Node's HTTP client throw at send time.\n .refine(\n (value) => !isUnsafeHeaderValue(value),\n \"header values may not contain line breaks, control characters, or characters beyond Latin-1\",\n )\n .refine(\n (value) =>\n !value.startsWith(HEADER_ENV_REFERENCE_PREFIX) ||\n ENV_VARIABLE_NAME_PATTERN.test(value.slice(HEADER_ENV_REFERENCE_PREFIX.length)),\n \"an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN\",\n );\n\nconst endpointSchema = z.string().url().max(2048);\n\nexport const exportDestinationSchema = z\n .strictObject({\n /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */\n name: z\n .string()\n .regex(DESTINATION_NAME_PATTERN, \"destination names are lowercase letters, digits, _ and -\"),\n /** Default true. A disabled destination is neither sent to nor drained. */\n enabled: z.boolean().optional(),\n /**\n * Traces URL, with the same meaning as `exporter.endpoint`: the logs URL is\n * derived from it (`/v1/traces` becomes `/v1/logs`) unless `logsEndpoint` is set.\n */\n endpoint: endpointSchema.optional(),\n /** Per-signal override of `endpoint` for traces. */\n tracesEndpoint: endpointSchema.optional(),\n /** Per-signal override of the derived logs URL. */\n logsEndpoint: endpointSchema.optional(),\n /** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */\n metricsEndpoint: endpointSchema.optional(),\n /** Defaults to `exporter.protocol`. */\n protocol: z.enum([\"http/protobuf\", \"http/json\", \"none\"]).optional(),\n /**\n * Header name to value. A value of the form `env:NAME` is read from that\n * environment variable at send time, so a credential never has to be written\n * into the file. Values never appear in a snapshot, a diagnostic, or `doctor`.\n */\n headers: z\n .record(z.string().regex(HEADER_NAME_PATTERN, \"not a valid header name\"), headerValueSchema)\n .refine(\n (headers) => Object.keys(headers).length <= MAX_DESTINATION_HEADERS,\n `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`,\n )\n .optional(),\n /**\n * Which signals this destination receives. Default: traces and logs. The logs\n * signal is still governed by `exporter.logs.enabled`, which stays the one\n * opt-in for content-bearing records leaving the host. `metrics` is never on by\n * default: a destination receives hook-derived metrics only when it lists them.\n */\n signals: z.array(exportSignalSchema).min(1).max(3).readonly().optional(),\n })\n .refine(\n (destination) =>\n destination.endpoint !== undefined ||\n destination.tracesEndpoint !== undefined ||\n destination.logsEndpoint !== undefined ||\n destination.metricsEndpoint !== undefined,\n \"a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint\",\n );\nexport type ExportDestinationConfig = z.infer<typeof exportDestinationSchema>;\n\n/** Signals a destination receives when it does not list any: never metrics. */\nexport const DEFAULT_DESTINATION_SIGNALS: readonly ExportSignal[] = Object.freeze([\"traces\", \"logs\"]);\n\nexport const exportDestinationsSchema = z\n .array(exportDestinationSchema)\n .max(MAX_EXPORT_DESTINATIONS)\n .readonly()\n .superRefine((destinations, context) => {\n const seen = new Set<string>();\n destinations.forEach((destination, index) => {\n if (destination.name === DEFAULT_DESTINATION_NAME) {\n context.addIssue({\n code: \"custom\",\n path: [index, \"name\"],\n message:\n 'the name \"default\" is reserved for exporter.endpoint and the OTEL_EXPORTER_OTLP_* variables',\n });\n }\n if (seen.has(destination.name)) {\n context.addIssue({\n code: \"custom\",\n path: [index, \"name\"],\n message: `duplicate destination name \"${destination.name}\"`,\n });\n }\n seen.add(destination.name);\n });\n });\n\n/**\n * Bounds on each destination's retry spool, per signal.\n *\n * Every destination spools independently, so one long outage can only ever cost\n * its own budget. When a bound is reached the *oldest* batches are dropped first —\n * a recent batch is the one a reader is still likely to look for — and every drop\n * is counted on disk so `doctor` can report it.\n */\nexport const spoolPolicySchema = z.strictObject({\n /** Total bytes of queued batches. Default 16 MiB. */\n maxBytes: z.number().int().min(1_024).max(1_073_741_824),\n /** A batch older than this is dropped instead of sent. Default 72 hours. */\n maxAgeMillis: z.number().int().min(1_000).max(30 * 24 * 60 * 60 * 1000),\n /** Number of queued batches. Default 500. */\n maxBatches: z.number().int().min(1).max(65_536),\n});\nexport type SpoolPolicy = z.infer<typeof spoolPolicySchema>;\n\nexport const DEFAULT_SPOOL_POLICY: SpoolPolicy = Object.freeze({\n maxBytes: 16 * 1024 * 1024,\n maxAgeMillis: 72 * 60 * 60 * 1000,\n maxBatches: 500,\n});\n\n/** The spool policy in force, with defaults filled in for any bound left unset. */\nexport const effectiveSpoolPolicy = (exporter: ExporterPolicy): SpoolPolicy => ({\n maxBytes: exporter.spool?.maxBytes ?? DEFAULT_SPOOL_POLICY.maxBytes,\n maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,\n maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches,\n});\n\n/**\n * One destination as the runtime sends to it.\n *\n * `headers` holds what the configuration holds — literal values and `env:`\n * references, unresolved. Resolution against an environment happens only at the\n * point of sending ({@link resolveDestinationHeaders}), and the `default`\n * destination's header values never pass through configuration at all: they are\n * handed to the runtime separately, as they always have been.\n */\nexport type ExportDestination = {\n readonly name: string;\n /** `exporter` for the `default` destination, `destinations` for a list entry. */\n readonly source: \"exporter\" | \"destinations\";\n readonly protocol: ExporterPolicy[\"protocol\"];\n /** Traces URL as configured; for `default` this is `exporter.endpoint`. */\n readonly endpoint?: string;\n readonly tracesEndpoint?: string;\n readonly logsEndpoint?: string;\n readonly metricsEndpoint?: string;\n readonly signals: { readonly traces: boolean; readonly logs: boolean; readonly metrics: boolean };\n readonly headers: Readonly<Record<string, string>>;\n};\n\nconst legacyDestination = (exporter: ExporterPolicy): ExportDestination => ({\n name: DEFAULT_DESTINATION_NAME,\n source: \"exporter\",\n protocol: exporter.protocol,\n ...(exporter.endpoint === undefined ? {} : { endpoint: exporter.endpoint }),\n ...(exporter.logs.endpoint === undefined ? {} : { logsEndpoint: exporter.logs.endpoint }),\n ...(exporter.metrics?.endpoint === undefined ? {} : { metricsEndpoint: exporter.metrics.endpoint }),\n signals: { traces: true, logs: exporter.logs.enabled, metrics: exporter.metrics?.enabled === true },\n headers: {},\n});\n\n/** Whether a configuration uses the destination list at all. */\nexport const hasConfiguredDestinations = (exporter: ExporterPolicy): boolean =>\n exporter.destinations !== undefined && exporter.destinations.length > 0;\n\n/**\n * The destinations an exporter policy sends to, in a stable order: `default`\n * first when present, then the list in file order.\n *\n * - No `destinations`: exactly one `default` destination, even when it has no\n * endpoint — the sink then reports itself unconfigured, as it always has.\n * - With `destinations`: `default` is included only when a single-endpoint setting\n * actually names an endpoint, and disabled entries are left out.\n */\nexport const resolveExportDestinations = (\n exporter: ExporterPolicy,\n): readonly ExportDestination[] => {\n if (!hasConfiguredDestinations(exporter)) {\n return [legacyDestination(exporter)];\n }\n const resolved: ExportDestination[] = [];\n if (\n exporter.endpoint !== undefined ||\n exporter.logs.endpoint !== undefined ||\n exporter.metrics?.endpoint !== undefined\n ) {\n resolved.push(legacyDestination(exporter));\n }\n for (const destination of exporter.destinations ?? []) {\n if (destination.enabled === false) {\n continue;\n }\n const signals: readonly ExportSignal[] = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;\n resolved.push({\n name: destination.name,\n source: \"destinations\",\n protocol: destination.protocol ?? exporter.protocol,\n ...(destination.endpoint === undefined ? {} : { endpoint: destination.endpoint }),\n ...(destination.tracesEndpoint === undefined\n ? {}\n : { tracesEndpoint: destination.tracesEndpoint }),\n ...(destination.logsEndpoint === undefined ? {} : { logsEndpoint: destination.logsEndpoint }),\n ...(destination.metricsEndpoint === undefined\n ? {}\n : { metricsEndpoint: destination.metricsEndpoint }),\n signals: {\n traces: signals.includes(\"traces\"),\n logs: exporter.logs.enabled && signals.includes(\"logs\"),\n metrics: signals.includes(\"metrics\"),\n },\n headers: { ...(destination.headers ?? {}) },\n });\n }\n return resolved;\n};\n\n/** A header value's meaning, without its content. */\nexport type HeaderValueReference =\n | { readonly kind: \"literal\" }\n | { readonly kind: \"env\"; readonly variable: string };\n\nexport const parseHeaderValueReference = (value: string): HeaderValueReference =>\n value.startsWith(HEADER_ENV_REFERENCE_PREFIX)\n ? { kind: \"env\", variable: value.slice(HEADER_ENV_REFERENCE_PREFIX.length) }\n : { kind: \"literal\" };\n\nexport type ResolvedDestinationHeaders = {\n /** Header values ready to send. Never logged, never reported. */\n readonly values: Readonly<Record<string, string>>;\n /** Names of referenced environment variables that are unset or empty. */\n readonly missingVariables: readonly string[];\n};\n\n/**\n * Resolve `env:` references against an explicitly supplied environment.\n *\n * Pure: the process environment is never read implicitly. An unset or empty\n * variable is reported by *name* — the only part of a reference that is safe to\n * say out loud — and its header is left out of `values`.\n */\nexport const resolveDestinationHeaders = (\n headers: Readonly<Record<string, string>>,\n environment: Readonly<Record<string, string | undefined>> | undefined,\n): ResolvedDestinationHeaders => {\n const values: Record<string, string> = {};\n const missing: string[] = [];\n for (const [name, value] of Object.entries(headers)) {\n const reference = parseHeaderValueReference(value);\n if (reference.kind === \"literal\") {\n values[name] = value;\n continue;\n }\n const resolved = environment?.[reference.variable];\n if (resolved === undefined || resolved === \"\") {\n missing.push(reference.variable);\n continue;\n }\n values[name] = resolved;\n }\n return { values, missingVariables: [...new Set(missing)].sort() };\n};\n\n/**\n * Attribute-safe description of one destination: names, origins, and variable\n * names. Never a header value, and never an endpoint beyond its origin.\n */\nexport type DestinationDescription = {\n readonly name: string;\n readonly enabled: boolean;\n readonly protocol: ExporterPolicy[\"protocol\"];\n readonly signals: readonly ExportSignal[];\n readonly tracesEndpointOrigin?: string;\n readonly logsEndpointOrigin?: string;\n readonly metricsEndpointOrigin?: string;\n readonly headerNames: readonly string[];\n /** Environment variables this destination's headers reference. */\n readonly headerVariables: readonly string[];\n};\n\nexport const endpointOrigin = (endpoint: string | undefined): string | undefined => {\n if (endpoint === undefined) {\n return undefined;\n }\n try {\n return new URL(endpoint).origin;\n } catch {\n return \"<unparsable>\";\n }\n};\n\n/** Every configured destination, disabled ones included, for `doctor` and snapshots. */\nexport const describeExportDestinations = (\n exporter: ExporterPolicy,\n): readonly DestinationDescription[] => {\n const describe = (\n destination: ExportDestination,\n enabled: boolean,\n ): DestinationDescription => {\n const tracesOrigin = endpointOrigin(destination.tracesEndpoint ?? destination.endpoint);\n const logsOrigin = endpointOrigin(\n destination.logsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint,\n );\n const metricsOrigin = endpointOrigin(\n destination.metricsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint,\n );\n const variables = Object.values(destination.headers)\n .map(parseHeaderValueReference)\n .flatMap((reference) => (reference.kind === \"env\" ? [reference.variable] : []));\n return {\n name: destination.name,\n enabled,\n protocol: destination.protocol,\n signals: exportSignalSchema.options.filter((signal) => destination.signals[signal]),\n ...(tracesOrigin === undefined || !destination.signals.traces\n ? {}\n : { tracesEndpointOrigin: tracesOrigin }),\n ...(logsOrigin === undefined || !destination.signals.logs\n ? {}\n : { logsEndpointOrigin: logsOrigin }),\n ...(metricsOrigin === undefined || !destination.signals.metrics\n ? {}\n : { metricsEndpointOrigin: metricsOrigin }),\n headerNames:\n destination.source === \"exporter\"\n ? [...exporter.headerNames].sort()\n : Object.keys(destination.headers).sort(),\n headerVariables: [...new Set(variables)].sort(),\n };\n };\n const enabled = resolveExportDestinations(exporter).map((destination) =>\n describe(destination, true),\n );\n const disabled = (exporter.destinations ?? [])\n .filter((destination) => destination.enabled === false)\n .map((destination) =>\n describe(\n {\n name: destination.name,\n source: \"destinations\",\n protocol: destination.protocol ?? exporter.protocol,\n ...(destination.endpoint === undefined ? {} : { endpoint: destination.endpoint }),\n signals: { traces: false, logs: false, metrics: false },\n headers: { ...(destination.headers ?? {}) },\n },\n false,\n ),\n );\n return [...enabled, ...disabled];\n};\n","/**\n * Internal: shared by `OTEL_EXPORTER_OTLP_*HEADERS` parsing and the\n * `exporter.destinations[].headers` schema. Not re-exported from the package.\n */\n\n/**\n * Characters an HTTP field value must not contain once decoded. CR and LF would\n * split the request; the other controls and anything beyond Latin-1 are refused\n * by Node's HTTP client anyway, and refusing them here turns a failed export into\n * a reported, skipped entry.\n */\nexport const isUnsafeHeaderValue = (value: string): boolean =>\n [...value].some((char) => {\n const code = char.codePointAt(0) ?? 0;\n return (code < 0x20 && code !== 0x09) || code === 0x7f || code > 0xff;\n });\n","/**\n * The standard OTLP exporter header variables.\n *\n * `OTEL_EXPORTER_OTLP_HEADERS` applies to every signal;\n * `OTEL_EXPORTER_OTLP_TRACES_HEADERS` and `OTEL_EXPORTER_OTLP_LOGS_HEADERS`\n * apply to one signal each. They exist so a credential (`authorization=Basic …`)\n * can reach the exporter without being written on a command line, where `ps` and\n * `/proc/<pid>/cmdline` would show it to every local user.\n *\n * Header *values* never enter configuration. Parsing returns them to the caller,\n * which hands them straight to the sink at construction; configuration carries\n * header *names* only (`exporter.headerNames`), because a resolved-config\n * snapshot is logged and exported. Every diagnostic here names an entry by its\n * position and the variable by its name — never a key, never a value — because a\n * malformed entry may be the secret itself (`Basic abc` with no `=`).\n */\n\nimport { isUnsafeHeaderValue } from \"./header-value.js\";\n\n/** Upper bound on headers per variable, matching `exporter.headerNames`. */\nexport const MAX_OTLP_HEADERS = 32;\n\nexport const OTLP_HEADER_VARIABLES = Object.freeze({\n generic: \"OTEL_EXPORTER_OTLP_HEADERS\",\n traces: \"OTEL_EXPORTER_OTLP_TRACES_HEADERS\",\n logs: \"OTEL_EXPORTER_OTLP_LOGS_HEADERS\",\n});\n\n/** RFC 9110 `token`: the characters an HTTP field name may contain. */\nconst HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n\nexport type ParsedOtlpHeaders = {\n readonly headers: Readonly<Record<string, string>>;\n /** Position-only explanations; never a key or a value. */\n readonly warnings: readonly string[];\n};\n\nconst decode = (raw: string): string | undefined => {\n try {\n return decodeURIComponent(raw);\n } catch {\n return undefined;\n }\n};\n\n/**\n * Parse one `OTEL_EXPORTER_OTLP_*HEADERS` value.\n *\n * The OpenTelemetry exporter specification defines the format as W3C\n * Baggage-like: comma-separated `key=value` pairs, surrounding whitespace\n * trimmed, keys and values percent-decoded. So `authorization=Basic%20abc` is\n * the header `authorization: Basic abc`, and a `,` inside a value must be\n * written `%2C`. A malformed entry is skipped and reported; the rest of the\n * variable still applies. A repeated key takes its last value.\n */\nexport const parseOtlpHeadersValue = (raw: string): ParsedOtlpHeaders => {\n const headers: Record<string, string> = {};\n const warnings: string[] = [];\n let overflowed = false;\n\n for (const [index, rawEntry] of raw.split(\",\").entries()) {\n const position = String(index + 1);\n const entry = rawEntry.trim();\n if (entry === \"\") {\n continue;\n }\n const equals = entry.indexOf(\"=\");\n if (equals <= 0) {\n warnings.push(`entry ${position} is not a key=value pair; ignored`);\n continue;\n }\n const key = decode(entry.slice(0, equals).trim());\n // Split on the first `=` only: a base64 credential ends in `=` padding.\n const value = decode(entry.slice(equals + 1).trim());\n if (key === undefined || value === undefined) {\n warnings.push(`entry ${position} has malformed percent-encoding; ignored`);\n continue;\n }\n const name = key.trim();\n const trimmedValue = value.trim();\n if (!HEADER_NAME_PATTERN.test(name)) {\n warnings.push(`entry ${position} does not name a valid HTTP header; ignored`);\n continue;\n }\n if (trimmedValue === \"\") {\n warnings.push(`entry ${position} has an empty value; ignored`);\n continue;\n }\n if (isUnsafeHeaderValue(trimmedValue)) {\n warnings.push(`entry ${position} has a character not allowed in an HTTP header value; ignored`);\n continue;\n }\n const existing = findHeaderName(headers, name);\n if (existing === undefined && Object.keys(headers).length >= MAX_OTLP_HEADERS) {\n overflowed = true;\n continue;\n }\n if (existing !== undefined) {\n delete headers[existing];\n }\n headers[name] = trimmedValue;\n }\n\n if (overflowed) {\n warnings.push(`more than ${String(MAX_OTLP_HEADERS)} headers were supplied; the excess was ignored`);\n }\n return { headers, warnings };\n};\n\n/** HTTP field names are case-insensitive: `Authorization` and `authorization` are one header. */\nconst findHeaderName = (headers: Readonly<Record<string, string>>, name: string): string | undefined => {\n const lower = name.toLowerCase();\n return Object.keys(headers).find((candidate) => candidate.toLowerCase() === lower);\n};\n\n/**\n * Overlay header maps, lowest precedence first, per header name.\n *\n * A higher source replaces only the names it sets (case-insensitively), so a\n * signal-specific variable can override `authorization` while a generic tenant\n * header still applies — the same per-key merge the OpenTelemetry SDKs apply.\n */\nexport const mergeOtlpHeaders = (\n ...sources: readonly Readonly<Record<string, string>>[]\n): Readonly<Record<string, string>> => {\n const merged: Record<string, string> = {};\n for (const source of sources) {\n for (const [name, value] of Object.entries(source)) {\n const existing = findHeaderName(merged, name);\n if (existing !== undefined) {\n delete merged[existing];\n }\n merged[name] = value;\n }\n }\n return merged;\n};\n\nexport type ResolvedOtlpHeaders = {\n /** Headers for the traces exporter. */\n readonly traces: Readonly<Record<string, string>>;\n /** Headers for the logs exporter. */\n readonly logs: Readonly<Record<string, string>>;\n /** Variable-qualified, value-free explanations of skipped entries. */\n readonly warnings: readonly { readonly variable: string; readonly detail: string }[];\n};\n\n/**\n * Resolve exporter headers per signal.\n *\n * Precedence, per header name, highest first:\n *\n * ```\n * explicit headers (--header) > OTEL_EXPORTER_OTLP_{TRACES,LOGS}_HEADERS > OTEL_EXPORTER_OTLP_HEADERS\n * ```\n *\n * Pure: the environment is passed in, never read from `process.env`.\n */\nexport const resolveOtlpHeaders = (\n env: Readonly<Record<string, string | undefined>>,\n explicit: Readonly<Record<string, string>> = {},\n): ResolvedOtlpHeaders => {\n const warnings: { variable: string; detail: string }[] = [];\n const read = (variable: string): Readonly<Record<string, string>> => {\n const raw = env[variable];\n if (raw === undefined || raw.trim() === \"\") {\n return {};\n }\n const parsed = parseOtlpHeadersValue(raw);\n for (const detail of parsed.warnings) {\n warnings.push({ variable, detail });\n }\n return parsed.headers;\n };\n const generic = read(OTLP_HEADER_VARIABLES.generic);\n const traces = read(OTLP_HEADER_VARIABLES.traces);\n const logs = read(OTLP_HEADER_VARIABLES.logs);\n return {\n traces: mergeOtlpHeaders(generic, traces, explicit),\n logs: mergeOtlpHeaders(generic, logs, explicit),\n warnings,\n };\n};\n\n/**\n * Header names, deduplicated case-insensitively (first spelling kept), sorted\n * and bounded — the only part of a header that may enter configuration or a\n * diagnostic.\n */\nexport const unionOtlpHeaderNames = (...lists: readonly (readonly string[])[]): readonly string[] => {\n const names: string[] = [];\n const seen = new Set<string>();\n for (const name of lists.flat()) {\n if (!seen.has(name.toLowerCase())) {\n seen.add(name.toLowerCase());\n names.push(name);\n }\n }\n return names.sort().slice(0, MAX_OTLP_HEADERS);\n};\n\n/** {@link unionOtlpHeaderNames} over the names of header maps. */\nexport const describeOtlpHeaderNames = (\n ...sources: readonly Readonly<Record<string, string>>[]\n): readonly string[] => unionOtlpHeaderNames(...sources.map((source) => Object.keys(source)));\n","import { z } from \"zod\";\n\nimport { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { Attributes } from \"../model/primitives.js\";\nimport {\n describeExportDestinations,\n effectiveSpoolPolicy,\n hasConfiguredDestinations,\n} from \"./destinations.js\";\nimport { describeResourceAttributeNames } from \"./resource-attributes.js\";\nimport {\n DEFAULT_CONFIG,\n effectiveMetricsPolicy,\n otelHookConfigPatchSchema,\n otelHookConfigSchema,\n type OtelHookConfig,\n type OtelHookConfigPatch,\n} from \"./schema.js\";\n\n/**\n * Configuration layers, lowest precedence first.\n *\n * Precedence is fixed and total: `inline-override` beats `environment`, which\n * beats `file`, which beats `defaults`. There is no partial-merge surprise —\n * merging happens per leaf field, so a file may set an endpoint while the\n * environment sets only a content mode.\n *\n * `exporter.resourceAttributes` follows the same rule one level deeper: each\n * *attribute key* is its own leaf. A file may set `deployment.environment`\n * while `OTEL_RESOURCE_ATTRIBUTES` adds `service.instance.id` and\n * `--resource-attr` overrides just one of them; the result is the union, with\n * the highest-precedence layer winning per key and provenance recorded per key.\n * A layer cannot *remove* a key a lower layer set — precedence is an override\n * relation, not a replacement one.\n */\nexport const CONFIG_SOURCE_PRECEDENCE = [\"defaults\", \"file\", \"environment\", \"inline-override\"] as const;\nexport type ConfigSource = (typeof CONFIG_SOURCE_PRECEDENCE)[number];\n\nexport const configSourceSchema = z.enum(CONFIG_SOURCE_PRECEDENCE);\n\nexport type ConfigLayer = {\n readonly source: Exclude<ConfigSource, \"defaults\">;\n readonly patch: OtelHookConfigPatch;\n /** Non-sensitive origin label, e.g. a file name without its directory. */\n readonly origin?: string;\n};\n\n/** Which layer supplied each resolved leaf, keyed by `section.field` path. */\nexport type ConfigProvenance = Readonly<Record<string, ConfigSource>>;\n\nexport type ConfigResolution =\n | {\n readonly status: \"ok\";\n readonly config: OtelHookConfig;\n readonly provenance: ConfigProvenance;\n readonly notes: readonly string[];\n }\n | { readonly status: \"invalid\"; readonly errors: readonly OtelHookErrorInfo[] };\n\ntype PlainRecord = Record<string, unknown>;\n\nconst isPlainObject = (value: unknown): value is PlainRecord =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst mergeLeaf = (\n target: PlainRecord,\n patch: PlainRecord,\n source: ConfigSource,\n provenance: Record<string, ConfigSource>,\n path: string,\n): void => {\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) {\n continue;\n }\n const childPath = path === \"\" ? key : `${path}.${key}`;\n const existing = target[key];\n // An object with no counterpart yet (an optional section such as\n // `exporter.spool`) is merged into an empty one, so its leaves get provenance\n // of their own and a later layer can set one of them without restating the rest.\n if (isPlainObject(value) && (isPlainObject(existing) || existing === undefined)) {\n const child: PlainRecord = { ...(existing ?? {}) };\n mergeLeaf(child, value, source, provenance, childPath);\n target[key] = child;\n continue;\n }\n target[key] = value;\n provenance[childPath] = source;\n }\n};\n\nconst initialProvenance = (config: OtelHookConfig): Record<string, ConfigSource> => {\n const provenance: Record<string, ConfigSource> = {};\n const walk = (value: unknown, path: string): void => {\n if (isPlainObject(value)) {\n for (const [key, child] of Object.entries(value)) {\n walk(child, path === \"\" ? key : `${path}.${key}`);\n }\n return;\n }\n provenance[path] = \"defaults\";\n };\n walk(config, \"\");\n return provenance;\n};\n\n/**\n * Resolve configuration from layered patches.\n *\n * Invalid layers are rejected rather than partially applied: a half-applied\n * privacy policy is exactly the failure mode this contract exists to prevent.\n * Callers that must not fail hard should fall back to {@link DEFAULT_CONFIG},\n * which is always valid.\n */\nexport const resolveConfig = (layers: readonly ConfigLayer[] = []): ConfigResolution => {\n const errors: OtelHookErrorInfo[] = [];\n const ordered = [...layers].sort(\n (a, b) =>\n CONFIG_SOURCE_PRECEDENCE.indexOf(a.source) - CONFIG_SOURCE_PRECEDENCE.indexOf(b.source),\n );\n\n const validated: { source: ConfigSource; patch: PlainRecord }[] = [];\n for (const layer of ordered) {\n const parsed = otelHookConfigPatchSchema.safeParse(layer.patch);\n if (!parsed.success) {\n errors.push(\n createErrorInfo({\n code: \"configuration-invalid\",\n phase: \"configuration\",\n detail: `layer ${layer.source} rejected: ${parsed.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`)\n .join(\"; \")}`.slice(0, 480),\n details: {\n \"config.layer\": layer.source,\n ...(layer.origin === undefined ? {} : { \"config.origin\": layer.origin }),\n },\n }),\n );\n continue;\n }\n validated.push({ source: layer.source, patch: parsed.data });\n }\n\n if (errors.length > 0) {\n return { status: \"invalid\", errors };\n }\n\n const merged: PlainRecord = structuredClone(DEFAULT_CONFIG);\n const provenance = initialProvenance(DEFAULT_CONFIG);\n for (const layer of validated) {\n mergeLeaf(merged, layer.patch, layer.source, provenance, \"\");\n }\n\n const parsed = otelHookConfigSchema.safeParse(merged);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n errors: [\n createErrorInfo({\n code: \"configuration-invalid\",\n phase: \"configuration\",\n detail: `merged configuration rejected: ${parsed.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`)\n .join(\"; \")}`.slice(0, 480),\n }),\n ],\n };\n }\n\n const notes: string[] = [];\n if (parsed.data.privacy.contentMode === \"raw\" && !parsed.data.privacy.allowRawContent) {\n notes.push(\"privacy.contentMode=raw will be downgraded to omit: allowRawContent is false\");\n }\n const withDestinations = hasConfiguredDestinations(parsed.data.exporter);\n if (\n parsed.data.exporter.enabled &&\n parsed.data.exporter.protocol !== \"none\" &&\n parsed.data.exporter.endpoint === undefined &&\n !withDestinations\n ) {\n notes.push(\"exporter.enabled is true but no endpoint is configured\");\n }\n if (withDestinations) {\n const enabled = (parsed.data.exporter.destinations ?? []).filter(\n (destination) => destination.enabled !== false,\n );\n if (enabled.length === 0 && parsed.data.exporter.endpoint === undefined) {\n notes.push(\"exporter.destinations is set but every destination is disabled\");\n }\n if (!parsed.data.exporter.logs.enabled) {\n const askingForLogs = enabled\n .filter((destination) => destination.signals?.includes(\"logs\") === true)\n .map((destination) => destination.name);\n if (askingForLogs.length > 0) {\n notes.push(\n `destination(s) ${askingForLogs.join(\", \")} list the logs signal but exporter.logs.enabled is false, so only traces are sent`,\n );\n }\n }\n }\n if (\n !withDestinations &&\n parsed.data.exporter.logs.enabled &&\n parsed.data.exporter.logs.endpoint === undefined &&\n parsed.data.exporter.endpoint === undefined\n ) {\n notes.push(\n \"exporter.logs.enabled is true but neither a logs endpoint nor a trace endpoint to derive one from is configured\",\n );\n }\n if (\n !withDestinations &&\n parsed.data.exporter.metrics?.enabled === true &&\n parsed.data.exporter.metrics.endpoint === undefined &&\n parsed.data.exporter.endpoint === undefined\n ) {\n notes.push(\n \"exporter.metrics.enabled is true but neither a metrics endpoint nor a trace endpoint to derive one from is configured\",\n );\n }\n if (parsed.data.exporter.logs.includeContent && parsed.data.privacy.contentMode === \"omit\") {\n // Not an error: the two settings are independent by design, and this is the\n // combination somebody lands on when they enable one and forget the other. Said\n // out loud because the symptom — every log body withheld — looks like a bug.\n notes.push(\n \"exporter.logs.includeContent is true but privacy.contentMode is omit, so no content is disclosed to describe\",\n );\n }\n\n return { status: \"ok\", config: parsed.data, provenance, notes };\n};\n\n/**\n * Destination attributes for the snapshot, present only when the list is in use,\n * so a configuration without destinations snapshots exactly as it always has.\n * Names, origins, and variable names only — never a header value.\n */\nconst describeDestinationAttributes = (config: OtelHookConfig): Attributes => {\n const attributes: Record<string, string | boolean | number | string[]> = {};\n if (config.exporter.spool !== undefined || hasConfiguredDestinations(config.exporter)) {\n const spool = effectiveSpoolPolicy(config.exporter);\n attributes[\"exporter.spool_max_bytes\"] = spool.maxBytes;\n attributes[\"exporter.spool_max_age_millis\"] = spool.maxAgeMillis;\n attributes[\"exporter.spool_max_batches\"] = spool.maxBatches;\n }\n if (!hasConfiguredDestinations(config.exporter)) {\n return attributes;\n }\n const destinations = describeExportDestinations(config.exporter);\n attributes[\"exporter.destination_names\"] = destinations.map((destination) => destination.name);\n for (const destination of destinations) {\n const prefix = `exporter.destination.${destination.name}`;\n attributes[`${prefix}.enabled`] = destination.enabled;\n attributes[`${prefix}.protocol`] = destination.protocol;\n attributes[`${prefix}.signals`] = [...destination.signals];\n if (destination.tracesEndpointOrigin !== undefined) {\n attributes[`${prefix}.traces_endpoint_origin`] = destination.tracesEndpointOrigin;\n }\n if (destination.logsEndpointOrigin !== undefined) {\n attributes[`${prefix}.logs_endpoint_origin`] = destination.logsEndpointOrigin;\n }\n if (destination.metricsEndpointOrigin !== undefined) {\n attributes[`${prefix}.metrics_endpoint_origin`] = destination.metricsEndpointOrigin;\n }\n attributes[`${prefix}.header_names`] = [...destination.headerNames];\n attributes[`${prefix}.header_variables`] = [...destination.headerVariables];\n }\n return attributes;\n};\n\n/**\n * Attribute-safe snapshot of resolved configuration, for logging and telemetry.\n *\n * Endpoints are reduced to origin form and header values never appear, because a\n * snapshot is exported to the very system whose credentials it would leak.\n */\nexport const describeResolvedConfig = (config: OtelHookConfig): Attributes => {\n const originOf = (endpoint: string | undefined): string | undefined => {\n if (endpoint === undefined) {\n return undefined;\n }\n try {\n return new URL(endpoint).origin;\n } catch {\n return \"<unparsable>\";\n }\n };\n const endpointOrigin = originOf(config.exporter.endpoint);\n const logsEndpointOrigin = originOf(config.exporter.logs.endpoint);\n const metrics = effectiveMetricsPolicy(config.exporter);\n const metricsEndpointOrigin = originOf(metrics.endpoint);\n return {\n \"exporter.enabled\": config.exporter.enabled,\n \"exporter.protocol\": config.exporter.protocol,\n ...(endpointOrigin === undefined ? {} : { \"exporter.endpoint_origin\": endpointOrigin }),\n \"exporter.logs_enabled\": config.exporter.logs.enabled,\n \"exporter.logs_include_content\": config.exporter.logs.includeContent,\n \"exporter.logs_max_batch_size\": config.exporter.logs.maxBatchSize,\n ...(logsEndpointOrigin === undefined\n ? {}\n : { \"exporter.logs_endpoint_origin\": logsEndpointOrigin }),\n \"exporter.metrics_enabled\": metrics.enabled,\n \"exporter.metrics_temporality\": metrics.temporality,\n \"exporter.metrics_include_session_id\": metrics.includeSessionId,\n ...(metricsEndpointOrigin === undefined\n ? {}\n : { \"exporter.metrics_endpoint_origin\": metricsEndpointOrigin }),\n \"exporter.header_names\": [...config.exporter.headerNames],\n // Names only. A resource attribute *name* is already on the wire in every\n // exported resource, so disclosing it here adds nothing; a *value* may hold\n // whatever an operator put in a shell profile, so it never appears.\n \"exporter.resource_attribute_names\": [\n ...describeResourceAttributeNames(config.exporter.resourceAttributes),\n ],\n ...describeDestinationAttributes(config),\n \"exporter.timeout_millis\": config.exporter.timeoutMillis,\n \"exporter.max_batch_size\": config.exporter.maxBatchSize,\n \"exporter.service_name\": config.exporter.serviceName,\n \"privacy.content_mode\": config.privacy.contentMode,\n \"privacy.allow_raw_content\": config.privacy.allowRawContent,\n \"privacy.hash_salted\": config.privacy.hashSalt.length > 0,\n \"privacy.max_string_length\": config.privacy.limits.maxStringLength,\n \"privacy.max_depth\": config.privacy.limits.maxDepth,\n \"privacy.max_array_length\": config.privacy.limits.maxArrayLength,\n \"privacy.max_events_per_invocation\": config.privacy.limits.maxEventsPerInvocation,\n \"detection.minimum_confidence\": config.detection.minimumConfidence,\n \"detection.allow_ambiguous_fallback\": config.detection.allowAmbiguousFallback,\n \"diagnostics.log_level\": config.diagnostics.logLevel,\n \"diagnostics.emit_error_events\": config.diagnostics.emitErrorEvents,\n // Whether, never where: the directory is a local path.\n \"session_context.enabled\": config.sessionContext?.dir !== undefined,\n };\n};\n","import { z } from \"zod\";\n\nimport { attributesSchema, epochMillisSchema, type Attributes } from \"../model/primitives.js\";\nimport {\n describeErrorCode,\n errorPhaseSchema,\n errorSeveritySchema,\n failurePostureSchema,\n otelHookErrorCodeSchema,\n type ErrorPhase,\n type OtelHookErrorCode,\n} from \"./taxonomy.js\";\n\nexport * from \"./taxonomy.js\";\n\n/**\n * Serializable, privacy-safe description of a failure.\n *\n * `message` is a fixed-vocabulary summary derived from the code and phase, never\n * a provider or exception string, because exception messages routinely contain\n * prompt text, file paths, and credentials. `details` is restricted to attribute\n * primitives for the same reason.\n */\nexport const otelHookErrorInfoSchema = z.strictObject({\n code: otelHookErrorCodeSchema,\n severity: errorSeveritySchema,\n phase: errorPhaseSchema,\n posture: failurePostureSchema,\n retryable: z.boolean(),\n message: z.string().min(1).max(512),\n details: attributesSchema.optional(),\n occurredAt: epochMillisSchema.optional(),\n});\nexport type OtelHookErrorInfo = z.infer<typeof otelHookErrorInfoSchema>;\n\nexport type CreateErrorInfoInput = {\n readonly code: OtelHookErrorCode;\n readonly phase: ErrorPhase;\n /** Short, non-sensitive detail, e.g. `\"2 adapters matched\"`. */\n readonly detail?: string;\n readonly details?: Attributes;\n readonly occurredAt?: number;\n};\n\nexport const createErrorInfo = (input: CreateErrorInfoInput): OtelHookErrorInfo => {\n const descriptor = describeErrorCode(input.code);\n const message =\n input.detail === undefined\n ? `${input.code} during ${input.phase}: ${descriptor.summary}`\n : `${input.code} during ${input.phase}: ${input.detail}`;\n return otelHookErrorInfoSchema.parse({\n code: descriptor.code,\n severity: descriptor.severity,\n phase: input.phase,\n posture: descriptor.posture,\n retryable: descriptor.retryable,\n message: message.slice(0, 512),\n ...(input.details === undefined ? {} : { details: input.details }),\n ...(input.occurredAt === undefined ? {} : { occurredAt: input.occurredAt }),\n });\n};\n\nexport class OtelHookError extends Error {\n public readonly info: OtelHookErrorInfo;\n\n public constructor(info: OtelHookErrorInfo) {\n super(info.message);\n this.name = \"OtelHookError\";\n this.info = info;\n }\n\n public static of(input: CreateErrorInfoInput): OtelHookError {\n return new OtelHookError(createErrorInfo(input));\n }\n}\n\nexport const isOtelHookError = (value: unknown): value is OtelHookError =>\n value instanceof OtelHookError;\n\n/**\n * Describe an arbitrary thrown value without disclosing its message.\n *\n * Only the constructor name crosses the boundary; the presence of a message is\n * reported as a boolean so operators can tell \"threw nothing useful\" from\n * \"threw something we deliberately did not log\".\n */\nexport const describeThrown = (\n thrown: unknown,\n): { readonly errorName: string; readonly hasMessage: boolean } => {\n if (thrown instanceof Error) {\n return {\n errorName: thrown.name.slice(0, 64) || \"Error\",\n hasMessage: typeof thrown.message === \"string\" && thrown.message.length > 0,\n };\n }\n return { errorName: typeof thrown, hasMessage: false };\n};\n\n/** Convert an unexpected throw into privacy-safe error info. */\nexport const errorInfoFromThrown = (\n thrown: unknown,\n input: { readonly code?: OtelHookErrorCode; readonly phase: ErrorPhase; readonly occurredAt?: number },\n): OtelHookErrorInfo => {\n if (isOtelHookError(thrown)) {\n return thrown.info;\n }\n const described = describeThrown(thrown);\n return createErrorInfo({\n code: input.code ?? \"internal-error\",\n phase: input.phase,\n detail: `contained ${described.errorName}`,\n details: { \"error.name\": described.errorName, \"error.has_message\": described.hasMessage },\n ...(input.occurredAt === undefined ? {} : { occurredAt: input.occurredAt }),\n });\n};\n","import { z } from \"zod\";\n\n/**\n * Closed set of error codes. Adding a code is a minor change; changing what a\n * code means is a breaking change.\n */\nexport const otelHookErrorCodeSchema = z.enum([\n /** Input was not usable at all (empty stdin, unparsable JSON). */\n \"invalid-input\",\n /** Input parsed but failed canonical schema validation. */\n \"schema-validation-failed\",\n /** No adapter claimed the input with sufficient confidence. */\n \"provider-unknown\",\n /** Several adapters claimed the input at the same confidence. */\n \"provider-detection-ambiguous\",\n /** An adapter threw or returned a malformed result. */\n \"provider-adapter-failure\",\n /** Two identity claims disagreed at equal confidence. */\n \"identity-conflict\",\n /** Required identity fields were absent. */\n \"identity-incomplete\",\n /** A usage report violated the canonical usage invariants. */\n \"usage-invalid\",\n /** The state store could not be read or written. */\n \"state-store-failure\",\n /** The telemetry sink rejected or could not deliver a batch. */\n \"telemetry-export-failure\",\n /** Content reached the sink boundary in a state the policy forbids. */\n \"privacy-policy-violation\",\n /** Configuration could not be resolved. */\n \"configuration-invalid\",\n /** A configured bound (events, batch size) dropped data. */\n \"limit-exceeded\",\n /**\n * No replay-stable delivery identifier was available for a callback while\n * deduplication was required.\n */\n \"delivery-identifier-unavailable\",\n \"delivery-claim-superseded\",\n /** Anything unanticipated. Always reported, never fatal to the host. */\n \"internal-error\",\n]);\nexport type OtelHookErrorCode = z.infer<typeof otelHookErrorCodeSchema>;\n\nexport const errorSeveritySchema = z.enum([\"warning\", \"error\"]);\nexport type ErrorSeverity = z.infer<typeof errorSeveritySchema>;\n\n/** Pipeline stage where a failure occurred. */\nexport const errorPhaseSchema = z.enum([\n \"configuration\",\n \"detection\",\n \"identity\",\n \"parsing\",\n \"normalization\",\n \"privacy\",\n \"state\",\n \"export\",\n \"shutdown\",\n]);\nexport type ErrorPhase = z.infer<typeof errorPhaseSchema>;\n\n/**\n * Which of the two safety postures a code participates in.\n *\n * - `fail-open`: the hook still reports success to the host agent. Telemetry may\n * be incomplete; the coding agent is never blocked.\n * - `fail-closed-attribution`: the observation is not attributed to a session or\n * provider. Data is dropped rather than labelled with a guess.\n */\nexport const failurePostureSchema = z.enum([\"fail-open\", \"fail-closed-attribution\"]);\nexport type FailurePosture = z.infer<typeof failurePostureSchema>;\n\nexport type ErrorCodeDescriptor = {\n readonly code: OtelHookErrorCode;\n readonly severity: ErrorSeverity;\n readonly posture: FailurePosture;\n /** Whether retrying the same input could succeed. */\n readonly retryable: boolean;\n readonly summary: string;\n};\n\nexport const ERROR_TAXONOMY: Readonly<Record<OtelHookErrorCode, ErrorCodeDescriptor>> =\n Object.freeze({\n \"invalid-input\": {\n code: \"invalid-input\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Input could not be read or decoded.\",\n },\n \"schema-validation-failed\": {\n code: \"schema-validation-failed\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"A canonical event failed schema validation and was dropped.\",\n },\n \"provider-unknown\": {\n code: \"provider-unknown\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"No adapter recognized the source provider; the input stays unattributed.\",\n },\n \"provider-detection-ambiguous\": {\n code: \"provider-detection-ambiguous\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Multiple adapters claimed the input at equal confidence.\",\n },\n \"provider-adapter-failure\": {\n code: \"provider-adapter-failure\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A provider adapter failed while parsing.\",\n },\n \"identity-conflict\": {\n code: \"identity-conflict\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Identity claims disagreed; attribution was declined.\",\n },\n \"identity-incomplete\": {\n code: \"identity-incomplete\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Required identity fields were missing; attribution was declined.\",\n },\n \"usage-invalid\": {\n code: \"usage-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A usage report violated the canonical usage invariants.\",\n },\n \"state-store-failure\": {\n code: \"state-store-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"State could not be read or written; derived values may be incomplete.\",\n },\n \"telemetry-export-failure\": {\n code: \"telemetry-export-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"The telemetry sink could not accept a batch.\",\n },\n \"privacy-policy-violation\": {\n code: \"privacy-policy-violation\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Content violated the resolved privacy policy and was dropped.\",\n },\n \"configuration-invalid\": {\n code: \"configuration-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Configuration could not be resolved; defaults apply.\",\n },\n \"limit-exceeded\": {\n code: \"limit-exceeded\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A configured bound was reached and data was dropped.\",\n },\n \"delivery-identifier-unavailable\": {\n code: \"delivery-identifier-unavailable\",\n severity: \"warning\",\n // Fail-open: the observation is still attributed and exported. Only the\n // at-most-once guarantee is missing, and refusing the telemetry to protect\n // a duplicate count would trade a certain loss for a possible one.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"No replay-stable delivery identifier was available; this callback was exported without deduplication.\",\n },\n \"delivery-claim-superseded\": {\n code: \"delivery-claim-superseded\",\n severity: \"warning\",\n // Fail-open, and specifically *not* silent. A peer reclaimed this callback's\n // claim while this process was still working on it, which means the\n // configured stale window is shorter than this installation's real worst\n // case. Both processes may now have exported the callback, so the\n // at-most-once guarantee did not hold for it — the only honest response is\n // to say so and let the operator raise the window.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"A delivery claim was reclaimed by another process before this one committed; the callback may have been exported twice.\",\n },\n \"internal-error\": {\n code: \"internal-error\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"An unexpected failure was contained.\",\n },\n });\n\nexport const describeErrorCode = (code: OtelHookErrorCode): ErrorCodeDescriptor =>\n ERROR_TAXONOMY[code];\n\n/** Outcome of attributing an observation to a provider and session. */\nexport const attributionOutcomeSchema = z.enum([\n /** Identity resolved; events carry provider and session identity. */\n \"attributed\",\n /** Identity could not be established safely; nothing was attributed. */\n \"declined\",\n /** Attribution was attempted and failed unexpectedly. */\n \"failed\",\n /** Input was recognized but intentionally carried no telemetry. */\n \"not-applicable\",\n]);\nexport type AttributionOutcome = z.infer<typeof attributionOutcomeSchema>;\n\nexport const attributionReasonSchema = z.enum([\n \"provider-unknown\",\n \"provider-detection-ambiguous\",\n \"identity-conflict\",\n \"identity-incomplete\",\n \"adapter-ignored-input\",\n \"adapter-failure\",\n \"invalid-input\",\n \"internal-error\",\n]);\nexport type AttributionReason = z.infer<typeof attributionReasonSchema>;\n","/**\n * OTLP/HTTP endpoint URLs per signal, as the OpenTelemetry exporter\n * specification defines them.\n *\n * - `OTEL_EXPORTER_OTLP_ENDPOINT` is a **base** URL: the signal path\n * (`/v1/traces`, `/v1/logs`) is appended to it.\n * - `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` / `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`\n * are full URLs, used as they are.\n *\n * One compatibility rule: earlier releases read `OTEL_EXPORTER_OTLP_ENDPOINT`\n * as the full traces URL. A base URL that already ends in `/v1/traces` is\n * therefore taken to be that full URL, not a base to append to, so an existing\n * `…/v1/traces` value keeps posting where it did.\n */\n\n/**\n * The standard endpoint variables. `generic` and `logs` also appear in\n * `ENVIRONMENT_VARIABLES`; `traces` does not, because that list is guarded\n * against identity-looking (`TRACE`) names.\n */\nexport const OTLP_ENDPOINT_VARIABLES = Object.freeze({\n generic: \"OTEL_EXPORTER_OTLP_ENDPOINT\",\n traces: \"OTEL_EXPORTER_OTLP_TRACES_ENDPOINT\",\n logs: \"OTEL_EXPORTER_OTLP_LOGS_ENDPOINT\",\n metrics: \"OTEL_EXPORTER_OTLP_METRICS_ENDPOINT\",\n});\n\nexport const OTLP_TRACES_PATH = \"/v1/traces\";\nexport const OTLP_LOGS_PATH = \"/v1/logs\";\nexport const OTLP_METRICS_PATH = \"/v1/metrics\";\n\nexport type OtlpSignal = \"traces\" | \"logs\" | \"metrics\";\n\nconst SIGNAL_PATHS: Readonly<Record<OtlpSignal, string>> = Object.freeze({\n traces: OTLP_TRACES_PATH,\n logs: OTLP_LOGS_PATH,\n metrics: OTLP_METRICS_PATH,\n});\n\n/**\n * Strip trailing slashes, by scan rather than by regex.\n *\n * `/\\/+$/` is a polynomial-ReDoS on this input: an endpoint of many `/` followed by\n * anything else makes the engine retry the `+` from every position. The endpoint is\n * operator-supplied configuration bounded to 2048 characters, so the practical cost\n * is small — but a linear scan is just as short, and the bound is not the guarantee.\n */\nexport const withoutTrailingSlashes = (value: string): string => {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === 0x2f) {\n end -= 1;\n }\n return value.slice(0, end);\n};\n\n/**\n * The URL a signal posts to, given an `OTEL_EXPORTER_OTLP_ENDPOINT` base.\n *\n * Trailing slashes on the base are dropped before the signal path is appended,\n * so `https://host/otlp` and `https://host/otlp/` both give\n * `https://host/otlp/v1/traces`. A base ending in `/v1/traces` (the legacy\n * full-URL form) is used as-is for traces and has that suffix swapped for\n * `/v1/logs` for logs.\n */\nexport const otlpSignalEndpointFromBase = (base: string, signal: OtlpSignal): string => {\n const trimmed = withoutTrailingSlashes(base);\n if (trimmed.endsWith(OTLP_TRACES_PATH)) {\n return signal === \"traces\"\n ? trimmed\n : `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${SIGNAL_PATHS[signal]}`;\n }\n return `${trimmed}${SIGNAL_PATHS[signal]}`;\n};\n\n/**\n * A sibling signal's URL derived from a traces URL: a trailing `/v1/traces` (or\n * the target signal's own path) is swapped for the target path, and any other URL\n * is treated as a base and has the path appended. The rule logs have always used.\n */\nexport const siblingSignalEndpoint = (tracesEndpoint: string, signal: OtlpSignal): string => {\n const trimmed = withoutTrailingSlashes(tracesEndpoint);\n const target = SIGNAL_PATHS[signal];\n if (trimmed.endsWith(target)) {\n return trimmed;\n }\n if (trimmed.endsWith(OTLP_TRACES_PATH)) {\n return `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${target}`;\n }\n return `${trimmed}${target}`;\n};\n","import { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport { detectionConfidenceSchema } from \"../model/primitives.js\";\nimport { contentModeSchema } from \"../privacy/policy.js\";\nimport { OTLP_ENDPOINT_VARIABLES, otlpSignalEndpointFromBase } from \"./otlp-endpoint.js\";\nimport { describeOtlpHeaderNames, resolveOtlpHeaders } from \"./otlp-headers.js\";\nimport {\n checkResourceAttributeKey,\n MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH,\n parseResourceAttributesValue,\n} from \"./resource-attributes.js\";\nimport type { OtelHookConfigPatch } from \"./schema.js\";\n\nexport type EnvironmentRecord = Readonly<Record<string, string | undefined>>;\n\nexport type EnvironmentConfigResult = {\n readonly patch: OtelHookConfigPatch;\n /**\n * Unusable variables are reported and skipped rather than failing resolution.\n * The environment is ambient: a stale variable in a shell profile must not\n * disable telemetry, and it must not silently change privacy either — hence\n * the warning.\n */\n readonly warnings: readonly OtelHookErrorInfo[];\n};\n\n/**\n * Environment variables read by the library.\n *\n * No identity variable appears here by design: session, invocation, and\n * workspace identity are supplied per invocation as identity claims, never\n * through ambient configuration (ADR 0001).\n *\n * The standard OTLP header variables are read too, but listed separately in\n * `OTLP_HEADER_VARIABLES`: only the header *names* they set enter the\n * configuration patch, and their values are resolved by `resolveOtlpHeaders`\n * for the sinks alone.\n *\n * `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` is read too, but listed in\n * `OTLP_ENDPOINT_VARIABLES` with its two siblings: an endpoint is not identity,\n * yet a `TRACE` name in this list would defeat the guard that keeps identity\n * variables out of it.\n */\nexport const ENVIRONMENT_VARIABLES = Object.freeze({\n exporterEnabled: \"OTEL_HOOK_ENABLED\",\n /** Full traces URL; otel-hook's own variable, above the standard ones. */\n exporterEndpoint: \"OTEL_HOOK_EXPORTER_ENDPOINT\",\n /**\n * Standard base URL: `/v1/traces` and `/v1/logs` are appended per signal. A\n * value already ending in `/v1/traces` is the legacy full traces URL and is\n * used as-is (see `otlpSignalEndpointFromBase`).\n */\n otlpEndpoint: \"OTEL_EXPORTER_OTLP_ENDPOINT\",\n exporterProtocol: \"OTEL_HOOK_EXPORTER_PROTOCOL\",\n exporterTimeoutMillis: \"OTEL_HOOK_EXPORTER_TIMEOUT_MS\",\n logsEnabled: \"OTEL_HOOK_LOGS_ENABLED\",\n logsEndpoint: \"OTEL_HOOK_LOGS_ENDPOINT\",\n /** Standard per-signal endpoint; the weaker source of the two. */\n otlpLogsEndpoint: \"OTEL_EXPORTER_OTLP_LOGS_ENDPOINT\",\n logsIncludeContent: \"OTEL_HOOK_LOGS_INCLUDE_CONTENT\",\n metricsEnabled: \"OTEL_HOOK_METRICS_ENABLED\",\n metricsEndpoint: \"OTEL_HOOK_METRICS_ENDPOINT\",\n /** Standard per-signal endpoint; the weaker source of the two. */\n otlpMetricsEndpoint: \"OTEL_EXPORTER_OTLP_METRICS_ENDPOINT\",\n /** Standard: `cumulative`, `delta`, or `lowmemory` (read as `delta` here). */\n otlpMetricsTemporality: \"OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE\",\n serviceName: \"OTEL_HOOK_SERVICE_NAME\",\n otlpServiceName: \"OTEL_SERVICE_NAME\",\n serviceNamespace: \"OTEL_HOOK_SERVICE_NAMESPACE\",\n /** Standard W3C-Baggage-encoded resource attributes (percent-encoded values). */\n resourceAttributes: \"OTEL_RESOURCE_ATTRIBUTES\",\n contentMode: \"OTEL_HOOK_CONTENT_MODE\",\n allowRawContent: \"OTEL_HOOK_ALLOW_RAW_CONTENT\",\n hashSalt: \"OTEL_HOOK_HASH_SALT\",\n maxStringLength: \"OTEL_HOOK_MAX_STRING_LENGTH\",\n maxDepth: \"OTEL_HOOK_MAX_DEPTH\",\n maxArrayLength: \"OTEL_HOOK_MAX_ARRAY_LENGTH\",\n maxEventsPerInvocation: \"OTEL_HOOK_MAX_EVENTS_PER_INVOCATION\",\n minimumConfidence: \"OTEL_HOOK_MIN_DETECTION_CONFIDENCE\",\n logLevel: \"OTEL_HOOK_LOG_LEVEL\",\n /** `providers.claudeCode.readTranscriptUsage`; see `providersPolicySchema`. */\n claudeTranscriptUsage: \"OTEL_HOOK_CLAUDE_TRANSCRIPT_USAGE\",\n /** `providers.codex.readRolloutUsage`; see `providersPolicySchema`. */\n codexRolloutUsage: \"OTEL_HOOK_CODEX_ROLLOUT_USAGE\",\n});\n\nconst BOOLEAN_TRUE = new Set([\"1\", \"true\", \"yes\", \"on\"]);\nconst BOOLEAN_FALSE = new Set([\"0\", \"false\", \"no\", \"off\"]);\n\n/**\n * Read configuration from an environment record.\n *\n * Pure: the process environment is never read implicitly, which keeps tests and\n * hosted embeddings from inheriting the developer's shell.\n */\nexport const parseEnvironmentConfig = (env: EnvironmentRecord): EnvironmentConfigResult => {\n const warnings: OtelHookErrorInfo[] = [];\n const warn = (variable: string, detail: string): void => {\n warnings.push(\n createErrorInfo({\n code: \"configuration-invalid\",\n phase: \"configuration\",\n detail: `${variable}: ${detail}`,\n details: { \"config.variable\": variable },\n }),\n );\n };\n\n const readBoolean = (variable: string): boolean | undefined => {\n const raw = env[variable];\n if (raw === undefined || raw === \"\") {\n return undefined;\n }\n const normalized = raw.trim().toLowerCase();\n if (BOOLEAN_TRUE.has(normalized)) {\n return true;\n }\n if (BOOLEAN_FALSE.has(normalized)) {\n return false;\n }\n warn(variable, \"expected a boolean\");\n return undefined;\n };\n\n const readInteger = (variable: string): number | undefined => {\n const raw = env[variable];\n if (raw === undefined || raw === \"\") {\n return undefined;\n }\n const value = Number(raw.trim());\n if (!Number.isInteger(value) || value < 0) {\n warn(variable, \"expected a non-negative integer\");\n return undefined;\n }\n return value;\n };\n\n const readString = (variable: string): string | undefined => {\n const raw = env[variable];\n if (raw === undefined) {\n return undefined;\n }\n const trimmed = raw.trim();\n return trimmed === \"\" ? undefined : trimmed;\n };\n\n const exporterEnabled = readBoolean(ENVIRONMENT_VARIABLES.exporterEnabled);\n /**\n * Traces endpoint, highest first: `OTEL_HOOK_EXPORTER_ENDPOINT` (full URL),\n * `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` (full URL), then\n * `OTEL_EXPORTER_OTLP_ENDPOINT` as a base URL with `/v1/traces` appended.\n */\n const hookEndpoint = readString(ENVIRONMENT_VARIABLES.exporterEndpoint);\n const otlpTracesEndpoint = readString(OTLP_ENDPOINT_VARIABLES.traces);\n const otlpBaseEndpoint = readString(ENVIRONMENT_VARIABLES.otlpEndpoint);\n const endpoint =\n hookEndpoint ??\n otlpTracesEndpoint ??\n (otlpBaseEndpoint === undefined ? undefined : otlpSignalEndpointFromBase(otlpBaseEndpoint, \"traces\"));\n const timeoutMillis = readInteger(ENVIRONMENT_VARIABLES.exporterTimeoutMillis);\n\n const resourceRaw = readString(ENVIRONMENT_VARIABLES.resourceAttributes);\n const resource =\n resourceRaw === undefined ? undefined : parseResourceAttributesValue(resourceRaw);\n for (const detail of resource?.warnings ?? []) {\n warn(ENVIRONMENT_VARIABLES.resourceAttributes, detail);\n }\n const resourceAttributes: Record<string, string> = { ...(resource?.attributes ?? {}) };\n\n /**\n * `HAR_SESSION_KEY` is a resource attribute, not invocation identity\n * (ADR 0001). `har env launch` also puts `har.session_key` on\n * `OTEL_RESOURCE_ATTRIBUTES`; this env var is the same fact when only the\n * dedicated variable is set. It never becomes `InvocationIdentity.sessionId`.\n */\n const harSessionKey = readString(\"HAR_SESSION_KEY\");\n if (\n harSessionKey !== undefined &&\n resourceAttributes[\"har.session_key\"] === undefined &&\n harSessionKey.length <= MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH &&\n checkResourceAttributeKey(\"har.session_key\") === undefined\n ) {\n resourceAttributes[\"har.session_key\"] = harSessionKey;\n }\n\n /**\n * Resolve one service field from its sources, highest precedence first.\n *\n * `service.name` inside `OTEL_RESOURCE_ATTRIBUTES` is honoured — that is the\n * shape a migrating deployment already has — but it is the *weakest* source,\n * and a disagreement with a dedicated variable is reported rather than\n * applied silently. Only variable names are named; values are not, because\n * this warning is written to a log the operator may ship elsewhere.\n */\n const resolveServiceField = (\n sources: readonly { readonly variable: string; readonly value: string | undefined }[],\n ): string | undefined => {\n const present = sources.filter(\n (source): source is { variable: string; value: string } => source.value !== undefined,\n );\n const winner = present[0];\n if (winner === undefined) {\n return undefined;\n }\n for (const loser of present.slice(1)) {\n if (loser.value !== winner.value) {\n warn(loser.variable, `overridden by ${winner.variable}, which sets a different value`);\n }\n }\n return winner.value;\n };\n\n const serviceName = resolveServiceField([\n { variable: ENVIRONMENT_VARIABLES.serviceName, value: readString(ENVIRONMENT_VARIABLES.serviceName) },\n {\n variable: ENVIRONMENT_VARIABLES.otlpServiceName,\n value: readString(ENVIRONMENT_VARIABLES.otlpServiceName),\n },\n {\n variable: `service.name in ${ENVIRONMENT_VARIABLES.resourceAttributes}`,\n value: resource?.serviceName,\n },\n ]);\n const serviceNamespace = resolveServiceField([\n {\n variable: ENVIRONMENT_VARIABLES.serviceNamespace,\n value: readString(ENVIRONMENT_VARIABLES.serviceNamespace),\n },\n {\n variable: `service.namespace in ${ENVIRONMENT_VARIABLES.resourceAttributes}`,\n value: resource?.serviceNamespace,\n },\n ]);\n\n const protocolRaw = readString(ENVIRONMENT_VARIABLES.exporterProtocol);\n let protocol: \"http/protobuf\" | \"http/json\" | \"none\" | undefined;\n if (protocolRaw !== undefined) {\n if (protocolRaw === \"http/protobuf\" || protocolRaw === \"http/json\" || protocolRaw === \"none\") {\n protocol = protocolRaw;\n } else {\n warn(ENVIRONMENT_VARIABLES.exporterProtocol, \"expected http/protobuf, http/json, or none\");\n }\n }\n\n const contentModeRaw = readString(ENVIRONMENT_VARIABLES.contentMode);\n const contentModeParsed =\n contentModeRaw === undefined ? undefined : contentModeSchema.safeParse(contentModeRaw);\n if (contentModeParsed !== undefined && !contentModeParsed.success) {\n warn(ENVIRONMENT_VARIABLES.contentMode, \"expected omit, mask, redact, or raw\");\n }\n\n const confidenceRaw = readString(ENVIRONMENT_VARIABLES.minimumConfidence);\n const confidenceParsed =\n confidenceRaw === undefined ? undefined : detectionConfidenceSchema.safeParse(confidenceRaw);\n if (confidenceParsed !== undefined && !confidenceParsed.success) {\n warn(ENVIRONMENT_VARIABLES.minimumConfidence, \"expected none, weak, strong, or exact\");\n }\n\n const logLevelRaw = readString(ENVIRONMENT_VARIABLES.logLevel);\n const logLevels = [\"silent\", \"error\", \"warn\", \"info\", \"debug\"] as const;\n type LogLevel = (typeof logLevels)[number];\n let logLevel: LogLevel | undefined;\n if (logLevelRaw !== undefined) {\n const match = logLevels.find((level) => level === logLevelRaw);\n if (match === undefined) {\n warn(ENVIRONMENT_VARIABLES.logLevel, `expected one of ${logLevels.join(\", \")}`);\n } else {\n logLevel = match;\n }\n }\n\n const allowRawContent = readBoolean(ENVIRONMENT_VARIABLES.allowRawContent);\n const hashSalt = readString(ENVIRONMENT_VARIABLES.hashSalt);\n const maxStringLength = readInteger(ENVIRONMENT_VARIABLES.maxStringLength);\n const maxDepth = readInteger(ENVIRONMENT_VARIABLES.maxDepth);\n const maxArrayLength = readInteger(ENVIRONMENT_VARIABLES.maxArrayLength);\n const maxEventsPerInvocation = readInteger(ENVIRONMENT_VARIABLES.maxEventsPerInvocation);\n\n const logsEnabled = readBoolean(ENVIRONMENT_VARIABLES.logsEnabled);\n const logsIncludeContent = readBoolean(ENVIRONMENT_VARIABLES.logsIncludeContent);\n /**\n * Logs endpoint, highest first: `OTEL_HOOK_LOGS_ENDPOINT`,\n * `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`, then `OTEL_EXPORTER_OTLP_ENDPOINT` with\n * `/v1/logs` appended — but only when the traces endpoint came from\n * `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`. Otherwise it is left unset and the\n * logs sink derives it from the resolved traces endpoint, as before: from the\n * base itself that gives the same URL, and `OTEL_HOOK_EXPORTER_ENDPOINT` or\n * `--endpoint` keep carrying logs along with traces, as they always have.\n */\n const logsEndpoint =\n readString(ENVIRONMENT_VARIABLES.logsEndpoint) ??\n readString(ENVIRONMENT_VARIABLES.otlpLogsEndpoint) ??\n (hookEndpoint === undefined && otlpTracesEndpoint !== undefined && otlpBaseEndpoint !== undefined\n ? otlpSignalEndpointFromBase(otlpBaseEndpoint, \"logs\")\n : undefined);\n\n const logs = {\n ...(logsEnabled === undefined ? {} : { enabled: logsEnabled }),\n ...(logsEndpoint === undefined ? {} : { endpoint: logsEndpoint }),\n ...(logsIncludeContent === undefined ? {} : { includeContent: logsIncludeContent }),\n };\n\n const metricsEnabled = readBoolean(ENVIRONMENT_VARIABLES.metricsEnabled);\n // Same precedence as the logs endpoint.\n const metricsEndpoint =\n readString(ENVIRONMENT_VARIABLES.metricsEndpoint) ??\n readString(ENVIRONMENT_VARIABLES.otlpMetricsEndpoint) ??\n (hookEndpoint === undefined && otlpTracesEndpoint !== undefined && otlpBaseEndpoint !== undefined\n ? otlpSignalEndpointFromBase(otlpBaseEndpoint, \"metrics\")\n : undefined);\n const temporalityRaw = readString(ENVIRONMENT_VARIABLES.otlpMetricsTemporality)?.toLowerCase();\n let metricsTemporality: \"cumulative\" | \"delta\" | undefined;\n if (temporalityRaw === \"cumulative\") {\n metricsTemporality = \"cumulative\";\n } else if (temporalityRaw === \"delta\" || temporalityRaw === \"lowmemory\") {\n // `lowmemory` is delta for counters and histograms, which is all otel-hook has.\n metricsTemporality = \"delta\";\n } else if (temporalityRaw !== undefined) {\n warn(ENVIRONMENT_VARIABLES.otlpMetricsTemporality, \"expected cumulative, delta, or lowmemory\");\n }\n const metrics = {\n ...(metricsEnabled === undefined ? {} : { enabled: metricsEnabled }),\n ...(metricsEndpoint === undefined ? {} : { endpoint: metricsEndpoint }),\n ...(metricsTemporality === undefined ? {} : { temporality: metricsTemporality }),\n };\n\n // Names only: the values stay out of configuration, and so out of every\n // resolved-config snapshot. Their warnings are position-only.\n const otlpHeaders = resolveOtlpHeaders(env);\n for (const { variable, detail } of otlpHeaders.warnings) {\n warn(variable, detail);\n }\n const headerNames = describeOtlpHeaderNames(otlpHeaders.traces, otlpHeaders.logs);\n\n const exporter = {\n ...(exporterEnabled === undefined ? {} : { enabled: exporterEnabled }),\n ...(endpoint === undefined ? {} : { endpoint }),\n ...(protocol === undefined ? {} : { protocol }),\n ...(timeoutMillis === undefined ? {} : { timeoutMillis }),\n ...(headerNames.length === 0 ? {} : { headerNames: [...headerNames] }),\n ...(serviceName === undefined ? {} : { serviceName }),\n ...(serviceNamespace === undefined ? {} : { serviceNamespace }),\n ...(Object.keys(resourceAttributes).length === 0 ? {} : { resourceAttributes }),\n ...(Object.keys(logs).length === 0 ? {} : { logs }),\n ...(Object.keys(metrics).length === 0 ? {} : { metrics }),\n };\n\n const limits = {\n ...(maxStringLength === undefined ? {} : { maxStringLength }),\n ...(maxDepth === undefined ? {} : { maxDepth }),\n ...(maxArrayLength === undefined ? {} : { maxArrayLength }),\n ...(maxEventsPerInvocation === undefined ? {} : { maxEventsPerInvocation }),\n };\n\n const privacy = {\n ...(contentModeParsed?.success === true ? { contentMode: contentModeParsed.data } : {}),\n ...(allowRawContent === undefined ? {} : { allowRawContent }),\n ...(hashSalt === undefined ? {} : { hashSalt }),\n ...(Object.keys(limits).length === 0 ? {} : { limits }),\n };\n\n const detection =\n confidenceParsed?.success === true ? { minimumConfidence: confidenceParsed.data } : {};\n\n const diagnostics = logLevel === undefined ? {} : { logLevel };\n\n const claudeTranscriptUsage = readBoolean(ENVIRONMENT_VARIABLES.claudeTranscriptUsage);\n const codexRolloutUsage = readBoolean(ENVIRONMENT_VARIABLES.codexRolloutUsage);\n const providers = {\n ...(claudeTranscriptUsage === undefined ? {} : { claudeCode: { readTranscriptUsage: claudeTranscriptUsage } }),\n ...(codexRolloutUsage === undefined ? {} : { codex: { readRolloutUsage: codexRolloutUsage } }),\n };\n\n const patch: OtelHookConfigPatch = {\n ...(Object.keys(exporter).length === 0 ? {} : { exporter }),\n ...(Object.keys(privacy).length === 0 ? {} : { privacy }),\n ...(Object.keys(detection).length === 0 ? {} : { detection }),\n ...(Object.keys(diagnostics).length === 0 ? {} : { diagnostics }),\n ...(Object.keys(providers).length === 0 ? {} : { providers }),\n };\n\n return { patch, warnings };\n};\n"],"mappings":";AAAA,SAAS,KAAAA,UAAS;;;ACAlB,SAAS,SAAS;AAGX,IAAM,wBAAwB;AAG9B,IAAM,8BAA8B;AAGpC,IAAM,6BAA6B;AAEnC,IAAM,uBAAuB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,qBAAqB;AAGxE,IAAM,oBAAoB,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,MAAqB;AAI3E,IAAM,uBAAuB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,OAAO;AAGtD,IAAM,mBAAmB,EAAE,OAAO,EAAE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K,MAAM,EAAE,WAAW,IAAI,CAAC,IAAI,EAAE,OAAO;AAAA,EACvD;AAEA,QAAM,YACJ,kBAAkB,YAAY,OAAO,EAAE,mBAAmB,iBAAiB,KAAK,IAAI,CAAC;AAEvF,QAAM,cAAc,aAAa,SAAY,CAAC,IAAI,EAAE,SAAS;AAE7D,QAAM,wBAAwB,YAAY,sBAAsB,qBAAqB;AACrF,QAAM,oBAAoB,YAAY,sBAAsB,iBAAiB;AAC7E,QAAM,YAAY;AAAA,IAChB,GAAI,0BAA0B,SAAY,CAAC,IAAI,EAAE,YAAY,EAAE,qBAAqB,sBAAsB,EAAE;AAAA,IAC5G,GAAI,sBAAsB,SAAY,CAAC,IAAI,EAAE,OAAO,EAAE,kBAAkB,kBAAkB,EAAE;AAAA,EAC9F;AAEA,QAAM,QAA6B;AAAA,IACjC,GAAI,OAAO,KAAK,QAAQ,EAAE,WAAW,IAAI,CAAC,IAAI,EAAE,SAAS;AAAA,IACzD,GAAI,OAAO,KAAK,OAAO,EAAE,WAAW,IAAI,CAAC,IAAI,EAAE,QAAQ;AAAA,IACvD,GAAI,OAAO,KAAK,SAAS,EAAE,WAAW,IAAI,CAAC,IAAI,EAAE,UAAU;AAAA,IAC3D,GAAI,OAAO,KAAK,WAAW,EAAE,WAAW,IAAI,CAAC,IAAI,EAAE,YAAY;AAAA,IAC/D,GAAI,OAAO,KAAK,SAAS,EAAE,WAAW,IAAI,CAAC,IAAI,EAAE,UAAU;AAAA,EAC7D;AAEA,SAAO,EAAE,OAAO,SAAS;AAC3B;","names":["z","z","z","z","z","HEADER_NAME_PATTERN","z","enabled","z","z","z","z","z","z","parsed","endpointOrigin"]}
|
|
1
|
+
{"version":3,"sources":["../src/config/resource-attributes.ts","../src/model/primitives.ts","../src/privacy/policy.ts","../src/config/schema.ts","../src/config/destinations.ts","../src/config/header-value.ts","../src/config/otlp-headers.ts","../src/config/repository-key.ts","../src/config/resolve.ts","../src/errors/index.ts","../src/errors/taxonomy.ts","../src/config/otlp-endpoint.ts","../src/config/environment.ts"],"sourcesContent":["import { z } from \"zod\";\n\nimport { MAX_IDENTIFIER_LENGTH } from \"../model/primitives.js\";\nimport { DEFAULT_SECRET_KEY_PATTERNS } from \"../privacy/policy.js\";\n\n/**\n * Custom OTLP **resource** attributes: facts about the emitting deployment\n * (`deployment.environment`, `service.instance.id`, a tenant label) that belong\n * on every span this installation exports.\n *\n * These are deliberately *not* {@link ConsumerAttributes}. Consumer attributes\n * are opaque per-invocation metadata that travels with one observation's\n * identity and is sanitized by the privacy service; resource attributes are\n * per-process exporter policy, resolved from configuration layers, and describe\n * the producer rather than the observation. The two never share a field name, a\n * flag, or a code path — see ADR 0001 on keeping identity out of configuration.\n */\n\n/** Upper bound on how many custom resource attributes one installation may set. */\nexport const MAX_RESOURCE_ATTRIBUTES = 64;\n/** Upper bound on a resource attribute key, matching the OpenTelemetry guidance. */\nexport const MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH = 255;\n/** Upper bound on a resource attribute value; values are repeated on every export. */\nexport const MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH = 2048;\n\n/**\n * Accepted shape of a resource attribute key.\n *\n * Deliberately narrower than \"any string\": a key becomes an attribute name on\n * the wire, so restricting it to the OpenTelemetry naming vocabulary keeps\n * newlines, control characters, and arbitrary binary out of the exported\n * resource by construction.\n */\nexport const RESOURCE_ATTRIBUTE_KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_./-]*$/;\n\n/**\n * Keys that resource attributes may never set directly.\n *\n * `service.name` and `service.namespace` are typed exporter policy with their\n * own precedence chain and their own diagnostics. If a resource-attribute map\n * could also write them, the winner would depend on merge order inside the\n * exporter rather than on the documented configuration precedence — which is\n * exactly the silent override this reservation prevents. Supplying either one\n * through `OTEL_RESOURCE_ATTRIBUTES` still works: the environment parser routes\n * it to the policy field at a defined precedence instead of smuggling it into\n * the resource map.\n */\nexport const RESERVED_RESOURCE_ATTRIBUTE_KEYS: readonly string[] = Object.freeze([\n \"service.name\",\n \"service.namespace\",\n]);\n\n/** Case-insensitive: `Service.Name` is the same reservation, spelled differently. */\nexport const isReservedResourceAttributeKey = (key: string): boolean =>\n RESERVED_RESOURCE_ATTRIBUTE_KEYS.includes(key.toLowerCase());\n\nconst SECRET_KEY_MATCHERS: readonly RegExp[] = Object.freeze(\n DEFAULT_SECRET_KEY_PATTERNS.flatMap((source) => {\n try {\n return [new RegExp(source, \"i\")];\n } catch {\n return [];\n }\n }),\n);\n\n/**\n * Whether a key names something that should never be exported.\n *\n * A resource attribute is attached to *every* span, so `api_key=...` in a\n * config file or a shell profile would be the most durable possible leak. The\n * central privacy policy's key patterns are reused rather than re-invented, so\n * one list governs both content sanitization and this boundary.\n */\nexport const isSecretResourceAttributeKey = (key: string): boolean =>\n SECRET_KEY_MATCHERS.some((pattern) => pattern.test(key));\n\nexport type ResourceAttributeKeyRejection =\n | \"empty\"\n | \"too-long\"\n | \"malformed\"\n | \"reserved\"\n | \"secret-like\";\n\n/** Non-sensitive explanations. None of these ever quotes an attribute *value*. */\nexport const RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL: Readonly<\n Record<ResourceAttributeKeyRejection, string>\n> = Object.freeze({\n empty: \"resource attribute key is empty\",\n \"too-long\": `resource attribute key exceeds ${String(MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH)} characters`,\n malformed:\n \"resource attribute key must start with a letter and use only letters, digits, and `_`, `.`, `-`, `/`\",\n reserved:\n \"service.name and service.namespace are exporter policy (--service-name / OTEL_HOOK_SERVICE_NAME), not resource attributes\",\n \"secret-like\":\n \"resource attribute key matches a secret-name pattern, so it is never exported\",\n});\n\n/** Returns why a key is unusable, or `undefined` when it is acceptable. */\nexport const checkResourceAttributeKey = (\n key: string,\n): ResourceAttributeKeyRejection | undefined => {\n if (key.length === 0) {\n return \"empty\";\n }\n if (key.length > MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH) {\n return \"too-long\";\n }\n if (!RESOURCE_ATTRIBUTE_KEY_PATTERN.test(key)) {\n return \"malformed\";\n }\n if (isReservedResourceAttributeKey(key)) {\n return \"reserved\";\n }\n if (isSecretResourceAttributeKey(key)) {\n return \"secret-like\";\n }\n return undefined;\n};\n\n/**\n * Resource attribute values are single primitives, never arrays.\n *\n * `OTEL_RESOURCE_ATTRIBUTES` cannot express an array, and allowing one only in\n * the file layer would make per-key precedence depend on which layer supplied a\n * key. A single primitive keeps the merge total and order-independent.\n */\nexport const resourceAttributeValueSchema = z.union([\n z.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),\n z.number().finite(),\n z.boolean(),\n]);\nexport type ResourceAttributeValue = z.infer<typeof resourceAttributeValueSchema>;\n\nexport const resourceAttributesSchema = z\n .record(z.string(), resourceAttributeValueSchema)\n .superRefine((value, ctx) => {\n const keys = Object.keys(value);\n if (keys.length > MAX_RESOURCE_ATTRIBUTES) {\n ctx.addIssue({\n code: \"custom\",\n message: `at most ${String(MAX_RESOURCE_ATTRIBUTES)} resource attributes are accepted`,\n });\n }\n for (const key of keys) {\n const rejection = checkResourceAttributeKey(key);\n if (rejection !== undefined) {\n ctx.addIssue({\n code: \"custom\",\n path: [key],\n message: RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL[rejection],\n });\n }\n }\n })\n .readonly();\nexport type ResourceAttributes = z.infer<typeof resourceAttributesSchema>;\n\nexport const EMPTY_RESOURCE_ATTRIBUTES: ResourceAttributes = Object.freeze({});\n\nexport type ParsedResourceAttributes = {\n readonly attributes: Readonly<Record<string, string>>;\n /** `service.name`, routed to exporter policy rather than into `attributes`. */\n readonly serviceName?: string;\n /** `service.namespace`, routed the same way. */\n readonly serviceNamespace?: string;\n /**\n * Why entries were skipped. Every message identifies an entry by its\n * *position*, never by quoting the entry — an ambient environment variable\n * may hold anything, and a diagnostic that echoes it would publish it.\n */\n readonly warnings: readonly string[];\n};\n\nconst stripSurroundingQuotes = (value: string): string =>\n value.length >= 2 && value.startsWith('\"') && value.endsWith('\"') ? value.slice(1, -1) : value;\n\n/**\n * Parse the standard `OTEL_RESOURCE_ATTRIBUTES` variable.\n *\n * The OpenTelemetry specification defines this as W3C Baggage: comma-separated\n * `key=value` pairs, optional whitespace around each part, an optional\n * `;`-delimited metadata suffix that carries no attribute meaning, and\n * **percent-encoded values**. Escaping is the part naive parsers get wrong, and\n * it is load-bearing here: without it `deployment.note=a%2Cb` silently becomes\n * two malformed entries, and `region=eu%2Dwest` keeps a literal `%2D`.\n *\n * Every rejection is reported and skipped rather than failing the whole\n * variable: a stale entry in a shell profile must not cost an operator the\n * attributes they got right, and must never disable telemetry (ADR 0004).\n */\nexport const parseResourceAttributesValue = (raw: string): ParsedResourceAttributes => {\n const attributes: Record<string, string> = {};\n const warnings: string[] = [];\n let serviceName: string | undefined;\n let serviceNamespace: string | undefined;\n let overflowed = false;\n\n const entries = raw.split(\",\");\n for (const [index, rawEntry] of entries.entries()) {\n const position = index + 1;\n // Baggage metadata (`key=value;prop=1`) carries no attribute meaning.\n const entry = (rawEntry.split(\";\")[0] ?? \"\").trim();\n if (entry === \"\") {\n continue;\n }\n\n const equals = entry.indexOf(\"=\");\n if (equals <= 0) {\n warnings.push(`entry ${String(position)} is not a key=value pair`);\n continue;\n }\n const key = entry.slice(0, equals).trim();\n // Split on the *first* `=` only: a percent-decoded value may legitimately\n // contain one, and re-joining would be lossy.\n const encoded = stripSurroundingQuotes(entry.slice(equals + 1).trim());\n let value: string;\n try {\n value = decodeURIComponent(encoded);\n } catch {\n warnings.push(`entry ${String(position)} has a malformed percent-encoded value`);\n continue;\n }\n\n if (isReservedResourceAttributeKey(key)) {\n if (value.length === 0 || value.length > MAX_IDENTIFIER_LENGTH) {\n warnings.push(\n `entry ${String(position)} sets ${key.toLowerCase()} to an empty or over-long value`,\n );\n continue;\n }\n if (key.toLowerCase() === \"service.name\") {\n serviceName = value;\n } else {\n serviceNamespace = value;\n }\n continue;\n }\n\n const rejection = checkResourceAttributeKey(key);\n if (rejection !== undefined) {\n warnings.push(\n `entry ${String(position)} was skipped: ${RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL[rejection]}`,\n );\n continue;\n }\n if (value.length > MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) {\n // Dropped rather than truncated: a silently shortened attribute value is\n // a wrong fact, which is worse than a missing one.\n warnings.push(\n `entry ${String(position)} has a value longer than ${String(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH)} characters`,\n );\n continue;\n }\n if (!(key in attributes) && Object.keys(attributes).length >= MAX_RESOURCE_ATTRIBUTES) {\n overflowed = true;\n continue;\n }\n // A repeated key takes its last value, matching every other layer here.\n attributes[key] = value;\n }\n\n if (overflowed) {\n warnings.push(\n `more than ${String(MAX_RESOURCE_ATTRIBUTES)} resource attributes were supplied; the excess was dropped`,\n );\n }\n\n return {\n attributes,\n ...(serviceName === undefined ? {} : { serviceName }),\n ...(serviceNamespace === undefined ? {} : { serviceNamespace }),\n warnings,\n };\n};\n\n/**\n * Drop anything that must not reach the exported resource.\n *\n * The schema already refuses these keys, but a {@link ExporterPolicy} can also\n * be hand-built by a library caller who never ran it through the schema. This\n * is the last gate before the wire, so it filters rather than trusts.\n */\nexport const sanitizeResourceAttributes = (\n attributes: ResourceAttributes,\n): Readonly<Record<string, ResourceAttributeValue>> => {\n const safe: Record<string, ResourceAttributeValue> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (checkResourceAttributeKey(key) !== undefined) {\n continue;\n }\n if (Object.keys(safe).length >= MAX_RESOURCE_ATTRIBUTES) {\n break;\n }\n safe[key] = value;\n }\n return safe;\n};\n\n/**\n * Attribute *names* only, for a logged or exported configuration snapshot.\n *\n * Names are safe to disclose because they are already part of every exported\n * resource; values are not disclosed, because a value is the half an operator\n * may have filled with something they would not want in a log line.\n */\nexport const describeResourceAttributeNames = (\n attributes: ResourceAttributes,\n): readonly string[] => Object.keys(attributes).sort();\n","import { z } from \"zod\";\n\n/** Maximum length accepted for short identifier-like strings. */\nexport const MAX_IDENTIFIER_LENGTH = 256;\n\n/** Maximum length accepted for a single string attribute value. */\nexport const MAX_ATTRIBUTE_STRING_LENGTH = 4096;\n\n/** Maximum number of entries accepted in an attribute array value. */\nexport const MAX_ATTRIBUTE_ARRAY_LENGTH = 128;\n\nexport const nonEmptyStringSchema = z.string().min(1).max(MAX_IDENTIFIER_LENGTH);\n\n/** Wall-clock time as whole milliseconds since the Unix epoch. */\nexport const epochMillisSchema = z.number().int().min(0).max(8_640_000_000_000_000);\nexport type EpochMillis = z.infer<typeof epochMillisSchema>;\n\n/** Non-negative duration in milliseconds; may be fractional. */\nexport const durationMillisSchema = z.number().min(0).finite();\n\n/** Token counts are always non-negative integers. */\nexport const tokenCountSchema = z.number().int().min(0);\n\n/** Monotonically increasing per-invocation ordering key. */\nexport const sequenceNumberSchema = z.number().int().min(0);\n\nconst brandedIdSchema = (): z.ZodString => z.string().min(1).max(MAX_IDENTIFIER_LENGTH);\n\nexport const invocationIdSchema = brandedIdSchema().brand<\"InvocationId\">();\nexport type InvocationId = z.infer<typeof invocationIdSchema>;\n\nexport const sessionIdSchema = brandedIdSchema().brand<\"SessionId\">();\nexport type SessionId = z.infer<typeof sessionIdSchema>;\n\nexport const eventIdSchema = brandedIdSchema().brand<\"EventId\">();\nexport type EventId = z.infer<typeof eventIdSchema>;\n\n/**\n * Workspace identifiers are opaque, privacy-safe handles of the form\n * `<scheme>:<token>`. Filesystem paths cannot satisfy this pattern, which keeps\n * home directories and repository paths out of telemetry by construction.\n */\nexport const WORKSPACE_ID_PATTERN = /^[a-z][a-z0-9]{0,15}:[A-Za-z0-9_-]{8,128}$/;\nexport const workspaceIdSchema = z\n .string()\n .regex(WORKSPACE_ID_PATTERN, \"workspace id must be an opaque `<scheme>:<token>` handle\")\n .brand<\"WorkspaceId\">();\nexport type WorkspaceId = z.infer<typeof workspaceIdSchema>;\n\n/** Provider ids are lowercase, hyphenated, and stable across releases. */\nexport const PROVIDER_ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\nexport const providerIdSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(PROVIDER_ID_PATTERN, \"provider id must be lowercase and hyphenated\")\n .brand<\"ProviderId\">();\nexport type ProviderId = z.infer<typeof providerIdSchema>;\n\n/** Sentinel used whenever the source provider could not be established. */\nexport const UNKNOWN_PROVIDER_ID = \"unknown\" as const;\nexport type UnknownProviderId = typeof UNKNOWN_PROVIDER_ID;\n\nexport const resolvedProviderIdSchema = z.union([\n providerIdSchema,\n z.literal(UNKNOWN_PROVIDER_ID),\n]);\nexport type ResolvedProviderId = z.infer<typeof resolvedProviderIdSchema>;\n\nexport const isUnknownProvider = (value: ResolvedProviderId): value is UnknownProviderId =>\n value === UNKNOWN_PROVIDER_ID;\n\n/**\n * Attribute values are restricted to OpenTelemetry-compatible primitives.\n *\n * This restriction is a containment boundary, not a convenience: because no\n * nested object can be represented, a raw provider payload cannot be smuggled\n * out of an adapter through attributes or extensions.\n */\nexport const attributePrimitiveSchema = z.union([\n z.string().max(MAX_ATTRIBUTE_STRING_LENGTH),\n z.number().finite(),\n z.boolean(),\n]);\nexport type AttributePrimitive = z.infer<typeof attributePrimitiveSchema>;\n\nexport const attributeValueSchema = z.union([\n attributePrimitiveSchema,\n z.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH),\n]);\nexport type AttributeValue = z.infer<typeof attributeValueSchema>;\n\nexport const attributesSchema = z.record(z.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);\nexport type Attributes = z.infer<typeof attributesSchema>;\n\n/** Ordered confidence ladder for provider detection. */\nexport const detectionConfidenceSchema = z.enum([\"none\", \"weak\", \"strong\", \"exact\"]);\nexport type DetectionConfidence = z.infer<typeof detectionConfidenceSchema>;\n\nexport const DETECTION_CONFIDENCE_RANK: Readonly<Record<DetectionConfidence, number>> =\n Object.freeze({\n none: 0,\n weak: 1,\n strong: 2,\n exact: 3,\n });\n\nexport const compareDetectionConfidence = (a: DetectionConfidence, b: DetectionConfidence): number =>\n DETECTION_CONFIDENCE_RANK[a] - DETECTION_CONFIDENCE_RANK[b];\n\n/** How the observed data reached this process. */\nexport const sourceTransportSchema = z.enum([\n \"hook-stdin\",\n \"cli-argument\",\n \"library-call\",\n \"test-fixture\",\n]);\nexport type SourceTransport = z.infer<typeof sourceTransportSchema>;\n","import { z } from \"zod\";\n\nimport type { ContentDisclosure } from \"../model/content.js\";\n\n/**\n * How much content the library is permitted to disclose.\n *\n * `omit` is the default and the only mode that requires no trust in the\n * downstream collector.\n */\nexport const contentModeSchema = z.enum([\"omit\", \"mask\", \"redact\", \"raw\"]);\nexport type ContentMode = z.infer<typeof contentModeSchema>;\n\nexport const CONTENT_MODE_DISCLOSURE: Readonly<Record<ContentMode, ContentDisclosure>> =\n Object.freeze({\n omit: \"omitted\",\n mask: \"masked\",\n redact: \"redacted\",\n raw: \"raw\",\n });\n\n/**\n * Default secret-key patterns, matched case-insensitively against object keys at\n * every depth. A key matching any of these has its value replaced before the\n * value itself is ever inspected.\n */\nexport const DEFAULT_SECRET_KEY_PATTERNS: readonly string[] = Object.freeze([\n \"(^|[._-])(secret|secrets)([._-]|$)\",\n \"(^|[._-])(token|tokens)([._-]|$)\",\n \"(^|[._-])(password|passwd|pwd)([._-]|$)\",\n \"(^|[._-])(credential|credentials)([._-]|$)\",\n \"(^|[._-])(api[._-]?key|apikey|access[._-]?key|secret[._-]?key|private[._-]?key)([._-]|$)\",\n \"(^|[._-])(authorization|auth[._-]?header|bearer)([._-]|$)\",\n \"(^|[._-])(cookie|set[._-]?cookie)([._-]|$)\",\n \"(^|[._-])(signature|sig)([._-]|$)\",\n]);\n\n/**\n * Default secret-value patterns applied to disclosed text in `redact` mode.\n * These are heuristics; they reduce accidental disclosure but are not a\n * substitute for `omit`.\n */\nexport const DEFAULT_SECRET_VALUE_PATTERNS: readonly string[] = Object.freeze([\n \"AKIA[0-9A-Z]{16}\",\n \"sk-[A-Za-z0-9_-]{16,}\",\n \"gh[pousr]_[A-Za-z0-9]{16,}\",\n \"xox[abprs]-[A-Za-z0-9-]{10,}\",\n \"-----BEGIN[A-Z ]*PRIVATE KEY-----\",\n \"eyJ[A-Za-z0-9_-]{10,}\\\\.[A-Za-z0-9_-]{10,}\\\\.[A-Za-z0-9_-]{10,}\",\n \"(?:Bearer|Basic)\\\\s+[A-Za-z0-9._~+/=-]{12,}\",\n]);\n\nexport const privacyLimitsSchema = z.strictObject({\n /** Maximum characters of disclosed text per content fact or string value. */\n maxStringLength: z.number().int().min(0).max(65_536),\n /** Maximum nesting depth walked when sanitizing structured values. */\n maxDepth: z.number().int().min(1).max(32),\n /** Maximum array entries retained when sanitizing structured values. */\n maxArrayLength: z.number().int().min(1).max(4096),\n /** Maximum canonical events emitted per invocation. */\n maxEventsPerInvocation: z.number().int().min(1).max(10_000),\n /** Maximum object keys retained per level when sanitizing. */\n maxObjectKeys: z.number().int().min(1).max(1024),\n});\nexport type PrivacyLimits = z.infer<typeof privacyLimitsSchema>;\n\nexport const privacyPolicySchema = z.strictObject({\n contentMode: contentModeSchema,\n /**\n * `raw` mode is refused unless this is also true, so a single mistyped\n * environment variable cannot start exporting prompts.\n */\n allowRawContent: z.boolean(),\n /**\n * Salt mixed into every hash. A per-deployment salt makes hashes\n * non-correlatable across deployments; an empty salt makes them globally\n * comparable. Both are legitimate; the choice is explicit.\n */\n hashSalt: z.string().max(256),\n maskCharacter: z.string().length(1),\n redactionPlaceholder: z.string().min(1).max(64),\n secretKeyPatterns: z.array(z.string().min(1)).max(128).readonly(),\n secretValuePatterns: z.array(z.string().min(1)).max(128).readonly(),\n limits: privacyLimitsSchema,\n});\nexport type PrivacyPolicy = z.infer<typeof privacyPolicySchema>;\n\nexport const DEFAULT_PRIVACY_LIMITS: PrivacyLimits = Object.freeze({\n maxStringLength: 1024,\n maxDepth: 6,\n maxArrayLength: 64,\n maxEventsPerInvocation: 512,\n maxObjectKeys: 128,\n});\n\nexport const DEFAULT_PRIVACY_POLICY: PrivacyPolicy = Object.freeze({\n contentMode: \"omit\",\n allowRawContent: false,\n hashSalt: \"\",\n maskCharacter: \"*\",\n redactionPlaceholder: \"[redacted]\",\n secretKeyPatterns: DEFAULT_SECRET_KEY_PATTERNS,\n secretValuePatterns: DEFAULT_SECRET_VALUE_PATTERNS,\n limits: DEFAULT_PRIVACY_LIMITS,\n});\n\nexport type PolicyResolution = {\n readonly policy: PrivacyPolicy;\n /** Non-sensitive notes about deterministic downgrades that were applied. */\n readonly notes: readonly string[];\n};\n\n/**\n * Validate a policy and apply the one deterministic downgrade the library\n * enforces: `raw` without `allowRawContent` becomes `omit`.\n */\nexport const resolvePrivacyPolicy = (policy: PrivacyPolicy): PolicyResolution => {\n const parsed = privacyPolicySchema.parse(policy);\n if (parsed.contentMode === \"raw\" && !parsed.allowRawContent) {\n return {\n policy: { ...parsed, contentMode: \"omit\" },\n notes: [\"contentMode=raw downgraded to omit because allowRawContent is false\"],\n };\n }\n return { policy: parsed, notes: [] };\n};\n","import { isAbsolute } from \"node:path\";\n\nimport { z } from \"zod\";\n\nimport { detectionConfidenceSchema, nonEmptyStringSchema } from \"../model/primitives.js\";\nimport {\n contentModeSchema,\n DEFAULT_PRIVACY_POLICY,\n privacyPolicySchema,\n} from \"../privacy/policy.js\";\nimport { exportDestinationsSchema, spoolPolicySchema } from \"./destinations.js\";\nimport { EMPTY_RESOURCE_ATTRIBUTES, resourceAttributesSchema } from \"./resource-attributes.js\";\n\n/**\n * Policy for the OTLP logs signal.\n *\n * Two switches rather than one, because they answer different questions and an\n * operator needs to be able to answer them differently:\n *\n * - `enabled` — whether a second signal leaves this host at all. Off by default:\n * an installation that upgrades must not silently start sending a new stream to a\n * collector whose receivers, quotas, and retention were sized for traces.\n * - `includeContent` — whether *disclosed* text may appear in a log body. Also off\n * by default, and deliberately not the same knob as `privacy.contentMode`: spans\n * carry no content in any content mode, so an installation that set\n * `contentMode` to get a hash and a length has never had content on the wire.\n * Reusing that setting to also mean \"publish prompts\" would change what an\n * existing configuration discloses without anybody editing it.\n *\n * `raw` content additionally requires the pre-existing `privacy.allowRawContent`\n * opt-in, which the privacy service enforces before a fact is ever built and the\n * log mapping re-checks at the wire.\n */\nexport const logsPolicySchema = z.strictObject({\n enabled: z.boolean(),\n /**\n * Full URL for the logs signal.\n *\n * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes\n * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.\n */\n endpoint: z.string().url().max(2048).optional(),\n includeContent: z.boolean(),\n maxBatchSize: z.number().int().min(1).max(4096),\n});\nexport type LogsPolicy = z.infer<typeof logsPolicySchema>;\n\nexport const DEFAULT_LOGS_POLICY: LogsPolicy = Object.freeze({\n enabled: false,\n includeContent: false,\n maxBatchSize: 128,\n});\n\n/**\n * Policy for hook-derived metrics (issue #69).\n *\n * Off by default, like logs: an upgrade must not start a new stream to a\n * collector nobody sized for it. `enabled` governs the `default` destination\n * (the single-endpoint settings); an `exporter.destinations[]` entry receives\n * metrics when its `signals` list names `metrics`. Metrics carry no content, so\n * listing the signal is the whole opt-in.\n *\n * - `temporality`: `cumulative` (default) exports running totals per series,\n * kept in the state store across hook processes, so a receiver that merges\n * counters by keeping the largest value stays correct. `delta` exports what one\n * callback observed and keeps no state.\n * - `includeSessionId`: put `session.id` on every data point (default true). Turn\n * it off where per-session series are too many for the backend.\n */\nexport const metricsPolicySchema = z.strictObject({\n enabled: z.boolean(),\n /** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */\n endpoint: z.string().url().max(2048).optional(),\n temporality: z.enum([\"cumulative\", \"delta\"]),\n includeSessionId: z.boolean(),\n});\nexport type MetricsPolicy = z.infer<typeof metricsPolicySchema>;\n\nexport const DEFAULT_METRICS_POLICY: MetricsPolicy = Object.freeze({\n enabled: false,\n temporality: \"cumulative\",\n includeSessionId: true,\n});\n\n/**\n * Runtime exporter policy.\n *\n * This describes *where and how* telemetry goes. It deliberately contains no\n * session, invocation, or workspace field: see ADR 0001. Mixing the two would\n * make identity globally reachable through configuration.\n */\nexport const exporterPolicySchema = z.strictObject({\n enabled: z.boolean(),\n protocol: z.enum([\"http/protobuf\", \"http/json\", \"none\"]),\n endpoint: z.string().url().max(2048).optional(),\n /**\n * Header names only. Values are supplied separately at construction time and\n * are never part of a resolved-config snapshot, which is logged and exported.\n */\n headerNames: z.array(nonEmptyStringSchema).max(32).readonly(),\n timeoutMillis: z.number().int().min(1).max(600_000),\n maxBatchSize: z.number().int().min(1).max(4096),\n maxQueueSize: z.number().int().min(1).max(65_536),\n maxRetryAttempts: z.number().int().min(0).max(10),\n serviceName: nonEmptyStringSchema,\n serviceNamespace: nonEmptyStringSchema.optional(),\n /**\n * Custom attributes merged into the exported OTLP Resource.\n *\n * Bounded and validated, and refusing `service.name`/`service.namespace`,\n * which are the two fields above. Distinct from an invocation's\n * `consumerAttributes`: this describes the emitting deployment, carries no\n * identity, and is the same for every span this process exports.\n */\n resourceAttributes: resourceAttributesSchema,\n /**\n * The logs signal. Nested under the exporter because it shares the endpoint,\n * headers, timeout, protocol, service identity, and resource attributes above —\n * a second top-level section would invite two of each to drift apart.\n */\n logs: logsPolicySchema,\n /**\n * Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before\n * metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.\n */\n metrics: metricsPolicySchema.optional(),\n /**\n * Additional OTLP destinations, each sent every batch in parallel.\n *\n * Absent (the default), the exporter has exactly one destination — the\n * single-endpoint settings above, named `default` — and behaves exactly as it\n * did before this list existed. See `destinations.ts`.\n *\n * Merged as one leaf: a higher layer that sets the list replaces it whole,\n * because \"the union of two partial lists\" has no answer an operator could\n * predict.\n */\n destinations: exportDestinationsSchema.optional(),\n /**\n * Per-destination retry spool bounds, each optional and merged per leaf; any\n * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.\n */\n spool: spoolPolicySchema.partial().optional(),\n /**\n * The most time one hook invocation spends trying to reach one endpoint, in\n * milliseconds: caps `timeoutMillis` for every OTLP request (connection setup\n * included) and the exporter's own retries inside it. A batch that does not\n * get through in time is spooled. Default {@link DEFAULT_EXPORT_BUDGET_MILLIS}:\n * the host agent waits for its hooks, so a down collector must not stall it.\n */\n exportBudgetMillis: z.number().int().min(50).max(600_000).optional(),\n /**\n * After an endpoint was unreachable (refused, timed out, or answered a\n * retryable status), every hook spools for it without trying for this long,\n * in milliseconds; then one hook probes it again. 0 disables the window.\n * Default {@link DEFAULT_ENDPOINT_DOWN_MILLIS}.\n */\n endpointDownMillis: z.number().int().min(0).max(3_600_000).optional(),\n});\nexport type ExporterPolicy = z.infer<typeof exporterPolicySchema>;\n\n/** Default `exporter.exportBudgetMillis`. */\nexport const DEFAULT_EXPORT_BUDGET_MILLIS = 1_500;\n/** Default `exporter.endpointDownMillis`. */\nexport const DEFAULT_ENDPOINT_DOWN_MILLIS = 30_000;\n\n/** The per-request OTLP timeout a hook uses: `timeoutMillis`, capped by the export budget. */\nexport const effectiveExportTimeoutMillis = (exporter: ExporterPolicy): number =>\n Math.min(exporter.timeoutMillis, exporter.exportBudgetMillis ?? DEFAULT_EXPORT_BUDGET_MILLIS);\n\nexport const detectionPolicySchema = z.strictObject({\n /** Detections below this confidence resolve to the unknown provider. */\n minimumConfidence: detectionConfidenceSchema,\n /** When false, an ambiguous detection is an error rather than unknown. */\n allowAmbiguousFallback: z.boolean(),\n /** Optional allow-list of provider ids; empty means \"any registered\". */\n allowedProviderIds: z.array(nonEmptyStringSchema).max(32).readonly(),\n});\nexport type DetectionPolicy = z.infer<typeof detectionPolicySchema>;\n\nexport const diagnosticsPolicySchema = z.strictObject({\n logLevel: z.enum([\"silent\", \"error\", \"warn\", \"info\", \"debug\"]),\n /** Emit `error.raised` events for contained failures. */\n emitErrorEvents: z.boolean(),\n});\nexport type DiagnosticsPolicy = z.infer<typeof diagnosticsPolicySchema>;\n\n/**\n * Per-provider behaviour that is not part of an adapter's parse.\n *\n * `claudeCode.readTranscriptUsage` is the one sanctioned exception to \"no\n * transcript reads in the hook\" (docs/claude-code-usage-contract.md, finding 8).\n * When true, the hook runtime — never the adapter — reads the session transcript\n * named by a Claude Code `Stop` / `StopFailure` payload, bounded, and attaches the\n * turn's model and summed token usage before the adapter parses it.\n *\n * `codex.readRolloutUsage` is the same exception for Codex, which puts no token\n * counters on any hook payload: at `Stop` the runtime reads the session's\n * rollout (`transcript_path`) from a per-session cursor, bounded, and attaches\n * the thread's running token total (docs/usage-semantics.md).\n *\n * Both off by default: without them, otel-hook reads no file a hook payload names.\n */\nexport const providersPolicySchema = z.strictObject({\n claudeCode: z\n .strictObject({\n readTranscriptUsage: z.boolean(),\n })\n .optional(),\n codex: z\n .strictObject({\n readRolloutUsage: z.boolean(),\n })\n .optional(),\n});\nexport type ProvidersPolicy = z.infer<typeof providersPolicySchema>;\n\n/**\n * Session context (`docs/session-context.md`): a directory a harness writes one\n * JSON file per agent session into, laid out `<dir>/<agent-tool>/<session-id>.json`.\n * With `dir` set, the hook reads that one file on every event and stamps the\n * attributes of the segment in force on every span, log record and metric point.\n * Absent (the default), nothing is read.\n *\n * Set in the configuration file or with `--session-context-dir`, never through\n * the environment: some agents (Claude Code) strip `OTEL_*` variables from the\n * hook processes they start.\n */\nexport const sessionContextPolicySchema = z.strictObject({\n /** Absolute path of the context directory. */\n dir: z\n .string()\n .min(1)\n .max(4096)\n .refine((value) => isAbsolute(value), { message: \"must be an absolute path\" }),\n});\nexport type SessionContextPolicy = z.infer<typeof sessionContextPolicySchema>;\n\nexport const otelHookConfigSchema = z.strictObject({\n exporter: exporterPolicySchema,\n privacy: privacyPolicySchema,\n detection: detectionPolicySchema,\n diagnostics: diagnosticsPolicySchema,\n /** Optional so a hand-built configuration from before it existed stays valid. */\n providers: providersPolicySchema.optional(),\n /** Optional: absent means no session context is read. */\n sessionContext: sessionContextPolicySchema.optional(),\n});\nexport type OtelHookConfig = z.infer<typeof otelHookConfigSchema>;\n\n/** Partial overlay accepted from a configuration layer. */\nexport const otelHookConfigPatchSchema = z.strictObject({\n // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:\n // merging happens per leaf, so a layer must be able to set `logs.enabled` alone\n // without also restating the endpoint and the batch size.\n exporter: exporterPolicySchema\n .omit({ logs: true, metrics: true, spool: true })\n .partial()\n .extend({\n logs: logsPolicySchema.partial().optional(),\n metrics: metricsPolicySchema.partial().optional(),\n spool: spoolPolicySchema.partial().optional(),\n })\n .optional(),\n privacy: privacyPolicySchema\n .omit({ limits: true })\n .partial()\n .extend({ limits: privacyPolicySchema.shape.limits.partial().optional() })\n .optional(),\n detection: detectionPolicySchema.partial().optional(),\n diagnostics: diagnosticsPolicySchema.partial().optional(),\n providers: z\n .strictObject({\n claudeCode: z.strictObject({ readTranscriptUsage: z.boolean() }).partial().optional(),\n codex: z.strictObject({ readRolloutUsage: z.boolean() }).partial().optional(),\n })\n .partial()\n .optional(),\n sessionContext: sessionContextPolicySchema.partial().optional(),\n});\nexport type OtelHookConfigPatch = z.infer<typeof otelHookConfigPatchSchema>;\n\nexport const DEFAULT_EXPORTER_POLICY: ExporterPolicy = Object.freeze({\n enabled: true,\n protocol: \"http/protobuf\",\n headerNames: Object.freeze([]),\n timeoutMillis: 10_000,\n maxBatchSize: 128,\n maxQueueSize: 2048,\n maxRetryAttempts: 2,\n serviceName: \"coding-agent\",\n resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,\n logs: DEFAULT_LOGS_POLICY,\n metrics: DEFAULT_METRICS_POLICY,\n});\n\nexport const DEFAULT_DETECTION_POLICY: DetectionPolicy = Object.freeze({\n minimumConfidence: \"strong\",\n allowAmbiguousFallback: true,\n allowedProviderIds: Object.freeze([]),\n});\n\nexport const DEFAULT_DIAGNOSTICS_POLICY: DiagnosticsPolicy = Object.freeze({\n logLevel: \"warn\",\n emitErrorEvents: true,\n});\n\nexport const DEFAULT_PROVIDERS_POLICY: ProvidersPolicy = Object.freeze({\n claudeCode: Object.freeze({ readTranscriptUsage: false }),\n codex: Object.freeze({ readRolloutUsage: false }),\n});\n\nexport const DEFAULT_CONFIG: OtelHookConfig = Object.freeze({\n exporter: DEFAULT_EXPORTER_POLICY,\n privacy: DEFAULT_PRIVACY_POLICY,\n detection: DEFAULT_DETECTION_POLICY,\n diagnostics: DEFAULT_DIAGNOSTICS_POLICY,\n providers: DEFAULT_PROVIDERS_POLICY,\n});\n\n/** Whether the runtime may read Claude Code transcripts at `Stop` (default false). */\nexport const readsClaudeTranscriptUsage = (config: OtelHookConfig): boolean =>\n config.providers?.claudeCode?.readTranscriptUsage === true;\n\n/** Whether the runtime may read Codex rollouts at `Stop` (default false). */\nexport const readsCodexRolloutUsage = (config: OtelHookConfig): boolean =>\n config.providers?.codex?.readRolloutUsage === true;\n\n/** The session context directory in force, or `undefined` when none is configured. */\nexport const sessionContextDir = (config: OtelHookConfig): string | undefined => config.sessionContext?.dir;\n\n/** Content mode is re-exported for callers building patches. */\nexport { contentModeSchema };\n\n/** The metrics policy in force, defaults filled in. */\nexport const effectiveMetricsPolicy = (exporter: ExporterPolicy): MetricsPolicy => ({\n ...DEFAULT_METRICS_POLICY,\n ...(exporter.metrics ?? {}),\n});\n","import { z } from \"zod\";\n\nimport { contentModeSchema, type ContentMode } from \"../privacy/policy.js\";\nimport { isUnsafeHeaderValue } from \"./header-value.js\";\nimport { MAX_OTLP_HEADERS } from \"./otlp-headers.js\";\nimport { MAX_REPOSITORY_REFERENCE_LENGTH, normalizeRepositoryKey } from \"./repository-key.js\";\nimport type { ExporterPolicy } from \"./schema.js\";\n\n/**\n * Export destinations: one batch, several OTLP endpoints.\n *\n * otel-hook is not a long-running process, so it cannot sit behind a proxy that\n * fans out for it. Instead every enabled destination is sent the same batch by the\n * same short-lived process, and what a destination could not take is kept in that\n * destination's own spool for the next invocation.\n *\n * ## The `default` destination\n *\n * The single-endpoint settings that predate this list — `exporter.endpoint`,\n * `exporter.logs.endpoint`, `exporter.protocol`, `--header`, and the standard\n * `OTEL_EXPORTER_OTLP_*` variables that feed them — describe one destination\n * named `default`. The name is therefore reserved: a `destinations[]` entry may\n * not take it, so there is exactly one place that destination is configured.\n *\n * A configuration with no `destinations` resolves to that one destination and\n * nothing else, exactly as before the list existed.\n */\n\nexport const DEFAULT_DESTINATION_NAME = \"default\";\n\n/**\n * Destination names become directory names (each destination spools on its own),\n * so they are held to a lowercase, filesystem-safe vocabulary rather than being\n * sanitized into something an operator would not recognize.\n */\nexport const DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;\n\nexport const MAX_EXPORT_DESTINATIONS = 16;\n/** The same bound `OTEL_EXPORTER_OTLP_*HEADERS` and `exporter.headerNames` have. */\nexport const MAX_DESTINATION_HEADERS = MAX_OTLP_HEADERS;\n\n/** Prefix of a header value that names an environment variable instead of holding a value. */\nexport const HEADER_ENV_REFERENCE_PREFIX = \"env:\";\n\n/** RFC 9110 `token`: the characters a header field name may use. */\nconst HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;\nconst ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;\nconst MAX_HEADER_VALUE_LENGTH = 8_192;\n\nexport const exportSignalSchema = z.enum([\"traces\", \"logs\", \"metrics\"]);\nexport type ExportSignal = z.infer<typeof exportSignalSchema>;\n\nconst headerValueSchema = z\n .string()\n .min(1)\n .max(MAX_HEADER_VALUE_LENGTH)\n // The rule `OTEL_EXPORTER_OTLP_*HEADERS` values are held to: a line break is a\n // request-splitting vector, and other controls or non-Latin-1 characters would\n // only make Node's HTTP client throw at send time.\n .refine(\n (value) => !isUnsafeHeaderValue(value),\n \"header values may not contain line breaks, control characters, or characters beyond Latin-1\",\n )\n .refine(\n (value) =>\n !value.startsWith(HEADER_ENV_REFERENCE_PREFIX) ||\n ENV_VARIABLE_NAME_PATTERN.test(value.slice(HEADER_ENV_REFERENCE_PREFIX.length)),\n \"an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN\",\n );\n\nconst endpointSchema = z.string().url().max(2048);\n\nexport const MAX_DESTINATION_SCOPES = 64;\nexport const MAX_SCOPE_REPOSITORIES = 256;\n\n/** Every repository, as a scope's `repositories`. */\nexport const ALL_REPOSITORIES = \"*\";\n\nconst repositoryReferenceSchema = z\n .string()\n .min(1)\n .max(MAX_REPOSITORY_REFERENCE_LENGTH)\n .refine(\n (value) => normalizeRepositoryKey(value) !== undefined,\n \"not a repository URL: use https://host/owner/repo, git@host:owner/repo.git, or host/owner/repo\",\n );\n\n/**\n * What one destination receives for a set of repositories.\n *\n * A scope can only *restrict* what the destination would otherwise get: its\n * signals are intersected with the destination's, its content mode can only\n * lower the disclosure the installation's `privacy.contentMode` produced, and\n * `includeSessionId: false` only removes `session.id` from metric points.\n */\nexport const destinationScopeSchema = z.strictObject({\n /**\n * Repository URLs (any spelling of the remote; compared by host and path,\n * case-insensitively, without `.git`), or `\"*\"` for every record that names\n * a repository. A record that names none never matches a scope.\n */\n repositories: z.union([\n z.literal(ALL_REPOSITORIES),\n z.array(repositoryReferenceSchema).min(1).max(MAX_SCOPE_REPOSITORIES).readonly(),\n ]),\n /** Signals sent for these repositories. Default: every signal the destination takes. */\n signals: z.array(exportSignalSchema).min(1).max(3).readonly().optional(),\n /** Content disclosure for these repositories, never above `privacy.contentMode`. Default: unchanged. */\n contentMode: contentModeSchema.optional(),\n /** False leaves `session.id` off metric data points for these repositories. Default true. */\n includeSessionId: z.boolean().optional(),\n});\nexport type DestinationScopeConfig = z.infer<typeof destinationScopeSchema>;\n\nexport const exportDestinationSchema = z\n .strictObject({\n /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */\n name: z\n .string()\n .regex(DESTINATION_NAME_PATTERN, \"destination names are lowercase letters, digits, _ and -\"),\n /** Default true. A disabled destination is neither sent to nor drained. */\n enabled: z.boolean().optional(),\n /**\n * Traces URL, with the same meaning as `exporter.endpoint`: the logs URL is\n * derived from it (`/v1/traces` becomes `/v1/logs`) unless `logsEndpoint` is set.\n */\n endpoint: endpointSchema.optional(),\n /** Per-signal override of `endpoint` for traces. */\n tracesEndpoint: endpointSchema.optional(),\n /** Per-signal override of the derived logs URL. */\n logsEndpoint: endpointSchema.optional(),\n /** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */\n metricsEndpoint: endpointSchema.optional(),\n /** Defaults to `exporter.protocol`. */\n protocol: z.enum([\"http/protobuf\", \"http/json\", \"none\"]).optional(),\n /**\n * Header name to value. A value of the form `env:NAME` is read from that\n * environment variable at send time, so a credential never has to be written\n * into the file. Values never appear in a snapshot, a diagnostic, or `doctor`.\n */\n headers: z\n .record(z.string().regex(HEADER_NAME_PATTERN, \"not a valid header name\"), headerValueSchema)\n .refine(\n (headers) => Object.keys(headers).length <= MAX_DESTINATION_HEADERS,\n `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`,\n )\n .optional(),\n /**\n * Which signals this destination receives. Default: traces and logs. The logs\n * signal is still governed by `exporter.logs.enabled`, which stays the one\n * opt-in for content-bearing records leaving the host. `metrics` is never on by\n * default: a destination receives hook-derived metrics only when it lists them.\n */\n signals: z.array(exportSignalSchema).min(1).max(3).readonly().optional(),\n /**\n * Per-repository filter. Absent: every record goes to this destination, as\n * before scopes existed. Present: a record goes only when its repository\n * (`vcs.repository.url.full`) matches a scope — the first matching scope\n * decides its signals, content mode, and session id — and a record that\n * names no repository is not sent here at all.\n */\n scopes: z.array(destinationScopeSchema).min(1).max(MAX_DESTINATION_SCOPES).readonly().optional(),\n })\n .refine(\n (destination) =>\n destination.endpoint !== undefined ||\n destination.tracesEndpoint !== undefined ||\n destination.logsEndpoint !== undefined ||\n destination.metricsEndpoint !== undefined,\n \"a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint\",\n );\nexport type ExportDestinationConfig = z.infer<typeof exportDestinationSchema>;\n\n/** Signals a destination receives when it does not list any: never metrics. */\nexport const DEFAULT_DESTINATION_SIGNALS: readonly ExportSignal[] = Object.freeze([\"traces\", \"logs\"]);\n\nexport const exportDestinationsSchema = z\n .array(exportDestinationSchema)\n .max(MAX_EXPORT_DESTINATIONS)\n .readonly()\n .superRefine((destinations, context) => {\n const seen = new Set<string>();\n destinations.forEach((destination, index) => {\n if (destination.name === DEFAULT_DESTINATION_NAME) {\n context.addIssue({\n code: \"custom\",\n path: [index, \"name\"],\n message:\n 'the name \"default\" is reserved for exporter.endpoint and the OTEL_EXPORTER_OTLP_* variables',\n });\n }\n if (seen.has(destination.name)) {\n context.addIssue({\n code: \"custom\",\n path: [index, \"name\"],\n message: `duplicate destination name \"${destination.name}\"`,\n });\n }\n seen.add(destination.name);\n });\n });\n\n/**\n * Bounds on each destination's retry spool, per signal.\n *\n * Every destination spools independently, so one long outage can only ever cost\n * its own budget. When a bound is reached the *oldest* batches are dropped first —\n * a recent batch is the one a reader is still likely to look for — and every drop\n * is counted on disk so `doctor` can report it.\n */\nexport const spoolPolicySchema = z.strictObject({\n /** Total bytes of queued batches. Default 16 MiB. */\n maxBytes: z.number().int().min(1_024).max(1_073_741_824),\n /** A batch older than this is dropped instead of sent. Default 72 hours. */\n maxAgeMillis: z.number().int().min(1_000).max(30 * 24 * 60 * 60 * 1000),\n /** Number of queued batches. Default 500. */\n maxBatches: z.number().int().min(1).max(65_536),\n});\nexport type SpoolPolicy = z.infer<typeof spoolPolicySchema>;\n\nexport const DEFAULT_SPOOL_POLICY: SpoolPolicy = Object.freeze({\n maxBytes: 16 * 1024 * 1024,\n maxAgeMillis: 72 * 60 * 60 * 1000,\n maxBatches: 500,\n});\n\n/** The spool policy in force, with defaults filled in for any bound left unset. */\nexport const effectiveSpoolPolicy = (exporter: ExporterPolicy): SpoolPolicy => ({\n maxBytes: exporter.spool?.maxBytes ?? DEFAULT_SPOOL_POLICY.maxBytes,\n maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,\n maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches,\n});\n\n/**\n * One destination as the runtime sends to it.\n *\n * `headers` holds what the configuration holds — literal values and `env:`\n * references, unresolved. Resolution against an environment happens only at the\n * point of sending ({@link resolveDestinationHeaders}), and the `default`\n * destination's header values never pass through configuration at all: they are\n * handed to the runtime separately, as they always have been.\n */\nexport type ExportDestination = {\n readonly name: string;\n /** `exporter` for the `default` destination, `destinations` for a list entry. */\n readonly source: \"exporter\" | \"destinations\";\n readonly protocol: ExporterPolicy[\"protocol\"];\n /** Traces URL as configured; for `default` this is `exporter.endpoint`. */\n readonly endpoint?: string;\n readonly tracesEndpoint?: string;\n readonly logsEndpoint?: string;\n readonly metricsEndpoint?: string;\n readonly signals: { readonly traces: boolean; readonly logs: boolean; readonly metrics: boolean };\n readonly headers: Readonly<Record<string, string>>;\n /** Per-repository filter; absent sends every record (see {@link destinationScopeSchema}). */\n readonly scopes?: readonly DestinationScope[];\n};\n\n/** Signal flags, as a destination or a scope holds them. */\nexport type SignalFlags = { readonly traces: boolean; readonly logs: boolean; readonly metrics: boolean };\n\n/** One scope as the runtime applies it: keys normalized, signals already intersected. */\nexport type DestinationScope = {\n /** Normalized repository keys, or every repository. */\n readonly repositories: typeof ALL_REPOSITORIES | ReadonlySet<string>;\n readonly signals: SignalFlags;\n readonly contentMode?: ContentMode;\n readonly includeSessionId: boolean;\n};\n\n/** Resolve configured scopes against the destination's own signals. */\nexport const resolveDestinationScopes = (\n scopes: readonly DestinationScopeConfig[],\n destinationSignals: SignalFlags,\n): readonly DestinationScope[] =>\n scopes.map((scope) => {\n const listed: readonly ExportSignal[] = scope.signals ?? exportSignalSchema.options;\n return {\n repositories:\n scope.repositories === ALL_REPOSITORIES\n ? ALL_REPOSITORIES\n : new Set(\n scope.repositories.flatMap((reference) => {\n const key = normalizeRepositoryKey(reference);\n return key === undefined ? [] : [key];\n }),\n ),\n signals: {\n traces: destinationSignals.traces && listed.includes(\"traces\"),\n logs: destinationSignals.logs && listed.includes(\"logs\"),\n metrics: destinationSignals.metrics && listed.includes(\"metrics\"),\n },\n ...(scope.contentMode === undefined ? {} : { contentMode: scope.contentMode }),\n includeSessionId: scope.includeSessionId ?? true,\n };\n });\n\n/**\n * The scope a repository key falls in: the first that lists it (or lists `*`).\n * `undefined` — not sent — for a record with no repository key, or one no scope lists.\n */\nexport const matchDestinationScope = (\n scopes: readonly DestinationScope[],\n repositoryKey: string | undefined,\n): DestinationScope | undefined => {\n if (repositoryKey === undefined) {\n return undefined;\n }\n return scopes.find(\n (scope) => scope.repositories === ALL_REPOSITORIES || scope.repositories.has(repositoryKey),\n );\n};\n\nconst legacyDestination = (exporter: ExporterPolicy): ExportDestination => ({\n name: DEFAULT_DESTINATION_NAME,\n source: \"exporter\",\n protocol: exporter.protocol,\n ...(exporter.endpoint === undefined ? {} : { endpoint: exporter.endpoint }),\n ...(exporter.logs.endpoint === undefined ? {} : { logsEndpoint: exporter.logs.endpoint }),\n ...(exporter.metrics?.endpoint === undefined ? {} : { metricsEndpoint: exporter.metrics.endpoint }),\n signals: { traces: true, logs: exporter.logs.enabled, metrics: exporter.metrics?.enabled === true },\n headers: {},\n});\n\n/** Whether a configuration uses the destination list at all. */\nexport const hasConfiguredDestinations = (exporter: ExporterPolicy): boolean =>\n exporter.destinations !== undefined && exporter.destinations.length > 0;\n\n/**\n * The destinations an exporter policy sends to, in a stable order: `default`\n * first when present, then the list in file order.\n *\n * - No `destinations`: exactly one `default` destination, even when it has no\n * endpoint — the sink then reports itself unconfigured, as it always has.\n * - With `destinations`: `default` is included only when a single-endpoint setting\n * actually names an endpoint, and disabled entries are left out.\n */\nexport const resolveExportDestinations = (\n exporter: ExporterPolicy,\n): readonly ExportDestination[] => {\n if (!hasConfiguredDestinations(exporter)) {\n return [legacyDestination(exporter)];\n }\n const resolved: ExportDestination[] = [];\n if (\n exporter.endpoint !== undefined ||\n exporter.logs.endpoint !== undefined ||\n exporter.metrics?.endpoint !== undefined\n ) {\n resolved.push(legacyDestination(exporter));\n }\n for (const destination of exporter.destinations ?? []) {\n if (destination.enabled === false) {\n continue;\n }\n const signals: readonly ExportSignal[] = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;\n const flags: SignalFlags = {\n traces: signals.includes(\"traces\"),\n logs: exporter.logs.enabled && signals.includes(\"logs\"),\n metrics: signals.includes(\"metrics\"),\n };\n resolved.push({\n name: destination.name,\n source: \"destinations\",\n protocol: destination.protocol ?? exporter.protocol,\n ...(destination.endpoint === undefined ? {} : { endpoint: destination.endpoint }),\n ...(destination.tracesEndpoint === undefined\n ? {}\n : { tracesEndpoint: destination.tracesEndpoint }),\n ...(destination.logsEndpoint === undefined ? {} : { logsEndpoint: destination.logsEndpoint }),\n ...(destination.metricsEndpoint === undefined\n ? {}\n : { metricsEndpoint: destination.metricsEndpoint }),\n signals: flags,\n headers: { ...(destination.headers ?? {}) },\n ...(destination.scopes === undefined\n ? {}\n : { scopes: resolveDestinationScopes(destination.scopes, flags) }),\n });\n }\n return resolved;\n};\n\n/** A header value's meaning, without its content. */\nexport type HeaderValueReference =\n | { readonly kind: \"literal\" }\n | { readonly kind: \"env\"; readonly variable: string };\n\nexport const parseHeaderValueReference = (value: string): HeaderValueReference =>\n value.startsWith(HEADER_ENV_REFERENCE_PREFIX)\n ? { kind: \"env\", variable: value.slice(HEADER_ENV_REFERENCE_PREFIX.length) }\n : { kind: \"literal\" };\n\nexport type ResolvedDestinationHeaders = {\n /** Header values ready to send. Never logged, never reported. */\n readonly values: Readonly<Record<string, string>>;\n /** Names of referenced environment variables that are unset or empty. */\n readonly missingVariables: readonly string[];\n};\n\n/**\n * Resolve `env:` references against an explicitly supplied environment.\n *\n * Pure: the process environment is never read implicitly. An unset or empty\n * variable is reported by *name* — the only part of a reference that is safe to\n * say out loud — and its header is left out of `values`.\n */\nexport const resolveDestinationHeaders = (\n headers: Readonly<Record<string, string>>,\n environment: Readonly<Record<string, string | undefined>> | undefined,\n): ResolvedDestinationHeaders => {\n const values: Record<string, string> = {};\n const missing: string[] = [];\n for (const [name, value] of Object.entries(headers)) {\n const reference = parseHeaderValueReference(value);\n if (reference.kind === \"literal\") {\n values[name] = value;\n continue;\n }\n const resolved = environment?.[reference.variable];\n if (resolved === undefined || resolved === \"\") {\n missing.push(reference.variable);\n continue;\n }\n values[name] = resolved;\n }\n return { values, missingVariables: [...new Set(missing)].sort() };\n};\n\n/**\n * Attribute-safe description of one destination: names, origins, and variable\n * names. Never a header value, and never an endpoint beyond its origin.\n */\nexport type DestinationDescription = {\n readonly name: string;\n readonly enabled: boolean;\n readonly protocol: ExporterPolicy[\"protocol\"];\n readonly signals: readonly ExportSignal[];\n readonly tracesEndpointOrigin?: string;\n readonly logsEndpointOrigin?: string;\n readonly metricsEndpointOrigin?: string;\n readonly headerNames: readonly string[];\n /** Environment variables this destination's headers reference. */\n readonly headerVariables: readonly string[];\n /** Per-repository filter, as configured (repositories normalized); absent when unscoped. */\n readonly scopes?: readonly DestinationScopeDescription[];\n};\n\nexport type DestinationScopeDescription = {\n readonly repositories: typeof ALL_REPOSITORIES | readonly string[];\n readonly signals: readonly ExportSignal[];\n readonly contentMode?: ContentMode;\n readonly includeSessionId: boolean;\n};\n\nconst describeScope = (scope: DestinationScope): DestinationScopeDescription => ({\n repositories:\n scope.repositories === ALL_REPOSITORIES ? ALL_REPOSITORIES : [...scope.repositories].sort(),\n signals: exportSignalSchema.options.filter((signal) => scope.signals[signal]),\n ...(scope.contentMode === undefined ? {} : { contentMode: scope.contentMode }),\n includeSessionId: scope.includeSessionId,\n});\n\nexport const endpointOrigin = (endpoint: string | undefined): string | undefined => {\n if (endpoint === undefined) {\n return undefined;\n }\n try {\n return new URL(endpoint).origin;\n } catch {\n return \"<unparsable>\";\n }\n};\n\n/** Every configured destination, disabled ones included, for `doctor` and snapshots. */\nexport const describeExportDestinations = (\n exporter: ExporterPolicy,\n): readonly DestinationDescription[] => {\n const describe = (\n destination: ExportDestination,\n enabled: boolean,\n ): DestinationDescription => {\n const tracesOrigin = endpointOrigin(destination.tracesEndpoint ?? destination.endpoint);\n const logsOrigin = endpointOrigin(\n destination.logsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint,\n );\n const metricsOrigin = endpointOrigin(\n destination.metricsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint,\n );\n const variables = Object.values(destination.headers)\n .map(parseHeaderValueReference)\n .flatMap((reference) => (reference.kind === \"env\" ? [reference.variable] : []));\n return {\n name: destination.name,\n enabled,\n protocol: destination.protocol,\n signals: exportSignalSchema.options.filter((signal) => destination.signals[signal]),\n ...(tracesOrigin === undefined || !destination.signals.traces\n ? {}\n : { tracesEndpointOrigin: tracesOrigin }),\n ...(logsOrigin === undefined || !destination.signals.logs\n ? {}\n : { logsEndpointOrigin: logsOrigin }),\n ...(metricsOrigin === undefined || !destination.signals.metrics\n ? {}\n : { metricsEndpointOrigin: metricsOrigin }),\n headerNames:\n destination.source === \"exporter\"\n ? [...exporter.headerNames].sort()\n : Object.keys(destination.headers).sort(),\n headerVariables: [...new Set(variables)].sort(),\n ...(destination.scopes === undefined ? {} : { scopes: destination.scopes.map(describeScope) }),\n };\n };\n const enabled = resolveExportDestinations(exporter).map((destination) =>\n describe(destination, true),\n );\n const disabled = (exporter.destinations ?? [])\n .filter((destination) => destination.enabled === false)\n .map((destination) =>\n describe(\n {\n name: destination.name,\n source: \"destinations\",\n protocol: destination.protocol ?? exporter.protocol,\n ...(destination.endpoint === undefined ? {} : { endpoint: destination.endpoint }),\n signals: { traces: false, logs: false, metrics: false },\n headers: { ...(destination.headers ?? {}) },\n ...(destination.scopes === undefined\n ? {}\n : {\n scopes: resolveDestinationScopes(destination.scopes, {\n traces: true,\n logs: true,\n metrics: true,\n }),\n }),\n },\n false,\n ),\n );\n return [...enabled, ...disabled];\n};\n","/**\n * Internal: shared by `OTEL_EXPORTER_OTLP_*HEADERS` parsing and the\n * `exporter.destinations[].headers` schema. Not re-exported from the package.\n */\n\n/**\n * Characters an HTTP field value must not contain once decoded. CR and LF would\n * split the request; the other controls and anything beyond Latin-1 are refused\n * by Node's HTTP client anyway, and refusing them here turns a failed export into\n * a reported, skipped entry.\n */\nexport const isUnsafeHeaderValue = (value: string): boolean =>\n [...value].some((char) => {\n const code = char.codePointAt(0) ?? 0;\n return (code < 0x20 && code !== 0x09) || code === 0x7f || code > 0xff;\n });\n","/**\n * The standard OTLP exporter header variables.\n *\n * `OTEL_EXPORTER_OTLP_HEADERS` applies to every signal;\n * `OTEL_EXPORTER_OTLP_TRACES_HEADERS` and `OTEL_EXPORTER_OTLP_LOGS_HEADERS`\n * apply to one signal each. They exist so a credential (`authorization=Basic …`)\n * can reach the exporter without being written on a command line, where `ps` and\n * `/proc/<pid>/cmdline` would show it to every local user.\n *\n * Header *values* never enter configuration. Parsing returns them to the caller,\n * which hands them straight to the sink at construction; configuration carries\n * header *names* only (`exporter.headerNames`), because a resolved-config\n * snapshot is logged and exported. Every diagnostic here names an entry by its\n * position and the variable by its name — never a key, never a value — because a\n * malformed entry may be the secret itself (`Basic abc` with no `=`).\n */\n\nimport { isUnsafeHeaderValue } from \"./header-value.js\";\n\n/** Upper bound on headers per variable, matching `exporter.headerNames`. */\nexport const MAX_OTLP_HEADERS = 32;\n\nexport const OTLP_HEADER_VARIABLES = Object.freeze({\n generic: \"OTEL_EXPORTER_OTLP_HEADERS\",\n traces: \"OTEL_EXPORTER_OTLP_TRACES_HEADERS\",\n logs: \"OTEL_EXPORTER_OTLP_LOGS_HEADERS\",\n});\n\n/** RFC 9110 `token`: the characters an HTTP field name may contain. */\nconst HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n\nexport type ParsedOtlpHeaders = {\n readonly headers: Readonly<Record<string, string>>;\n /** Position-only explanations; never a key or a value. */\n readonly warnings: readonly string[];\n};\n\nconst decode = (raw: string): string | undefined => {\n try {\n return decodeURIComponent(raw);\n } catch {\n return undefined;\n }\n};\n\n/**\n * Parse one `OTEL_EXPORTER_OTLP_*HEADERS` value.\n *\n * The OpenTelemetry exporter specification defines the format as W3C\n * Baggage-like: comma-separated `key=value` pairs, surrounding whitespace\n * trimmed, keys and values percent-decoded. So `authorization=Basic%20abc` is\n * the header `authorization: Basic abc`, and a `,` inside a value must be\n * written `%2C`. A malformed entry is skipped and reported; the rest of the\n * variable still applies. A repeated key takes its last value.\n */\nexport const parseOtlpHeadersValue = (raw: string): ParsedOtlpHeaders => {\n const headers: Record<string, string> = {};\n const warnings: string[] = [];\n let overflowed = false;\n\n for (const [index, rawEntry] of raw.split(\",\").entries()) {\n const position = String(index + 1);\n const entry = rawEntry.trim();\n if (entry === \"\") {\n continue;\n }\n const equals = entry.indexOf(\"=\");\n if (equals <= 0) {\n warnings.push(`entry ${position} is not a key=value pair; ignored`);\n continue;\n }\n const key = decode(entry.slice(0, equals).trim());\n // Split on the first `=` only: a base64 credential ends in `=` padding.\n const value = decode(entry.slice(equals + 1).trim());\n if (key === undefined || value === undefined) {\n warnings.push(`entry ${position} has malformed percent-encoding; ignored`);\n continue;\n }\n const name = key.trim();\n const trimmedValue = value.trim();\n if (!HEADER_NAME_PATTERN.test(name)) {\n warnings.push(`entry ${position} does not name a valid HTTP header; ignored`);\n continue;\n }\n if (trimmedValue === \"\") {\n warnings.push(`entry ${position} has an empty value; ignored`);\n continue;\n }\n if (isUnsafeHeaderValue(trimmedValue)) {\n warnings.push(`entry ${position} has a character not allowed in an HTTP header value; ignored`);\n continue;\n }\n const existing = findHeaderName(headers, name);\n if (existing === undefined && Object.keys(headers).length >= MAX_OTLP_HEADERS) {\n overflowed = true;\n continue;\n }\n if (existing !== undefined) {\n delete headers[existing];\n }\n headers[name] = trimmedValue;\n }\n\n if (overflowed) {\n warnings.push(`more than ${String(MAX_OTLP_HEADERS)} headers were supplied; the excess was ignored`);\n }\n return { headers, warnings };\n};\n\n/** HTTP field names are case-insensitive: `Authorization` and `authorization` are one header. */\nconst findHeaderName = (headers: Readonly<Record<string, string>>, name: string): string | undefined => {\n const lower = name.toLowerCase();\n return Object.keys(headers).find((candidate) => candidate.toLowerCase() === lower);\n};\n\n/**\n * Overlay header maps, lowest precedence first, per header name.\n *\n * A higher source replaces only the names it sets (case-insensitively), so a\n * signal-specific variable can override `authorization` while a generic tenant\n * header still applies — the same per-key merge the OpenTelemetry SDKs apply.\n */\nexport const mergeOtlpHeaders = (\n ...sources: readonly Readonly<Record<string, string>>[]\n): Readonly<Record<string, string>> => {\n const merged: Record<string, string> = {};\n for (const source of sources) {\n for (const [name, value] of Object.entries(source)) {\n const existing = findHeaderName(merged, name);\n if (existing !== undefined) {\n delete merged[existing];\n }\n merged[name] = value;\n }\n }\n return merged;\n};\n\nexport type ResolvedOtlpHeaders = {\n /** Headers for the traces exporter. */\n readonly traces: Readonly<Record<string, string>>;\n /** Headers for the logs exporter. */\n readonly logs: Readonly<Record<string, string>>;\n /** Variable-qualified, value-free explanations of skipped entries. */\n readonly warnings: readonly { readonly variable: string; readonly detail: string }[];\n};\n\n/**\n * Resolve exporter headers per signal.\n *\n * Precedence, per header name, highest first:\n *\n * ```\n * explicit headers (--header) > OTEL_EXPORTER_OTLP_{TRACES,LOGS}_HEADERS > OTEL_EXPORTER_OTLP_HEADERS\n * ```\n *\n * Pure: the environment is passed in, never read from `process.env`.\n */\nexport const resolveOtlpHeaders = (\n env: Readonly<Record<string, string | undefined>>,\n explicit: Readonly<Record<string, string>> = {},\n): ResolvedOtlpHeaders => {\n const warnings: { variable: string; detail: string }[] = [];\n const read = (variable: string): Readonly<Record<string, string>> => {\n const raw = env[variable];\n if (raw === undefined || raw.trim() === \"\") {\n return {};\n }\n const parsed = parseOtlpHeadersValue(raw);\n for (const detail of parsed.warnings) {\n warnings.push({ variable, detail });\n }\n return parsed.headers;\n };\n const generic = read(OTLP_HEADER_VARIABLES.generic);\n const traces = read(OTLP_HEADER_VARIABLES.traces);\n const logs = read(OTLP_HEADER_VARIABLES.logs);\n return {\n traces: mergeOtlpHeaders(generic, traces, explicit),\n logs: mergeOtlpHeaders(generic, logs, explicit),\n warnings,\n };\n};\n\n/**\n * Header names, deduplicated case-insensitively (first spelling kept), sorted\n * and bounded — the only part of a header that may enter configuration or a\n * diagnostic.\n */\nexport const unionOtlpHeaderNames = (...lists: readonly (readonly string[])[]): readonly string[] => {\n const names: string[] = [];\n const seen = new Set<string>();\n for (const name of lists.flat()) {\n if (!seen.has(name.toLowerCase())) {\n seen.add(name.toLowerCase());\n names.push(name);\n }\n }\n return names.sort().slice(0, MAX_OTLP_HEADERS);\n};\n\n/** {@link unionOtlpHeaderNames} over the names of header maps. */\nexport const describeOtlpHeaderNames = (\n ...sources: readonly Readonly<Record<string, string>>[]\n): readonly string[] => unionOtlpHeaderNames(...sources.map((source) => Object.keys(source)));\n","/**\n * Repository keys: how a destination scope names a repository, and how a record's\n * `vcs.repository.url.full` is compared against it.\n *\n * A key is the repository URL's host and path, lowercased, without scheme,\n * credentials, port, trailing slash, or `.git` suffix — `github.com/acme/widget`.\n * The same remote spelled as HTTPS, `git@host:path` or `ssh://` gives the same\n * key, so a scope written from `git remote get-url origin` matches a record\n * stamped with the browse URL and the other way around.\n *\n * Pure: no I/O, never throws.\n */\n\n/** OpenTelemetry VCS attribute a record's repository is read from. */\nexport const ATTR_VCS_REPOSITORY_URL_FULL = \"vcs.repository.url.full\";\n\n/** Longest repository reference accepted, in a scope or on a record. */\nexport const MAX_REPOSITORY_REFERENCE_LENGTH = 2048;\n\nconst SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:\\/\\//i;\n/** `user@host:path` (scp-like git syntax), never `C:\\...` or `host:port/...`. */\nconst SCP_LIKE_PATTERN = /^(?:[^@/\\s]+@)?([^:/\\s]+):(?!\\/\\/)(.+)$/;\n\n/** Drops trailing `/` with a linear scan (`/\\/+$/` backtracks quadratically). */\nconst trimTrailingSlashes = (value: string): string => {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === 0x2f) end -= 1;\n return value.slice(0, end);\n};\n\nconst keyOf = (host: string, pathname: string): string | undefined => {\n const withoutSlashes = trimTrailingSlashes(pathname);\n const cleanedPath = trimTrailingSlashes(\n withoutSlashes.toLowerCase().endsWith(\".git\") ? withoutSlashes.slice(0, -4) : withoutSlashes,\n );\n if (host.length === 0 || cleanedPath.length === 0 || cleanedPath === \"/\") {\n return undefined;\n }\n const withSlash = cleanedPath.startsWith(\"/\") ? cleanedPath : `/${cleanedPath}`;\n return `${host}${withSlash}`.toLowerCase();\n};\n\n/**\n * The key of a repository URL or remote, or `undefined` when it does not name\n * one (empty, unparsable, no path, or a local path).\n *\n * Accepted: `https://host/path(.git)`, `http://…`, `ssh://user@host[:port]/path`,\n * `git://…`, `user@host:path` (scp-like), and an already-normalized\n * `host/path`. Credentials and ports never reach the key.\n */\nexport const normalizeRepositoryKey = (reference: string): string | undefined => {\n const trimmed = reference.trim();\n if (trimmed.length === 0 || trimmed.length > MAX_REPOSITORY_REFERENCE_LENGTH) {\n return undefined;\n }\n if (SCHEME_PATTERN.test(trimmed)) {\n let url: URL;\n try {\n url = new URL(trimmed);\n } catch {\n return undefined;\n }\n if (url.protocol === \"file:\") {\n return undefined;\n }\n return keyOf(url.hostname, url.pathname);\n }\n if (trimmed.startsWith(\"/\") || trimmed.startsWith(\".\") || trimmed.includes(\"\\\\\")) {\n // A local path is not a repository identity a receiver could share.\n return undefined;\n }\n const scp = SCP_LIKE_PATTERN.exec(trimmed);\n if (scp !== null && !trimmed.split(\":\")[0]?.includes(\"/\")) {\n const [, host, pathPart] = scp;\n return host === undefined || pathPart === undefined ? undefined : keyOf(host, pathPart);\n }\n // `host/path`, already a key (or a browse URL without its scheme).\n try {\n const url = new URL(`https://${trimmed}`);\n return keyOf(url.hostname, url.pathname);\n } catch {\n return undefined;\n }\n};\n","import { z } from \"zod\";\n\nimport { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { Attributes } from \"../model/primitives.js\";\nimport {\n describeExportDestinations,\n effectiveSpoolPolicy,\n hasConfiguredDestinations,\n} from \"./destinations.js\";\nimport { describeResourceAttributeNames } from \"./resource-attributes.js\";\nimport {\n DEFAULT_CONFIG,\n effectiveMetricsPolicy,\n otelHookConfigPatchSchema,\n otelHookConfigSchema,\n type OtelHookConfig,\n type OtelHookConfigPatch,\n} from \"./schema.js\";\n\n/**\n * Configuration layers, lowest precedence first.\n *\n * Precedence is fixed and total: `inline-override` beats `environment`, which\n * beats `file`, which beats `defaults`. There is no partial-merge surprise —\n * merging happens per leaf field, so a file may set an endpoint while the\n * environment sets only a content mode.\n *\n * `exporter.resourceAttributes` follows the same rule one level deeper: each\n * *attribute key* is its own leaf. A file may set `deployment.environment`\n * while `OTEL_RESOURCE_ATTRIBUTES` adds `service.instance.id` and\n * `--resource-attr` overrides just one of them; the result is the union, with\n * the highest-precedence layer winning per key and provenance recorded per key.\n * A layer cannot *remove* a key a lower layer set — precedence is an override\n * relation, not a replacement one.\n */\nexport const CONFIG_SOURCE_PRECEDENCE = [\"defaults\", \"file\", \"environment\", \"inline-override\"] as const;\nexport type ConfigSource = (typeof CONFIG_SOURCE_PRECEDENCE)[number];\n\nexport const configSourceSchema = z.enum(CONFIG_SOURCE_PRECEDENCE);\n\nexport type ConfigLayer = {\n readonly source: Exclude<ConfigSource, \"defaults\">;\n readonly patch: OtelHookConfigPatch;\n /** Non-sensitive origin label, e.g. a file name without its directory. */\n readonly origin?: string;\n};\n\n/** Which layer supplied each resolved leaf, keyed by `section.field` path. */\nexport type ConfigProvenance = Readonly<Record<string, ConfigSource>>;\n\nexport type ConfigResolution =\n | {\n readonly status: \"ok\";\n readonly config: OtelHookConfig;\n readonly provenance: ConfigProvenance;\n readonly notes: readonly string[];\n }\n | { readonly status: \"invalid\"; readonly errors: readonly OtelHookErrorInfo[] };\n\ntype PlainRecord = Record<string, unknown>;\n\nconst isPlainObject = (value: unknown): value is PlainRecord =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst mergeLeaf = (\n target: PlainRecord,\n patch: PlainRecord,\n source: ConfigSource,\n provenance: Record<string, ConfigSource>,\n path: string,\n): void => {\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) {\n continue;\n }\n const childPath = path === \"\" ? key : `${path}.${key}`;\n const existing = target[key];\n // An object with no counterpart yet (an optional section such as\n // `exporter.spool`) is merged into an empty one, so its leaves get provenance\n // of their own and a later layer can set one of them without restating the rest.\n if (isPlainObject(value) && (isPlainObject(existing) || existing === undefined)) {\n const child: PlainRecord = { ...(existing ?? {}) };\n mergeLeaf(child, value, source, provenance, childPath);\n target[key] = child;\n continue;\n }\n target[key] = value;\n provenance[childPath] = source;\n }\n};\n\nconst initialProvenance = (config: OtelHookConfig): Record<string, ConfigSource> => {\n const provenance: Record<string, ConfigSource> = {};\n const walk = (value: unknown, path: string): void => {\n if (isPlainObject(value)) {\n for (const [key, child] of Object.entries(value)) {\n walk(child, path === \"\" ? key : `${path}.${key}`);\n }\n return;\n }\n provenance[path] = \"defaults\";\n };\n walk(config, \"\");\n return provenance;\n};\n\n/**\n * Resolve configuration from layered patches.\n *\n * Invalid layers are rejected rather than partially applied: a half-applied\n * privacy policy is exactly the failure mode this contract exists to prevent.\n * Callers that must not fail hard should fall back to {@link DEFAULT_CONFIG},\n * which is always valid.\n */\nexport const resolveConfig = (layers: readonly ConfigLayer[] = []): ConfigResolution => {\n const errors: OtelHookErrorInfo[] = [];\n const ordered = [...layers].sort(\n (a, b) =>\n CONFIG_SOURCE_PRECEDENCE.indexOf(a.source) - CONFIG_SOURCE_PRECEDENCE.indexOf(b.source),\n );\n\n const validated: { source: ConfigSource; patch: PlainRecord }[] = [];\n for (const layer of ordered) {\n const parsed = otelHookConfigPatchSchema.safeParse(layer.patch);\n if (!parsed.success) {\n errors.push(\n createErrorInfo({\n code: \"configuration-invalid\",\n phase: \"configuration\",\n detail: `layer ${layer.source} rejected: ${parsed.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`)\n .join(\"; \")}`.slice(0, 480),\n details: {\n \"config.layer\": layer.source,\n ...(layer.origin === undefined ? {} : { \"config.origin\": layer.origin }),\n },\n }),\n );\n continue;\n }\n validated.push({ source: layer.source, patch: parsed.data });\n }\n\n if (errors.length > 0) {\n return { status: \"invalid\", errors };\n }\n\n const merged: PlainRecord = structuredClone(DEFAULT_CONFIG);\n const provenance = initialProvenance(DEFAULT_CONFIG);\n for (const layer of validated) {\n mergeLeaf(merged, layer.patch, layer.source, provenance, \"\");\n }\n\n const parsed = otelHookConfigSchema.safeParse(merged);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n errors: [\n createErrorInfo({\n code: \"configuration-invalid\",\n phase: \"configuration\",\n detail: `merged configuration rejected: ${parsed.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`)\n .join(\"; \")}`.slice(0, 480),\n }),\n ],\n };\n }\n\n const notes: string[] = [];\n if (parsed.data.privacy.contentMode === \"raw\" && !parsed.data.privacy.allowRawContent) {\n notes.push(\"privacy.contentMode=raw will be downgraded to omit: allowRawContent is false\");\n }\n const withDestinations = hasConfiguredDestinations(parsed.data.exporter);\n if (\n parsed.data.exporter.enabled &&\n parsed.data.exporter.protocol !== \"none\" &&\n parsed.data.exporter.endpoint === undefined &&\n !withDestinations\n ) {\n notes.push(\"exporter.enabled is true but no endpoint is configured\");\n }\n if (withDestinations) {\n const enabled = (parsed.data.exporter.destinations ?? []).filter(\n (destination) => destination.enabled !== false,\n );\n if (enabled.length === 0 && parsed.data.exporter.endpoint === undefined) {\n notes.push(\"exporter.destinations is set but every destination is disabled\");\n }\n if (!parsed.data.exporter.logs.enabled) {\n const askingForLogs = enabled\n .filter((destination) => destination.signals?.includes(\"logs\") === true)\n .map((destination) => destination.name);\n if (askingForLogs.length > 0) {\n notes.push(\n `destination(s) ${askingForLogs.join(\", \")} list the logs signal but exporter.logs.enabled is false, so only traces are sent`,\n );\n }\n }\n // A scope can only restrict: say so when one asks for more than the installation discloses.\n const rank = { omit: 0, mask: 1, redact: 2, raw: 3 } as const;\n const effectiveMode =\n parsed.data.privacy.contentMode === \"raw\" && !parsed.data.privacy.allowRawContent\n ? \"omit\"\n : parsed.data.privacy.contentMode;\n const widening = enabled\n .filter((destination) =>\n (destination.scopes ?? []).some(\n (scope) => scope.contentMode !== undefined && rank[scope.contentMode] > rank[effectiveMode],\n ),\n )\n .map((destination) => destination.name);\n if (widening.length > 0) {\n notes.push(\n `destination(s) ${widening.join(\", \")} have a scope contentMode above privacy.contentMode=${effectiveMode}; a scope can only lower disclosure, so ${effectiveMode} applies`,\n );\n }\n }\n if (\n !withDestinations &&\n parsed.data.exporter.logs.enabled &&\n parsed.data.exporter.logs.endpoint === undefined &&\n parsed.data.exporter.endpoint === undefined\n ) {\n notes.push(\n \"exporter.logs.enabled is true but neither a logs endpoint nor a trace endpoint to derive one from is configured\",\n );\n }\n if (\n !withDestinations &&\n parsed.data.exporter.metrics?.enabled === true &&\n parsed.data.exporter.metrics.endpoint === undefined &&\n parsed.data.exporter.endpoint === undefined\n ) {\n notes.push(\n \"exporter.metrics.enabled is true but neither a metrics endpoint nor a trace endpoint to derive one from is configured\",\n );\n }\n if (parsed.data.exporter.logs.includeContent && parsed.data.privacy.contentMode === \"omit\") {\n // Not an error: the two settings are independent by design, and this is the\n // combination somebody lands on when they enable one and forget the other. Said\n // out loud because the symptom — every log body withheld — looks like a bug.\n notes.push(\n \"exporter.logs.includeContent is true but privacy.contentMode is omit, so no content is disclosed to describe\",\n );\n }\n\n return { status: \"ok\", config: parsed.data, provenance, notes };\n};\n\n/**\n * Destination attributes for the snapshot, present only when the list is in use,\n * so a configuration without destinations snapshots exactly as it always has.\n * Names, origins, and variable names only — never a header value.\n */\nconst describeDestinationAttributes = (config: OtelHookConfig): Attributes => {\n const attributes: Record<string, string | boolean | number | string[]> = {};\n if (config.exporter.spool !== undefined || hasConfiguredDestinations(config.exporter)) {\n const spool = effectiveSpoolPolicy(config.exporter);\n attributes[\"exporter.spool_max_bytes\"] = spool.maxBytes;\n attributes[\"exporter.spool_max_age_millis\"] = spool.maxAgeMillis;\n attributes[\"exporter.spool_max_batches\"] = spool.maxBatches;\n }\n if (!hasConfiguredDestinations(config.exporter)) {\n return attributes;\n }\n const destinations = describeExportDestinations(config.exporter);\n attributes[\"exporter.destination_names\"] = destinations.map((destination) => destination.name);\n for (const destination of destinations) {\n const prefix = `exporter.destination.${destination.name}`;\n attributes[`${prefix}.enabled`] = destination.enabled;\n attributes[`${prefix}.protocol`] = destination.protocol;\n attributes[`${prefix}.signals`] = [...destination.signals];\n if (destination.tracesEndpointOrigin !== undefined) {\n attributes[`${prefix}.traces_endpoint_origin`] = destination.tracesEndpointOrigin;\n }\n if (destination.logsEndpointOrigin !== undefined) {\n attributes[`${prefix}.logs_endpoint_origin`] = destination.logsEndpointOrigin;\n }\n if (destination.metricsEndpointOrigin !== undefined) {\n attributes[`${prefix}.metrics_endpoint_origin`] = destination.metricsEndpointOrigin;\n }\n attributes[`${prefix}.header_names`] = [...destination.headerNames];\n attributes[`${prefix}.header_variables`] = [...destination.headerVariables];\n if (destination.scopes !== undefined) {\n // A count only: the snapshot is exported, and which repositories one\n // destination takes is not something every other destination should learn.\n attributes[`${prefix}.scope_count`] = destination.scopes.length;\n }\n }\n return attributes;\n};\n\n/**\n * Attribute-safe snapshot of resolved configuration, for logging and telemetry.\n *\n * Endpoints are reduced to origin form and header values never appear, because a\n * snapshot is exported to the very system whose credentials it would leak.\n */\nexport const describeResolvedConfig = (config: OtelHookConfig): Attributes => {\n const originOf = (endpoint: string | undefined): string | undefined => {\n if (endpoint === undefined) {\n return undefined;\n }\n try {\n return new URL(endpoint).origin;\n } catch {\n return \"<unparsable>\";\n }\n };\n const endpointOrigin = originOf(config.exporter.endpoint);\n const logsEndpointOrigin = originOf(config.exporter.logs.endpoint);\n const metrics = effectiveMetricsPolicy(config.exporter);\n const metricsEndpointOrigin = originOf(metrics.endpoint);\n return {\n \"exporter.enabled\": config.exporter.enabled,\n \"exporter.protocol\": config.exporter.protocol,\n ...(endpointOrigin === undefined ? {} : { \"exporter.endpoint_origin\": endpointOrigin }),\n \"exporter.logs_enabled\": config.exporter.logs.enabled,\n \"exporter.logs_include_content\": config.exporter.logs.includeContent,\n \"exporter.logs_max_batch_size\": config.exporter.logs.maxBatchSize,\n ...(logsEndpointOrigin === undefined\n ? {}\n : { \"exporter.logs_endpoint_origin\": logsEndpointOrigin }),\n \"exporter.metrics_enabled\": metrics.enabled,\n \"exporter.metrics_temporality\": metrics.temporality,\n \"exporter.metrics_include_session_id\": metrics.includeSessionId,\n ...(metricsEndpointOrigin === undefined\n ? {}\n : { \"exporter.metrics_endpoint_origin\": metricsEndpointOrigin }),\n \"exporter.header_names\": [...config.exporter.headerNames],\n // Names only. A resource attribute *name* is already on the wire in every\n // exported resource, so disclosing it here adds nothing; a *value* may hold\n // whatever an operator put in a shell profile, so it never appears.\n \"exporter.resource_attribute_names\": [\n ...describeResourceAttributeNames(config.exporter.resourceAttributes),\n ],\n ...describeDestinationAttributes(config),\n \"exporter.timeout_millis\": config.exporter.timeoutMillis,\n \"exporter.max_batch_size\": config.exporter.maxBatchSize,\n \"exporter.service_name\": config.exporter.serviceName,\n \"privacy.content_mode\": config.privacy.contentMode,\n \"privacy.allow_raw_content\": config.privacy.allowRawContent,\n \"privacy.hash_salted\": config.privacy.hashSalt.length > 0,\n \"privacy.max_string_length\": config.privacy.limits.maxStringLength,\n \"privacy.max_depth\": config.privacy.limits.maxDepth,\n \"privacy.max_array_length\": config.privacy.limits.maxArrayLength,\n \"privacy.max_events_per_invocation\": config.privacy.limits.maxEventsPerInvocation,\n \"detection.minimum_confidence\": config.detection.minimumConfidence,\n \"detection.allow_ambiguous_fallback\": config.detection.allowAmbiguousFallback,\n \"diagnostics.log_level\": config.diagnostics.logLevel,\n \"diagnostics.emit_error_events\": config.diagnostics.emitErrorEvents,\n // Whether, never where: the directory is a local path.\n \"session_context.enabled\": config.sessionContext?.dir !== undefined,\n };\n};\n","import { z } from \"zod\";\n\nimport { attributesSchema, epochMillisSchema, type Attributes } from \"../model/primitives.js\";\nimport {\n describeErrorCode,\n errorPhaseSchema,\n errorSeveritySchema,\n failurePostureSchema,\n otelHookErrorCodeSchema,\n type ErrorPhase,\n type OtelHookErrorCode,\n} from \"./taxonomy.js\";\n\nexport * from \"./taxonomy.js\";\n\n/**\n * Serializable, privacy-safe description of a failure.\n *\n * `message` is a fixed-vocabulary summary derived from the code and phase, never\n * a provider or exception string, because exception messages routinely contain\n * prompt text, file paths, and credentials. `details` is restricted to attribute\n * primitives for the same reason.\n */\nexport const otelHookErrorInfoSchema = z.strictObject({\n code: otelHookErrorCodeSchema,\n severity: errorSeveritySchema,\n phase: errorPhaseSchema,\n posture: failurePostureSchema,\n retryable: z.boolean(),\n message: z.string().min(1).max(512),\n details: attributesSchema.optional(),\n occurredAt: epochMillisSchema.optional(),\n});\nexport type OtelHookErrorInfo = z.infer<typeof otelHookErrorInfoSchema>;\n\nexport type CreateErrorInfoInput = {\n readonly code: OtelHookErrorCode;\n readonly phase: ErrorPhase;\n /** Short, non-sensitive detail, e.g. `\"2 adapters matched\"`. */\n readonly detail?: string;\n readonly details?: Attributes;\n readonly occurredAt?: number;\n};\n\nexport const createErrorInfo = (input: CreateErrorInfoInput): OtelHookErrorInfo => {\n const descriptor = describeErrorCode(input.code);\n const message =\n input.detail === undefined\n ? `${input.code} during ${input.phase}: ${descriptor.summary}`\n : `${input.code} during ${input.phase}: ${input.detail}`;\n return otelHookErrorInfoSchema.parse({\n code: descriptor.code,\n severity: descriptor.severity,\n phase: input.phase,\n posture: descriptor.posture,\n retryable: descriptor.retryable,\n message: message.slice(0, 512),\n ...(input.details === undefined ? {} : { details: input.details }),\n ...(input.occurredAt === undefined ? {} : { occurredAt: input.occurredAt }),\n });\n};\n\nexport class OtelHookError extends Error {\n public readonly info: OtelHookErrorInfo;\n\n public constructor(info: OtelHookErrorInfo) {\n super(info.message);\n this.name = \"OtelHookError\";\n this.info = info;\n }\n\n public static of(input: CreateErrorInfoInput): OtelHookError {\n return new OtelHookError(createErrorInfo(input));\n }\n}\n\nexport const isOtelHookError = (value: unknown): value is OtelHookError =>\n value instanceof OtelHookError;\n\n/**\n * Describe an arbitrary thrown value without disclosing its message.\n *\n * Only the constructor name crosses the boundary; the presence of a message is\n * reported as a boolean so operators can tell \"threw nothing useful\" from\n * \"threw something we deliberately did not log\".\n */\nexport const describeThrown = (\n thrown: unknown,\n): { readonly errorName: string; readonly hasMessage: boolean } => {\n if (thrown instanceof Error) {\n return {\n errorName: thrown.name.slice(0, 64) || \"Error\",\n hasMessage: typeof thrown.message === \"string\" && thrown.message.length > 0,\n };\n }\n return { errorName: typeof thrown, hasMessage: false };\n};\n\n/** Convert an unexpected throw into privacy-safe error info. */\nexport const errorInfoFromThrown = (\n thrown: unknown,\n input: { readonly code?: OtelHookErrorCode; readonly phase: ErrorPhase; readonly occurredAt?: number },\n): OtelHookErrorInfo => {\n if (isOtelHookError(thrown)) {\n return thrown.info;\n }\n const described = describeThrown(thrown);\n return createErrorInfo({\n code: input.code ?? \"internal-error\",\n phase: input.phase,\n detail: `contained ${described.errorName}`,\n details: { \"error.name\": described.errorName, \"error.has_message\": described.hasMessage },\n ...(input.occurredAt === undefined ? {} : { occurredAt: input.occurredAt }),\n });\n};\n","import { z } from \"zod\";\n\n/**\n * Closed set of error codes. Adding a code is a minor change; changing what a\n * code means is a breaking change.\n */\nexport const otelHookErrorCodeSchema = z.enum([\n /** Input was not usable at all (empty stdin, unparsable JSON). */\n \"invalid-input\",\n /** Input parsed but failed canonical schema validation. */\n \"schema-validation-failed\",\n /** No adapter claimed the input with sufficient confidence. */\n \"provider-unknown\",\n /** Several adapters claimed the input at the same confidence. */\n \"provider-detection-ambiguous\",\n /** An adapter threw or returned a malformed result. */\n \"provider-adapter-failure\",\n /** Two identity claims disagreed at equal confidence. */\n \"identity-conflict\",\n /** Required identity fields were absent. */\n \"identity-incomplete\",\n /** A usage report violated the canonical usage invariants. */\n \"usage-invalid\",\n /** The state store could not be read or written. */\n \"state-store-failure\",\n /** The telemetry sink rejected or could not deliver a batch. */\n \"telemetry-export-failure\",\n /** Content reached the sink boundary in a state the policy forbids. */\n \"privacy-policy-violation\",\n /** Configuration could not be resolved. */\n \"configuration-invalid\",\n /** A configured bound (events, batch size) dropped data. */\n \"limit-exceeded\",\n /**\n * No replay-stable delivery identifier was available for a callback while\n * deduplication was required.\n */\n \"delivery-identifier-unavailable\",\n \"delivery-claim-superseded\",\n /** Anything unanticipated. Always reported, never fatal to the host. */\n \"internal-error\",\n]);\nexport type OtelHookErrorCode = z.infer<typeof otelHookErrorCodeSchema>;\n\nexport const errorSeveritySchema = z.enum([\"warning\", \"error\"]);\nexport type ErrorSeverity = z.infer<typeof errorSeveritySchema>;\n\n/** Pipeline stage where a failure occurred. */\nexport const errorPhaseSchema = z.enum([\n \"configuration\",\n \"detection\",\n \"identity\",\n \"parsing\",\n \"normalization\",\n \"privacy\",\n \"state\",\n \"export\",\n \"shutdown\",\n]);\nexport type ErrorPhase = z.infer<typeof errorPhaseSchema>;\n\n/**\n * Which of the two safety postures a code participates in.\n *\n * - `fail-open`: the hook still reports success to the host agent. Telemetry may\n * be incomplete; the coding agent is never blocked.\n * - `fail-closed-attribution`: the observation is not attributed to a session or\n * provider. Data is dropped rather than labelled with a guess.\n */\nexport const failurePostureSchema = z.enum([\"fail-open\", \"fail-closed-attribution\"]);\nexport type FailurePosture = z.infer<typeof failurePostureSchema>;\n\nexport type ErrorCodeDescriptor = {\n readonly code: OtelHookErrorCode;\n readonly severity: ErrorSeverity;\n readonly posture: FailurePosture;\n /** Whether retrying the same input could succeed. */\n readonly retryable: boolean;\n readonly summary: string;\n};\n\nexport const ERROR_TAXONOMY: Readonly<Record<OtelHookErrorCode, ErrorCodeDescriptor>> =\n Object.freeze({\n \"invalid-input\": {\n code: \"invalid-input\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Input could not be read or decoded.\",\n },\n \"schema-validation-failed\": {\n code: \"schema-validation-failed\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"A canonical event failed schema validation and was dropped.\",\n },\n \"provider-unknown\": {\n code: \"provider-unknown\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"No adapter recognized the source provider; the input stays unattributed.\",\n },\n \"provider-detection-ambiguous\": {\n code: \"provider-detection-ambiguous\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Multiple adapters claimed the input at equal confidence.\",\n },\n \"provider-adapter-failure\": {\n code: \"provider-adapter-failure\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A provider adapter failed while parsing.\",\n },\n \"identity-conflict\": {\n code: \"identity-conflict\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Identity claims disagreed; attribution was declined.\",\n },\n \"identity-incomplete\": {\n code: \"identity-incomplete\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Required identity fields were missing; attribution was declined.\",\n },\n \"usage-invalid\": {\n code: \"usage-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A usage report violated the canonical usage invariants.\",\n },\n \"state-store-failure\": {\n code: \"state-store-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"State could not be read or written; derived values may be incomplete.\",\n },\n \"telemetry-export-failure\": {\n code: \"telemetry-export-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"The telemetry sink could not accept a batch.\",\n },\n \"privacy-policy-violation\": {\n code: \"privacy-policy-violation\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Content violated the resolved privacy policy and was dropped.\",\n },\n \"configuration-invalid\": {\n code: \"configuration-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Configuration could not be resolved; defaults apply.\",\n },\n \"limit-exceeded\": {\n code: \"limit-exceeded\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A configured bound was reached and data was dropped.\",\n },\n \"delivery-identifier-unavailable\": {\n code: \"delivery-identifier-unavailable\",\n severity: \"warning\",\n // Fail-open: the observation is still attributed and exported. Only the\n // at-most-once guarantee is missing, and refusing the telemetry to protect\n // a duplicate count would trade a certain loss for a possible one.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"No replay-stable delivery identifier was available; this callback was exported without deduplication.\",\n },\n \"delivery-claim-superseded\": {\n code: \"delivery-claim-superseded\",\n severity: \"warning\",\n // Fail-open, and specifically *not* silent. A peer reclaimed this callback's\n // claim while this process was still working on it, which means the\n // configured stale window is shorter than this installation's real worst\n // case. Both processes may now have exported the callback, so the\n // at-most-once guarantee did not hold for it — the only honest response is\n // to say so and let the operator raise the window.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"A delivery claim was reclaimed by another process before this one committed; the callback may have been exported twice.\",\n },\n \"internal-error\": {\n code: \"internal-error\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"An unexpected failure was contained.\",\n },\n });\n\nexport const describeErrorCode = (code: OtelHookErrorCode): ErrorCodeDescriptor =>\n ERROR_TAXONOMY[code];\n\n/** Outcome of attributing an observation to a provider and session. */\nexport const attributionOutcomeSchema = z.enum([\n /** Identity resolved; events carry provider and session identity. */\n \"attributed\",\n /** Identity could not be established safely; nothing was attributed. */\n \"declined\",\n /** Attribution was attempted and failed unexpectedly. */\n \"failed\",\n /** Input was recognized but intentionally carried no telemetry. */\n \"not-applicable\",\n]);\nexport type AttributionOutcome = z.infer<typeof attributionOutcomeSchema>;\n\nexport const attributionReasonSchema = z.enum([\n \"provider-unknown\",\n \"provider-detection-ambiguous\",\n \"identity-conflict\",\n \"identity-incomplete\",\n \"adapter-ignored-input\",\n \"adapter-failure\",\n \"invalid-input\",\n \"internal-error\",\n]);\nexport type AttributionReason = z.infer<typeof attributionReasonSchema>;\n","/**\n * OTLP/HTTP endpoint URLs per signal, as the OpenTelemetry exporter\n * specification defines them.\n *\n * - `OTEL_EXPORTER_OTLP_ENDPOINT` is a **base** URL: the signal path\n * (`/v1/traces`, `/v1/logs`) is appended to it.\n * - `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` / `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`\n * are full URLs, used as they are.\n *\n * One compatibility rule: earlier releases read `OTEL_EXPORTER_OTLP_ENDPOINT`\n * as the full traces URL. A base URL that already ends in `/v1/traces` is\n * therefore taken to be that full URL, not a base to append to, so an existing\n * `…/v1/traces` value keeps posting where it did.\n */\n\n/**\n * The standard endpoint variables. `generic` and `logs` also appear in\n * `ENVIRONMENT_VARIABLES`; `traces` does not, because that list is guarded\n * against identity-looking (`TRACE`) names.\n */\nexport const OTLP_ENDPOINT_VARIABLES = Object.freeze({\n generic: \"OTEL_EXPORTER_OTLP_ENDPOINT\",\n traces: \"OTEL_EXPORTER_OTLP_TRACES_ENDPOINT\",\n logs: \"OTEL_EXPORTER_OTLP_LOGS_ENDPOINT\",\n metrics: \"OTEL_EXPORTER_OTLP_METRICS_ENDPOINT\",\n});\n\nexport const OTLP_TRACES_PATH = \"/v1/traces\";\nexport const OTLP_LOGS_PATH = \"/v1/logs\";\nexport const OTLP_METRICS_PATH = \"/v1/metrics\";\n\nexport type OtlpSignal = \"traces\" | \"logs\" | \"metrics\";\n\nconst SIGNAL_PATHS: Readonly<Record<OtlpSignal, string>> = Object.freeze({\n traces: OTLP_TRACES_PATH,\n logs: OTLP_LOGS_PATH,\n metrics: OTLP_METRICS_PATH,\n});\n\n/**\n * Strip trailing slashes, by scan rather than by regex.\n *\n * `/\\/+$/` is a polynomial-ReDoS on this input: an endpoint of many `/` followed by\n * anything else makes the engine retry the `+` from every position. The endpoint is\n * operator-supplied configuration bounded to 2048 characters, so the practical cost\n * is small — but a linear scan is just as short, and the bound is not the guarantee.\n */\nexport const withoutTrailingSlashes = (value: string): string => {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === 0x2f) {\n end -= 1;\n }\n return value.slice(0, end);\n};\n\n/**\n * The URL a signal posts to, given an `OTEL_EXPORTER_OTLP_ENDPOINT` base.\n *\n * Trailing slashes on the base are dropped before the signal path is appended,\n * so `https://host/otlp` and `https://host/otlp/` both give\n * `https://host/otlp/v1/traces`. A base ending in `/v1/traces` (the legacy\n * full-URL form) is used as-is for traces and has that suffix swapped for\n * `/v1/logs` for logs.\n */\nexport const otlpSignalEndpointFromBase = (base: string, signal: OtlpSignal): string => {\n const trimmed = withoutTrailingSlashes(base);\n if (trimmed.endsWith(OTLP_TRACES_PATH)) {\n return signal === \"traces\"\n ? trimmed\n : `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${SIGNAL_PATHS[signal]}`;\n }\n return `${trimmed}${SIGNAL_PATHS[signal]}`;\n};\n\n/**\n * A sibling signal's URL derived from a traces URL: a trailing `/v1/traces` (or\n * the target signal's own path) is swapped for the target path, and any other URL\n * is treated as a base and has the path appended. The rule logs have always used.\n */\nexport const siblingSignalEndpoint = (tracesEndpoint: string, signal: OtlpSignal): string => {\n const trimmed = withoutTrailingSlashes(tracesEndpoint);\n const target = SIGNAL_PATHS[signal];\n if (trimmed.endsWith(target)) {\n return trimmed;\n }\n if (trimmed.endsWith(OTLP_TRACES_PATH)) {\n return `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${target}`;\n }\n return `${trimmed}${target}`;\n};\n","import { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport { detectionConfidenceSchema } from \"../model/primitives.js\";\nimport { contentModeSchema } from \"../privacy/policy.js\";\nimport { OTLP_ENDPOINT_VARIABLES, otlpSignalEndpointFromBase } from \"./otlp-endpoint.js\";\nimport { describeOtlpHeaderNames, resolveOtlpHeaders } from \"./otlp-headers.js\";\nimport {\n checkResourceAttributeKey,\n MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH,\n parseResourceAttributesValue,\n} from \"./resource-attributes.js\";\nimport type { OtelHookConfigPatch } from \"./schema.js\";\n\nexport type EnvironmentRecord = Readonly<Record<string, string | undefined>>;\n\nexport type EnvironmentConfigResult = {\n readonly patch: OtelHookConfigPatch;\n /**\n * Unusable variables are reported and skipped rather than failing resolution.\n * The environment is ambient: a stale variable in a shell profile must not\n * disable telemetry, and it must not silently change privacy either — hence\n * the warning.\n */\n readonly warnings: readonly OtelHookErrorInfo[];\n};\n\n/**\n * Environment variables read by the library.\n *\n * No identity variable appears here by design: session, invocation, and\n * workspace identity are supplied per invocation as identity claims, never\n * through ambient configuration (ADR 0001).\n *\n * The standard OTLP header variables are read too, but listed separately in\n * `OTLP_HEADER_VARIABLES`: only the header *names* they set enter the\n * configuration patch, and their values are resolved by `resolveOtlpHeaders`\n * for the sinks alone.\n *\n * `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` is read too, but listed in\n * `OTLP_ENDPOINT_VARIABLES` with its two siblings: an endpoint is not identity,\n * yet a `TRACE` name in this list would defeat the guard that keeps identity\n * variables out of it.\n */\nexport const ENVIRONMENT_VARIABLES = Object.freeze({\n exporterEnabled: \"OTEL_HOOK_ENABLED\",\n /** Full traces URL; otel-hook's own variable, above the standard ones. */\n exporterEndpoint: \"OTEL_HOOK_EXPORTER_ENDPOINT\",\n /**\n * Standard base URL: `/v1/traces` and `/v1/logs` are appended per signal. A\n * value already ending in `/v1/traces` is the legacy full traces URL and is\n * used as-is (see `otlpSignalEndpointFromBase`).\n */\n otlpEndpoint: \"OTEL_EXPORTER_OTLP_ENDPOINT\",\n exporterProtocol: \"OTEL_HOOK_EXPORTER_PROTOCOL\",\n exporterTimeoutMillis: \"OTEL_HOOK_EXPORTER_TIMEOUT_MS\",\n logsEnabled: \"OTEL_HOOK_LOGS_ENABLED\",\n logsEndpoint: \"OTEL_HOOK_LOGS_ENDPOINT\",\n /** Standard per-signal endpoint; the weaker source of the two. */\n otlpLogsEndpoint: \"OTEL_EXPORTER_OTLP_LOGS_ENDPOINT\",\n logsIncludeContent: \"OTEL_HOOK_LOGS_INCLUDE_CONTENT\",\n metricsEnabled: \"OTEL_HOOK_METRICS_ENABLED\",\n metricsEndpoint: \"OTEL_HOOK_METRICS_ENDPOINT\",\n /** Standard per-signal endpoint; the weaker source of the two. */\n otlpMetricsEndpoint: \"OTEL_EXPORTER_OTLP_METRICS_ENDPOINT\",\n /** Standard: `cumulative`, `delta`, or `lowmemory` (read as `delta` here). */\n otlpMetricsTemporality: \"OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE\",\n serviceName: \"OTEL_HOOK_SERVICE_NAME\",\n otlpServiceName: \"OTEL_SERVICE_NAME\",\n serviceNamespace: \"OTEL_HOOK_SERVICE_NAMESPACE\",\n /** Standard W3C-Baggage-encoded resource attributes (percent-encoded values). */\n resourceAttributes: \"OTEL_RESOURCE_ATTRIBUTES\",\n contentMode: \"OTEL_HOOK_CONTENT_MODE\",\n allowRawContent: \"OTEL_HOOK_ALLOW_RAW_CONTENT\",\n hashSalt: \"OTEL_HOOK_HASH_SALT\",\n maxStringLength: \"OTEL_HOOK_MAX_STRING_LENGTH\",\n maxDepth: \"OTEL_HOOK_MAX_DEPTH\",\n maxArrayLength: \"OTEL_HOOK_MAX_ARRAY_LENGTH\",\n maxEventsPerInvocation: \"OTEL_HOOK_MAX_EVENTS_PER_INVOCATION\",\n minimumConfidence: \"OTEL_HOOK_MIN_DETECTION_CONFIDENCE\",\n logLevel: \"OTEL_HOOK_LOG_LEVEL\",\n /** `providers.claudeCode.readTranscriptUsage`; see `providersPolicySchema`. */\n claudeTranscriptUsage: \"OTEL_HOOK_CLAUDE_TRANSCRIPT_USAGE\",\n /** `providers.codex.readRolloutUsage`; see `providersPolicySchema`. */\n codexRolloutUsage: \"OTEL_HOOK_CODEX_ROLLOUT_USAGE\",\n});\n\nconst BOOLEAN_TRUE = new Set([\"1\", \"true\", \"yes\", \"on\"]);\nconst BOOLEAN_FALSE = new Set([\"0\", \"false\", \"no\", \"off\"]);\n\n/**\n * Read configuration from an environment record.\n *\n * Pure: the process environment is never read implicitly, which keeps tests and\n * hosted embeddings from inheriting the developer's shell.\n */\nexport const parseEnvironmentConfig = (env: EnvironmentRecord): EnvironmentConfigResult => {\n const warnings: OtelHookErrorInfo[] = [];\n const warn = (variable: string, detail: string): void => {\n warnings.push(\n createErrorInfo({\n code: \"configuration-invalid\",\n phase: \"configuration\",\n detail: `${variable}: ${detail}`,\n details: { \"config.variable\": variable },\n }),\n );\n };\n\n const readBoolean = (variable: string): boolean | undefined => {\n const raw = env[variable];\n if (raw === undefined || raw === \"\") {\n return undefined;\n }\n const normalized = raw.trim().toLowerCase();\n if (BOOLEAN_TRUE.has(normalized)) {\n return true;\n }\n if (BOOLEAN_FALSE.has(normalized)) {\n return false;\n }\n warn(variable, \"expected a boolean\");\n return undefined;\n };\n\n const readInteger = (variable: string): number | undefined => {\n const raw = env[variable];\n if (raw === undefined || raw === \"\") {\n return undefined;\n }\n const value = Number(raw.trim());\n if (!Number.isInteger(value) || value < 0) {\n warn(variable, \"expected a non-negative integer\");\n return undefined;\n }\n return value;\n };\n\n const readString = (variable: string): string | undefined => {\n const raw = env[variable];\n if (raw === undefined) {\n return undefined;\n }\n const trimmed = raw.trim();\n return trimmed === \"\" ? undefined : trimmed;\n };\n\n const exporterEnabled = readBoolean(ENVIRONMENT_VARIABLES.exporterEnabled);\n /**\n * Traces endpoint, highest first: `OTEL_HOOK_EXPORTER_ENDPOINT` (full URL),\n * `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` (full URL), then\n * `OTEL_EXPORTER_OTLP_ENDPOINT` as a base URL with `/v1/traces` appended.\n */\n const hookEndpoint = readString(ENVIRONMENT_VARIABLES.exporterEndpoint);\n const otlpTracesEndpoint = readString(OTLP_ENDPOINT_VARIABLES.traces);\n const otlpBaseEndpoint = readString(ENVIRONMENT_VARIABLES.otlpEndpoint);\n const endpoint =\n hookEndpoint ??\n otlpTracesEndpoint ??\n (otlpBaseEndpoint === undefined ? undefined : otlpSignalEndpointFromBase(otlpBaseEndpoint, \"traces\"));\n const timeoutMillis = readInteger(ENVIRONMENT_VARIABLES.exporterTimeoutMillis);\n\n const resourceRaw = readString(ENVIRONMENT_VARIABLES.resourceAttributes);\n const resource =\n resourceRaw === undefined ? undefined : parseResourceAttributesValue(resourceRaw);\n for (const detail of resource?.warnings ?? []) {\n warn(ENVIRONMENT_VARIABLES.resourceAttributes, detail);\n }\n const resourceAttributes: Record<string, string> = { ...(resource?.attributes ?? {}) };\n\n /**\n * `HAR_SESSION_KEY` is a resource attribute, not invocation identity\n * (ADR 0001). `har env launch` also puts `har.session_key` on\n * `OTEL_RESOURCE_ATTRIBUTES`; this env var is the same fact when only the\n * dedicated variable is set. It never becomes `InvocationIdentity.sessionId`.\n */\n const harSessionKey = readString(\"HAR_SESSION_KEY\");\n if (\n harSessionKey !== undefined &&\n resourceAttributes[\"har.session_key\"] === undefined &&\n harSessionKey.length <= MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH &&\n checkResourceAttributeKey(\"har.session_key\") === undefined\n ) {\n resourceAttributes[\"har.session_key\"] = harSessionKey;\n }\n\n /**\n * Resolve one service field from its sources, highest precedence first.\n *\n * `service.name` inside `OTEL_RESOURCE_ATTRIBUTES` is honoured — that is the\n * shape a migrating deployment already has — but it is the *weakest* source,\n * and a disagreement with a dedicated variable is reported rather than\n * applied silently. Only variable names are named; values are not, because\n * this warning is written to a log the operator may ship elsewhere.\n */\n const resolveServiceField = (\n sources: readonly { readonly variable: string; readonly value: string | undefined }[],\n ): string | undefined => {\n const present = sources.filter(\n (source): source is { variable: string; value: string } => source.value !== undefined,\n );\n const winner = present[0];\n if (winner === undefined) {\n return undefined;\n }\n for (const loser of present.slice(1)) {\n if (loser.value !== winner.value) {\n warn(loser.variable, `overridden by ${winner.variable}, which sets a different value`);\n }\n }\n return winner.value;\n };\n\n const serviceName = resolveServiceField([\n { variable: ENVIRONMENT_VARIABLES.serviceName, value: readString(ENVIRONMENT_VARIABLES.serviceName) },\n {\n variable: ENVIRONMENT_VARIABLES.otlpServiceName,\n value: readString(ENVIRONMENT_VARIABLES.otlpServiceName),\n },\n {\n variable: `service.name in ${ENVIRONMENT_VARIABLES.resourceAttributes}`,\n value: resource?.serviceName,\n },\n ]);\n const serviceNamespace = resolveServiceField([\n {\n variable: ENVIRONMENT_VARIABLES.serviceNamespace,\n value: readString(ENVIRONMENT_VARIABLES.serviceNamespace),\n },\n {\n variable: `service.namespace in ${ENVIRONMENT_VARIABLES.resourceAttributes}`,\n value: resource?.serviceNamespace,\n },\n ]);\n\n const protocolRaw = readString(ENVIRONMENT_VARIABLES.exporterProtocol);\n let protocol: \"http/protobuf\" | \"http/json\" | \"none\" | undefined;\n if (protocolRaw !== undefined) {\n if (protocolRaw === \"http/protobuf\" || protocolRaw === \"http/json\" || protocolRaw === \"none\") {\n protocol = protocolRaw;\n } else {\n warn(ENVIRONMENT_VARIABLES.exporterProtocol, \"expected http/protobuf, http/json, or none\");\n }\n }\n\n const contentModeRaw = readString(ENVIRONMENT_VARIABLES.contentMode);\n const contentModeParsed =\n contentModeRaw === undefined ? undefined : contentModeSchema.safeParse(contentModeRaw);\n if (contentModeParsed !== undefined && !contentModeParsed.success) {\n warn(ENVIRONMENT_VARIABLES.contentMode, \"expected omit, mask, redact, or raw\");\n }\n\n const confidenceRaw = readString(ENVIRONMENT_VARIABLES.minimumConfidence);\n const confidenceParsed =\n confidenceRaw === undefined ? undefined : detectionConfidenceSchema.safeParse(confidenceRaw);\n if (confidenceParsed !== undefined && !confidenceParsed.success) {\n warn(ENVIRONMENT_VARIABLES.minimumConfidence, \"expected none, weak, strong, or exact\");\n }\n\n const logLevelRaw = readString(ENVIRONMENT_VARIABLES.logLevel);\n const logLevels = [\"silent\", \"error\", \"warn\", \"info\", \"debug\"] as const;\n type LogLevel = (typeof logLevels)[number];\n let logLevel: LogLevel | undefined;\n if (logLevelRaw !== undefined) {\n const match = logLevels.find((level) => level === logLevelRaw);\n if (match === undefined) {\n warn(ENVIRONMENT_VARIABLES.logLevel, `expected one of ${logLevels.join(\", \")}`);\n } else {\n logLevel = match;\n }\n }\n\n const allowRawContent = readBoolean(ENVIRONMENT_VARIABLES.allowRawContent);\n const hashSalt = readString(ENVIRONMENT_VARIABLES.hashSalt);\n const maxStringLength = readInteger(ENVIRONMENT_VARIABLES.maxStringLength);\n const maxDepth = readInteger(ENVIRONMENT_VARIABLES.maxDepth);\n const maxArrayLength = readInteger(ENVIRONMENT_VARIABLES.maxArrayLength);\n const maxEventsPerInvocation = readInteger(ENVIRONMENT_VARIABLES.maxEventsPerInvocation);\n\n const logsEnabled = readBoolean(ENVIRONMENT_VARIABLES.logsEnabled);\n const logsIncludeContent = readBoolean(ENVIRONMENT_VARIABLES.logsIncludeContent);\n /**\n * Logs endpoint, highest first: `OTEL_HOOK_LOGS_ENDPOINT`,\n * `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`, then `OTEL_EXPORTER_OTLP_ENDPOINT` with\n * `/v1/logs` appended — but only when the traces endpoint came from\n * `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`. Otherwise it is left unset and the\n * logs sink derives it from the resolved traces endpoint, as before: from the\n * base itself that gives the same URL, and `OTEL_HOOK_EXPORTER_ENDPOINT` or\n * `--endpoint` keep carrying logs along with traces, as they always have.\n */\n const logsEndpoint =\n readString(ENVIRONMENT_VARIABLES.logsEndpoint) ??\n readString(ENVIRONMENT_VARIABLES.otlpLogsEndpoint) ??\n (hookEndpoint === undefined && otlpTracesEndpoint !== undefined && otlpBaseEndpoint !== undefined\n ? otlpSignalEndpointFromBase(otlpBaseEndpoint, \"logs\")\n : undefined);\n\n const logs = {\n ...(logsEnabled === undefined ? {} : { enabled: logsEnabled }),\n ...(logsEndpoint === undefined ? {} : { endpoint: logsEndpoint }),\n ...(logsIncludeContent === undefined ? {} : { includeContent: logsIncludeContent }),\n };\n\n const metricsEnabled = readBoolean(ENVIRONMENT_VARIABLES.metricsEnabled);\n // Same precedence as the logs endpoint.\n const metricsEndpoint =\n readString(ENVIRONMENT_VARIABLES.metricsEndpoint) ??\n readString(ENVIRONMENT_VARIABLES.otlpMetricsEndpoint) ??\n (hookEndpoint === undefined && otlpTracesEndpoint !== undefined && otlpBaseEndpoint !== undefined\n ? otlpSignalEndpointFromBase(otlpBaseEndpoint, \"metrics\")\n : undefined);\n const temporalityRaw = readString(ENVIRONMENT_VARIABLES.otlpMetricsTemporality)?.toLowerCase();\n let metricsTemporality: \"cumulative\" | \"delta\" | undefined;\n if (temporalityRaw === \"cumulative\") {\n metricsTemporality = \"cumulative\";\n } else if (temporalityRaw === \"delta\" || temporalityRaw === \"lowmemory\") {\n // `lowmemory` is delta for counters and histograms, which is all otel-hook has.\n metricsTemporality = \"delta\";\n } else if (temporalityRaw !== undefined) {\n warn(ENVIRONMENT_VARIABLES.otlpMetricsTemporality, \"expected cumulative, delta, or lowmemory\");\n }\n const metrics = {\n ...(metricsEnabled === undefined ? {} : { enabled: metricsEnabled }),\n ...(metricsEndpoint === undefined ? {} : { endpoint: metricsEndpoint }),\n ...(metricsTemporality === undefined ? {} : { temporality: metricsTemporality }),\n };\n\n // Names only: the values stay out of configuration, and so out of every\n // resolved-config snapshot. Their warnings are position-only.\n const otlpHeaders = resolveOtlpHeaders(env);\n for (const { variable, detail } of otlpHeaders.warnings) {\n warn(variable, detail);\n }\n const headerNames = describeOtlpHeaderNames(otlpHeaders.traces, otlpHeaders.logs);\n\n const exporter = {\n ...(exporterEnabled === undefined ? {} : { enabled: exporterEnabled }),\n ...(endpoint === undefined ? {} : { endpoint }),\n ...(protocol === undefined ? {} : { protocol }),\n ...(timeoutMillis === undefined ? {} : { timeoutMillis }),\n ...(headerNames.length === 0 ? {} : { headerNames: [...headerNames] }),\n ...(serviceName === undefined ? {} : { serviceName }),\n ...(serviceNamespace === undefined ? {} : { serviceNamespace }),\n ...(Object.keys(resourceAttributes).length === 0 ? {} : { resourceAttributes }),\n ...(Object.keys(logs).length === 0 ? {} : { logs }),\n ...(Object.keys(metrics).length === 0 ? {} : { metrics }),\n };\n\n const limits = {\n ...(maxStringLength === undefined ? {} : { maxStringLength }),\n ...(maxDepth === undefined ? {} : { maxDepth }),\n ...(maxArrayLength === undefined ? {} : { maxArrayLength }),\n ...(maxEventsPerInvocation === undefined ? {} : { maxEventsPerInvocation }),\n };\n\n const privacy = {\n ...(contentModeParsed?.success === true ? { contentMode: contentModeParsed.data } : {}),\n ...(allowRawContent === undefined ? {} : { allowRawContent }),\n ...(hashSalt === undefined ? {} : { hashSalt }),\n ...(Object.keys(limits).length === 0 ? {} : { limits }),\n };\n\n const detection =\n confidenceParsed?.success === true ? { minimumConfidence: confidenceParsed.data } : {};\n\n const diagnostics = logLevel === undefined ? {} : { logLevel };\n\n const claudeTranscriptUsage = readBoolean(ENVIRONMENT_VARIABLES.claudeTranscriptUsage);\n const codexRolloutUsage = readBoolean(ENVIRONMENT_VARIABLES.codexRolloutUsage);\n const providers = {\n ...(claudeTranscriptUsage === undefined ? {} : { claudeCode: { readTranscriptUsage: claudeTranscriptUsage } }),\n ...(codexRolloutUsage === undefined ? {} : { codex: { readRolloutUsage: codexRolloutUsage } }),\n };\n\n const patch: OtelHookConfigPatch = {\n ...(Object.keys(exporter).length === 0 ? {} : { exporter }),\n ...(Object.keys(privacy).length === 0 ? {} : { privacy }),\n ...(Object.keys(detection).length === 0 ? {} : { detection }),\n ...(Object.keys(diagnostics).length === 0 ? {} : { diagnostics }),\n ...(Object.keys(providers).length === 0 ? {} : { providers }),\n };\n\n return { patch, warnings };\n};\n"],"mappings":";AAAA,SAAS,KAAAA,UAAS;;;ACAlB,SAAS,SAAS;AAGX,IAAM,wBAAwB;AAG9B,IAAM,8BAA8B;AAGpC,IAAM,6BAA6B;AAEnC,IAAM,uBAAuB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,qBAAqB;AAGxE,IAAM,oBAAoB,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,MAAqB;AAI3E,IAAM,uBAAuB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,OAAO;AAGtD,IAAM,mBAAmB,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAG/C,IAAM,uBAAuB,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAA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