@osfactory/otel-hook 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +72 -7
  2. package/dist/{adapter-BS7xHKGQ.d.ts → adapter-BJiz6lqM.d.ts} +2 -2
  3. package/dist/cli.js +207 -34
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +85 -1
  6. package/dist/config.js +135 -1
  7. package/dist/config.js.map +1 -1
  8. package/dist/{events-CzZ5kukS.d.ts → events-B3MHoJTD.d.ts} +72 -1
  9. package/dist/{filesystem-store-BcOveJYY.d.ts → filesystem-store-r-nNA3BA.d.ts} +1 -1
  10. package/dist/{hook-DxTakjAD.d.ts → hook-Dh8OO4Wa.d.ts} +4 -4
  11. package/dist/index.d.ts +12 -12
  12. package/dist/index.js +197 -31
  13. package/dist/index.js.map +1 -1
  14. package/dist/install.d.ts +4 -4
  15. package/dist/install.js +8 -2
  16. package/dist/install.js.map +1 -1
  17. package/dist/integration.d.ts +13 -8
  18. package/dist/integration.js +2273 -2256
  19. package/dist/integration.js.map +1 -1
  20. package/dist/lifecycle.d.ts +3 -3
  21. package/dist/lifecycle.js +761 -212
  22. package/dist/lifecycle.js.map +1 -1
  23. package/dist/{memory-DkTohdIa.d.ts → memory-Bl9ANVff.d.ts} +2 -2
  24. package/dist/model.d.ts +1 -1
  25. package/dist/model.js +13 -2
  26. package/dist/model.js.map +1 -1
  27. package/dist/{otlp-log-sink-DaZDPKnR.d.ts → otlp-log-sink-eUEjaLhk.d.ts} +3 -3
  28. package/dist/{payload-2lnpKodw.d.ts → payload-Ci8_ERm6.d.ts} +1 -1
  29. package/dist/{ports-B0rC49b3.d.ts → ports-n7KFOpKo.d.ts} +1 -1
  30. package/dist/providers.d.ts +10 -10
  31. package/dist/providers.js +32 -13
  32. package/dist/providers.js.map +1 -1
  33. package/dist/{registry-DVnPA_b6.d.ts → registry-CIVvRlVK.d.ts} +1 -1
  34. package/dist/runtime.d.ts +8 -8
  35. package/dist/runtime.js +11 -6
  36. package/dist/runtime.js.map +1 -1
  37. package/dist/{semconv-CtnDdsPk.d.ts → semconv-fPRb-dpU.d.ts} +1 -1
  38. package/dist/state.d.ts +4 -4
  39. package/dist/telemetry.d.ts +6 -6
  40. package/dist/telemetry.js +956 -418
  41. package/dist/telemetry.js.map +1 -1
  42. package/dist/testing.d.ts +14 -8
  43. package/dist/testing.js +36 -18
  44. package/dist/testing.js.map +1 -1
  45. package/package.json +1 -1
@@ -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/resolve.ts","../src/errors/index.ts","../src/errors/taxonomy.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 { 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 { 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 * 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});\nexport type ExporterPolicy = z.infer<typeof exporterPolicySchema>;\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\nexport const otelHookConfigSchema = z.strictObject({\n exporter: exporterPolicySchema,\n privacy: privacyPolicySchema,\n detection: detectionPolicySchema,\n diagnostics: diagnosticsPolicySchema,\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 })\n .partial()\n .extend({ logs: logsPolicySchema.partial().optional() })\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});\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});\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_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});\n\n/** Content mode is re-exported for callers building patches. */\nexport { contentModeSchema };\n","import { z } from \"zod\";\n\nimport { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { Attributes } from \"../model/primitives.js\";\nimport { describeResourceAttributeNames } from \"./resource-attributes.js\";\nimport {\n DEFAULT_CONFIG,\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 if (isPlainObject(value) && isPlainObject(existing)) {\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 if (parsed.data.exporter.enabled && parsed.data.exporter.protocol !== \"none\" && parsed.data.exporter.endpoint === undefined) {\n notes.push(\"exporter.enabled is true but no endpoint is configured\");\n }\n if (\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 (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 * 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 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.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 \"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 };\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","import { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport { detectionConfidenceSchema } from \"../model/primitives.js\";\nimport { contentModeSchema } from \"../privacy/policy.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 */\nexport const ENVIRONMENT_VARIABLES = Object.freeze({\n exporterEnabled: \"OTEL_HOOK_ENABLED\",\n exporterEndpoint: \"OTEL_HOOK_EXPORTER_ENDPOINT\",\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 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});\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 const endpoint =\n readString(ENVIRONMENT_VARIABLES.exporterEndpoint) ??\n readString(ENVIRONMENT_VARIABLES.otlpEndpoint);\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 const logsEndpoint =\n readString(ENVIRONMENT_VARIABLES.logsEndpoint) ??\n readString(ENVIRONMENT_VARIABLES.otlpLogsEndpoint);\n\n const logs = {\n ...(logsEnabled === undefined ? {} : { enabled: logsEnabled }),\n ...(logsEndpoint === undefined ? {} : { endpoint: logsEndpoint }),\n ...(logsIncludeContent === undefined ? {} : { includeContent: logsIncludeContent }),\n };\n\n const exporter = {\n ...(exporterEnabled === undefined ? {} : { enabled: exporterEnabled }),\n ...(endpoint === undefined ? {} : { endpoint }),\n ...(protocol === undefined ? {} : { protocol }),\n ...(timeoutMillis === undefined ? {} : { timeoutMillis }),\n ...(serviceName === undefined ? {} : { serviceName }),\n ...(serviceNamespace === undefined ? {} : { serviceNamespace }),\n ...(Object.keys(resourceAttributes).length === 0 ? {} : { resourceAttributes }),\n ...(Object.keys(logs).length === 0 ? {} : { logs }),\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 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 };\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,CAAC;AAE1D,IAAM,kBAAkB,MAAmB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,qBAAqB;AAE/E,IAAM,qBAAqB,gBAAgB,EAAE,MAAsB;AAGnE,IAAM,kBAAkB,gBAAgB,EAAE,MAAmB;AAG7D,IAAM,gBAAgB,gBAAgB,EAAE,MAAiB;AAQzD,IAAM,uBAAuB;AAC7B,IAAM,oBAAoB,EAC9B,OAAO,EACP,MAAM,sBAAsB,0DAA0D,EACtF,MAAqB;AAIjB,IAAM,sBAAsB;AAC5B,IAAM,mBAAmB,EAC7B,OAAO,EACP,IAAI,CAAC,EACL,IAAI,EAAE,EACN,MAAM,qBAAqB,8CAA8C,EACzE,MAAoB;AAIhB,IAAM,sBAAsB;AAG5B,IAAM,2BAA2B,EAAE,MAA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,QAAM,cAAc,aAAa,SAAY,CAAC,IAAI,EAAE,SAAS;AAE7D,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,EACjE;AAEA,SAAO,EAAE,OAAO,SAAS;AAC3B;","names":["z","z","z","z","z","z","z","z","z","z","parsed"]}
1
+ {"version":3,"sources":["../src/config/resource-attributes.ts","../src/model/primitives.ts","../src/privacy/policy.ts","../src/config/schema.ts","../src/config/resolve.ts","../src/errors/index.ts","../src/errors/taxonomy.ts","../src/config/otlp-headers.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 { 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 { 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 * 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});\nexport type ExporterPolicy = z.infer<typeof exporterPolicySchema>;\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\nexport const otelHookConfigSchema = z.strictObject({\n exporter: exporterPolicySchema,\n privacy: privacyPolicySchema,\n detection: detectionPolicySchema,\n diagnostics: diagnosticsPolicySchema,\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 })\n .partial()\n .extend({ logs: logsPolicySchema.partial().optional() })\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});\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});\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_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});\n\n/** Content mode is re-exported for callers building patches. */\nexport { contentModeSchema };\n","import { z } from \"zod\";\n\nimport { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { Attributes } from \"../model/primitives.js\";\nimport { describeResourceAttributeNames } from \"./resource-attributes.js\";\nimport {\n DEFAULT_CONFIG,\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 if (isPlainObject(value) && isPlainObject(existing)) {\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 if (parsed.data.exporter.enabled && parsed.data.exporter.protocol !== \"none\" && parsed.data.exporter.endpoint === undefined) {\n notes.push(\"exporter.enabled is true but no endpoint is configured\");\n }\n if (\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 (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 * 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 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.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 \"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 };\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 * 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\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\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 */\nconst 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\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 { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport { detectionConfidenceSchema } from \"../model/primitives.js\";\nimport { contentModeSchema } from \"../privacy/policy.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 */\nexport const ENVIRONMENT_VARIABLES = Object.freeze({\n exporterEnabled: \"OTEL_HOOK_ENABLED\",\n exporterEndpoint: \"OTEL_HOOK_EXPORTER_ENDPOINT\",\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 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});\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 const endpoint =\n readString(ENVIRONMENT_VARIABLES.exporterEndpoint) ??\n readString(ENVIRONMENT_VARIABLES.otlpEndpoint);\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 const logsEndpoint =\n readString(ENVIRONMENT_VARIABLES.logsEndpoint) ??\n readString(ENVIRONMENT_VARIABLES.otlpLogsEndpoint);\n\n const logs = {\n ...(logsEnabled === undefined ? {} : { enabled: logsEnabled }),\n ...(logsEndpoint === undefined ? {} : { endpoint: logsEndpoint }),\n ...(logsIncludeContent === undefined ? {} : { includeContent: logsIncludeContent }),\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 };\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 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 }),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S;AAC3B;","names":["z","z","z","z","z","z","z","z","z","z","parsed"]}
@@ -209,6 +209,11 @@ declare const targetHintSchema: z.ZodReadonly<z.ZodObject<{
209
209
  baseDirectory: z.ZodOptional<z.ZodString>;
210
210
  }, z.core.$strict>>;
211
211
  type TargetHint = z.infer<typeof targetHintSchema>;
212
+ /**
213
+ * The weakest hint: the session's own directory. Every adapter gives it to a
214
+ * session start and a prompt, and to a tool call that names no path.
215
+ */
216
+ declare const sessionCwdHint: (cwd: string | undefined) => TargetHint | undefined;
212
217
  /**
213
218
  * Whether a worktree is its repository's main checkout (`main`) or one added
214
219
  * beside it with `git worktree add` (`linked`).
@@ -347,6 +352,20 @@ declare const sessionStartEventSchema: z.ZodObject<{
347
352
  vendor: z.ZodOptional<z.ZodString>;
348
353
  family: z.ZodOptional<z.ZodString>;
349
354
  }, z.core.$strict>>;
355
+ target: z.ZodOptional<z.ZodReadonly<z.ZodObject<{
356
+ workspaceId: z.core.$ZodBranded<z.ZodString, "WorkspaceId", "out">;
357
+ vcsBranchName: z.ZodOptional<z.ZodString>;
358
+ source: z.ZodEnum<{
359
+ "tool-path": "tool-path";
360
+ "shell-cwd": "shell-cwd";
361
+ "session-cwd": "session-cwd";
362
+ }>;
363
+ repositoryId: z.ZodOptional<z.core.$ZodBranded<z.ZodString, "WorkspaceId", "out">>;
364
+ worktreeKind: z.ZodOptional<z.ZodEnum<{
365
+ main: "main";
366
+ linked: "linked";
367
+ }>>;
368
+ }, z.core.$strict>>>;
350
369
  }, z.core.$strict>;
351
370
  declare const sessionEndEventSchema: z.ZodObject<{
352
371
  schemaVersion: z.ZodLiteral<1>;
@@ -512,6 +531,20 @@ declare const promptSubmittedEventSchema: z.ZodObject<{
512
531
  label: z.ZodOptional<z.ZodString>;
513
532
  }, z.core.$strict>>;
514
533
  turnIndex: z.ZodOptional<z.ZodNumber>;
534
+ target: z.ZodOptional<z.ZodReadonly<z.ZodObject<{
535
+ workspaceId: z.core.$ZodBranded<z.ZodString, "WorkspaceId", "out">;
536
+ vcsBranchName: z.ZodOptional<z.ZodString>;
537
+ source: z.ZodEnum<{
538
+ "tool-path": "tool-path";
539
+ "shell-cwd": "shell-cwd";
540
+ "session-cwd": "session-cwd";
541
+ }>;
542
+ repositoryId: z.ZodOptional<z.core.$ZodBranded<z.ZodString, "WorkspaceId", "out">>;
543
+ worktreeKind: z.ZodOptional<z.ZodEnum<{
544
+ main: "main";
545
+ linked: "linked";
546
+ }>>;
547
+ }, z.core.$strict>>>;
515
548
  }, z.core.$strict>;
516
549
  declare const generationStartEventSchema: z.ZodObject<{
517
550
  schemaVersion: z.ZodLiteral<1>;
@@ -1304,6 +1337,20 @@ declare const canonicalEventSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
1304
1337
  vendor: z.ZodOptional<z.ZodString>;
1305
1338
  family: z.ZodOptional<z.ZodString>;
1306
1339
  }, z.core.$strict>>;
1340
+ target: z.ZodOptional<z.ZodReadonly<z.ZodObject<{
1341
+ workspaceId: z.core.$ZodBranded<z.ZodString, "WorkspaceId", "out">;
1342
+ vcsBranchName: z.ZodOptional<z.ZodString>;
1343
+ source: z.ZodEnum<{
1344
+ "tool-path": "tool-path";
1345
+ "shell-cwd": "shell-cwd";
1346
+ "session-cwd": "session-cwd";
1347
+ }>;
1348
+ repositoryId: z.ZodOptional<z.core.$ZodBranded<z.ZodString, "WorkspaceId", "out">>;
1349
+ worktreeKind: z.ZodOptional<z.ZodEnum<{
1350
+ main: "main";
1351
+ linked: "linked";
1352
+ }>>;
1353
+ }, z.core.$strict>>>;
1307
1354
  }, z.core.$strict>, z.ZodObject<{
1308
1355
  schemaVersion: z.ZodLiteral<1>;
1309
1356
  eventId: z.core.$ZodBranded<z.ZodString, "EventId", "out">;
@@ -1467,6 +1514,20 @@ declare const canonicalEventSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
1467
1514
  label: z.ZodOptional<z.ZodString>;
1468
1515
  }, z.core.$strict>>;
1469
1516
  turnIndex: z.ZodOptional<z.ZodNumber>;
1517
+ target: z.ZodOptional<z.ZodReadonly<z.ZodObject<{
1518
+ workspaceId: z.core.$ZodBranded<z.ZodString, "WorkspaceId", "out">;
1519
+ vcsBranchName: z.ZodOptional<z.ZodString>;
1520
+ source: z.ZodEnum<{
1521
+ "tool-path": "tool-path";
1522
+ "shell-cwd": "shell-cwd";
1523
+ "session-cwd": "session-cwd";
1524
+ }>;
1525
+ repositoryId: z.ZodOptional<z.core.$ZodBranded<z.ZodString, "WorkspaceId", "out">>;
1526
+ worktreeKind: z.ZodOptional<z.ZodEnum<{
1527
+ main: "main";
1528
+ linked: "linked";
1529
+ }>>;
1530
+ }, z.core.$strict>>>;
1470
1531
  }, z.core.$strict>, z.ZodObject<{
1471
1532
  schemaVersion: z.ZodLiteral<1>;
1472
1533
  eventId: z.core.$ZodBranded<z.ZodString, "EventId", "out">;
@@ -2202,6 +2263,16 @@ type ErrorRaisedEvent = z.infer<typeof errorRaisedEventSchema>;
2202
2263
  type CanonicalEventOfType<TType extends CanonicalEventType> = Extract<CanonicalEvent, {
2203
2264
  type: TType;
2204
2265
  }>;
2266
+ /**
2267
+ * The event types that may carry a resolved `target` (ADR 0008): a tool call
2268
+ * names the worktree it touched; a session start and a prompt name the one the
2269
+ * session runs in, so a consumer knows the session's place before its first
2270
+ * tool call.
2271
+ */
2272
+ declare const TARGETED_EVENT_TYPES: readonly ["session.start", "prompt.submitted", "tool.start", "tool.end"];
2273
+ type TargetedEventType = (typeof TARGETED_EVENT_TYPES)[number];
2274
+ type TargetedEvent = CanonicalEventOfType<TargetedEventType>;
2275
+ declare const isTargetedEvent: (event: CanonicalEvent) => event is TargetedEvent;
2205
2276
  type EventValidationResult = {
2206
2277
  readonly status: "ok";
2207
2278
  readonly event: CanonicalEvent;
@@ -2217,4 +2288,4 @@ declare const eventUsage: (event: CanonicalEvent) => CanonicalUsage | undefined;
2217
2288
  /** Stable ordering: by sequence, then by timestamp, then by event id. */
2218
2289
  declare const compareEvents: (a: CanonicalEvent, b: CanonicalEvent) => number;
2219
2290
 
2220
- export { normalizeUsage as $, type UsageNormalizationResult as A, type UsageReport as B, CANONICAL_EVENT_TYPES as C, type UsageTemporality as D, EMPTY_DELTA_USAGE as E, type WorktreeKind as F, type GenerationEndEvent as G, addUsage as H, cacheCreationAccountingSchema as I, canonicalEventSchema as J, canonicalEventTypeSchema as K, canonicalUsageSchema as L, MAX_TARGET_HINT_PATHS as M, compactionPerformedEventSchema as N, compareEvents as O, type PromptSubmittedEvent as P, costFactsSchema as Q, cumulativeToDelta as R, SUBAGENT_ID_PATTERN as S, type TargetHint as T, type UsageDeltaResult as U, errorRaisedEventSchema as V, type WorkspaceTarget as W, eventUsage as X, generationEndEventSchema as Y, generationStartEventSchema as Z, modelDescriptorSchema as _, type CacheCreationAccounting as a, normalizeUsageOrThrow as a0, parseCanonicalEvent as a1, promptSubmittedEventSchema as a2, providerTotalAgreementSchema as a3, sessionEndEventSchema as a4, sessionStartEventSchema as a5, subagentEndEventSchema as a6, subagentIdSchema as a7, subagentStartEventSchema as a8, targetHintSchema as a9, targetSourceSchema as aa, toReport as ab, toolEndEventSchema as ac, toolKindSchema as ad, toolStartEventSchema as ae, usageReportSchema as af, usageTemporalitySchema as ag, validateCanonicalEvent as ah, workspaceTargetSchema as ai, worktreeKindSchema as aj, type CanonicalEvent as b, type CanonicalEventInput as c, type CanonicalEventOfType as d, type CanonicalEventType as e, type CanonicalUsage as f, type CompactionPerformedEvent as g, type CostFacts as h, type ErrorRaisedEvent as i, type EventOutcome as j, type EventValidationResult as k, type GenerationStartEvent as l, MAX_TARGET_PATH_LENGTH as m, type ModelDescriptor as n, type ProviderTotalAgreement as o, type SessionEndEvent as p, type SessionStartEvent as q, type SubagentEndEvent as r, type SubagentId as s, type SubagentStartEvent as t, type TargetSource as u, type ToolEndEvent as v, type ToolKind as w, type ToolStartEvent as x, UsageNormalizationError as y, type UsageNormalizationIssue as z };
2291
+ export { generationEndEventSchema as $, type ToolStartEvent as A, UsageNormalizationError as B, CANONICAL_EVENT_TYPES as C, type UsageNormalizationIssue as D, EMPTY_DELTA_USAGE as E, type UsageNormalizationResult as F, type GenerationEndEvent as G, type UsageReport as H, type UsageTemporality as I, type WorktreeKind as J, addUsage as K, cacheCreationAccountingSchema as L, MAX_TARGET_HINT_PATHS as M, canonicalEventSchema as N, canonicalEventTypeSchema as O, type PromptSubmittedEvent as P, canonicalUsageSchema as Q, compactionPerformedEventSchema as R, SUBAGENT_ID_PATTERN as S, TARGETED_EVENT_TYPES as T, type UsageDeltaResult as U, compareEvents as V, type WorkspaceTarget as W, costFactsSchema as X, cumulativeToDelta as Y, errorRaisedEventSchema as Z, eventUsage as _, type CacheCreationAccounting as a, generationStartEventSchema as a0, isTargetedEvent as a1, modelDescriptorSchema as a2, normalizeUsage as a3, normalizeUsageOrThrow as a4, parseCanonicalEvent as a5, promptSubmittedEventSchema as a6, providerTotalAgreementSchema as a7, sessionCwdHint as a8, sessionEndEventSchema as a9, sessionStartEventSchema as aa, subagentEndEventSchema as ab, subagentIdSchema as ac, subagentStartEventSchema as ad, targetHintSchema as ae, targetSourceSchema as af, toReport as ag, toolEndEventSchema as ah, toolKindSchema as ai, toolStartEventSchema as aj, usageReportSchema as ak, usageTemporalitySchema as al, validateCanonicalEvent as am, workspaceTargetSchema as an, worktreeKindSchema as ao, type CanonicalEvent as b, type CanonicalEventInput as c, type CanonicalEventOfType as d, type CanonicalEventType as e, type CanonicalUsage as f, type CompactionPerformedEvent as g, type CostFacts as h, type ErrorRaisedEvent as i, type EventOutcome as j, type EventValidationResult as k, type GenerationStartEvent as l, MAX_TARGET_PATH_LENGTH as m, type ModelDescriptor as n, type ProviderTotalAgreement as o, type SessionEndEvent as p, type SessionStartEvent as q, type SubagentEndEvent as r, type SubagentId as s, type SubagentStartEvent as t, type TargetHint as u, type TargetSource as v, type TargetedEvent as w, type TargetedEventType as x, type ToolEndEvent as y, type ToolKind as z };
@@ -1,4 +1,4 @@
1
- import { e as StateStore, C as Clock, d as Logger } from './ports-B0rC49b3.js';
1
+ import { e as StateStore, C as Clock, d as Logger } from './ports-n7KFOpKo.js';
2
2
  import { S as StoreNamespace } from './keys-Dej5bN3L.js';
3
3
 
4
4
  /**
@@ -1,13 +1,13 @@
1
1
  import { z } from 'zod';
2
2
  import { O as OtelHookConfig } from './schema-Cn0-xz8L.js';
3
3
  import { OtelHookErrorInfo } from './errors.js';
4
- import { b as CanonicalEvent, D as UsageTemporality, f as CanonicalUsage } from './events-CzZ5kukS.js';
4
+ import { b as CanonicalEvent, I as UsageTemporality, f as CanonicalUsage } from './events-B3MHoJTD.js';
5
5
  import { I as IdentityClaim, W as WorkspaceIdentity, d as InvocationIdentity } from './identity-BrVBs901.js';
6
6
  import { h as SourceTransport, R as ResolvedProviderId, c as DetectionConfidence, d as EventId } from './primitives-CJ8-rn-f.js';
7
7
  import { P as PrivacyService } from './service-CbI9CObT.js';
8
- import { b as DeliveryIdentifierSupport, f as ProviderDeliveryClaim, j as ProviderHookResponse } from './adapter-BS7xHKGQ.js';
9
- import { P as ProviderRegistry } from './registry-DVnPA_b6.js';
10
- import { I as IdGenerator, g as TelemetrySink, e as StateStore, C as Clock, d as Logger, W as WorktreeLocator } from './ports-B0rC49b3.js';
8
+ import { b as DeliveryIdentifierSupport, f as ProviderDeliveryClaim, j as ProviderHookResponse } from './adapter-BJiz6lqM.js';
9
+ import { P as ProviderRegistry } from './registry-CIVvRlVK.js';
10
+ import { I as IdGenerator, g as TelemetrySink, e as StateStore, C as Clock, d as Logger, W as WorktreeLocator } from './ports-n7KFOpKo.js';
11
11
  import { A as AttributionOutcome, a as AttributionReason } from './taxonomy-DwhTtuWd.js';
12
12
 
13
13
  /**