@osfactory/otel-hook 0.12.0 → 0.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -4
- package/dist/{adapter-DQiPu8xF.d.ts → adapter-DyCb7y1N.d.ts} +1 -1
- package/dist/cli.js +260 -74
- package/dist/cli.js.map +1 -1
- package/dist/{export-destinations-CI7z4n3i.d.ts → export-destinations-DUeQKr_C.d.ts} +2 -2
- package/dist/{filesystem-store-CmnUlj1O.d.ts → filesystem-store-B3CpiIRl.d.ts} +1 -1
- package/dist/{hook-vM_cgqS2.d.ts → hook-D5imE0Qc.d.ts} +3 -3
- package/dist/index.d.ts +10 -10
- package/dist/index.js +252 -66
- package/dist/index.js.map +1 -1
- package/dist/install.d.ts +3 -3
- package/dist/install.js +14 -2
- package/dist/install.js.map +1 -1
- package/dist/integration.d.ts +7 -7
- package/dist/integration.js +211 -58
- package/dist/integration.js.map +1 -1
- package/dist/lifecycle.d.ts +9 -2
- package/dist/lifecycle.js +10 -3
- package/dist/lifecycle.js.map +1 -1
- package/dist/{memory-DdU1U91y.d.ts → memory-B3r6sZtC.d.ts} +1 -1
- package/dist/{metric-model-C9lLqqpI.d.ts → metric-model-B4lIuk6i.d.ts} +10 -1
- package/dist/{payload-BT19hiVZ.d.ts → payload-CdDKeRpH.d.ts} +1 -1
- package/dist/{ports-C3k_5eOQ.d.ts → ports-DhpSDIkp.d.ts} +8 -1
- package/dist/providers.d.ts +27 -11
- package/dist/providers.js +132 -43
- package/dist/providers.js.map +1 -1
- package/dist/{registry-gyJqaWmp.d.ts → registry-BKQhhIO3.d.ts} +1 -1
- package/dist/runtime.d.ts +6 -6
- package/dist/runtime.js +12 -2
- package/dist/runtime.js.map +1 -1
- package/dist/state.d.ts +3 -3
- package/dist/state.js +20 -6
- package/dist/state.js.map +1 -1
- package/dist/telemetry.d.ts +3 -3
- package/dist/telemetry.js +72 -6
- package/dist/telemetry.js.map +1 -1
- package/dist/testing.d.ts +6 -6
- package/dist/testing.js +63 -8
- package/dist/testing.js.map +1 -1
- package/package.json +2 -1
package/dist/telemetry.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/telemetry/semconv.ts","../src/version.ts","../src/telemetry/export-identity.ts","../src/model/events.ts","../src/errors/taxonomy.ts","../src/model/content.ts","../src/model/primitives.ts","../src/model/extensions.ts","../src/model/identity.ts","../src/model/target.ts","../src/model/usage.ts","../src/model/version.ts","../src/telemetry/spool-queue.ts","../src/state/keys.ts","../src/telemetry/durable-spool.ts","../src/telemetry/otlp-sink.ts","../src/errors/index.ts","../src/diagnostics/health.ts","../src/telemetry/export-failure.ts","../src/telemetry/exporter-resource.ts","../src/config/resource-attributes.ts","../src/privacy/policy.ts","../src/telemetry/log-records.ts","../src/telemetry/durable-log-spool.ts","../src/telemetry/otlp-log-sink.ts","../src/config/otlp-endpoint.ts","../src/telemetry/signal-fanout.ts","../src/config/destinations.ts","../src/config/header-value.ts","../src/config/otlp-headers.ts","../src/config/schema.ts","../src/telemetry/metric-model.ts","../src/telemetry/durable-metric-spool.ts","../src/telemetry/otlp-metric-sink.ts","../src/telemetry/export-destinations.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\n\nimport { SpanKind, SpanStatusCode, TraceFlags, type Attributes, type SpanContext, type SpanStatus } from \"@opentelemetry/api\";\nimport { millisToHrTime } from \"@opentelemetry/core\";\nimport type { InstrumentationScope } from \"@opentelemetry/core\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport type { ReadableSpan } from \"@opentelemetry/sdk-trace\";\nimport {\n ATTR_ERROR_TYPE,\n ATTR_GEN_AI_OPERATION_NAME,\n ATTR_GEN_AI_REQUEST_MODEL,\n ATTR_GEN_AI_RESPONSE_MODEL,\n ATTR_GEN_AI_SYSTEM,\n ATTR_GEN_AI_TOOL_CALL_ID,\n ATTR_GEN_AI_TOOL_NAME,\n ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n} from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport type { CanonicalEvent, CanonicalEventType } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\nimport { VERSION } from \"../version.js\";\nimport {\n ATTR_OTELHOOK_TARGET_REPOSITORY_ID,\n ATTR_OTELHOOK_TARGET_SOURCE,\n ATTR_OTELHOOK_TARGET_WORKSPACE_ID,\n ATTR_OTELHOOK_TARGET_WORKTREE_KIND,\n ATTR_VCS_REF_HEAD_NAME,\n exportIdentityAttributes,\n profileAttributes,\n targetAttributes,\n usageTemporalityAttributes,\n} from \"./export-identity.js\";\n\nconst SCOPE_NAME = \"@osfactory/otel-hook\";\n\nexport const DEFAULT_INSTRUMENTATION_SCOPE: InstrumentationScope = Object.freeze({\n name: SCOPE_NAME,\n version: VERSION,\n});\n\nconst ATTR_OTELHOOK_SPAN_PAIRED = \"otelhook.span.paired\";\nconst ATTR_OTELHOOK_SPAN_PAIRING = \"otelhook.span.pairing\";\nconst ATTR_OTELHOOK_SPAN_ORPHAN = \"otelhook.span.orphan\";\nconst ATTR_OTELHOOK_OUTCOME = \"otelhook.outcome\";\nconst ATTR_OTELHOOK_RESET_DETECTED = \"otelhook.usage.reset_detected\";\n/** True when a generation's usage covers only part of it; see `generation.end.usagePartial`. */\nexport const ATTR_OTELHOOK_USAGE_PARTIAL = \"otelhook.usage.partial\";\nconst ATTR_OTELHOOK_TOOL_KIND = \"otelhook.tool.kind\";\nconst ATTR_OTELHOOK_DELEGATION_DEPTH = \"otelhook.delegation_depth\";\nconst ATTR_OTELHOOK_COMPACTION_TRIGGER = \"otelhook.compaction.trigger\";\nconst ATTR_OTELHOOK_AGENT_NAME = \"otelhook.agent.name\";\nconst ATTR_OTELHOOK_AGENT_VERSION = \"otelhook.agent.version\";\nconst ATTR_OTELHOOK_GENERATION_ID = \"otelhook.generation.id\";\n\n/**\n * Pure, stateless canonical-event-to-span mapping.\n *\n * Isolated in one module so every other piece of the telemetry pipeline\n * — batching, retry, spooling — can change without touching what an attribute\n * means. Two edges of the same lifecycle scope are merged into one span when\n * they appear in the same batch; when they arrive in *different* short-lived\n * hook processes they are merged through a {@link SpanCorrelation} the caller\n * resolved from persisted state. Either way the mapping itself stays a pure\n * function: state is read by the correlator, never by this module.\n *\n * ## Identity of a span\n *\n * Trace and span ids are derived, never random, so two processes that never\n * meet still agree on them:\n *\n * - `traceId = H(providerId, sessionId)` — one trace per session per provider.\n * Deriving it from the session rather than the invocation is what lets a\n * `tool.end` emitted minutes later land in the same trace as its `tool.start`;\n * including the provider is what stops two providers that happen to reuse a\n * session id from being stitched into one trace.\n * - `spanId = H(providerId, sessionId, family, scopeKey)` — stable across\n * processes and idempotent under redelivery, so a collector that sees a\n * start-only span and later the completed span treats them as one span\n * rather than two.\n */\n// NUL, so joined parts cannot collide across a different split: no identifier\n// this library accepts can contain one, which a printable separator cannot\n// promise. Never emitted — only hashed, or used as an in-memory map key.\nconst FIELD_SEPARATOR = \"\\u0000\";\n\nconst digestHex = (parts: readonly string[], length: number): string =>\n createHash(\"sha256\").update(parts.join(FIELD_SEPARATOR)).digest(\"hex\").slice(0, length);\n\n/** Lifecycle scopes that pair a `*.start` edge with a later `*.end` edge. */\nexport type SpanFamily = \"session\" | \"generation\" | \"tool\" | \"subagent\";\n\n/** Identifies one lifecycle span within a session. */\nexport type SpanScopeRef = {\n readonly family: SpanFamily;\n readonly scopeKey: string;\n};\n\n/**\n * Why a lifecycle span is, or is not, a complete pair.\n *\n * Deliberately explicit rather than a bare boolean: \"we never saw the start\",\n * \"we saw it but it aged out of state\", and \"state could not be read at all\"\n * are different operational facts, and a dashboard that cannot tell them apart\n * cannot tell a broken host from a broken exporter.\n */\nexport type SpanOrphanClassification =\n /** Both edges are known — from this batch, or from persisted state. */\n | \"none\"\n /** The start is known; its end has not arrived yet. */\n | \"missing-end\"\n /** An end arrived and no start was ever recorded for this scope. */\n | \"missing-start\"\n /** A start was recorded but aged past the retention window before the end arrived. */\n | \"expired-start\"\n /** A start exists but was recorded by a different provider; pairing it would be a guess. */\n | \"provider-mismatch\"\n /** A second, distinct end arrived for a scope that was already closed. */\n | \"already-closed\"\n /** The persisted record was written by an incompatible version and was discarded. */\n | \"state-incompatible\"\n /** The persisted record could not be understood. */\n | \"state-corrupt\"\n /** State could not be consulted at all; the mapping degraded rather than failing. */\n | \"state-unavailable\";\n\nexport type SpanPairing =\n /** Both edges were present in this batch. */\n | \"in-batch\"\n /** The other edge came from state written by an earlier process. */\n | \"cross-process\"\n | \"unpaired\";\n\n/**\n * Whether this scope should produce an OTLP record now.\n *\n * OTLP has no notion of updating a span: a span is exported once, when it ends,\n * and a second record carrying the same trace and span id is not a revision of\n * the first — it is a duplicate that backends variously drop, keep the older of,\n * or display twice. Since every lifecycle span id here is *derived* from\n * `(provider, session, family, scopeKey)`, a `*.start` edge and its later `*.end`\n * edge compute the identical id, so exporting on both is precisely that\n * duplicate.\n *\n * `defer` is therefore the answer for a start whose end has not arrived: the\n * start is durable in the state store, and the end edge exports the one complete\n * span using the times recovered from it. Nothing is lost by waiting, and what is\n * gained is that the record a collector receives has a real duration.\n */\nexport type SpanDisposition =\n /** Export a record for this scope now. */\n | \"emit\"\n /** Hold: the start is recorded, and the end edge will export the complete span. */\n | \"defer\";\n\n/**\n * One scope's correlation facts, resolved from persisted state by the caller.\n *\n * Plain data on purpose: the telemetry layer must not reach into the state\n * store itself (ADR 0006), so it declares what it needs and the lifecycle layer\n * supplies it.\n */\nexport type SpanCorrelation = {\n readonly providerId: string;\n readonly sessionId: string;\n readonly ref: SpanScopeRef;\n readonly pairing: SpanPairing;\n readonly orphan: SpanOrphanClassification;\n /**\n * Whether to export a record for this scope now. Defaults to `emit` when a\n * correlation is supplied without one.\n */\n readonly disposition?: SpanDisposition;\n /**\n * Extra component mixed into the derived span id.\n *\n * Set only when this record is a genuinely *additional* observation of a scope\n * that has already been exported once — a second, distinct end for a scope that\n * was already closed. Both records are real, so neither is dropped, and the\n * discriminator keeps them from claiming the same span id.\n */\n readonly spanIdDiscriminator?: string;\n /** Start recovered from state; authoritative over the batch's own start edge. */\n readonly startMillis?: number;\n /** End recovered from state; authoritative so a redelivered end re-exports an identical span. */\n readonly endMillis?: number;\n /** Parent recorded at start time, so an end-only process hangs the span in the same place. */\n readonly parent?: SpanScopeRef;\n /** Attributes only the start edge could supply, recovered for an end-only span. */\n readonly attributes?: Attributes;\n};\n\n/**\n * Resolves persisted correlation for one batch.\n *\n * Must never reject: a state failure is a degraded span, never a lost export.\n */\nexport type SpanCorrelationResolver = (\n events: readonly CanonicalEvent[],\n) => Promise<readonly SpanCorrelation[]>;\n\n/**\n * Upper bound on how many start-edge attributes the correlator may carry\n * forward, so persisted state cannot grow with provider-controlled input.\n */\nexport const MAX_RECOVERED_START_ATTRIBUTES = 16;\n\nconst familyOf = (type: CanonicalEventType): SpanFamily | undefined => {\n switch (type) {\n case \"session.start\":\n case \"session.end\":\n return \"session\";\n case \"generation.start\":\n case \"generation.end\":\n return \"generation\";\n case \"tool.start\":\n case \"tool.end\":\n return \"tool\";\n case \"subagent.start\":\n case \"subagent.end\":\n return \"subagent\";\n default:\n return undefined;\n }\n};\n\n/** The lifecycle span an event is an edge of, or undefined for a point-in-time event. */\nexport const spanScopeRefOf = (event: CanonicalEvent): SpanScopeRef | undefined => {\n const family = familyOf(event.type);\n if (family === undefined) {\n return undefined;\n }\n switch (event.type) {\n case \"session.start\":\n case \"session.end\":\n return { family, scopeKey: event.sessionId };\n case \"generation.start\":\n case \"generation.end\":\n return { family, scopeKey: event.generationId };\n case \"tool.start\":\n case \"tool.end\":\n return { family, scopeKey: event.toolCallId };\n case \"subagent.start\":\n case \"subagent.end\":\n return { family, scopeKey: event.subagentInvocationId };\n default:\n return undefined;\n }\n};\n\n/**\n * Where a span hangs in the trace, judged from this event alone.\n *\n * Everything in a session descends from the session span. A tool call names its\n * generation only on `tool.start`, which is exactly why the correlator persists\n * the parent: the `tool.end` process would otherwise reparent the same span to\n * the session and produce a tree whose shape depends on which edge happened to\n * be exported last.\n */\nexport const parentScopeRefOf = (event: CanonicalEvent): SpanScopeRef | undefined => {\n if (event.type === \"session.start\" || event.type === \"session.end\") {\n return undefined;\n }\n if (event.type === \"tool.start\" && event.generationId !== undefined) {\n return { family: \"generation\", scopeKey: event.generationId };\n }\n return { family: \"session\", scopeKey: event.sessionId };\n};\n\n/**\n * Span attributes that only a `*.start` edge can supply.\n *\n * The correlator persists these verbatim so an end-only span in a later process\n * still carries the tool kind, requested model, delegation depth, or agent name\n * the start process saw. An allowlist, and bounded, so persisted state can\n * never become a second route for provider payload content to escape.\n */\nexport const startOnlySpanAttributes = (event: CanonicalEvent): Attributes => {\n switch (event.type) {\n // The session's own worktree is carried forward like a tool's target, so\n // the session span a later `session.end` process exports still names it.\n case \"session.start\":\n return {\n ...(event.agentName === undefined ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: event.agentName }),\n ...(event.agentVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_AGENT_VERSION]: event.agentVersion }),\n ...targetAttributes(event),\n };\n case \"generation.start\":\n return {\n [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId,\n ...(event.model.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: event.model.vendor }),\n };\n // `toolName` and `toolCallId` are on both tool edges, so they are not\n // start-only and persisting them would just pad every record.\n // The target is carried forward too: an end-only process may see a payload\n // with less to go on (no tool input), and the start's evidence still holds.\n case \"tool.start\":\n return { [ATTR_OTELHOOK_TOOL_KIND]: event.toolKind, ...targetAttributes(event) };\n case \"subagent.start\":\n return { [ATTR_OTELHOOK_DELEGATION_DEPTH]: event.delegationDepth };\n default:\n return {};\n }\n};\n\nconst deriveTraceId = (providerId: string, sessionId: string): string =>\n digestHex([\"otelhook/trace\", providerId, sessionId], 32);\n\nconst deriveSpanId = (providerId: string, sessionId: string, ref: SpanScopeRef): string =>\n digestHex([\"otelhook/span\", providerId, sessionId, ref.family, ref.scopeKey], 16);\n\nconst deriveStandaloneSpanId = (\n providerId: string,\n sessionId: string,\n eventType: string,\n eventId: string,\n): string => digestHex([\"otelhook/span\", providerId, sessionId, \"event\", eventType, eventId], 16);\n\nconst correlationKey = (providerId: string, sessionId: string, ref: SpanScopeRef): string =>\n [providerId, sessionId, ref.family, ref.scopeKey].join(FIELD_SEPARATOR);\n\nconst outcomeStatus = (outcome: string | undefined): SpanStatus => {\n if (outcome === undefined || outcome === \"ok\" || outcome === \"unknown\") {\n return { code: SpanStatusCode.UNSET };\n }\n if (outcome === \"cancelled\") {\n return { code: SpanStatusCode.UNSET };\n }\n return { code: SpanStatusCode.ERROR, message: outcome };\n};\n\nconst identityAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n ids: { readonly traceId: string; readonly spanId: string; readonly parentSpanId?: string },\n): Attributes => exportIdentityAttributes(event, resource, ids);\n\nconst usageAttributes = (usage: CanonicalUsage | undefined, resetDetected: boolean): Attributes => {\n if (usage === undefined) {\n return {};\n }\n return {\n [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: usage.inputTokens,\n [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: usage.outputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: usage.cachedInputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: usage.cacheCreationInputTokens,\n [ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]: usage.reasoningOutputTokens,\n ...usageTemporalityAttributes(usage),\n ...(resetDetected ? { [ATTR_OTELHOOK_RESET_DETECTED]: true } : {}),\n };\n};\n\n/** Evidence strength of a target source; see `targetSourceSchema`. */\nconst TARGET_SOURCE_RANK: Readonly<Record<string, number>> = Object.freeze({\n \"tool-path\": 3,\n \"shell-cwd\": 2,\n \"session-cwd\": 1,\n});\n\nconst TARGET_KEYS = [\n ATTR_OTELHOOK_TARGET_WORKSPACE_ID,\n ATTR_OTELHOOK_TARGET_SOURCE,\n ATTR_VCS_REF_HEAD_NAME,\n ATTR_OTELHOOK_TARGET_REPOSITORY_ID,\n ATTR_OTELHOOK_TARGET_WORKTREE_KIND,\n] as const;\n\nconst pickTarget = (attributes: Attributes): Attributes => {\n const picked: Attributes = {};\n for (const key of TARGET_KEYS) {\n if (attributes[key] !== undefined) {\n picked[key] = attributes[key];\n }\n }\n return picked;\n};\n\n/**\n * Drop the target keys so they can be re-chosen as one unit, keeping only what\n * the launcher put on the Resource or the session context named (a\n * `vcs.ref.head.name` passed through by `exportIdentityAttributes`) as the\n * fallback beneath the chosen target.\n */\nconst withoutTarget = (attributes: Attributes, resource: Resource, event: CanonicalEvent): Attributes => {\n const rest: Attributes = { ...attributes };\n for (const key of TARGET_KEYS) {\n delete rest[key];\n }\n return { ...rest, ...pickTarget(profileAttributes(event, resource)) };\n};\n\nconst rankOf = (candidate: Attributes): number => {\n const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];\n return typeof source === \"string\" && Object.hasOwn(TARGET_SOURCE_RANK, source)\n ? (TARGET_SOURCE_RANK[source] ?? 0)\n : 0;\n};\n\n/**\n * One span, one target: the strongest evidence among the recovered start,\n * the live start, and the live end — later wins a tie. A Cursor shell call's\n * start knows its `cwd` and its end does not; the span must keep the former,\n * not be downgraded to the workspace root by whichever edge exported last.\n */\nconst strongestTarget = (candidates: readonly Attributes[]): Attributes => {\n let best: Attributes = {};\n let bestRank = 0;\n for (const candidate of candidates) {\n const rank = rankOf(candidate);\n if (rank > 0 && rank >= bestRank) {\n best = candidate;\n bestRank = rank;\n }\n }\n return best;\n};\n\ntype SpanGroup = {\n readonly ref: SpanScopeRef;\n start?: CanonicalEvent;\n end?: CanonicalEvent;\n};\n\nconst buildSpanContext = (traceId: string, spanId: string): SpanContext => ({\n traceId,\n spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n});\n\nexport type ReadableSpanInput = {\n readonly name: string;\n readonly kind: SpanKind;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly attributes: Attributes;\n readonly status: SpanStatus;\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n};\n\n/** Reconstructs a {@link ReadableSpan} from plain, serializable fields. Used by the durable spool to replay a span it persisted earlier. */\nexport const assembleReadableSpan = (input: ReadableSpanInput): ReadableSpan => toReadableSpan(input);\n\nconst toReadableSpan = (input: ReadableSpanInput): ReadableSpan => {\n const startTime = millisToHrTime(input.startMillis);\n const endTime = millisToHrTime(Math.max(input.startMillis, input.endMillis));\n const duration = millisToHrTime(Math.max(0, input.endMillis - input.startMillis));\n return {\n name: input.name,\n kind: input.kind,\n spanContext: (): SpanContext => buildSpanContext(input.traceId, input.spanId),\n ...(input.parentSpanId === undefined\n ? {}\n : { parentSpanContext: buildSpanContext(input.traceId, input.parentSpanId) }),\n startTime,\n endTime,\n status: input.status,\n attributes: input.attributes,\n links: [],\n events: [],\n duration,\n ended: true,\n resource: input.resource,\n instrumentationScope: input.instrumentationScope,\n droppedAttributesCount: 0,\n droppedEventsCount: 0,\n droppedLinksCount: 0,\n };\n};\n\ntype ResolvedPairing = {\n readonly pairing: SpanPairing;\n readonly orphan: SpanOrphanClassification;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly parent: SpanScopeRef | undefined;\n readonly recovered: Attributes;\n};\n\nconst resolvePairing = (\n group: SpanGroup,\n anchor: CanonicalEvent,\n correlation: SpanCorrelation | undefined,\n): ResolvedPairing => {\n const inBatch = group.start !== undefined && group.end !== undefined;\n const batchStart = group.start?.occurredAt ?? anchor.occurredAt;\n const batchEnd = group.end?.occurredAt ?? anchor.occurredAt;\n\n if (correlation === undefined) {\n return {\n pairing: inBatch ? \"in-batch\" : \"unpaired\",\n orphan: inBatch ? \"none\" : group.start === undefined ? \"missing-start\" : \"missing-end\",\n startMillis: batchStart,\n endMillis: inBatch ? batchEnd : batchStart,\n parent: parentScopeRefOf(anchor),\n recovered: {},\n };\n }\n\n // A correlation that reports no start (an orphaned end) must not fabricate\n // one: the span collapses onto the end instant rather than claiming a\n // duration measured from an event nobody ever saw.\n const startMillis = correlation.startMillis ?? (inBatch ? batchStart : batchEnd);\n const endMillis = correlation.endMillis ?? (group.end === undefined ? startMillis : batchEnd);\n return {\n pairing: correlation.pairing,\n orphan: correlation.orphan,\n startMillis,\n endMillis,\n parent: correlation.parent ?? parentScopeRefOf(anchor),\n recovered: correlation.attributes ?? {},\n };\n};\n\nconst buildLifecycleSpan = (\n plan: GroupPlan,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan => {\n const group = plan.group;\n const anchor = plan.anchor;\n const correlation = plan.correlation;\n const providerId = anchor.provenance.providerId;\n const sessionId = anchor.sessionId;\n const resolved = resolvePairing(group, anchor, correlation);\n const traceId = plan.traceId;\n const spanId = plan.spanId;\n const parentSpanId =\n resolved.parent === undefined ? undefined : deriveSpanId(providerId, sessionId, resolved.parent);\n\n let name: string = group.ref.family;\n let kind: SpanKind = SpanKind.INTERNAL;\n let status: SpanStatus = { code: SpanStatusCode.UNSET };\n // Attributes recovered from the start process sit *beneath* whatever this\n // batch observed: a live edge always wins over a remembered one.\n let attributes: Attributes = {\n ...identityAttributes(anchor, resource, {\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n }),\n ...resolved.recovered,\n [ATTR_OTELHOOK_SPAN_PAIRED]: resolved.pairing !== \"unpaired\",\n [ATTR_OTELHOOK_SPAN_PAIRING]: resolved.pairing,\n [ATTR_OTELHOOK_SPAN_ORPHAN]: resolved.orphan,\n };\n\n switch (group.ref.family) {\n case \"session\": {\n const end = group.end?.type === \"session.end\" ? group.end : undefined;\n const start = group.start?.type === \"session.start\" ? group.start : undefined;\n name = \"session\";\n kind = SpanKind.INTERNAL;\n attributes = {\n ...withoutTarget(attributes, resource, anchor),\n ...strongestTarget([pickTarget(resolved.recovered), start === undefined ? {} : targetAttributes(start)]),\n ...(start?.agentName === undefined ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName }),\n ...(start?.agentVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion }),\n ...(end === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.reason }),\n ...usageAttributes(end?.usage, false),\n };\n if (end?.reason === \"error\" || end?.reason === \"timeout\") {\n status = { code: SpanStatusCode.ERROR, message: end.reason };\n }\n break;\n }\n case \"generation\": {\n const start = group.start?.type === \"generation.start\" ? group.start : undefined;\n const end = group.end?.type === \"generation.end\" ? group.end : undefined;\n const model = end?.model ?? start?.model;\n name = model === undefined ? \"generation\" : `generation ${model.modelId}`;\n kind = SpanKind.CLIENT;\n attributes = {\n ...attributes,\n [ATTR_GEN_AI_OPERATION_NAME]: \"chat\",\n ...(model?.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: model.vendor }),\n ...(start?.model?.modelId === undefined ? {} : { [ATTR_GEN_AI_REQUEST_MODEL]: start.model.modelId }),\n ...(end?.model?.modelId === undefined ? {} : { [ATTR_GEN_AI_RESPONSE_MODEL]: end.model.modelId }),\n // The provider's own id for this unit of work (Cursor generation,\n // Codex turn): the key a consumer stores a usage observation under.\n [ATTR_OTELHOOK_GENERATION_ID]: group.ref.scopeKey,\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...usageAttributes(end?.usage, false),\n ...(end?.usage === undefined || end.usagePartial === undefined\n ? {}\n : { [ATTR_OTELHOOK_USAGE_PARTIAL]: end.usagePartial }),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n case \"tool\": {\n const start = group.start?.type === \"tool.start\" ? group.start : undefined;\n const end = group.end?.type === \"tool.end\" ? group.end : undefined;\n const toolName = start?.toolName ?? end?.toolName ?? \"unknown\";\n name = `tool ${toolName}`;\n kind = SpanKind.CLIENT;\n attributes = {\n // Target keys are re-chosen below as one unit, never mixed across edges.\n ...withoutTarget(attributes, resource, anchor),\n [ATTR_GEN_AI_TOOL_NAME]: toolName,\n [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,\n ...(start?.toolKind === undefined ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind }),\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...strongestTarget([\n pickTarget(resolved.recovered),\n start === undefined ? {} : targetAttributes(start),\n end === undefined ? {} : targetAttributes(end),\n ]),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n case \"subagent\": {\n const start = group.start?.type === \"subagent.start\" ? group.start : undefined;\n const end = group.end?.type === \"subagent.end\" ? group.end : undefined;\n name = \"subagent\";\n kind = SpanKind.INTERNAL;\n attributes = {\n ...attributes,\n ...(start?.delegationDepth === undefined\n ? {}\n : { [ATTR_OTELHOOK_DELEGATION_DEPTH]: start.delegationDepth }),\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...usageAttributes(end?.usage, false),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n }\n\n if (status.code === SpanStatusCode.ERROR) {\n attributes = { ...attributes, [ATTR_ERROR_TYPE]: status.message ?? \"error\" };\n }\n\n return toReadableSpan({\n name,\n kind,\n startMillis: resolved.startMillis,\n endMillis: resolved.endMillis,\n attributes,\n status,\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n resource,\n instrumentationScope: scope,\n });\n};\n\nconst buildStandaloneSpan = (\n event: CanonicalEvent,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan => {\n const providerId = event.provenance.providerId;\n const traceId = deriveTraceId(providerId, event.sessionId);\n const spanId = deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId);\n const parent = parentScopeRefOf(event);\n const parentSpanId =\n parent === undefined ? undefined : deriveSpanId(providerId, event.sessionId, parent);\n let attributes: Attributes = {\n ...identityAttributes(event, resource, {\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n }),\n [ATTR_OTELHOOK_SPAN_PAIRED]: true,\n };\n let status: SpanStatus = { code: SpanStatusCode.UNSET };\n let name: string = event.type;\n\n switch (event.type) {\n case \"prompt.submitted\":\n name = \"prompt\";\n attributes = { ...attributes, \"otelhook.prompt.source\": event.promptSource, ...targetAttributes(event) };\n break;\n case \"compaction.performed\":\n name = \"compaction\";\n attributes = {\n ...attributes,\n [ATTR_OTELHOOK_COMPACTION_TRIGGER]: event.trigger,\n ...usageAttributes(event.usage, false),\n };\n break;\n case \"error.raised\":\n name = \"error\";\n status = { code: SpanStatusCode.ERROR, message: event.errorCode };\n attributes = {\n ...attributes,\n [ATTR_ERROR_TYPE]: event.errorCode,\n \"otelhook.error.phase\": event.phase,\n \"otelhook.error.retryable\": event.retryable,\n };\n break;\n default:\n break;\n }\n\n return toReadableSpan({\n name,\n kind: SpanKind.INTERNAL,\n startMillis: event.occurredAt,\n endMillis: event.occurredAt,\n attributes,\n status,\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n resource,\n instrumentationScope: scope,\n });\n};\n\nexport type SemanticMappingOptions = {\n readonly resource: Resource;\n readonly instrumentationScope?: InstrumentationScope;\n /**\n * Cross-process pairing facts, at most one entry per lifecycle scope in\n * `events`. Omitted entirely, the mapping degrades to in-batch pairing only —\n * the behavior of a host that wired no state store.\n */\n readonly correlations?: readonly SpanCorrelation[];\n /**\n * Whether a correlator was consulted at all, and whether it answered.\n *\n * This is what separates \"the state store is holding this start, so the end edge\n * will publish it\" from \"nothing recorded this start\". Both look like an empty\n * `correlations` list, and only the first is safe to drop — dropping the second\n * would discard an observation that was neither persisted nor exported, while a\n * caller that saw zero rejections went on to mark the callback handled.\n *\n * - `true` — the correlator ran; an absent or non-`defer` entry means emit.\n * - `false` — the correlator failed; every unpaired start is emitted as an\n * explicitly labelled, uniquely identified fallback.\n * - omitted — no correlator is wired, so cross-process pairing was never on\n * offer and an unpaired start is deferred (the documented no-state-root\n * degradation).\n */\n readonly correlationAvailable?: boolean;\n};\n\n/**\n * Fill in a correlation for an unpaired start that nothing recorded.\n *\n * Reached when a correlator was consulted and either failed outright or reported\n * nothing for this scope. The synthesized entry says what is true — the state was\n * not consulted successfully, so this span is unpaired and no end can complete it\n * — and carries a discriminator so the record cannot claim the span id a later end\n * will publish for the same scope.\n */\nconst effectiveCorrelation = (\n group: SpanGroup,\n correlation: SpanCorrelation | undefined,\n): SpanCorrelation | undefined => {\n if (correlation !== undefined || group.end !== undefined || group.start === undefined) {\n return correlation;\n }\n return {\n providerId: group.start.provenance.providerId,\n sessionId: group.start.sessionId,\n ref: group.ref,\n pairing: \"unpaired\",\n orphan: \"state-unavailable\",\n disposition: \"emit\",\n spanIdDiscriminator: group.start.eventId,\n };\n};\n\n/** How one batch's events distribute over the lifecycle scopes they are edges of. */\ntype BatchLayout = {\n readonly groups: ReadonlyMap<string, SpanGroup>;\n readonly standalone: readonly CanonicalEvent[];\n /** Event id of each lifecycle edge, mapped to the group key it belongs to. */\n readonly groupOf: ReadonlyMap<string, string>;\n};\n\nconst layoutBatch = (events: readonly CanonicalEvent[]): BatchLayout => {\n const groups = new Map<string, SpanGroup>();\n const standalone: CanonicalEvent[] = [];\n const groupOf = new Map<string, string>();\n\n for (const event of events) {\n const ref = spanScopeRefOf(event);\n if (ref === undefined) {\n standalone.push(event);\n continue;\n }\n const groupKey = correlationKey(event.provenance.providerId, event.sessionId, ref);\n const group: SpanGroup = groups.get(groupKey) ?? { ref };\n if (event.type.endsWith(\".start\")) {\n group.start = event;\n } else {\n group.end = event;\n }\n groups.set(groupKey, group);\n groupOf.set(event.eventId, groupKey);\n }\n return { groups, standalone, groupOf };\n};\n\nconst indexCorrelations = (\n correlations: readonly SpanCorrelation[] | undefined,\n): ReadonlyMap<string, SpanCorrelation> => {\n const indexed = new Map<string, SpanCorrelation>();\n for (const correlation of correlations ?? []) {\n indexed.set(\n correlationKey(correlation.providerId, correlation.sessionId, correlation.ref),\n correlation,\n );\n }\n return indexed;\n};\n\n/**\n * What this batch does with one lifecycle scope, decided once.\n *\n * Both the span mapping and the log mapping need the *same* answer to \"which\n * span id identifies this scope, and is a record for it going out now?\" — a log\n * record whose `spanContext` names a span id the exporter never published would\n * dangle at the collector. Computing it in one place is what keeps the two\n * signals pointing at the same span rather than at two plausible derivations of\n * it.\n */\ntype GroupPlan = {\n readonly group: SpanGroup;\n /** The event the span's identity and provenance are read from. */\n readonly anchor: CanonicalEvent;\n /**\n * False when the start is deferred: the state store is holding it and the end\n * edge will publish the one complete span, so nothing is exported for it now.\n */\n readonly emits: boolean;\n readonly correlation: SpanCorrelation | undefined;\n readonly traceId: string;\n readonly spanId: string;\n};\n\nconst planGroup = (\n group: SpanGroup,\n correlation: SpanCorrelation | undefined,\n correlationAvailable: boolean | undefined,\n): GroupPlan | undefined => {\n const anchor = group.start ?? group.end;\n if (anchor === undefined) {\n // Unreachable: a group exists only because an event was filed into it.\n return undefined;\n }\n const providerId = anchor.provenance.providerId;\n const sessionId = anchor.sessionId;\n\n // A start with no end in this batch is dropped **only** when something states\n // that it is durably recorded, because its span id is a pure function of the\n // scope: emitting here and again at the end edge would put two records with one\n // id on the wire, and OTLP has no update operation.\n //\n // `defer` is that statement, and it is the correlator's to make — it just wrote\n // the record. Anything else means nothing is holding this start, so dropping it\n // would lose an observation that was neither persisted nor exported, while the\n // caller saw zero rejections and marked the callback handled. Those are exported\n // under a discriminated span id instead.\n const durablyRecorded =\n group.end === undefined &&\n (correlation?.disposition === \"defer\" ||\n // No correlator wired at all: cross-process pairing was never on offer, so\n // this is the documented no-state-root degradation rather than a failure to\n // persist something that should have been persisted.\n (correlation === undefined && correlationAvailable === undefined));\n\n // A deferred start keeps the scope's *plain* span id, because that is the id the\n // end edge will publish. Only a record actually going out now may claim a\n // discriminated one.\n const effective = durablyRecorded ? correlation : effectiveCorrelation(group, correlation);\n const discriminator = durablyRecorded ? undefined : effective?.spanIdDiscriminator;\n\n return {\n group,\n anchor,\n emits: !durablyRecorded,\n correlation: effective,\n traceId: deriveTraceId(providerId, sessionId),\n spanId:\n discriminator === undefined\n ? deriveSpanId(providerId, sessionId, group.ref)\n : digestHex(\n [\n \"otelhook/span\",\n providerId,\n sessionId,\n group.ref.family,\n group.ref.scopeKey,\n discriminator,\n ],\n 16,\n ),\n };\n};\n\n/** Trace and span a record derived from one canonical event belongs to. */\nexport type EventTraceIdentity = {\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n};\n\n/**\n * Resolve the trace and span identity of every event in one batch.\n *\n * Exposed for signals other than traces — a log record correlates by carrying\n * the *same* derived ids the span mapping would compute, including the deferred\n * and discriminated cases. Whole batch at once because a start's identity\n * depends on whether its end is in the same batch.\n *\n * Both ids come from the event's own `(providerId, sessionId)`, never from a\n * batch-level or module-level value, which is what makes cross-session\n * contamination structurally impossible: two sessions in one batch derive two\n * different trace ids.\n */\nexport const canonicalEventTraceIdentities = (\n events: readonly CanonicalEvent[],\n options: {\n readonly correlations?: readonly SpanCorrelation[];\n readonly correlationAvailable?: boolean;\n } = {},\n): ReadonlyMap<string, EventTraceIdentity> => {\n const layout = layoutBatch(events);\n const correlations = indexCorrelations(options.correlations);\n const plans = new Map<string, GroupPlan>();\n for (const [groupKey, group] of layout.groups) {\n const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);\n if (plan !== undefined) {\n plans.set(groupKey, plan);\n }\n }\n\n const identities = new Map<string, EventTraceIdentity>();\n for (const event of events) {\n const providerId = event.provenance.providerId;\n const groupKey = layout.groupOf.get(event.eventId);\n const plan = groupKey === undefined ? undefined : plans.get(groupKey);\n if (plan === undefined) {\n const parent = parentScopeRefOf(event);\n identities.set(event.eventId, {\n traceId: deriveTraceId(providerId, event.sessionId),\n spanId: deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId),\n ...(parent === undefined\n ? {}\n : { parentSpanId: deriveSpanId(providerId, event.sessionId, parent) }),\n });\n continue;\n }\n const parent = plan.correlation?.parent ?? parentScopeRefOf(event);\n identities.set(event.eventId, {\n traceId: plan.traceId,\n spanId: plan.spanId,\n ...(parent === undefined\n ? {}\n : { parentSpanId: deriveSpanId(providerId, event.sessionId, parent) }),\n });\n }\n return identities;\n};\n\n/** Maps one invocation's canonical event batch into OTLP-ready spans. */\nexport const canonicalEventsToReadableSpans = (\n events: readonly CanonicalEvent[],\n options: SemanticMappingOptions,\n): readonly ReadableSpan[] => {\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const layout = layoutBatch(events);\n const correlations = indexCorrelations(options.correlations);\n\n const spans: ReadableSpan[] = [];\n for (const [groupKey, group] of layout.groups) {\n const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);\n if (plan === undefined || !plan.emits) {\n continue;\n }\n spans.push(buildLifecycleSpan(plan, options.resource, scope));\n }\n for (const event of layout.standalone) {\n spans.push(buildStandaloneSpan(event, options.resource, scope));\n }\n return spans;\n};\n","/**\n * Package version, kept in its own module so the CLI can report it without\n * importing the whole library barrel (and every provider adapter with it).\n *\n * Updated by `scripts/release/sync-version.mjs` during semantic-release.\n */\nexport const VERSION = \"0.12.0\";\n","import type { Attributes } from \"@opentelemetry/api\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport { ATTR_SESSION_ID } from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport { isTargetedEvent, type CanonicalEvent } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\n\n/**\n * W3C hex identity attributes on every log and span.\n *\n * Mission Control (and any consumer that decodes OTLP protobuf with a JSON\n * `toObject` that stringifies bytes as UTF-8) cannot recover a usable id from\n * the protobuf `trace_id` / `span_id` fields. These attributes are already hex\n * in the OpenTelemetry JS API; they are copied onto the attribute map so a\n * consumer never has to stringify binary ids.\n */\nexport const ATTR_TRACE_ID = \"trace_id\";\nexport const ATTR_SPAN_ID = \"span_id\";\nexport const ATTR_PARENT_SPAN_ID = \"parent_span_id\";\n\n/** Provider session id, kept when `session.id` is an externally supplied key. */\nexport const ATTR_OTELHOOK_SESSION_ID = \"otelhook.session.id\";\n/** Same provider session id under the gen_ai conversation attribute. */\nexport const ATTR_GEN_AI_CONVERSATION_ID = \"gen_ai.conversation.id\";\n\nexport const TRACE_ID_HEX_PATTERN = /^[0-9a-f]{32}$/;\nexport const SPAN_ID_HEX_PATTERN = /^[0-9a-f]{16}$/;\n\nconst ATTR_OTELHOOK_INVOCATION_ID = \"otelhook.invocation.id\";\nconst ATTR_OTELHOOK_PROVIDER_ID = \"otelhook.provider.id\";\nconst ATTR_OTELHOOK_PROVIDER_VERSION = \"otelhook.provider.version\";\nconst ATTR_OTELHOOK_WORKSPACE_ID = \"otelhook.workspace.id\";\n\n/**\n * Resource attributes a launcher may set to supply the session key, in\n * preference order: the OpenTelemetry semantic-convention `session.id`, then the\n * legacy `har.session_key` that earlier launchers still send.\n */\nexport const EXTERNAL_SESSION_KEY_ATTRIBUTES: readonly string[] = Object.freeze([\n ATTR_SESSION_ID,\n \"har.session_key\",\n]);\n\n/**\n * The provider's own subagent id (Claude Code `agent_id`), on every record of an\n * event emitted inside a subagent. Same class as `session.id`: a provider-minted\n * opaque identifier, exported verbatim so a consumer can join it to the\n * provider's own per-subagent records.\n */\nexport const ATTR_OTELHOOK_SUBAGENT_ID = \"otelhook.subagent.id\";\n\n/**\n * Worktree an event targeted (ADR 0008): the one a tool call touched, or the one\n * a session runs in on its start and prompts. Branch under the OTel VCS\n * attribute; the worktree root, and its repository's main worktree root, only\n * as salted `git-root` handles.\n */\nexport const ATTR_VCS_REF_HEAD_NAME = \"vcs.ref.head.name\";\nexport const ATTR_OTELHOOK_TARGET_WORKSPACE_ID = \"otelhook.target.workspace.id\";\nexport const ATTR_OTELHOOK_TARGET_SOURCE = \"otelhook.target.source\";\nexport const ATTR_OTELHOOK_TARGET_REPOSITORY_ID = \"otelhook.target.repository.id\";\nexport const ATTR_OTELHOOK_TARGET_WORKTREE_KIND = \"otelhook.target.worktree.kind\";\n\n/** Whether `gen_ai.usage.*` on this record is a delta or a running total. */\nexport const ATTR_OTELHOOK_USAGE_TEMPORALITY = \"otelhook.usage.temporality\";\n\n/** Target attributes for a targeted event; empty when the core resolved none. */\nexport const targetAttributes = (event: CanonicalEvent): Attributes => {\n if (!isTargetedEvent(event) || event.target === undefined) {\n return {};\n }\n const { target } = event;\n return {\n [ATTR_OTELHOOK_TARGET_WORKSPACE_ID]: target.workspaceId,\n [ATTR_OTELHOOK_TARGET_SOURCE]: target.source,\n ...(target.vcsBranchName === undefined ? {} : { [ATTR_VCS_REF_HEAD_NAME]: target.vcsBranchName }),\n ...(target.repositoryId === undefined\n ? {}\n : { [ATTR_OTELHOOK_TARGET_REPOSITORY_ID]: target.repositoryId }),\n ...(target.worktreeKind === undefined\n ? {}\n : { [ATTR_OTELHOOK_TARGET_WORKTREE_KIND]: target.worktreeKind }),\n };\n};\n\n/** Temporality of reported usage, so a consumer never sums running totals. */\nexport const usageTemporalityAttributes = (usage: CanonicalUsage | undefined): Attributes =>\n usage === undefined ? {} : { [ATTR_OTELHOOK_USAGE_TEMPORALITY]: usage.temporality };\n\nconst isPrimitiveAttribute = (value: unknown): value is string | number | boolean =>\n typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\";\n\n/**\n * Resource attribute namespaces a launcher puts on the process that are also\n * copied onto every span and log record.\n *\n * Many backends index only record attributes (filters, search, dashboards), so a\n * value that exists only on the Resource is invisible there. Copied:\n *\n * - `har.*` — attributes earlier launchers send;\n * - `factory.*` — the Factory Commits telemetry profile (work unit, slot, …),\n * **except** `factory.local.*`, which the profile defines as local-only: it\n * stays on the Resource and never reaches a record;\n * - `vcs.*` — OpenTelemetry VCS attributes. An event's own resolved target\n * (ADR 0008) still wins for the keys it sets, such as `vcs.ref.head.name`.\n *\n * `session.id` is not copied: it is resolved separately (see\n * `resolveExportedSessionId`), so a resource value cannot overwrite the\n * trimmed, resolved one.\n */\nexport const PASSTHROUGH_RESOURCE_PREFIXES: readonly string[] = Object.freeze([\"har.\", \"factory.\", \"vcs.\"]);\n/** Local-only profile namespace: never copied from the Resource onto records. */\nexport const LOCAL_ONLY_RESOURCE_PREFIX = \"factory.local.\";\n\nconst isPassthroughKey = (key: string): boolean =>\n PASSTHROUGH_RESOURCE_PREFIXES.some((prefix) => key.startsWith(prefix)) &&\n !key.startsWith(LOCAL_ONLY_RESOURCE_PREFIX) &&\n key !== \"factory.local\";\n\n/**\n * Primitive resource attributes to copy onto every log and span record.\n *\n * Only the namespaces in `PASSTHROUGH_RESOURCE_PREFIXES` are forwarded, minus\n * `factory.local.*`; nothing is invented when they are absent.\n */\nexport const passthroughResourceAttributes = (resource: Resource): Attributes => {\n const attributes: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(resource.attributes)) {\n if (isPassthroughKey(key) && isPrimitiveAttribute(value)) {\n attributes[key] = value;\n }\n }\n return attributes;\n};\n\n/**\n * Session context attributes the core stamped on this event\n * (`docs/session-context.md`); empty when none applies.\n */\nexport const contextAttributesOf = (event: CanonicalEvent): Attributes =>\n event.contextAttributes === undefined ? {} : { ...event.contextAttributes };\n\n/**\n * The profile layer of a record: the Resource's passthrough namespaces,\n * overridden key by key by the event's session context.\n *\n * Context wins because it is the more specific and more recent statement: a\n * session that moved from one attempt to another still has the first one in its\n * process environment (and so on the Resource), but its context names the\n * second. Everything otel-hook derives for the event itself — `session.id`,\n * `otelhook.*`, `gen_ai.*`, trace ids, and a resolved worktree target — is\n * layered above this and is never overridden by it.\n */\nexport const profileAttributes = (event: CanonicalEvent, resource: Resource): Attributes => ({\n ...passthroughResourceAttributes(resource),\n ...contextAttributesOf(event),\n});\n\n/**\n * Session id to put on `session.id`, preferring an externally supplied key.\n *\n * A launcher supplies the key as a resource attribute (usually through\n * `OTEL_RESOURCE_ATTRIBUTES`): `session.id` first, then the legacy\n * `har.session_key`, then the provider's own session id. The provider's id is\n * never discarded: it is returned separately so callers can emit it as\n * `otelhook.session.id` / `gen_ai.conversation.id`.\n */\nexport const resolveExportedSessionId = (\n eventSessionId: string,\n resource: Resource,\n): { readonly sessionId: string; readonly providerSessionId: string } => {\n for (const key of EXTERNAL_SESSION_KEY_ATTRIBUTES) {\n const supplied = resource.attributes[key];\n if (typeof supplied === \"string\") {\n const trimmed = supplied.trim();\n if (trimmed.length > 0) {\n return { sessionId: trimmed, providerSessionId: eventSessionId };\n }\n }\n }\n return { sessionId: eventSessionId, providerSessionId: eventSessionId };\n};\n\nexport type ExportedTraceIds = {\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n};\n\n/**\n * Hex-only trace/span attributes. A value that is not W3C hex is omitted\n * rather than stringified — binary blobs must never appear in id fields.\n */\nexport const hexTraceAttributes = (ids: ExportedTraceIds): Attributes => ({\n ...(TRACE_ID_HEX_PATTERN.test(ids.traceId) ? { [ATTR_TRACE_ID]: ids.traceId } : {}),\n ...(SPAN_ID_HEX_PATTERN.test(ids.spanId) ? { [ATTR_SPAN_ID]: ids.spanId } : {}),\n ...(ids.parentSpanId !== undefined && SPAN_ID_HEX_PATTERN.test(ids.parentSpanId)\n ? { [ATTR_PARENT_SPAN_ID]: ids.parentSpanId }\n : {}),\n});\n\n/**\n * Identity attributes shared by the log and span mappings.\n *\n * `session.id` is the externally supplied session key when the resource carries\n * one (`session.id`, then `har.session_key`), otherwise the provider session id.\n * The provider id is always also emitted under `otelhook.session.id` and\n * `gen_ai.conversation.id`. Profile resource attributes and the event's session\n * context are copied on too, beneath them (see `profileAttributes`).\n */\nexport const exportIdentityAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n ids: ExportedTraceIds,\n): Attributes => {\n const { sessionId, providerSessionId } = resolveExportedSessionId(event.sessionId, resource);\n return {\n // First, so nothing in the profile layer can replace an identity attribute.\n ...profileAttributes(event, resource),\n [ATTR_SESSION_ID]: sessionId,\n [ATTR_OTELHOOK_SESSION_ID]: providerSessionId,\n [ATTR_GEN_AI_CONVERSATION_ID]: providerSessionId,\n [ATTR_OTELHOOK_INVOCATION_ID]: event.invocationId,\n [ATTR_OTELHOOK_PROVIDER_ID]: event.provenance.providerId,\n ...(event.provenance.providerVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event.provenance.providerVersion }),\n [ATTR_OTELHOOK_WORKSPACE_ID]: event.workspace.workspaceId,\n ...(event.subagentId === undefined ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event.subagentId }),\n ...hexTraceAttributes(ids),\n };\n};\n","import { z } from \"zod\";\n\nimport {\n errorPhaseSchema,\n errorSeveritySchema,\n otelHookErrorCodeSchema,\n} from \"../errors/taxonomy.js\";\nimport { contentFactSchema, contentFactsSchema } from \"./content.js\";\nimport { extensionsSchema, emptyExtensions } from \"./extensions.js\";\nimport { sourceProvenanceSchema, workspaceIdentitySchema } from \"./identity.js\";\nimport { subagentIdSchema, workspaceTargetSchema } from \"./target.js\";\nimport {\n durationMillisSchema,\n epochMillisSchema,\n eventIdSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n sequenceNumberSchema,\n sessionIdSchema,\n tokenCountSchema,\n} from \"./primitives.js\";\nimport { canonicalUsageSchema, type CanonicalUsage } from \"./usage.js\";\nimport { canonicalSchemaVersionSchema } from \"./version.js\";\n\n/** Model being invoked. Model identifiers are not treated as sensitive. */\nexport const modelDescriptorSchema = z.strictObject({\n modelId: nonEmptyStringSchema,\n /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */\n vendor: nonEmptyStringSchema.optional(),\n family: nonEmptyStringSchema.optional(),\n});\nexport type ModelDescriptor = z.infer<typeof modelDescriptorSchema>;\n\nexport const costFactsSchema = z.strictObject({\n /** ISO 4217 code. */\n currency: z.string().length(3),\n amount: z.number().min(0).finite(),\n source: z.enum([\"provider-reported\", \"computed\"]),\n});\nexport type CostFacts = z.infer<typeof costFactsSchema>;\n\nexport const canonicalEventTypeSchema = z.enum([\n \"session.start\",\n \"session.end\",\n \"prompt.submitted\",\n \"generation.start\",\n \"generation.end\",\n \"tool.start\",\n \"tool.end\",\n \"subagent.start\",\n \"subagent.end\",\n \"compaction.performed\",\n \"error.raised\",\n]);\nexport type CanonicalEventType = z.infer<typeof canonicalEventTypeSchema>;\n\nexport const CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;\n\nconst outcomeSchema = z.enum([\"ok\", \"error\", \"cancelled\", \"timeout\", \"denied\", \"unknown\"]);\nexport type EventOutcome = z.infer<typeof outcomeSchema>;\n\n/**\n * Fields present on every canonical event.\n *\n * Identity fields are duplicated onto each event rather than referenced through\n * shared state, so an event is self-describing once it leaves the process.\n */\nconst baseEventFields = {\n schemaVersion: canonicalSchemaVersionSchema,\n eventId: eventIdSchema,\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Per-invocation ordering key. Stable across replays of the same input. */\n sequence: sequenceNumberSchema,\n occurredAt: epochMillisSchema,\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n /**\n * The provider's own id for the subagent this event was emitted inside (e.g.\n * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event\n * factory, never by hand.\n */\n subagentId: subagentIdSchema.optional(),\n extensions: extensionsSchema.default(emptyExtensions),\n /**\n * Attributes of the session context segment in force when the event\n * occurred (`docs/session-context.md`), stamped by the core from a file a\n * harness wrote. Exported on every record of the event, over the same keys\n * from the Resource. Absent when no context applies. Set by the core only,\n * never by an adapter.\n */\n contextAttributes: z.record(z.string().min(1).max(255), z.union([z.string(), z.number(), z.boolean()])).optional(),\n} as const;\n\nconst event = <TShape extends z.ZodRawShape>(shape: TShape) =>\n z.strictObject({ ...baseEventFields, ...shape });\n\nexport const sessionStartEventSchema = event({\n type: z.literal(\"session.start\"),\n sessionKind: z.enum([\"interactive\", \"non-interactive\", \"unknown\"]),\n agentName: nonEmptyStringSchema.optional(),\n agentVersion: nonEmptyStringSchema.optional(),\n model: modelDescriptorSchema.optional(),\n /** The git worktree the session runs in, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const sessionEndEventSchema = event({\n type: z.literal(\"session.end\"),\n reason: z.enum([\"completed\", \"aborted\", \"error\", \"timeout\", \"unknown\"]),\n durationMillis: durationMillisSchema.optional(),\n /** Session totals, typically cumulative. */\n usage: canonicalUsageSchema.optional(),\n cost: costFactsSchema.optional(),\n});\n\nexport const promptSubmittedEventSchema = event({\n type: z.literal(\"prompt.submitted\"),\n promptSource: z.enum([\"user\", \"automation\", \"resumed\", \"unknown\"]),\n content: contentFactSchema.optional(),\n turnIndex: z.number().int().min(0).optional(),\n /** The git worktree the session runs in, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const generationStartEventSchema = event({\n type: z.literal(\"generation.start\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n requestedMaxOutputTokens: tokenCountSchema.optional(),\n inputContent: contentFactsSchema.optional(),\n});\n\nexport const generationEndEventSchema = event({\n type: z.literal(\"generation.end\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n outcome: outcomeSchema,\n stopReason: nonEmptyStringSchema.optional(),\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n /**\n * True when `usage` is known to cover only part of the generation (for\n * example the last model request of a multi-request turn); false when the\n * provider or harness said it is the whole. Absent: not stated. Meaningless\n * without `usage`.\n */\n usagePartial: z.boolean().optional(),\n cost: costFactsSchema.optional(),\n outputContent: contentFactsSchema.optional(),\n});\n\nexport const toolKindSchema = z.enum([\n \"read\",\n \"write\",\n \"execute\",\n \"search\",\n \"network\",\n \"delegate\",\n \"other\",\n \"unknown\",\n]);\nexport type ToolKind = z.infer<typeof toolKindSchema>;\n\nexport const toolStartEventSchema = event({\n type: z.literal(\"tool.start\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n toolKind: toolKindSchema,\n generationId: nonEmptyStringSchema.optional(),\n input: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const toolEndEventSchema = event({\n type: z.literal(\"tool.end\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n /** Present when the host asked for or recorded a permission decision. */\n permissionDecision: z.enum([\"allowed\", \"denied\", \"deferred\", \"not-required\"]).optional(),\n output: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const subagentStartEventSchema = event({\n type: z.literal(\"subagent.start\"),\n subagentInvocationId: invocationIdSchema,\n subagentType: nonEmptyStringSchema.optional(),\n /** 0 for the top-level agent; 1 for its direct children. */\n delegationDepth: z.number().int().min(0).max(64),\n model: modelDescriptorSchema.optional(),\n});\n\nexport const subagentEndEventSchema = event({\n type: z.literal(\"subagent.end\"),\n subagentInvocationId: invocationIdSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const compactionPerformedEventSchema = event({\n type: z.literal(\"compaction.performed\"),\n trigger: z.enum([\"automatic\", \"manual\", \"unknown\"]),\n /** Provider-reported context size before and after compaction, if known. */\n contextTokensBefore: tokenCountSchema.optional(),\n contextTokensAfter: tokenCountSchema.optional(),\n droppedMessageCount: z.number().int().min(0).optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const errorRaisedEventSchema = event({\n type: z.literal(\"error.raised\"),\n errorCode: otelHookErrorCodeSchema,\n severity: errorSeveritySchema,\n phase: errorPhaseSchema,\n retryable: z.boolean(),\n /** Error text is content: it is described, never embedded verbatim by default. */\n message: contentFactSchema.optional(),\n /** Non-sensitive, provider-agnostic short label. */\n detail: nonEmptyStringSchema.optional(),\n});\n\nexport const canonicalEventSchema = z.discriminatedUnion(\"type\", [\n sessionStartEventSchema,\n sessionEndEventSchema,\n promptSubmittedEventSchema,\n generationStartEventSchema,\n generationEndEventSchema,\n toolStartEventSchema,\n toolEndEventSchema,\n subagentStartEventSchema,\n subagentEndEventSchema,\n compactionPerformedEventSchema,\n errorRaisedEventSchema,\n]);\n\nexport type CanonicalEvent = z.infer<typeof canonicalEventSchema>;\nexport type CanonicalEventInput = z.input<typeof canonicalEventSchema>;\n\nexport type SessionStartEvent = z.infer<typeof sessionStartEventSchema>;\nexport type SessionEndEvent = z.infer<typeof sessionEndEventSchema>;\nexport type PromptSubmittedEvent = z.infer<typeof promptSubmittedEventSchema>;\nexport type GenerationStartEvent = z.infer<typeof generationStartEventSchema>;\nexport type GenerationEndEvent = z.infer<typeof generationEndEventSchema>;\nexport type ToolStartEvent = z.infer<typeof toolStartEventSchema>;\nexport type ToolEndEvent = z.infer<typeof toolEndEventSchema>;\nexport type SubagentStartEvent = z.infer<typeof subagentStartEventSchema>;\nexport type SubagentEndEvent = z.infer<typeof subagentEndEventSchema>;\nexport type CompactionPerformedEvent = z.infer<typeof compactionPerformedEventSchema>;\nexport type ErrorRaisedEvent = z.infer<typeof errorRaisedEventSchema>;\n\nexport type CanonicalEventOfType<TType extends CanonicalEventType> = Extract<\n CanonicalEvent,\n { type: TType }\n>;\n\n/**\n * The event types that may carry a resolved `target` (ADR 0008): a tool call\n * names the worktree it touched; a session start and a prompt name the one the\n * session runs in, so a consumer knows the session's place before its first\n * tool call.\n */\nexport const TARGETED_EVENT_TYPES = [\"session.start\", \"prompt.submitted\", \"tool.start\", \"tool.end\"] as const;\nexport type TargetedEventType = (typeof TARGETED_EVENT_TYPES)[number];\nexport type TargetedEvent = CanonicalEventOfType<TargetedEventType>;\n\nconst TARGETED: ReadonlySet<string> = new Set(TARGETED_EVENT_TYPES);\nexport const isTargetedEvent = (event: CanonicalEvent): event is TargetedEvent => TARGETED.has(event.type);\n\nexport type EventValidationResult =\n | { readonly status: \"ok\"; readonly event: CanonicalEvent }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nexport const validateCanonicalEvent = (value: unknown): EventValidationResult => {\n const parsed = canonicalEventSchema.safeParse(value);\n if (parsed.success) {\n return { status: \"ok\", event: parsed.data };\n }\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n};\n\n/** Parse or throw. Intended for fixtures and tests, not the hook path. */\nexport const parseCanonicalEvent = (value: unknown): CanonicalEvent =>\n canonicalEventSchema.parse(value);\n\n/** Usage carried by an event, if the event type can carry any. */\nexport const eventUsage = (event: CanonicalEvent): CanonicalUsage | undefined =>\n \"usage\" in event ? event.usage : undefined;\n\n/** Stable ordering: by sequence, then by timestamp, then by event id. */\nexport const compareEvents = (a: CanonicalEvent, b: CanonicalEvent): number =>\n a.sequence - b.sequence || a.occurredAt - b.occurredAt || a.eventId.localeCompare(b.eventId);\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 { z } from \"zod\";\n\nimport { nonEmptyStringSchema } from \"./primitives.js\";\n\n/** What kind of conversational or tool content a fact describes. */\nexport const contentKindSchema = z.enum([\n \"prompt\",\n \"response\",\n \"reasoning\",\n \"tool-input\",\n \"tool-output\",\n \"error-message\",\n \"system-instruction\",\n \"attachment\",\n]);\nexport type ContentKind = z.infer<typeof contentKindSchema>;\n\nexport const contentRoleSchema = z.enum([\"user\", \"assistant\", \"system\", \"tool\", \"unknown\"]);\nexport type ContentRole = z.infer<typeof contentRoleSchema>;\n\n/**\n * How much of the original content this fact discloses.\n *\n * - `omitted`: no text at all (the default posture).\n * - `masked`: a shape-preserving mask; non-whitespace characters replaced.\n * - `redacted`: text with secret-looking spans replaced by a placeholder.\n * - `raw`: verbatim text. Only reachable through explicit opt-in.\n */\nexport const contentDisclosureSchema = z.enum([\"omitted\", \"masked\", \"redacted\", \"raw\"]);\nexport type ContentDisclosure = z.infer<typeof contentDisclosureSchema>;\n\nexport const CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;\n\n/**\n * A privacy-safe description of content.\n *\n * Lengths and a stable hash are always present so consumers can measure and\n * correlate volume without receiving the content itself. `text` is present only\n * when the resolved privacy policy allows disclosure, and is produced solely by\n * the central privacy service.\n */\nexport const contentFactSchema = z.strictObject({\n kind: contentKindSchema,\n role: contentRoleSchema.optional(),\n /** Unicode code point count of the original content. */\n characterLength: z.number().int().min(0),\n /** UTF-8 byte length of the original content. */\n byteLength: z.number().int().min(0),\n /** Stable salted digest of the original content. */\n contentHash: z.string().regex(CONTENT_HASH_PATTERN),\n disclosure: contentDisclosureSchema,\n /** Disclosed text, bounded by the privacy policy. Absent when omitted. */\n text: z.string().optional(),\n /** True when `text` was cut short by the configured string bound. */\n truncated: z.boolean(),\n /** Number of secret-looking spans replaced while producing `text`. */\n secretsRedacted: z.number().int().min(0),\n /** Optional non-sensitive label, e.g. a MIME type or tool name. */\n label: nonEmptyStringSchema.optional(),\n});\nexport type ContentFact = z.infer<typeof contentFactSchema>;\n\nexport const contentFactsSchema = z.array(contentFactSchema).max(64);\n\n/**\n * Guard used in tests and at the sink boundary: an omitted fact must not carry\n * text, and a disclosing fact must carry it.\n */\nexport const isContentFactConsistent = (fact: ContentFact): boolean =>\n fact.disclosure === \"omitted\" ? fact.text === undefined : fact.text !== undefined;\n\n/**\n * A fact for a content kind the event can carry when the provider sent no text.\n *\n * Always `omitted` with zero length, regardless of the installation's content\n * mode: there is nothing to mask, redact, or export.\n */\nexport const isUnavailableContentFact = (fact: ContentFact): boolean =>\n fact.disclosure === \"omitted\" &&\n fact.text === undefined &&\n fact.characterLength === 0 &&\n fact.byteLength === 0;\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 { attributeValueSchema, type AttributeValue } from \"./primitives.js\";\n\n/**\n * Extension keys must be namespaced: at least one dot-separated segment before\n * the leaf, e.g. `acme.deployment-tier`. Namespacing keeps provider- and\n * consumer-specific fields from colliding with core fields or each other.\n */\nexport const EXTENSION_KEY_PATTERN =\n /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;\n\n/** Namespaces owned by the core model; extensions may not use them. */\nexport const RESERVED_EXTENSION_NAMESPACES: readonly string[] = Object.freeze([\n \"otelhook\",\n \"otel\",\n \"telemetry\",\n]);\n\nexport const MAX_EXTENSION_ENTRIES = 64;\n\nexport const extensionKeyNamespace = (key: string): string => key.slice(0, key.indexOf(\".\"));\n\nexport const isReservedExtensionNamespace = (key: string): boolean =>\n RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));\n\nexport const isValidExtensionKey = (key: string): boolean =>\n EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);\n\n/**\n * Namespaced extension bag.\n *\n * Values are restricted to attribute primitives, so extensions cannot carry\n * nested provider payloads.\n */\nexport const extensionsSchema = z\n .record(z.string(), attributeValueSchema)\n .check((ctx) => {\n const keys = Object.keys(ctx.value);\n if (keys.length > MAX_EXTENSION_ENTRIES) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`,\n });\n }\n for (const key of keys) {\n if (!EXTENSION_KEY_PATTERN.test(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. \"acme.tier\"`,\n });\n continue;\n }\n if (isReservedExtensionNamespace(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`,\n });\n }\n }\n });\n\nexport type Extensions = Record<string, AttributeValue>;\n\nexport const EMPTY_EXTENSIONS: Extensions = Object.freeze({});\n\nexport const emptyExtensions = (): Extensions => ({});\n","import { z } from \"zod\";\n\nimport {\n attributesSchema,\n detectionConfidenceSchema,\n DETECTION_CONFIDENCE_RANK,\n epochMillisSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n resolvedProviderIdSchema,\n sessionIdSchema,\n sourceTransportSchema,\n workspaceIdSchema,\n type DetectionConfidence,\n type InvocationId,\n type SessionId,\n type WorkspaceId,\n} from \"./primitives.js\";\n\n/**\n * Where a workspace identifier came from.\n *\n * Ordered from most to least stable. The source is recorded so consumers can\n * tell a repository-scoped identity from a directory-scoped one instead of\n * assuming they are comparable.\n */\nexport const workspaceKeySourceSchema = z.enum([\n \"git-remote\",\n \"git-root\",\n \"working-directory\",\n \"explicit\",\n \"unknown\",\n]);\nexport type WorkspaceKeySource = z.infer<typeof workspaceKeySourceSchema>;\n\n/**\n * Privacy-safe workspace identity.\n *\n * Only opaque handles and explicitly allowed labels are modelled. There is no\n * field for a filesystem path, so paths cannot be exported through this type.\n */\nexport const workspaceIdentitySchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n keySource: workspaceKeySourceSchema,\n /** Repository name only; never an owner path or URL with credentials. */\n repositoryName: nonEmptyStringSchema.optional(),\n vcsBranchName: nonEmptyStringSchema.optional(),\n /** Opaque handle for the checked-out revision. */\n vcsRevisionId: nonEmptyStringSchema.optional(),\n })\n .readonly();\nexport type WorkspaceIdentity = z.infer<typeof workspaceIdentitySchema>;\n\nexport const UNKNOWN_WORKSPACE_ID = \"unknown:0000000000000000\" as WorkspaceId;\n\nexport const unknownWorkspaceIdentity = (): WorkspaceIdentity =>\n workspaceIdentitySchema.parse({\n workspaceId: UNKNOWN_WORKSPACE_ID,\n keySource: \"unknown\",\n });\n\n/**\n * Provenance of an observation: which provider produced it and which adapter\n * interpreted it, with the confidence of that attribution.\n */\nexport const sourceProvenanceSchema = z\n .strictObject({\n providerId: resolvedProviderIdSchema,\n providerVersion: nonEmptyStringSchema.optional(),\n adapterId: nonEmptyStringSchema,\n adapterVersion: nonEmptyStringSchema,\n detectionConfidence: detectionConfidenceSchema,\n /** The provider's own name for the source event, e.g. a hook event name. */\n sourceEventName: nonEmptyStringSchema.optional(),\n transport: sourceTransportSchema,\n })\n .readonly();\nexport type SourceProvenance = z.infer<typeof sourceProvenanceSchema>;\n\n/**\n * Opaque, immutable metadata supplied by the embedding consumer.\n *\n * The library never interprets these values; it only carries and exports them.\n */\nexport const consumerAttributesSchema = attributesSchema.readonly();\nexport type ConsumerAttributes = z.infer<typeof consumerAttributesSchema>;\n\n/**\n * Immutable identity of a single hook invocation.\n *\n * Frozen on parse. There is deliberately no setter, no builder that mutates in\n * place, and no module-level instance: identity is passed explicitly so two\n * concurrent invocations can never observe each other's fields.\n */\nexport const invocationIdentitySchema = z\n .strictObject({\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Set when this invocation runs beneath another agent invocation. */\n parentInvocationId: invocationIdSchema.optional(),\n /** Root of the session tree when the provider exposes one. */\n rootSessionId: sessionIdSchema.optional(),\n /** Stable handle for the agent process/instance, when available. */\n agentInstanceId: nonEmptyStringSchema.optional(),\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n startedAt: epochMillisSchema,\n consumerAttributes: consumerAttributesSchema,\n })\n .readonly();\nexport type InvocationIdentity = z.infer<typeof invocationIdentitySchema>;\n\n/** Fields an identity claim may contribute. */\nexport const identityClaimFieldsSchema = z.strictObject({\n invocationId: invocationIdSchema.optional(),\n sessionId: sessionIdSchema.optional(),\n parentInvocationId: invocationIdSchema.optional(),\n rootSessionId: sessionIdSchema.optional(),\n agentInstanceId: nonEmptyStringSchema.optional(),\n workspace: workspaceIdentitySchema.optional(),\n startedAt: epochMillisSchema.optional(),\n});\nexport type IdentityClaimFields = z.infer<typeof identityClaimFieldsSchema>;\n\n/**\n * A claim about invocation identity from one source.\n *\n * Claims are evidence, not truth. Resolution keeps the highest-confidence claim\n * per field and refuses to merge disagreeing peers.\n */\nexport const identityClaimSchema = z.strictObject({\n /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */\n source: nonEmptyStringSchema,\n confidence: detectionConfidenceSchema,\n fields: identityClaimFieldsSchema,\n});\nexport type IdentityClaim = z.infer<typeof identityClaimSchema>;\n\nexport type IdentityConflict = {\n readonly field: keyof IdentityClaimFields;\n readonly confidence: DetectionConfidence;\n /** Rendered, non-sensitive representations of the disagreeing values. */\n readonly values: readonly string[];\n readonly sources: readonly string[];\n};\n\nexport type IdentityResolution =\n | { readonly status: \"resolved\"; readonly identity: InvocationIdentity }\n | {\n readonly status: \"conflict\";\n readonly conflicts: readonly IdentityConflict[];\n }\n | {\n readonly status: \"incomplete\";\n readonly missing: readonly (keyof IdentityClaimFields)[];\n }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nconst CLAIM_FIELDS = [\n \"invocationId\",\n \"sessionId\",\n \"parentInvocationId\",\n \"rootSessionId\",\n \"agentInstanceId\",\n \"workspace\",\n \"startedAt\",\n] as const satisfies readonly (keyof IdentityClaimFields)[];\n\nconst renderClaimValue = (value: unknown): string => {\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (value !== null && typeof value === \"object\" && \"workspaceId\" in value) {\n const { workspaceId } = value;\n return typeof workspaceId === \"string\" ? workspaceId : \"<workspace>\";\n }\n return \"<opaque>\";\n};\n\nexport type ResolveIdentityInput = {\n readonly claims: readonly IdentityClaim[];\n readonly provenance: SourceProvenance;\n /** Used only for fields no claim provides and that have a safe default. */\n readonly fallback?: {\n readonly startedAt?: number;\n readonly workspace?: WorkspaceIdentity;\n };\n readonly consumerAttributes?: Readonly<Record<string, unknown>>;\n};\n\n/**\n * Resolve identity from claims, failing closed.\n *\n * Rules:\n * 1. For each field, only claims at the highest confidence that provided it are\n * considered. Lower-confidence claims never fill in or override.\n * 2. Two distinct values at that highest confidence produce a `conflict`. The\n * invocation is then not attributed at all — a mislabelled session is worse\n * than a missing one.\n * 3. `invocationId` and `sessionId` are mandatory. Missing either yields\n * `incomplete`; neither is invented here.\n * 4. `startedAt` and `workspace` may come from an explicit fallback, because a\n * clock reading and an `unknown` workspace handle assert nothing false.\n */\nexport const resolveInvocationIdentity = (input: ResolveIdentityInput): IdentityResolution => {\n const parsedClaims: IdentityClaim[] = [];\n const issues: string[] = [];\n for (const [index, claim] of input.claims.entries()) {\n const parsed = identityClaimSchema.safeParse(claim);\n if (parsed.success) {\n parsedClaims.push(parsed.data);\n } else {\n issues.push(\n `claim[${index}]: ${parsed.error.issues.map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`).join(\", \")}`,\n );\n }\n }\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const conflicts: IdentityConflict[] = [];\n const selected: Record<string, unknown> = {};\n\n for (const field of CLAIM_FIELDS) {\n const contributors = parsedClaims.filter((claim) => claim.fields[field] !== undefined);\n if (contributors.length === 0) {\n continue;\n }\n const bestRank = Math.max(\n ...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence]),\n );\n const best = contributors.filter(\n (claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank,\n );\n const rendered = new Map<string, string[]>();\n for (const claim of best) {\n const key = JSON.stringify(claim.fields[field]);\n const sources = rendered.get(key) ?? [];\n sources.push(claim.source);\n rendered.set(key, sources);\n }\n if (rendered.size > 1) {\n const [firstBest] = best;\n conflicts.push({\n field,\n confidence: firstBest?.confidence ?? \"none\",\n values: best.map((claim) => renderClaimValue(claim.fields[field])),\n sources: best.map((claim) => claim.source),\n });\n continue;\n }\n const [winner] = best;\n if (winner !== undefined) {\n selected[field] = winner.fields[field];\n }\n }\n\n if (conflicts.length > 0) {\n return { status: \"conflict\", conflicts };\n }\n\n const missing: (keyof IdentityClaimFields)[] = [];\n if (selected.invocationId === undefined) {\n missing.push(\"invocationId\");\n }\n if (selected.sessionId === undefined) {\n missing.push(\"sessionId\");\n }\n if (missing.length > 0) {\n return { status: \"incomplete\", missing };\n }\n\n const startedAt = (selected.startedAt as number | undefined) ?? input.fallback?.startedAt;\n if (startedAt === undefined) {\n return { status: \"incomplete\", missing: [\"startedAt\"] };\n }\n const workspace =\n (selected.workspace as WorkspaceIdentity | undefined) ??\n input.fallback?.workspace ??\n unknownWorkspaceIdentity();\n\n const candidate = {\n invocationId: selected.invocationId as InvocationId,\n sessionId: selected.sessionId as SessionId,\n ...(selected.parentInvocationId === undefined\n ? {}\n : { parentInvocationId: selected.parentInvocationId as InvocationId }),\n ...(selected.rootSessionId === undefined\n ? {}\n : { rootSessionId: selected.rootSessionId as SessionId }),\n ...(selected.agentInstanceId === undefined\n ? {}\n : { agentInstanceId: selected.agentInstanceId as string }),\n provenance: input.provenance,\n workspace,\n startedAt,\n consumerAttributes: input.consumerAttributes ?? {},\n };\n\n const parsed = invocationIdentitySchema.safeParse(candidate);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n }\n return { status: \"resolved\", identity: parsed.data };\n};\n","import { z } from \"zod\";\n\nimport { nonEmptyStringSchema, workspaceIdSchema } from \"./primitives.js\";\n\n/**\n * Per-event workspace targeting (ADR 0008).\n *\n * A session's `workspace` is where the agent was *started*. An agent routinely\n * works somewhere else — in a linked git worktree beside the checkout it was\n * launched from — and the session-level identity cannot show that. A tool event\n * can: the file it edited, or the directory its shell command ran in, names the\n * worktree it actually touched.\n *\n * Two values model that, and the split between them is the privacy boundary:\n *\n * - {@link TargetHint} is what an adapter observed — local paths. It is an\n * in-process value only: it is never part of a {@link CanonicalEvent}, never\n * persisted, never exported. The core resolves it and drops it.\n * - {@link WorkspaceTarget} is what the core resolved — salted handles of the\n * worktree and its repository, the worktree's kind, the checked-out branch, and\n * what the evidence was. It travels on the event.\n */\n\n/**\n * What a target was derived from, strongest evidence first.\n *\n * - `tool-path` — a path the tool call itself named (an edited or read file, a\n * patch header).\n * - `shell-cwd` — the working directory the provider reports a shell command ran in.\n * - `session-cwd` — only the session's own directory was known; the event may\n * have reached elsewhere (e.g. a shell `cd`) without the provider saying so.\n */\nexport const targetSourceSchema = z.enum([\"tool-path\", \"shell-cwd\", \"session-cwd\"]);\nexport type TargetSource = z.infer<typeof targetSourceSchema>;\n\n/** Most paths one hint may name; a bound, not a sampling rule (all must agree). */\nexport const MAX_TARGET_HINT_PATHS = 8;\n\n/** Longest local path a hint may carry. Longer input is dropped, never truncated. */\nexport const MAX_TARGET_PATH_LENGTH = 4096;\n\nconst localPathSchema = z\n .string()\n .min(1)\n .max(MAX_TARGET_PATH_LENGTH)\n .refine((value) => !value.includes(\"\\u0000\"), \"path must not contain NUL\");\n\n/**\n * An adapter's observation of where a tool event pointed. **Carries local paths**\n * — in-process only, see the module note.\n *\n * Every path in one hint must resolve to the same worktree, or the event gets no\n * target at all: a patch touching two worktrees did not target either of them.\n */\nexport const targetHintSchema = z\n .strictObject({\n source: targetSourceSchema,\n paths: z.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),\n /** Absolute directory that relative `paths` resolve against. */\n baseDirectory: localPathSchema.optional(),\n })\n .readonly();\nexport type TargetHint = z.infer<typeof targetHintSchema>;\n\n/**\n * The weakest hint: the session's own directory. Every adapter gives it to a\n * session start and a prompt, and to a tool call that names no path.\n */\nexport const sessionCwdHint = (cwd: string | undefined): TargetHint | undefined =>\n cwd === undefined || cwd.length === 0 ? undefined : { source: \"session-cwd\", paths: [cwd] };\n\n/**\n * Whether a worktree is its repository's main checkout (`main`) or one added\n * beside it with `git worktree add` (`linked`).\n */\nexport const worktreeKindSchema = z.enum([\"main\", \"linked\"]);\nexport type WorktreeKind = z.infer<typeof worktreeKindSchema>;\n\n/**\n * The git worktree a tool event targeted. Exported; carries no path.\n *\n * `workspaceId` is derived exactly like a `git-root` workspace identity, so a\n * consumer holding the same salt can match it against one it derived itself.\n * `repositoryId` is the same derivation applied to the repository's main\n * worktree, so every worktree of one repository shares it — and for a main\n * worktree it equals `workspaceId`.\n */\nexport const workspaceTargetSchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n /** Branch checked out in that worktree; absent on a detached HEAD. */\n vcsBranchName: nonEmptyStringSchema.optional(),\n source: targetSourceSchema,\n /** `git-root` handle of the repository's main worktree; absent when there is none to name. */\n repositoryId: workspaceIdSchema.optional(),\n worktreeKind: worktreeKindSchema.optional(),\n })\n .readonly();\nexport type WorkspaceTarget = z.infer<typeof workspaceTargetSchema>;\n\n/**\n * Shape a provider's own subagent identifier must have to be exported.\n *\n * Identifier-shaped on purpose — no whitespace, no path separators — so a\n * malformed payload field cannot carry prose or a path onto the wire under an id\n * attribute. A value that does not fit is dropped, not repaired.\n */\nexport const SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;\nexport const subagentIdSchema = z.string().regex(SUBAGENT_ID_PATTERN);\nexport type SubagentId = z.infer<typeof subagentIdSchema>;\n","import { z } from \"zod\";\n\nimport { tokenCountSchema } from \"./primitives.js\";\n\n/**\n * Whether an observation reports the change since the previous observation\n * (`delta`) or the running total for the session/generation (`cumulative`).\n *\n * The canonical model keeps temporality explicit rather than assuming one:\n * summing cumulative observations double-counts, and diffing delta observations\n * silently loses tokens.\n */\nexport const usageTemporalitySchema = z.enum([\"delta\", \"cumulative\"]);\nexport type UsageTemporality = z.infer<typeof usageTemporalitySchema>;\n\n/**\n * Whether the provider counts cache-creation tokens inside its input total or\n * reports them as a disjoint bucket.\n *\n * - `included-in-input`: `cacheCreationInputTokens` is a subset of `inputTokens`.\n * - `disjoint-from-input`: cache-creation tokens are billed in addition to\n * `inputTokens` and must be added when computing a total.\n * - `not-reported`: the provider exposes no cache-creation counter; the field is\n * pinned to zero.\n */\nexport const cacheCreationAccountingSchema = z.enum([\n \"included-in-input\",\n \"disjoint-from-input\",\n \"not-reported\",\n]);\nexport type CacheCreationAccounting = z.infer<typeof cacheCreationAccountingSchema>;\n\n/** Whether a provider-reported total agrees with the canonical computation. */\nexport const providerTotalAgreementSchema = z.enum([\"unreported\", \"agrees\", \"disagrees\"]);\nexport type ProviderTotalAgreement = z.infer<typeof providerTotalAgreementSchema>;\n\n/**\n * What an adapter reports, before normalization.\n *\n * `inputTokens` is *inclusive*: it counts every input token the provider\n * attributes to the call, including cache reads (and cache creation when the\n * provider folds it in). `outputTokens` is likewise inclusive of reasoning\n * output. Subset fields describe portions of those totals, never additions.\n */\nexport const usageReportSchema = z.strictObject({\n temporality: usageTemporalitySchema,\n /** Inclusive input tokens. */\n inputTokens: tokenCountSchema.optional(),\n /** Subset of `inputTokens` served from a prompt cache. */\n cachedInputTokens: tokenCountSchema.optional(),\n /** Tokens written to a prompt cache. */\n cacheCreationInputTokens: tokenCountSchema.optional(),\n /** Required when `cacheCreationInputTokens` is present and non-zero. */\n cacheCreationAccounting: cacheCreationAccountingSchema.optional(),\n /** Inclusive output tokens. */\n outputTokens: tokenCountSchema.optional(),\n /** Subset of `outputTokens` spent on reasoning. */\n reasoningOutputTokens: tokenCountSchema.optional(),\n /** Total exactly as the provider reported it, if it reported one. */\n providerTotalTokens: tokenCountSchema.optional(),\n});\nexport type UsageReport = z.infer<typeof usageReportSchema>;\n\n/**\n * Fully normalized usage.\n *\n * Derived fields (`uncachedInputTokens`, `totalTokens`,\n * `providerTotalAgreement`) are part of the schema and are re-checked on parse,\n * so an inconsistent object cannot exist. Construct values with\n * {@link normalizeUsage} rather than by hand.\n */\nexport const canonicalUsageSchema = z\n .strictObject({\n temporality: usageTemporalitySchema,\n inputTokens: tokenCountSchema,\n cachedInputTokens: tokenCountSchema,\n cacheCreationInputTokens: tokenCountSchema,\n cacheCreationAccounting: cacheCreationAccountingSchema,\n outputTokens: tokenCountSchema,\n reasoningOutputTokens: tokenCountSchema,\n /** Derived: input tokens that were neither cache reads nor cache writes. */\n uncachedInputTokens: tokenCountSchema,\n /** Derived: canonical billable total. */\n totalTokens: tokenCountSchema,\n providerTotalTokens: tokenCountSchema.optional(),\n providerTotalAgreement: providerTotalAgreementSchema,\n })\n .check((ctx) => {\n const usage = ctx.value;\n const push = (message: string): void => {\n ctx.issues.push({ code: \"custom\", input: usage, message });\n };\n\n if (usage.cachedInputTokens > usage.inputTokens) {\n push(\"cachedInputTokens must not exceed inputTokens (it is a subset)\");\n }\n if (usage.reasoningOutputTokens > usage.outputTokens) {\n push(\"reasoningOutputTokens must not exceed outputTokens (it is a subset)\");\n }\n if (usage.cacheCreationAccounting === \"not-reported\" && usage.cacheCreationInputTokens !== 0) {\n push(\"cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported\");\n }\n const creationInsideInput =\n usage.cacheCreationAccounting === \"included-in-input\" ? usage.cacheCreationInputTokens : 0;\n if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {\n push(\n \"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input\",\n );\n }\n const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;\n if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {\n push(`uncachedInputTokens must equal ${expectedUncached}`);\n }\n const creationOutsideInput =\n usage.cacheCreationAccounting === \"disjoint-from-input\" ? usage.cacheCreationInputTokens : 0;\n const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;\n if (usage.totalTokens !== expectedTotal) {\n push(`totalTokens must equal ${expectedTotal}`);\n }\n const expectedAgreement: ProviderTotalAgreement =\n usage.providerTotalTokens === undefined\n ? \"unreported\"\n : usage.providerTotalTokens === expectedTotal\n ? \"agrees\"\n : \"disagrees\";\n if (usage.providerTotalAgreement !== expectedAgreement) {\n push(`providerTotalAgreement must be ${expectedAgreement}`);\n }\n });\nexport type CanonicalUsage = z.infer<typeof canonicalUsageSchema>;\n\nexport type UsageNormalizationIssue = {\n readonly code:\n | \"invalid-report\"\n | \"cached-exceeds-input\"\n | \"reasoning-exceeds-output\"\n | \"cache-creation-exceeds-input\"\n | \"cache-creation-accounting-missing\";\n readonly message: string;\n};\n\nexport type UsageNormalizationResult =\n | { readonly status: \"ok\"; readonly usage: CanonicalUsage; readonly notes: readonly string[] }\n | { readonly status: \"invalid\"; readonly issues: readonly UsageNormalizationIssue[] };\n\n/**\n * Normalize a provider usage report into canonical usage.\n *\n * Deterministic rules:\n * 1. Absent counters default to `0`; `providerTotalTokens` stays absent.\n * 2. Non-integer, negative, or non-finite counters are rejected.\n * 3. A subset exceeding its total is rejected — never clamped — because\n * clamping would silently invent a billing story.\n * 4. `cacheCreationAccounting` defaults to `not-reported` when no cache-creation\n * tokens are reported, and is *required* when they are: guessing whether the\n * bucket is disjoint would mis-total every downstream cost calculation.\n * 5. A provider total that disagrees with the canonical total is preserved as\n * reported and flagged `disagrees`. Both numbers survive; neither is edited.\n */\nexport const normalizeUsage = (report: unknown): UsageNormalizationResult => {\n const parsed = usageReportSchema.safeParse(report);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map((issue) => ({\n code: \"invalid-report\" as const,\n message: `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n })),\n };\n }\n\n const input = parsed.data;\n const issues: UsageNormalizationIssue[] = [];\n const notes: string[] = [];\n\n const inputTokens = input.inputTokens ?? 0;\n const cachedInputTokens = input.cachedInputTokens ?? 0;\n const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;\n const outputTokens = input.outputTokens ?? 0;\n const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;\n\n let accounting: CacheCreationAccounting;\n if (cacheCreationInputTokens === 0) {\n accounting = input.cacheCreationAccounting ?? \"not-reported\";\n if (accounting !== \"not-reported\") {\n notes.push(\n `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`,\n );\n }\n } else if (input.cacheCreationAccounting === undefined) {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message:\n \"cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred\",\n });\n accounting = \"not-reported\";\n } else if (input.cacheCreationAccounting === \"not-reported\") {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message: \"cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens\",\n });\n accounting = \"not-reported\";\n } else {\n accounting = input.cacheCreationAccounting;\n }\n\n if (cachedInputTokens > inputTokens) {\n issues.push({\n code: \"cached-exceeds-input\",\n message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n if (reasoningOutputTokens > outputTokens) {\n issues.push({\n code: \"reasoning-exceeds-output\",\n message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`,\n });\n }\n\n const creationInsideInput = accounting === \"included-in-input\" ? cacheCreationInputTokens : 0;\n if (cachedInputTokens + creationInsideInput > inputTokens) {\n issues.push({\n code: \"cache-creation-exceeds-input\",\n message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const creationOutsideInput = accounting === \"disjoint-from-input\" ? cacheCreationInputTokens : 0;\n const totalTokens = inputTokens + creationOutsideInput + outputTokens;\n const providerTotalAgreement: ProviderTotalAgreement =\n input.providerTotalTokens === undefined\n ? \"unreported\"\n : input.providerTotalTokens === totalTokens\n ? \"agrees\"\n : \"disagrees\";\n\n if (providerTotalAgreement === \"disagrees\") {\n notes.push(\n `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`,\n );\n }\n\n const usage: CanonicalUsage = {\n temporality: input.temporality,\n inputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens,\n reasoningOutputTokens,\n uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,\n totalTokens,\n ...(input.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: input.providerTotalTokens }),\n providerTotalAgreement,\n };\n\n return { status: \"ok\", usage, notes };\n};\n\nexport class UsageNormalizationError extends Error {\n public readonly issues: readonly UsageNormalizationIssue[];\n\n public constructor(issues: readonly UsageNormalizationIssue[]) {\n super(`invalid usage report: ${issues.map((issue) => issue.message).join(\"; \")}`);\n this.name = \"UsageNormalizationError\";\n this.issues = issues;\n }\n}\n\n/** Convenience wrapper for call sites that treat invalid usage as a bug. */\nexport const normalizeUsageOrThrow = (report: unknown): CanonicalUsage => {\n const result = normalizeUsage(report);\n if (result.status === \"invalid\") {\n throw new UsageNormalizationError(result.issues);\n }\n return result.usage;\n};\n\nexport const EMPTY_DELTA_USAGE: CanonicalUsage = Object.freeze(\n normalizeUsageOrThrow({ temporality: \"delta\" }),\n);\n\nexport type UsageDeltaResult = {\n readonly usage: CanonicalUsage;\n /**\n * True when the current snapshot is smaller than the previous one on any\n * counter. That means the cumulative series restarted (new session, replayed\n * transcript, provider reset), so the current snapshot is emitted as the delta\n * instead of a negative difference.\n */\n readonly resetDetected: boolean;\n};\n\nconst requireCumulative = (usage: CanonicalUsage, label: string): void => {\n if (usage.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: `${label} must have cumulative temporality` },\n ]);\n }\n};\n\n/**\n * Convert two cumulative snapshots into a delta observation.\n *\n * Replay safety: re-processing the same snapshot yields an all-zero delta, and a\n * decreasing series is reported as a reset rather than a negative delta.\n * Accounting mode must match; mixing modes would make the subtraction meaningless.\n */\nexport const cumulativeToDelta = (\n previous: CanonicalUsage,\n current: CanonicalUsage,\n): UsageDeltaResult => {\n requireCumulative(previous, \"previous usage\");\n requireCumulative(current, \"current usage\");\n\n if (\n previous.cacheCreationAccounting !== current.cacheCreationAccounting &&\n previous.cacheCreationInputTokens !== 0 &&\n current.cacheCreationInputTokens !== 0\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot diff cumulative usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const resetDetected =\n current.inputTokens < previous.inputTokens ||\n current.cachedInputTokens < previous.cachedInputTokens ||\n current.cacheCreationInputTokens < previous.cacheCreationInputTokens ||\n current.outputTokens < previous.outputTokens ||\n current.reasoningOutputTokens < previous.reasoningOutputTokens;\n\n if (resetDetected) {\n return {\n usage: normalizeUsageOrThrow({ ...toReport(current), temporality: \"delta\" }),\n resetDetected: true,\n };\n }\n\n const usage = normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: current.inputTokens - previous.inputTokens,\n cachedInputTokens: current.cachedInputTokens - previous.cachedInputTokens,\n cacheCreationInputTokens:\n current.cacheCreationInputTokens - previous.cacheCreationInputTokens,\n cacheCreationAccounting: current.cacheCreationAccounting,\n outputTokens: current.outputTokens - previous.outputTokens,\n reasoningOutputTokens: current.reasoningOutputTokens - previous.reasoningOutputTokens,\n });\n\n return { usage, resetDetected: false };\n};\n\n/** Project canonical usage back onto the reported shape. */\nexport const toReport = (usage: CanonicalUsage): UsageReport => ({\n temporality: usage.temporality,\n inputTokens: usage.inputTokens,\n cachedInputTokens: usage.cachedInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n cacheCreationAccounting: usage.cacheCreationAccounting,\n outputTokens: usage.outputTokens,\n reasoningOutputTokens: usage.reasoningOutputTokens,\n ...(usage.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: usage.providerTotalTokens }),\n});\n\n/**\n * Add two delta observations. Cumulative usage is never summed, because two\n * running totals do not compose.\n */\nexport const addUsage = (a: CanonicalUsage, b: CanonicalUsage): CanonicalUsage => {\n if (a.temporality !== \"delta\" || b.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"only delta usage may be summed\" },\n ]);\n }\n const accounting =\n a.cacheCreationInputTokens === 0 && a.cacheCreationAccounting === \"not-reported\"\n ? b.cacheCreationAccounting\n : b.cacheCreationInputTokens === 0 && b.cacheCreationAccounting === \"not-reported\"\n ? a.cacheCreationAccounting\n : a.cacheCreationAccounting;\n\n if (\n a.cacheCreationInputTokens !== 0 &&\n b.cacheCreationInputTokens !== 0 &&\n a.cacheCreationAccounting !== b.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot sum usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n a.providerTotalTokens === undefined && b.providerTotalTokens === undefined\n ? undefined\n : (a.providerTotalTokens ?? 0) + (b.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: a.inputTokens + b.inputTokens,\n cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,\n cacheCreationInputTokens: a.cacheCreationInputTokens + b.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: a.outputTokens + b.outputTokens,\n reasoningOutputTokens: a.reasoningOutputTokens + b.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n","import { z } from \"zod\";\n\n/**\n * Version of the canonical event model.\n *\n * Every emitted event carries this value. Consumers must treat an unknown\n * version as unreadable rather than guessing field semantics.\n *\n * Compatibility rules:\n * - Additive optional fields do not change the version.\n * - Renaming, removing, or re-interpreting a field increments the version.\n */\nexport const CANONICAL_SCHEMA_VERSION = 1 as const;\n\nexport type CanonicalSchemaVersion = typeof CANONICAL_SCHEMA_VERSION;\n\nexport const canonicalSchemaVersionSchema = z.literal(CANONICAL_SCHEMA_VERSION);\n","import { randomBytes } from \"node:crypto\";\nimport { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport type { Clock, Logger } from \"../runtime/ports.js\";\nimport { namespaceSegments, type StoreNamespace } from \"../state/keys.js\";\n\nexport type SpoolEnqueueResult =\n | { readonly spooled: true }\n | { readonly spooled: false; readonly reason: \"capacity-exceeded\" };\n\nexport type SpoolDrainResult = {\n readonly drained: number;\n readonly remaining: number;\n readonly failed: number;\n /**\n * Batches removed from the queue because they were unusable rather than\n * undeliverable.\n *\n * Distinct from `failed`, which means \"the collector would not take it, try\n * later\". A quarantined batch will never become deliverable, so counting it\n * separately is what stops a permanent problem from reading as transient.\n */\n readonly quarantined: number;\n};\n\n/**\n * Why a queued batch was dropped rather than delivered.\n *\n * - `age` — older than the queue's `maxAgeMillis`.\n * - `size` — evicted (or refused) to stay within `maxBytes`.\n * - `count` — evicted (or refused) to stay within the batch-count bound.\n * - `rejected` — the destination answered with a non-retryable status on replay,\n * so sending it again could never succeed.\n */\nexport type SpoolDropReason = \"age\" | \"size\" | \"count\" | \"rejected\";\n\n/** Drop counts, persisted beside the queue so they outlive the process that dropped. */\nexport type SpoolDropCounts = {\n readonly total: number;\n readonly age: number;\n readonly size: number;\n readonly count: number;\n readonly rejected: number;\n readonly lastDroppedAt?: number;\n};\n\nexport type SpoolStats = {\n readonly batches: number;\n readonly bytes: number;\n /** Enqueue time of the oldest queued batch. Absent when the queue is empty. */\n readonly oldestEnqueuedAt?: number;\n readonly dropped: SpoolDropCounts;\n};\n\n/**\n * What a queue does when a new batch would exceed a bound.\n *\n * `refuse-new` keeps what is queued and reports the new batch as lost — the\n * original behavior, still the default for a queue built directly. `drop-oldest`\n * evicts from the head until the new batch fits, which is what the runtime's\n * per-destination spools use.\n */\nexport type SpoolOverflowPolicy = \"refuse-new\" | \"drop-oldest\";\n\n/**\n * What a drain's sender reports for one batch: delivered (`true`), still\n * undeliverable and worth retrying (`false`), or permanently undeliverable\n * (`\"discard\"`), which removes it and counts it as a `rejected` drop instead of\n * stopping the drain behind it.\n */\nexport type SpoolSendOutcome = boolean | \"discard\";\n\nexport const EMPTY_SPOOL_DROP_COUNTS: SpoolDropCounts = Object.freeze({\n total: 0,\n age: 0,\n size: 0,\n count: 0,\n rejected: 0,\n});\n\n/** Outcome of validating one batch read back from a queue file. */\nexport type SpoolValidation<TBatch> =\n | { readonly batch: TBatch }\n | { readonly rejection: string };\n\nexport type SpoolQueueOptions<TBatch> = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Bound on the number of queued batches. */\n readonly maxFiles: number;\n /** Bound on the total bytes of queued batches. Unbounded when absent. */\n readonly maxBytes?: number;\n /** A batch older than this is dropped, at enqueue and at drain. No age bound when absent. */\n readonly maxAgeMillis?: number;\n /** Default `refuse-new`. */\n readonly overflow?: SpoolOverflowPolicy;\n /**\n * Directory holding the queue, under the identity namespace. One name per\n * signal, so a batch of one signal can never be drained by the other's sender —\n * the two encode different payloads and a mixed queue would quarantine\n * perfectly good batches.\n */\n readonly queueName: string;\n /** Re-validates a batch read back from disk, before any of it reaches a sender. */\n readonly validate: (value: unknown, identity: StoreNamespace) => SpoolValidation<TBatch>;\n};\n\n/**\n * Durable filesystem queue for export batches a collector could not accept.\n *\n * A hook process is short-lived, so \"retry later\" means \"persist and let a later\n * invocation retry\" rather than an in-process backoff loop. Each instance is\n * rooted at `<rootDir>/<providerId>/<installationId>/<queueName>`; two queues for\n * different providers, installations, or signals never share a directory, so a\n * batch from one identity cannot physically land in another's drain — batches\n * cannot mix identities by construction, not by a runtime check alone (the check\n * inside {@link SpoolQueue.drain} is defense in depth for a hand-edited or\n * misplaced file).\n *\n * Shared by the trace and log spools rather than written twice: the drain's\n * quarantine-and-continue behavior is the subtle part, and a second copy of it is\n * a second place for the head-of-queue-blocking bug to come back.\n */\nexport interface SpoolQueue<TBatch> {\n enqueue(batch: TBatch): Promise<SpoolEnqueueResult>;\n /** Sequential, bounded drain: stops after the first failed send, or after `maxBatches`. */\n drain(\n send: (batch: TBatch) => Promise<SpoolSendOutcome>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\n /** Depth, bytes, and persisted drop counts. Read-only: creates no directory. */\n stats(): Promise<SpoolStats>;\n}\n\n/** Name of the drop-count file, inside the queue directory and outside its `*.json` listing. */\nexport const SPOOL_DROPS_FILE = \".drops\";\n\n/** Enqueue time encoded in a queue file name, or undefined for a foreign name. */\nconst enqueuedAtOf = (fileName: string): number | undefined => {\n const match = /^(\\d{16})-/.exec(fileName);\n return match?.[1] === undefined ? undefined : Number(match[1]);\n};\n\nconst isCount = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isInteger(value) && value >= 0;\n\n/** Read a queue directory's drop counts. Missing or unreadable reads as zero. */\nexport const readSpoolDropCounts = async (queueDir: string): Promise<SpoolDropCounts> => {\n try {\n const parsed = JSON.parse(await readFile(path.join(queueDir, SPOOL_DROPS_FILE), \"utf8\")) as unknown;\n if (typeof parsed !== \"object\" || parsed === null) {\n return EMPTY_SPOOL_DROP_COUNTS;\n }\n const record = parsed as Record<string, unknown>;\n const field = (name: string): number => (isCount(record[name]) ? record[name] : 0);\n return {\n total: field(\"total\"),\n age: field(\"age\"),\n size: field(\"size\"),\n count: field(\"count\"),\n rejected: field(\"rejected\"),\n ...(isCount(record.lastDroppedAt) ? { lastDroppedAt: record.lastDroppedAt } : {}),\n };\n } catch {\n return EMPTY_SPOOL_DROP_COUNTS;\n }\n};\n\n/**\n * Depth, bytes, and drop counts of one queue directory, without creating it.\n *\n * Exported for `doctor`, which inspects queues on disk without constructing the\n * sinks that own them.\n */\nexport const readSpoolQueueStats = async (queueDir: string): Promise<SpoolStats> => {\n let entries: string[];\n try {\n entries = await readdir(queueDir);\n } catch {\n return { batches: 0, bytes: 0, dropped: await readSpoolDropCounts(queueDir) };\n }\n const files = entries.filter((entry) => entry.endsWith(\".json\") && !entry.startsWith(\".tmp-\")).sort();\n let bytes = 0;\n for (const file of files) {\n try {\n bytes += (await stat(path.join(queueDir, file))).size;\n } catch {\n // Drained by a peer between the listing and the stat.\n }\n }\n const oldest = files[0] === undefined ? undefined : enqueuedAtOf(files[0]);\n return {\n batches: files.length,\n bytes,\n ...(oldest === undefined ? {} : { oldestEnqueuedAt: oldest }),\n dropped: await readSpoolDropCounts(queueDir),\n };\n};\n\n/** Default bound on a single drain pass, so one invocation's flush stays short. */\nexport const DEFAULT_DRAIN_MAX_BATCHES = 20;\n\nconst isErrnoException = (thrown: unknown, code: string): boolean =>\n thrown instanceof Error && (thrown as NodeJS.ErrnoException).code === code;\n\nexport const createSpoolQueue = <TBatch>(\n options: SpoolQueueOptions<TBatch>,\n): SpoolQueue<TBatch> => {\n const [providerSegment, installationSegment] = namespaceSegments(options);\n const queueDir = path.join(options.rootDir, providerSegment, installationSegment, options.queueName);\n const corruptDir = path.join(\n options.rootDir,\n providerSegment,\n installationSegment,\n `${options.queueName}-corrupt`,\n );\n\n let dirsReady: Promise<void> | undefined;\n const ensureDirs = async (): Promise<void> => {\n if (dirsReady !== undefined) {\n return dirsReady;\n }\n const promise = (async (): Promise<void> => {\n await mkdir(queueDir, { recursive: true });\n await mkdir(corruptDir, { recursive: true });\n })();\n dirsReady = promise;\n try {\n await promise;\n } catch (thrown) {\n dirsReady = undefined;\n throw thrown;\n }\n };\n\n const listSorted = async (): Promise<readonly string[]> => {\n let entries: string[];\n try {\n entries = await readdir(queueDir);\n } catch (thrown) {\n if (isErrnoException(thrown, \"ENOENT\")) {\n return [];\n }\n throw thrown;\n }\n return entries.filter((entry) => entry.endsWith(\".json\") && !entry.startsWith(\".tmp-\")).sort();\n };\n\n /**\n * Add drops to the persisted counts.\n *\n * A read-modify-write without a lock: two processes dropping at the same moment\n * can lose one increment. The counts are a diagnostic, not an invoice, and a\n * lock here would put a second contention point on the failure path.\n */\n const recordDrops = async (reason: SpoolDropReason, dropped: number): Promise<void> => {\n if (dropped <= 0) {\n return;\n }\n try {\n const current = await readSpoolDropCounts(queueDir);\n const next: SpoolDropCounts = {\n ...current,\n total: current.total + dropped,\n [reason]: current[reason] + dropped,\n lastDroppedAt: options.clock.now(),\n };\n const tmp = path.join(queueDir, `.tmp-${randomBytes(6).toString(\"hex\")}.drops`);\n await writeFile(tmp, JSON.stringify(next), \"utf8\");\n await rename(tmp, path.join(queueDir, SPOOL_DROPS_FILE));\n } catch {\n // Counting is best-effort; the drop itself already happened.\n }\n options.logger?.warn(\"durable spool dropped batches\", {\n \"spool.queue\": options.queueName,\n \"spool.drop_reason\": reason,\n \"spool.dropped\": dropped,\n });\n };\n\n type QueuedFile = { readonly name: string; readonly enqueuedAt?: number; readonly bytes: number };\n\n const listWithSizes = async (): Promise<QueuedFile[]> => {\n const names = await listSorted();\n const files: QueuedFile[] = [];\n for (const name of names) {\n let bytes = 0;\n if (options.maxBytes !== undefined) {\n try {\n bytes = (await stat(path.join(queueDir, name))).size;\n } catch {\n continue;\n }\n }\n const enqueuedAt = enqueuedAtOf(name);\n files.push({ name, bytes, ...(enqueuedAt === undefined ? {} : { enqueuedAt }) });\n }\n return files;\n };\n\n /** Remove queued files; the count is what actually left the queue. */\n const evict = async (files: readonly QueuedFile[]): Promise<number> => {\n let removed = 0;\n for (const file of files) {\n try {\n await unlink(path.join(queueDir, file.name));\n removed += 1;\n } catch {\n // Already drained or evicted by a peer: it left the queue either way, but\n // not because of this process, so it is not counted here.\n }\n }\n return removed;\n };\n\n const isExpired = (file: QueuedFile, now: number): boolean =>\n options.maxAgeMillis !== undefined &&\n file.enqueuedAt !== undefined &&\n now - file.enqueuedAt > options.maxAgeMillis;\n\n const enqueue = async (batch: TBatch): Promise<SpoolEnqueueResult> => {\n await ensureDirs();\n const serialized = JSON.stringify(batch);\n const bytes = Buffer.byteLength(serialized, \"utf8\");\n const refuse = async (reason: \"size\" | \"count\"): Promise<SpoolEnqueueResult> => {\n options.logger?.warn(\"durable spool at capacity; batch dropped\", {\n \"spool.max_files\": options.maxFiles,\n ...(options.maxBytes === undefined ? {} : { \"spool.max_bytes\": options.maxBytes }),\n \"spool.queue\": options.queueName,\n });\n await recordDrops(reason, 1);\n return { spooled: false, reason: \"capacity-exceeded\" };\n };\n\n if (options.maxBytes !== undefined && bytes > options.maxBytes) {\n // Larger than the whole budget: evicting everything else still would not\n // make room, so it is the one batch that is refused under either policy.\n return refuse(\"size\");\n }\n\n let queued = await listWithSizes();\n const now = options.clock.now();\n const expired = queued.filter((file) => isExpired(file, now));\n if (expired.length > 0) {\n await recordDrops(\"age\", await evict(expired));\n queued = queued.filter((file) => !isExpired(file, now));\n }\n\n const overflow = options.overflow ?? \"refuse-new\";\n const totalBytes = (): number => queued.reduce((sum, file) => sum + file.bytes, 0);\n if (overflow === \"refuse-new\") {\n if (queued.length >= options.maxFiles) {\n return refuse(\"count\");\n }\n if (options.maxBytes !== undefined && totalBytes() + bytes > options.maxBytes) {\n return refuse(\"size\");\n }\n } else {\n // Oldest first: the listing is sorted by enqueue time.\n const overCount = Math.max(0, queued.length + 1 - options.maxFiles);\n if (overCount > 0) {\n await recordDrops(\"count\", await evict(queued.slice(0, overCount)));\n queued = queued.slice(overCount);\n }\n if (options.maxBytes !== undefined) {\n let excess = totalBytes() + bytes - options.maxBytes;\n let cut = 0;\n while (excess > 0 && cut < queued.length) {\n excess -= queued[cut]?.bytes ?? 0;\n cut += 1;\n }\n if (cut > 0) {\n await recordDrops(\"size\", await evict(queued.slice(0, cut)));\n queued = queued.slice(cut);\n }\n }\n }\n\n const fileName = `${String(now).padStart(16, \"0\")}-${randomBytes(6).toString(\"hex\")}.json`;\n const target = path.join(queueDir, fileName);\n const tmp = path.join(queueDir, `.tmp-${randomBytes(6).toString(\"hex\")}.json`);\n await writeFile(tmp, serialized, \"utf8\");\n await rename(tmp, target);\n return { spooled: true };\n };\n\n const drain = async (\n send: (batch: TBatch) => Promise<SpoolSendOutcome>,\n drainOptions?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult> => {\n await ensureDirs();\n const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;\n let files = await listSorted();\n if (options.maxAgeMillis !== undefined) {\n // Expired batches are dropped, not sent: a collector would place them far in\n // the past, and they would spend this invocation's short flush window.\n const now = options.clock.now();\n const expired = files\n .map((name): QueuedFile => {\n const enqueuedAt = enqueuedAtOf(name);\n return { name, bytes: 0, ...(enqueuedAt === undefined ? {} : { enqueuedAt }) };\n })\n .filter((file) => isExpired(file, now));\n if (expired.length > 0) {\n await recordDrops(\"age\", await evict(expired));\n const gone = new Set(expired.map((file) => file.name));\n files = files.filter((name) => !gone.has(name));\n }\n }\n let drained = 0;\n let failed = 0;\n let quarantined = 0;\n let index = 0;\n\n for (; index < files.length && index < cap; index += 1) {\n const fileName = files[index];\n if (fileName === undefined) {\n break;\n }\n const filePath = path.join(queueDir, fileName);\n\n /**\n * Move a file out of the queue, or delete it if quarantine is unavailable.\n *\n * Getting it *out of the queue* is the part that matters. A file the drain\n * cannot use and cannot move would be re-read on every pass, and because the\n * head is processed first it would block every healthy batch behind it — the\n * one failure mode a retry queue must not have. So a failed quarantine falls\n * back to deleting: losing one unusable batch beats losing all the usable\n * ones queued behind it.\n */\n const quarantine = async (rejection: string): Promise<void> => {\n quarantined += 1;\n options.logger?.error(\"durable spool quarantined an unusable batch\", {\n \"spool.rejection\": rejection,\n \"spool.file\": fileName,\n \"spool.queue\": options.queueName,\n });\n try {\n await rename(filePath, path.join(corruptDir, fileName));\n } catch {\n await unlink(filePath).catch(() => undefined);\n }\n };\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(await readFile(filePath, \"utf8\")) as unknown;\n } catch {\n await quarantine(\"unparseable-json\");\n continue;\n }\n\n const validation = options.validate(parsed, {\n providerId: options.providerId,\n installationId: options.installationId,\n });\n if (\"rejection\" in validation) {\n await quarantine(validation.rejection);\n continue;\n }\n\n let delivered: SpoolSendOutcome;\n try {\n delivered = await send(validation.batch);\n } catch {\n delivered = false;\n }\n if (delivered === \"discard\") {\n // Permanently refused: retrying can never succeed, and stopping here would\n // wedge every batch queued behind it.\n if (await unlink(filePath).then(() => true, () => false)) {\n await recordDrops(\"rejected\", 1);\n }\n continue;\n }\n if (delivered) {\n await unlink(filePath).catch(() => undefined);\n drained += 1;\n } else {\n failed += 1;\n break;\n }\n }\n\n const remaining = (await listSorted()).length;\n return { drained, remaining, failed, quarantined };\n };\n\n return {\n enqueue,\n drain,\n size: async (): Promise<number> => {\n await ensureDirs();\n return (await listSorted()).length;\n },\n stats: (): Promise<SpoolStats> => readSpoolQueueStats(queueDir),\n };\n};\n","import { createHash } from \"node:crypto\";\n\n/**\n * Segments derived from arbitrary strings must be safe path components on any\n * filesystem: no separators, no traversal, no reserved characters. Anything\n * that already looks safe is kept as-is (for readable directory names);\n * anything else is replaced by a stable hash so no input can escape its\n * namespace directory or collide with a sibling by accident.\n */\nconst SAFE_SEGMENT_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;\n\nexport const isSafeSegment = (segment: string): boolean => SAFE_SEGMENT_PATTERN.test(segment);\n\nexport const sanitizeSegment = (segment: string): string => {\n if (isSafeSegment(segment)) {\n return segment;\n }\n return `h_${createHash(\"sha256\").update(segment, \"utf8\").digest(\"hex\").slice(0, 32)}`;\n};\n\n/** Scopes a state store to one provider deployed under one installation. */\nexport type StoreNamespace = {\n readonly providerId: string;\n readonly installationId: string;\n};\n\nexport const namespaceSegments = (namespace: StoreNamespace): readonly [string, string] => [\n sanitizeSegment(namespace.providerId),\n sanitizeSegment(namespace.installationId),\n];\n\n/** Stable, collision-resistant digest of a logical state key. */\nexport const keyDigest = (key: string): string =>\n createHash(\"sha256\").update(key, \"utf8\").digest(\"hex\");\n","import type { Attributes } from \"@opentelemetry/api\";\n\nimport type { Clock, Logger } from \"../runtime/ports.js\";\nimport type { StoreNamespace } from \"../state/keys.js\";\n// Deliberately not re-exported: `spool-queue.js` is their one home, and a second\n// `export *` path to the same names makes them ambiguous in the barrel below.\nimport {\n createSpoolQueue,\n type SpoolDrainResult,\n type SpoolEnqueueResult,\n type SpoolOverflowPolicy,\n type SpoolSendOutcome,\n type SpoolStats,\n} from \"./spool-queue.js\";\n\nexport type SerializedSpan = {\n readonly name: string;\n readonly kind: number;\n readonly traceId: string;\n readonly spanId: string;\n /** Absent on batches spooled before cross-process parenting existed, and on root spans. */\n readonly parentSpanId?: string;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly attributes: Attributes;\n readonly statusCode: number;\n readonly statusMessage?: string;\n};\n\nexport type SpoolBatch = {\n readonly providerId: string;\n readonly installationId: string;\n readonly resourceAttributes: Attributes;\n readonly instrumentationScope: { readonly name: string; readonly version?: string };\n readonly spans: readonly SerializedSpan[];\n readonly enqueuedAt: number;\n};\n\n/** Upper bounds on a replayed batch. A spool file is untrusted input. */\nexport const MAX_SPOOLED_SPANS_PER_BATCH = 4_096;\nexport const MAX_SPOOLED_STRING_LENGTH = 8_192;\nconst MAX_SPOOLED_ATTRIBUTES_PER_SPAN = 256;\nconst TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;\nconst SPAN_ID_PATTERN = /^[0-9a-f]{16}$/;\n\nconst isFiniteNonNegative = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n\nconst isBoundedString = (value: unknown, maxLength = MAX_SPOOLED_STRING_LENGTH): value is string =>\n typeof value === \"string\" && value.length > 0 && value.length <= maxLength;\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * Whether one recorded span can be replayed.\n *\n * Every field is checked, not just the ones a happy path reads. `assembleReadableSpan`\n * hands its output straight to the OTLP encoder, which assumes the shapes the type\n * declares — so a `spanId` of the wrong length, a `startMillis` of `null`, or an\n * `attributes` value holding a nested object becomes an encoder error deep inside\n * the exporter rather than a rejected file here. Trace and span ids are further held\n * to their hex forms, because a malformed id is not a span a collector can place.\n */\nconst isReplayableSpan = (value: unknown): value is SerializedSpan => {\n if (!isPlainObject(value)) {\n return false;\n }\n if (!isBoundedString(value.name) || !isFiniteNonNegative(value.kind)) {\n return false;\n }\n if (typeof value.traceId !== \"string\" || !TRACE_ID_PATTERN.test(value.traceId)) {\n return false;\n }\n if (typeof value.spanId !== \"string\" || !SPAN_ID_PATTERN.test(value.spanId)) {\n return false;\n }\n if (\n value.parentSpanId !== undefined &&\n (typeof value.parentSpanId !== \"string\" || !SPAN_ID_PATTERN.test(value.parentSpanId))\n ) {\n return false;\n }\n if (!isFiniteNonNegative(value.startMillis) || !isFiniteNonNegative(value.endMillis)) {\n return false;\n }\n if (!isFiniteNonNegative(value.statusCode)) {\n return false;\n }\n if (\n value.statusMessage !== undefined &&\n typeof value.statusMessage !== \"string\"\n ) {\n return false;\n }\n if (!isPlainObject(value.attributes)) {\n return false;\n }\n const entries = Object.entries(value.attributes);\n if (entries.length > MAX_SPOOLED_ATTRIBUTES_PER_SPAN) {\n return false;\n }\n return entries.every(([, attribute]) => {\n if (Array.isArray(attribute)) {\n // OTLP permits homogeneous primitive arrays; anything nested is not a span\n // attribute and would fail encoding.\n return attribute.every(\n (item) =>\n (typeof item === \"string\" && item.length <= MAX_SPOOLED_STRING_LENGTH) ||\n (typeof item === \"number\" && Number.isFinite(item)) ||\n typeof item === \"boolean\" ||\n item === null,\n );\n }\n return (\n (typeof attribute === \"string\" && attribute.length <= MAX_SPOOLED_STRING_LENGTH) ||\n (typeof attribute === \"number\" && Number.isFinite(attribute)) ||\n typeof attribute === \"boolean\" ||\n attribute === undefined\n );\n });\n};\n\nexport type SpoolBatchRejection =\n | \"not-an-object\"\n | \"identity-mismatch\"\n | \"resource-attributes-invalid\"\n | \"instrumentation-scope-invalid\"\n | \"spans-invalid\"\n | \"span-field-invalid\";\n\n/**\n * Validate a whole batch read back from disk, before any of it reaches an exporter.\n *\n * The identity check alone is not enough. `spans` being anything other than an array\n * makes the sink's `spans.map(...)` throw, and a throwing send is indistinguishable\n * from an unreachable collector — so the drain would treat a permanently poisoned\n * file as a transient failure and stop at it on every pass, wedging the queue head\n * and every batch behind it forever. Validation is what turns that into a single\n * quarantined file.\n */\nexport const validateSpoolBatch = (\n value: unknown,\n identity: StoreNamespace,\n): { readonly batch: SpoolBatch } | { readonly rejection: SpoolBatchRejection } => {\n if (!isPlainObject(value)) {\n return { rejection: \"not-an-object\" };\n }\n if (\n value.providerId !== identity.providerId ||\n value.installationId !== identity.installationId\n ) {\n return { rejection: \"identity-mismatch\" };\n }\n if (!isPlainObject(value.resourceAttributes)) {\n // Not merely absent: `replayResource` iterates it, and a string or an array\n // would silently produce a resource built from its indices.\n return { rejection: \"resource-attributes-invalid\" };\n }\n if (!isPlainObject(value.instrumentationScope) || !isBoundedString(value.instrumentationScope.name)) {\n return { rejection: \"instrumentation-scope-invalid\" };\n }\n if (\n value.instrumentationScope.version !== undefined &&\n typeof value.instrumentationScope.version !== \"string\"\n ) {\n return { rejection: \"instrumentation-scope-invalid\" };\n }\n if (!Array.isArray(value.spans) || value.spans.length === 0) {\n return { rejection: \"spans-invalid\" };\n }\n if (value.spans.length > MAX_SPOOLED_SPANS_PER_BATCH) {\n return { rejection: \"spans-invalid\" };\n }\n if (!value.spans.every(isReplayableSpan)) {\n return { rejection: \"span-field-invalid\" };\n }\n if (!isFiniteNonNegative(value.enqueuedAt)) {\n return { rejection: \"not-an-object\" };\n }\n return { batch: value as unknown as SpoolBatch };\n};\n\nexport type DurableSpoolOptions = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Refuses new entries once this many are queued, rather than growing without bound. Default 500. */\n readonly maxSpoolFiles?: number;\n /**\n * Queue directory below the identity namespace. Default `spool`; each\n * export destination other than `default` gets its own.\n */\n readonly queueName?: string;\n /** Bound on total queued bytes. Unbounded when absent. */\n readonly maxBytes?: number;\n /** Batches older than this are dropped rather than sent. No age bound when absent. */\n readonly maxAgeMillis?: number;\n /** Default `refuse-new`, the original behavior. */\n readonly overflow?: SpoolOverflowPolicy;\n};\n\n/**\n * Durable filesystem queue for export batches a collector could not accept.\n *\n * A hook process is short-lived, so \"retry later\" means \"persist and let a\n * later invocation retry\" rather than an in-process backoff loop. Each\n * instance is rooted at `<rootDir>/<providerId>/<installationId>/spool`; two\n * spools for different providers or installations never share a directory,\n * so a batch from one identity cannot physically land in another's drain —\n * batches cannot mix identities by construction, not by a runtime check\n * alone (the check in {@link DurableSpool.drain} is defense in depth for a\n * hand-edited or misplaced file).\n */\nexport interface DurableSpool {\n enqueue(batch: SpoolBatch): Promise<SpoolEnqueueResult>;\n /** Sequential, bounded drain: stops after the first failed send, or after `maxBatches`. */\n drain(\n send: (batch: SpoolBatch) => Promise<SpoolSendOutcome>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\n /**\n * Depth, bytes, and persisted drop counts. Optional so a host's own\n * implementation of this interface keeps compiling; the file-backed one has it.\n */\n stats?(): Promise<SpoolStats>;\n}\n\n/** Default bound on queued trace batches, so the spool cannot grow without limit. */\nexport const DEFAULT_MAX_SPOOL_FILES = 500;\n\nexport const createFileDurableSpool = (options: DurableSpoolOptions): DurableSpool =>\n createSpoolQueue<SpoolBatch>({\n rootDir: options.rootDir,\n providerId: options.providerId,\n installationId: options.installationId,\n clock: options.clock,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_SPOOL_FILES,\n queueName: options.queueName ?? \"spool\",\n ...(options.maxBytes === undefined ? {} : { maxBytes: options.maxBytes }),\n ...(options.maxAgeMillis === undefined ? {} : { maxAgeMillis: options.maxAgeMillis }),\n ...(options.overflow === undefined ? {} : { overflow: options.overflow }),\n validate: validateSpoolBatch,\n });\n","import { ExportResultCode, type ExportResult } from \"@opentelemetry/core\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-proto\";\nimport type { InstrumentationScope } from \"@opentelemetry/core\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport type { ReadableSpan } from \"@opentelemetry/sdk-trace\";\n\nimport type { ExporterPolicy } from \"../config/schema.js\";\nimport { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport { createHealthTracker, type DeliveryHealthSnapshot } from \"../diagnostics/health.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { Clock, Logger, TelemetryEmitResult, TelemetrySink } from \"../runtime/ports.js\";\nimport type { DurableSpool, SerializedSpan, SpoolBatch } from \"./durable-spool.js\";\nimport { isPermanentExportFailure } from \"./export-failure.js\";\nimport type { SpoolSendOutcome } from \"./spool-queue.js\";\nimport {\n agreedContextAttributes,\n replayResource,\n resourceFromExporterPolicy,\n resourceWithContext,\n} from \"./exporter-resource.js\";\nimport {\n assembleReadableSpan,\n canonicalEventsToReadableSpans,\n DEFAULT_INSTRUMENTATION_SCOPE,\n type SpanCorrelation,\n type SpanCorrelationResolver,\n} from \"./semconv.js\";\n\nconst chunk = <T,>(items: readonly T[], size: number): readonly (readonly T[])[] => {\n if (size <= 0 || items.length <= size) {\n return [items];\n }\n const chunks: T[][] = [];\n for (let index = 0; index < items.length; index += size) {\n chunks.push(items.slice(index, index + size));\n }\n return chunks;\n};\n\nconst serializeSpan = (span: ReadableSpan): SerializedSpan => ({\n name: span.name,\n kind: span.kind,\n traceId: span.spanContext().traceId,\n spanId: span.spanContext().spanId,\n ...(span.parentSpanContext === undefined\n ? {}\n : { parentSpanId: span.parentSpanContext.spanId }),\n startMillis: span.startTime[0] * 1000 + Math.round(span.startTime[1] / 1e6),\n endMillis: span.endTime[0] * 1000 + Math.round(span.endTime[1] / 1e6),\n attributes: { ...span.attributes },\n statusCode: span.status.code,\n ...(span.status.message === undefined ? {} : { statusMessage: span.status.message }),\n});\n\nconst deserializeSpan = (\n serialized: SerializedSpan,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan =>\n assembleReadableSpan({\n name: serialized.name,\n kind: serialized.kind,\n startMillis: serialized.startMillis,\n endMillis: serialized.endMillis,\n attributes: serialized.attributes,\n status: { code: serialized.statusCode, ...(serialized.statusMessage === undefined ? {} : { message: serialized.statusMessage }) },\n traceId: serialized.traceId,\n spanId: serialized.spanId,\n ...(serialized.parentSpanId === undefined ? {} : { parentSpanId: serialized.parentSpanId }),\n resource,\n instrumentationScope: scope,\n });\n\nexport type OtlpTraceSinkOptions = {\n readonly exporter: ExporterPolicy;\n /** Header values, kept out of the resolved-config snapshot (ADR: config carries only header *names*). */\n readonly headers?: Readonly<Record<string, string>>;\n readonly providerId: string;\n readonly installationId: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Persists batches an unreachable collector rejected, for a later retry. */\n readonly spool?: DurableSpool;\n readonly instrumentationScope?: InstrumentationScope;\n /**\n * Supplies cross-process pairing for lifecycle spans, normally the\n * {@link SpanCorrelator}. Omitted, the sink pairs only within a batch.\n *\n * Injected as a plain function rather than as a correlator so the telemetry\n * layer keeps no dependency on lifecycle or on the state store (ADR 0006).\n */\n readonly correlate?: SpanCorrelationResolver;\n /**\n * Export destination this sink delivers to, when `exporter.destinations` is in\n * use. Labels health snapshots, diagnostics, and log lines; absent, all three are\n * exactly what a single-destination installation has always produced.\n */\n readonly destination?: string;\n};\n\nexport interface OtlpTelemetrySink extends TelemetrySink {\n health(): DeliveryHealthSnapshot;\n /** Attempts to resend previously spooled batches, bounded by `maxBatches`. */\n drainSpool(maxBatches?: number): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }>;\n}\n\n/** Sink that accepts every batch and does nothing else: exporter disabled or protocol `none`. */\nconst createDisabledSink = (destination?: string): OtlpTelemetrySink => {\n const health = createHealthTracker(\n \"telemetry-sink\",\n destination === undefined ? {} : { destination },\n );\n return {\n emit: (events): Promise<TelemetryEmitResult> => {\n health.recordSuccess(events.length);\n return Promise.resolve({ accepted: events.length, rejected: 0, errors: [] });\n },\n flush: (): Promise<void> => Promise.resolve(),\n shutdown: (): Promise<void> => Promise.resolve(),\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool: (): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }> =>\n Promise.resolve({ drained: 0, remaining: 0, failed: 0 }),\n };\n};\n\n/**\n * OTLP HTTP/protobuf {@link TelemetrySink}.\n *\n * Semantic mapping lives entirely in `semconv.ts`; this module only owns\n * batching, delivery, bounded flush/shutdown, health tracking, and — when a\n * spool is configured — persisting what a down collector rejected. Every\n * failure mode (disabled config, missing endpoint, export failure, timeout,\n * spool write failure, unreadable correlation state) degrades to a reported\n * diagnostic rather than a thrown error, preserving the hook's fail-open\n * contract.\n *\n * A disabled sink never calls `correlate`: with nothing being exported there is\n * no span to pair, and writing correlation state anyway would leave a disabled\n * installation quietly accumulating files.\n */\nexport const createOtlpTraceSink = (options: OtlpTraceSinkOptions): OtlpTelemetrySink => {\n const destinationFields =\n options.destination === undefined ? {} : { \"export.destination\": options.destination };\n if (!options.exporter.enabled || options.exporter.protocol === \"none\") {\n return createDisabledSink(options.destination);\n }\n if (options.exporter.endpoint === undefined) {\n options.logger?.warn(\"otlp sink disabled: no endpoint configured\", destinationFields);\n return createDisabledSink(options.destination);\n }\n if (options.exporter.protocol !== \"http/protobuf\") {\n options.logger?.warn(\"otlp sink: protocol not supported by this build, falling back to disabled\", {\n \"exporter.protocol\": options.exporter.protocol,\n ...destinationFields,\n });\n return createDisabledSink(options.destination);\n }\n\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const resource = resourceFromExporterPolicy(options.exporter);\n const health = createHealthTracker(\n \"telemetry-sink\",\n options.destination === undefined ? {} : { destination: options.destination },\n );\n const exporter = new OTLPTraceExporter({\n url: options.exporter.endpoint,\n headers: { ...options.headers },\n timeoutMillis: options.exporter.timeoutMillis,\n });\n let shutdownCompleted = false;\n\n const exportSpans = (spans: readonly ReadableSpan[]): Promise<ExportResult> =>\n new Promise((resolve) => {\n exporter.export([...spans], (result: ExportResult) => resolve(result));\n });\n\n const toSpoolBatch = (spans: readonly ReadableSpan[], batchResource: Resource): SpoolBatch => ({\n providerId: options.providerId,\n installationId: options.installationId,\n resourceAttributes: { ...batchResource.attributes },\n instrumentationScope: { name: scope.name, ...(scope.version === undefined ? {} : { version: scope.version }) },\n spans: spans.map(serializeSpan),\n enqueuedAt: options.clock.now(),\n });\n\n const sendSerializedBatch = async (batch: SpoolBatch): Promise<SpoolSendOutcome> => {\n const batchResource = replayResource(batch.resourceAttributes, options.exporter);\n const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));\n const result = await exportSpans(spans);\n if (result.code === ExportResultCode.SUCCESS) {\n return true;\n }\n return isPermanentExportFailure(result) ? \"discard\" : false;\n };\n\n /**\n * Cross-process pairing is an enrichment, never a precondition: if state is\n * unreadable the batch still exports, with each lifecycle span flagged\n * unpaired rather than dropped.\n *\n * `available` is reported separately from the (possibly empty) list because the\n * mapping needs the two apart. An empty list from a healthy correlator and an\n * empty list from a correlator that threw look identical, and only the first\n * means \"the state store is holding these starts\". Conflating them would drop an\n * unpaired start that nothing recorded, and the export would then report zero\n * rejections — so a caller would commit a callback whose telemetry went nowhere.\n */\n const resolveCorrelations = async (\n events: readonly CanonicalEvent[],\n ): Promise<{\n readonly correlations: readonly SpanCorrelation[];\n readonly available: boolean | undefined;\n }> => {\n if (options.correlate === undefined) {\n return { correlations: [], available: undefined };\n }\n try {\n return { correlations: await options.correlate(events), available: true };\n } catch {\n options.logger?.warn(\"span correlation unavailable; exporting unpaired spans\", {});\n return { correlations: [], available: false };\n }\n };\n\n const emit = async (events: Parameters<TelemetrySink[\"emit\"]>[0]): Promise<TelemetryEmitResult> => {\n if (events.length === 0) {\n return { accepted: 0, rejected: 0, errors: [] };\n }\n const resolved = await resolveCorrelations(events);\n // Session context overrides the same keys on the Resource for this batch, so\n // a backend reading the Resource sees what the records say.\n const batchResource = resourceWithContext(resource, agreedContextAttributes(events));\n const spans = canonicalEventsToReadableSpans(events, {\n resource: batchResource,\n instrumentationScope: scope,\n correlations: resolved.correlations,\n ...(resolved.available === undefined ? {} : { correlationAvailable: resolved.available }),\n });\n const errors: OtelHookErrorInfo[] = [];\n let accepted = 0;\n let rejected = 0;\n\n for (const batch of chunk(spans, options.exporter.maxBatchSize)) {\n if (batch.length === 0) {\n // A batch of only start edges maps to no span at all: a lone `*.start` is\n // held for its end rather than exported. Sending it anyway POSTed an\n // `ExportTraceServiceRequest` with no resource spans — an empty body at the\n // collector — and, against a down collector, spooled an empty batch that\n // the drain could only quarantine.\n continue;\n }\n let result: ExportResult;\n try {\n result = await exportSpans(batch);\n } catch (thrown) {\n result = { code: ExportResultCode.FAILED, error: thrown instanceof Error ? thrown : new Error(\"export threw\") };\n }\n if (result.code === ExportResultCode.SUCCESS) {\n accepted += batch.length;\n health.recordSuccess(batch.length, options.clock.now());\n continue;\n }\n\n health.recordFailure(\"telemetry-export-failure\", batch.length, options.clock.now());\n const permanent = isPermanentExportFailure(result);\n if (options.spool !== undefined && !permanent) {\n const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({\n spooled: false as const,\n reason: \"capacity-exceeded\" as const,\n }));\n if (spoolResult.spooled) {\n accepted += batch.length;\n options.logger?.warn(\"span batch not delivered; spooled for the next invocation\", {\n \"export.batch_size\": batch.length,\n ...destinationFields,\n });\n continue;\n }\n }\n rejected += batch.length;\n errors.push(\n createErrorInfo({\n code: \"telemetry-export-failure\",\n phase: \"export\",\n detail: permanent\n ? \"collector refused a span batch with a non-retryable status\"\n : \"collector rejected or was unreachable for a span batch\",\n details: { \"export.batch_size\": batch.length, ...destinationFields },\n }),\n );\n }\n\n return { accepted, rejected, errors };\n };\n\n const drainSpool = async (\n maxBatches?: number,\n ): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }> => {\n if (options.spool === undefined) {\n return { drained: 0, remaining: 0, failed: 0 };\n }\n const result = await options.spool.drain(sendSerializedBatch, { ...(maxBatches === undefined ? {} : { maxBatches }) });\n if (result.drained > 0) {\n health.recordSuccess(result.drained, options.clock.now());\n }\n return result;\n };\n\n const flush = async (): Promise<void> => {\n try {\n await exporter.forceFlush();\n } catch {\n // Best-effort: flush failures are reported through health, never thrown.\n }\n await drainSpool().catch(() => undefined);\n };\n\n const shutdown = async (): Promise<void> => {\n if (shutdownCompleted) {\n return;\n }\n shutdownCompleted = true;\n await flush();\n try {\n await exporter.shutdown();\n } catch {\n // Idempotent, non-throwing per the TelemetrySink contract.\n }\n };\n\n return {\n emit,\n flush,\n shutdown,\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool,\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 type { OtelHookErrorCode } from \"../errors/index.js\";\nimport type { EpochMillis } from \"../model/primitives.js\";\n\n/**\n * One tracked delivery path.\n *\n * The two telemetry signals are separate subsystems because they fail\n * independently — a collector with no logs receiver leaves traces perfectly\n * healthy — and a single combined verdict would make an operator bisect which one\n * is broken. `telemetry-sink` remains the traces signal, unrenamed, so an existing\n * `doctor --json` consumer keeps reading the same field.\n */\nexport type DeliverySubsystem =\n | \"state-store\"\n | \"telemetry-sink\"\n | \"telemetry-log-sink\"\n | \"telemetry-metric-sink\"\n | \"lifecycle\";\n\n/**\n * Sanitized delivery health.\n *\n * Every field is a count, a timestamp, a boolean, or a closed-vocabulary error\n * code — the same restriction the privacy service applies to everything else\n * that might reach a sink, so a health snapshot is itself safe to export or log\n * without a second review.\n */\nexport type DeliveryHealthSnapshot = {\n readonly subsystem: DeliverySubsystem;\n readonly healthy: boolean;\n readonly totalAccepted: number;\n readonly totalRejected: number;\n readonly consecutiveFailures: number;\n readonly lastSuccessAt?: EpochMillis;\n readonly lastFailureAt?: EpochMillis;\n readonly lastErrorCode?: OtelHookErrorCode;\n /**\n * Export destination this snapshot describes. Present only when\n * `exporter.destinations` is in use, so a single-destination snapshot is\n * unchanged.\n */\n readonly destination?: string;\n};\n\nexport type HealthTrackerOptions = {\n /** Consecutive failures at or beyond this count flip `healthy` to false. Default 3. */\n readonly unhealthyAfterConsecutiveFailures?: number;\n /** Labels every snapshot with an export destination name. */\n readonly destination?: string;\n};\n\n/**\n * Accumulates success/failure counts for one subsystem instance.\n *\n * Deliberately per-instance rather than a module-level registry: a store or\n * sink constructs its own tracker and exposes a `health()` accessor, so two\n * instances in one process never share counters (see ADR 0001 on module-level\n * identity).\n */\nexport interface HealthTracker {\n recordSuccess(count?: number, at?: number): void;\n recordFailure(code: OtelHookErrorCode, count?: number, at?: number): void;\n snapshot(): DeliveryHealthSnapshot;\n}\n\nexport const createHealthTracker = (\n subsystem: DeliverySubsystem,\n options: HealthTrackerOptions = {},\n): HealthTracker => {\n const unhealthyThreshold = options.unhealthyAfterConsecutiveFailures ?? 3;\n let totalAccepted = 0;\n let totalRejected = 0;\n let consecutiveFailures = 0;\n let lastSuccessAt: number | undefined;\n let lastFailureAt: number | undefined;\n let lastErrorCode: OtelHookErrorCode | undefined;\n\n return {\n recordSuccess: (count = 1, at?: number): void => {\n totalAccepted += count;\n consecutiveFailures = 0;\n if (at !== undefined) {\n lastSuccessAt = at;\n }\n },\n recordFailure: (code: OtelHookErrorCode, count = 1, at?: number): void => {\n totalRejected += count;\n consecutiveFailures += 1;\n lastErrorCode = code;\n if (at !== undefined) {\n lastFailureAt = at;\n }\n },\n snapshot: (): DeliveryHealthSnapshot => ({\n subsystem,\n healthy: consecutiveFailures < unhealthyThreshold,\n totalAccepted,\n totalRejected,\n consecutiveFailures,\n ...(lastSuccessAt === undefined ? {} : { lastSuccessAt }),\n ...(lastFailureAt === undefined ? {} : { lastFailureAt }),\n ...(lastErrorCode === undefined ? {} : { lastErrorCode }),\n ...(options.destination === undefined ? {} : { destination: options.destination }),\n }),\n };\n};\n\nexport type OverallHealth = {\n readonly healthy: boolean;\n readonly subsystems: readonly DeliveryHealthSnapshot[];\n};\n\n/** Combines snapshots from every configured subsystem into one overall verdict. */\nexport const summarizeHealth = (snapshots: readonly DeliveryHealthSnapshot[]): OverallHealth => ({\n healthy: snapshots.every((snapshot) => snapshot.healthy),\n subsystems: [...snapshots],\n});\n","import type { ExportResult } from \"@opentelemetry/core\";\n\n/**\n * HTTP statuses that mean \"try again later\" rather than \"never send this\".\n *\n * The OTLP specification's retryable set (429, 502, 503, 504), plus:\n *\n * - 408, which is a timeout by another name;\n * - 500, by decision for this project: a backend that is restarting, overloaded,\n * or briefly broken commonly answers 500, and losing those batches costs more\n * than retrying them. A backend that answers 500 *forever* cannot pin a batch\n * in the spool: every spooled batch is still subject to the spool's age,\n * size, and count bounds (`exporter.spool`), and is dropped and counted when\n * it exceeds them.\n *\n * Anything else the server answered with a status for is a refusal of *this\n * batch*: replaying it can only fail the same way, and a spool that kept it would\n * retry it on every invocation and stop behind it.\n */\nexport const RETRYABLE_HTTP_STATUSES: ReadonlySet<number> = new Set([408, 429, 500, 502, 503, 504]);\n\n/**\n * Whether a failed export was a permanent refusal.\n *\n * With `@opentelemetry/otlp-exporter-base` (OpenTelemetry JS 3.x), the HTTP\n * transport reports a status outside its own retryable set (429, 502, 503, 504)\n * as an `OTLPExporterError` whose numeric `code` is the HTTP status — so 400,\n * 401, 408, 413, and 500 all arrive with a `code`, and 408 and 500 are then held\n * retryable here. Its retryable statuses are retried inside the exporter and,\n * once retries or the timeout run out, arrive without a `code`, as do a refused\n * connection, a timeout, and an oversized response. Those are exactly the \"never\n * reached it, or asked us to come back\" failures a spool is for.\n */\nexport const isPermanentExportFailure = (result: ExportResult): boolean => {\n const code = (result.error as { readonly code?: unknown } | undefined)?.code;\n return (\n typeof code === \"number\" &&\n Number.isInteger(code) &&\n code >= 400 &&\n code < 600 &&\n !RETRYABLE_HTTP_STATUSES.has(code)\n );\n};\n","import { resourceFromAttributes, type Resource } from \"@opentelemetry/resources\";\nimport type { Attributes } from \"@opentelemetry/api\";\n\nimport {\n checkResourceAttributeKey,\n isReservedResourceAttributeKey,\n MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH,\n MAX_RESOURCE_ATTRIBUTES,\n sanitizeResourceAttributes,\n} from \"../config/resource-attributes.js\";\nimport type { ExporterPolicy } from \"../config/schema.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport { MAX_IDENTIFIER_LENGTH } from \"../model/primitives.js\";\n\n/**\n * The OTLP `Resource` every record of a signal is exported under.\n *\n * Shared by the trace and log sinks rather than written twice: a resource carries\n * the service identity, so two sinks disagreeing about how it is built or\n * re-validated would attribute the same installation's two signals to two\n * services — and the divergence would only be visible in a backend, long after.\n */\n\n/**\n * Resource for the live path, from exporter policy.\n *\n * Custom attributes first, then service identity: spread order makes the policy\n * fields structurally unoverridable. `sanitizeResourceAttributes` already drops\n * the reserved keys, so this is belt-and-braces for a caller who hand-built an\n * `ExporterPolicy` without running it through the schema — but between them,\n * `service.name` can only ever come from policy.\n */\nexport const resourceFromExporterPolicy = (policy: ExporterPolicy): Resource =>\n resourceFromAttributes({\n ...sanitizeResourceAttributes(policy.resourceAttributes),\n \"service.name\": policy.serviceName,\n ...(policy.serviceNamespace === undefined\n ? {}\n : { \"service.namespace\": policy.serviceNamespace }),\n });\n\n/**\n * A spool file is a plain JSON file in a state directory, so everything read back\n * out of one is untrusted input — it can be hand-edited, truncated, or written by\n * an older release with a different schema. These bounds mirror the live path's,\n * because \"what the exporter would have refused from a flag\" and \"what it accepts\n * from disk\" diverging is the whole vulnerability.\n */\nconst isReplayableValue = (value: unknown): value is string | number | boolean =>\n (typeof value === \"string\" && value.length <= MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) ||\n (typeof value === \"number\" && Number.isFinite(value)) ||\n typeof value === \"boolean\";\n\n/**\n * Validate a service identity read back from a spool file.\n *\n * `service.name` decides which service every replayed record is attributed to, so\n * a spool that could set it freely could attribute this installation's telemetry\n * to somebody else's service — the one resource field where a forged value is a\n * reporting-integrity problem rather than a cosmetic one. It is therefore held to\n * the same contract as the typed policy field: a non-empty string within\n * {@link MAX_IDENTIFIER_LENGTH}. Anything else is not \"replayed as recorded\", it is\n * discarded in favour of the draining process's own policy.\n */\nconst replayableServiceIdentity = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 && value.length <= MAX_IDENTIFIER_LENGTH\n ? value\n : undefined;\n\n/**\n * Rebuild the resource a spooled batch was recorded with.\n *\n * A recorded `service.name` is a fact about the process that made the observation,\n * not about the one draining the spool, so a *valid* one is replayed as recorded.\n * But every field is re-validated on the way out, at the same bounds the live path\n * enforces: custom keys must pass {@link checkResourceAttributeKey} (which refuses\n * reserved and secret-looking names), values must be primitives within the length\n * bound, the custom count is capped, and the two reserved service fields must look\n * like the identifiers they are. A batch that fails the service check falls back to\n * the live policy rather than exporting with no service identity, because a resource\n * without `service.name` is rejected or bucketed as \"unknown_service\" by most\n * collectors — losing the batch to a tampered byte would make the validation itself\n * the outage.\n */\nexport const replayResource = (attributes: Attributes, policy: ExporterPolicy): Resource => {\n const safe: Record<string, string | number | boolean> = {};\n let customCount = 0;\n for (const [key, value] of Object.entries(attributes)) {\n if (isReservedResourceAttributeKey(key)) {\n // Handled below against the policy fallback, never copied verbatim.\n continue;\n }\n if (!isReplayableValue(value)) {\n continue;\n }\n if (checkResourceAttributeKey(key) !== undefined || customCount >= MAX_RESOURCE_ATTRIBUTES) {\n continue;\n }\n customCount += 1;\n safe[key] = value;\n }\n\n // Reserved keys last and unconditionally, so a spooled custom attribute can\n // never occupy the slot a service field is about to be written into.\n const recordedName = replayableServiceIdentity(attributes[\"service.name\"]);\n const recordedNamespace = replayableServiceIdentity(attributes[\"service.namespace\"]);\n safe[\"service.name\"] = recordedName ?? policy.serviceName;\n const namespace = recordedNamespace ?? policy.serviceNamespace;\n if (namespace !== undefined) {\n safe[\"service.namespace\"] = namespace;\n }\n\n return resourceFromAttributes(safe);\n};\n\n/**\n * The session context attributes every event of a batch agrees on.\n *\n * The core stamps one invocation's events from one context file, so a batch\n * normally agrees on everything. Should two events disagree on a key (a segment\n * boundary inside one callback), or one event lack it, the key is left out: the\n * Resource is shared by the whole batch and must not state a value one of its\n * records contradicts. Each record still carries its own value.\n */\nexport const agreedContextAttributes = (\n events: readonly CanonicalEvent[],\n): Readonly<Record<string, string | number | boolean>> => {\n const [first, ...rest] = events;\n if (first?.contextAttributes === undefined) {\n return {};\n }\n const agreed: Record<string, string | number | boolean> = { ...first.contextAttributes };\n for (const event of rest) {\n for (const key of Object.keys(agreed)) {\n if (event.contextAttributes?.[key] !== agreed[key]) {\n delete agreed[key];\n }\n }\n }\n return agreed;\n};\n\n/**\n * The Resource a batch is exported under, with session context applied.\n *\n * Context overrides only keys the Resource already carries — a stale\n * `factory.attempt.id` from the process environment, say — so the Resource and\n * the records say the same thing to a backend that reads either. It adds no new\n * key: the Resource describes the producer, and the context's own keys are on\n * every record already. Service identity is never touched (context cannot carry\n * it). Returns the input unchanged when nothing applies.\n */\nexport const resourceWithContext = (\n resource: Resource,\n context: Readonly<Record<string, string | number | boolean>>,\n): Resource => {\n const overrides: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(context)) {\n if (\n Object.hasOwn(resource.attributes, key) &&\n !isReservedResourceAttributeKey(key) &&\n resource.attributes[key] !== value\n ) {\n overrides[key] = value;\n }\n }\n if (Object.keys(overrides).length === 0) {\n return resource;\n }\n return resourceFromAttributes({ ...resource.attributes, ...overrides });\n};\n","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\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 { SeverityNumber, TraceFlags, type Attributes, type SpanContext } from \"@opentelemetry/api\";\nimport { millisToHrTime, type InstrumentationScope } from \"@opentelemetry/core\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport type { ReadableLogRecord } from \"@opentelemetry/sdk-logs\";\nimport {\n ATTR_ERROR_TYPE,\n ATTR_GEN_AI_OPERATION_NAME,\n ATTR_GEN_AI_REQUEST_MODEL,\n ATTR_GEN_AI_RESPONSE_MODEL,\n ATTR_GEN_AI_SYSTEM,\n ATTR_GEN_AI_TOOL_CALL_ID,\n ATTR_GEN_AI_TOOL_NAME,\n ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n} from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport type { ContentFact } from \"../model/content.js\";\nimport type { CanonicalEvent, CanonicalEventType } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\nimport {\n exportIdentityAttributes,\n targetAttributes,\n usageTemporalityAttributes,\n} from \"./export-identity.js\";\nimport {\n ATTR_OTELHOOK_USAGE_PARTIAL,\n canonicalEventTraceIdentities,\n DEFAULT_INSTRUMENTATION_SCOPE,\n type SpanCorrelation,\n} from \"./semconv.js\";\n\n/**\n * Pure, stateless canonical-event-to-OTLP-log-record mapping.\n *\n * The counterpart of `semconv.ts` for the logs signal, and deliberately the same\n * shape: no state is read here, no clock is consulted, and the only inputs are\n * the batch plus the correlations the caller already resolved. Batching, retry,\n * spooling, and delivery live in `otlp-log-sink.ts`.\n *\n * ## Why logs at all, when traces already exist\n *\n * A span reports that a tool call happened, how long it took, and whether it\n * failed. It does not report *what was in it*, and it cannot: span attributes are\n * a flat bounded map, one record per span, exported once. A conversation turn is a\n * sequence of distinct pieces of content — a prompt, a response, reasoning, a tool\n * input, a tool output — each with its own role, its own length, and its own\n * disclosure decision. That is a log stream, and OTLP has one.\n *\n * So this mapping emits **one record per content fact**, plus one record per event\n * that carries no content, and correlates every record to the span the same batch\n * produced (or will produce). Nothing here decides *whether* content is\n * disclosed — the privacy service already did that, upstream, once — but the\n * gate is re-checked here because this is the last boundary before the wire.\n *\n * ## Identity and correlation\n *\n * Every record carries the same identity attributes a span does, and a\n * `spanContext` built from {@link canonicalEventTraceIdentities}: the trace id and\n * span id are derived from the event's own `(providerId, sessionId)` and its\n * lifecycle scope, so a record lands in the same trace as its span without either\n * signal knowing about the other. Two sessions in one batch derive two trace ids;\n * there is no batch-level or module-level trace state to contaminate.\n */\n\n/**\n * Version of this mapping.\n *\n * Consumers pin it. Bumped on any change to what an existing attribute or signal\n * *means*; adding a new attribute or a new signal value does not bump it, on the\n * same additive-compatibility rule the canonical model follows\n * (`CANONICAL_SCHEMA_VERSION`). Every record carries it as\n * `otelhook.log.mapping_version`, so a consumer never has to infer which\n * vocabulary it is reading.\n */\nexport const LOG_MAPPING_VERSION = 1 as const;\n\n/**\n * Coarse routing key for one log record.\n *\n * The fact's own `otelhook.content.kind` states precisely what the content is;\n * this states which *pipeline* it belongs to, so an operator can route or drop a\n * whole class (\"no tool output off this host\") with one collector rule rather\n * than an enumeration of event types.\n */\nexport const LOG_SIGNALS = [\n \"session\",\n \"prompt\",\n \"response\",\n \"reasoning\",\n \"tool\",\n \"shell\",\n \"file-operation\",\n \"mcp\",\n \"delegation\",\n \"compaction\",\n \"error\",\n] as const;\nexport type LogSignal = (typeof LOG_SIGNALS)[number];\n\n/**\n * Naming convention that marks a tool call as MCP-mediated.\n *\n * The canonical model has no \"this went through MCP\" field, because no provider\n * contract this package has verified carries one: what they carry is a *tool\n * name*, and three of the four non-synthetic contracts (Claude Code, Codex,\n * Gemini CLI) name MCP tools `mcp__<server>__<tool>`. So the convention is the\n * evidence, matched on the canonical tool name rather than on any provider's\n * payload.\n *\n * This deliberately **under-reports**: a provider whose MCP tool names do not\n * follow the convention classifies as `tool`, which is true but less specific.\n * The alternative — per-provider branching in the canonical layer, or a canonical\n * field no adapter can populate from a verified contract — would either leak\n * provider knowledge across the boundary or invent a contract. See\n * `docs/canonical-log-mapping.md`.\n */\nexport const MCP_TOOL_NAME_PATTERN = /^mcp__/i;\n\n/**\n * Most records one event may produce.\n *\n * Matches `contentFactsSchema`'s own cap, so in practice the mapping never drops\n * a fact an adapter produced; it is the backstop for a hand-built event, not a\n * routine truncation.\n */\nexport const MAX_LOG_RECORDS_PER_EVENT = 64;\n\n/** Most records one batch may produce, whatever the batch contains. */\nexport const MAX_LOG_RECORDS_PER_BATCH = 2_048;\n\n/**\n * Longest disclosed body this mapping will put on the wire.\n *\n * Separate from, and stricter than, the privacy policy's `maxStringLength` (which\n * may be configured up to 64Ki characters): a policy bound is about *disclosure*,\n * this is about the size of one OTLP record. A body cut here is reported as\n * `otelhook.content.body_truncated` rather than as the fact's own `truncated`\n * flag, so \"the privacy policy shortened this\" and \"the log record shortened\n * this\" stay distinguishable.\n */\nexport const MAX_LOG_BODY_CHARACTERS = 8_192;\n\nconst ATTR_OTELHOOK_EVENT_TYPE = \"otelhook.event.type\";\nconst ATTR_OTELHOOK_EVENT_ID = \"otelhook.event.id\";\nconst ATTR_OTELHOOK_EVENT_SEQUENCE = \"otelhook.event.sequence\";\nconst ATTR_OTELHOOK_LOG_SIGNAL = \"otelhook.log.signal\";\nconst ATTR_OTELHOOK_LOG_MAPPING_VERSION = \"otelhook.log.mapping_version\";\nconst ATTR_OTELHOOK_OUTCOME = \"otelhook.outcome\";\nconst ATTR_OTELHOOK_TOOL_KIND = \"otelhook.tool.kind\";\nconst ATTR_OTELHOOK_TOOL_PERMISSION = \"otelhook.tool.permission_decision\";\nconst ATTR_OTELHOOK_DELEGATION_DEPTH = \"otelhook.delegation_depth\";\nconst ATTR_OTELHOOK_SUBAGENT_TYPE = \"otelhook.subagent.type\";\nconst ATTR_OTELHOOK_AGENT_NAME = \"otelhook.agent.name\";\nconst ATTR_OTELHOOK_AGENT_VERSION = \"otelhook.agent.version\";\nconst ATTR_OTELHOOK_SESSION_KIND = \"otelhook.session.kind\";\nconst ATTR_OTELHOOK_PROMPT_SOURCE = \"otelhook.prompt.source\";\nconst ATTR_OTELHOOK_PROMPT_TURN_INDEX = \"otelhook.prompt.turn_index\";\nconst ATTR_OTELHOOK_GENERATION_ID = \"otelhook.generation.id\";\nconst ATTR_OTELHOOK_STOP_REASON = \"otelhook.generation.stop_reason\";\nconst ATTR_OTELHOOK_COMPACTION_TRIGGER = \"otelhook.compaction.trigger\";\nconst ATTR_OTELHOOK_CONTEXT_TOKENS_BEFORE = \"otelhook.compaction.context_tokens_before\";\nconst ATTR_OTELHOOK_CONTEXT_TOKENS_AFTER = \"otelhook.compaction.context_tokens_after\";\nconst ATTR_OTELHOOK_DROPPED_MESSAGES = \"otelhook.compaction.dropped_message_count\";\nconst ATTR_OTELHOOK_ERROR_PHASE = \"otelhook.error.phase\";\nconst ATTR_OTELHOOK_ERROR_RETRYABLE = \"otelhook.error.retryable\";\nconst ATTR_OTELHOOK_ERROR_SEVERITY = \"otelhook.error.severity\";\n\nconst ATTR_CONTENT_KIND = \"otelhook.content.kind\";\nconst ATTR_CONTENT_ROLE = \"otelhook.content.role\";\nconst ATTR_CONTENT_DISCLOSURE = \"otelhook.content.disclosure\";\nconst ATTR_CONTENT_CHARACTER_LENGTH = \"otelhook.content.character_length\";\nconst ATTR_CONTENT_BYTE_LENGTH = \"otelhook.content.byte_length\";\nconst ATTR_CONTENT_HASH = \"otelhook.content.hash\";\nconst ATTR_CONTENT_TRUNCATED = \"otelhook.content.truncated\";\nconst ATTR_CONTENT_SECRETS_REDACTED = \"otelhook.content.secrets_redacted\";\nconst ATTR_CONTENT_LABEL = \"otelhook.content.label\";\nconst ATTR_CONTENT_WITHHELD = \"otelhook.content.withheld\";\nconst ATTR_CONTENT_BODY_TRUNCATED = \"otelhook.content.body_truncated\";\n\n/**\n * Why a content fact reached the wire without its text.\n *\n * Stated rather than left as an absence, because \"this prompt was empty\", \"this\n * deployment omits content\", and \"this deployment discloses content but not to\n * the logs pipeline\" are three different operational facts that all look like a\n * missing body.\n */\nexport type ContentWithholdingReason =\n /** The privacy policy produced no text at all — the default `omit` posture. */\n | \"privacy-policy\"\n /** Content is disclosed elsewhere, but the logs pipeline is not permitted it. */\n | \"logs-content-disabled\"\n /** The fact carries verbatim text and `allowRawContent` is not set. */\n | \"raw-not-permitted\";\n\n/**\n * Whether disclosed content text may reach a log body.\n *\n * Two gates rather than one, and both must open. `includeContent` is the logs\n * pipeline's own switch, and it exists because spans carry no content in *any*\n * content mode: without it, turning on `privacy.contentMode` to get a hash and a\n * length — which is all it ever bought before — would start putting prompts on\n * the wire. `allowRawContent` is the pre-existing verbatim-content opt-in,\n * re-checked here because the sink is the last boundary before the wire and a\n * hand-built fact could otherwise carry `disclosure: \"raw\"` past a policy that\n * never permitted it.\n */\nexport type LogContentPolicy = {\n readonly includeContent: boolean;\n readonly allowRawContent: boolean;\n};\n\n/** Content disabled, which is what an unconfigured installation gets. */\nexport const NO_LOG_CONTENT: LogContentPolicy = Object.freeze({\n includeContent: false,\n allowRawContent: false,\n});\n\nconst codePointLength = (value: string): number => [...value].length;\n\nconst sliceCodePoints = (value: string, max: number): string => {\n let result = \"\";\n let count = 0;\n for (const char of value) {\n if (count >= max) {\n break;\n }\n result += char;\n count += 1;\n }\n return result;\n};\n\n/**\n * Which pipeline an event's records belong to.\n *\n * `factKind` refines the answer where one event type carries more than one kind\n * of content: a `generation.end` holds the response *and*, on providers that\n * report it, the reasoning that produced it, and collapsing those into one signal\n * would make \"drop reasoning, keep responses\" unexpressible.\n */\nexport const logSignalOf = (event: CanonicalEvent, factKind?: ContentFact[\"kind\"]): LogSignal => {\n switch (event.type) {\n case \"session.start\":\n case \"session.end\":\n return \"session\";\n case \"prompt.submitted\":\n return \"prompt\";\n case \"generation.start\":\n return factKind === \"reasoning\" ? \"reasoning\" : \"prompt\";\n case \"generation.end\":\n return factKind === \"reasoning\" ? \"reasoning\" : \"response\";\n case \"subagent.start\":\n case \"subagent.end\":\n return \"delegation\";\n case \"compaction.performed\":\n return \"compaction\";\n case \"error.raised\":\n return \"error\";\n case \"tool.start\":\n return toolSignal(event.toolName, event.toolKind);\n case \"tool.end\":\n // A `tool.end` carries no `toolKind`: only the start edge does. Classifying\n // from the name alone is what the canonical model permits here, so a shell\n // or file operation whose name does not say so lands on `tool` — and the\n // span for the same scope, which *did* recover the kind from state, is where\n // that detail is authoritative.\n return toolSignal(event.toolName, undefined);\n }\n};\n\nconst toolSignal = (\n toolName: string,\n toolKind: Extract<CanonicalEvent, { type: \"tool.start\" }>[\"toolKind\"] | undefined,\n): LogSignal => {\n if (MCP_TOOL_NAME_PATTERN.test(toolName)) {\n return \"mcp\";\n }\n switch (toolKind) {\n case \"execute\":\n return \"shell\";\n case \"read\":\n case \"write\":\n return \"file-operation\";\n case \"delegate\":\n return \"delegation\";\n default:\n return \"tool\";\n }\n};\n\n/**\n * Log signals an adapter declaring these lifecycle events can produce.\n *\n * Derived from the adapter's existing `lifecycleEvents` declaration rather than\n * declared separately, which is the whole point: a hand-maintained second list\n * can disagree with the first, and a capability declaration that has gone stale is\n * worse than none — a consumer cannot tell \"this provider reports no tool output\"\n * from \"this declaration was never updated\".\n *\n * The tool refinements (`shell`, `file-operation`, `mcp`) are reported whenever\n * the adapter emits tool events at all, because which of them a given callback\n * produces depends on the payload, not on the adapter. So this is a statement\n * about what *may* appear, not what always will.\n */\nexport const logSignalsForLifecycleEvents = (\n lifecycleEvents: readonly CanonicalEventType[],\n): readonly LogSignal[] => {\n const signals = new Set<LogSignal>();\n const add = (...values: readonly LogSignal[]): void => {\n for (const value of values) {\n signals.add(value);\n }\n };\n for (const type of lifecycleEvents) {\n switch (type) {\n case \"session.start\":\n case \"session.end\":\n add(\"session\");\n break;\n case \"prompt.submitted\":\n add(\"prompt\");\n break;\n case \"generation.start\":\n add(\"prompt\");\n break;\n case \"generation.end\":\n add(\"response\", \"reasoning\");\n break;\n case \"tool.start\":\n case \"tool.end\":\n add(\"tool\", \"shell\", \"file-operation\", \"mcp\", \"delegation\");\n break;\n case \"subagent.start\":\n case \"subagent.end\":\n add(\"delegation\");\n break;\n case \"compaction.performed\":\n add(\"compaction\");\n break;\n case \"error.raised\":\n add(\"error\");\n break;\n }\n }\n return LOG_SIGNALS.filter((signal) => signals.has(signal));\n};\n\nconst severityFor = (event: CanonicalEvent): SeverityNumber => {\n switch (event.type) {\n case \"error.raised\":\n return event.severity === \"error\" ? SeverityNumber.ERROR : SeverityNumber.WARN;\n case \"session.end\":\n return event.reason === \"error\" || event.reason === \"timeout\"\n ? SeverityNumber.ERROR\n : event.reason === \"aborted\"\n ? SeverityNumber.WARN\n : SeverityNumber.INFO;\n case \"generation.end\":\n case \"tool.end\":\n case \"subagent.end\":\n return event.outcome === \"error\" || event.outcome === \"timeout\"\n ? SeverityNumber.ERROR\n : event.outcome === \"denied\" || event.outcome === \"cancelled\"\n ? SeverityNumber.WARN\n : SeverityNumber.INFO;\n default:\n return SeverityNumber.INFO;\n }\n};\n\nconst SEVERITY_TEXT: Readonly<Record<number, string>> = Object.freeze({\n [SeverityNumber.INFO]: \"INFO\",\n [SeverityNumber.WARN]: \"WARN\",\n [SeverityNumber.ERROR]: \"ERROR\",\n});\n\nconst identityAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n ids: { readonly traceId: string; readonly spanId: string; readonly parentSpanId?: string },\n): Attributes => exportIdentityAttributes(event, resource, ids);\n\n/**\n * Attributes describing the event itself, independent of any content it carries.\n *\n * Every attribute here is a closed vocabulary, an identifier this library\n * derived, a count, or a boolean — the same restriction the privacy service\n * applies everywhere else, so an attribute can never become a second disclosure\n * path alongside the body.\n */\nconst eventAttributes = (event: CanonicalEvent): Attributes => {\n switch (event.type) {\n case \"session.start\":\n return {\n [ATTR_OTELHOOK_SESSION_KIND]: event.sessionKind,\n ...(event.agentName === undefined ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: event.agentName }),\n ...(event.agentVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_AGENT_VERSION]: event.agentVersion }),\n ...(event.model === undefined\n ? {}\n : { [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId }),\n ...targetAttributes(event),\n };\n case \"session.end\":\n return {\n [ATTR_OTELHOOK_OUTCOME]: event.reason,\n ...usageAttributes(event.usage),\n };\n case \"prompt.submitted\":\n return {\n [ATTR_OTELHOOK_PROMPT_SOURCE]: event.promptSource,\n ...(event.turnIndex === undefined\n ? {}\n : { [ATTR_OTELHOOK_PROMPT_TURN_INDEX]: event.turnIndex }),\n ...targetAttributes(event),\n };\n case \"generation.start\":\n return {\n [ATTR_GEN_AI_OPERATION_NAME]: \"chat\",\n [ATTR_OTELHOOK_GENERATION_ID]: event.generationId,\n [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId,\n ...(event.model.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: event.model.vendor }),\n };\n case \"generation.end\":\n return {\n [ATTR_GEN_AI_OPERATION_NAME]: \"chat\",\n [ATTR_OTELHOOK_GENERATION_ID]: event.generationId,\n [ATTR_GEN_AI_RESPONSE_MODEL]: event.model.modelId,\n ...(event.model.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: event.model.vendor }),\n [ATTR_OTELHOOK_OUTCOME]: event.outcome,\n ...(event.stopReason === undefined ? {} : { [ATTR_OTELHOOK_STOP_REASON]: event.stopReason }),\n ...usageAttributes(event.usage),\n ...(event.usage === undefined || event.usagePartial === undefined\n ? {}\n : { [ATTR_OTELHOOK_USAGE_PARTIAL]: event.usagePartial }),\n };\n case \"tool.start\":\n return {\n [ATTR_GEN_AI_TOOL_NAME]: event.toolName,\n [ATTR_GEN_AI_TOOL_CALL_ID]: event.toolCallId,\n [ATTR_OTELHOOK_TOOL_KIND]: event.toolKind,\n ...(event.generationId === undefined\n ? {}\n : { [ATTR_OTELHOOK_GENERATION_ID]: event.generationId }),\n ...targetAttributes(event),\n };\n case \"tool.end\":\n return {\n [ATTR_GEN_AI_TOOL_NAME]: event.toolName,\n [ATTR_GEN_AI_TOOL_CALL_ID]: event.toolCallId,\n [ATTR_OTELHOOK_OUTCOME]: event.outcome,\n ...(event.permissionDecision === undefined\n ? {}\n : { [ATTR_OTELHOOK_TOOL_PERMISSION]: event.permissionDecision }),\n ...targetAttributes(event),\n };\n case \"subagent.start\":\n return {\n [ATTR_OTELHOOK_DELEGATION_DEPTH]: event.delegationDepth,\n ...(event.subagentType === undefined\n ? {}\n : { [ATTR_OTELHOOK_SUBAGENT_TYPE]: event.subagentType }),\n ...(event.model === undefined ? {} : { [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId }),\n };\n case \"subagent.end\":\n return {\n [ATTR_OTELHOOK_OUTCOME]: event.outcome,\n ...usageAttributes(event.usage),\n };\n case \"compaction.performed\":\n return {\n [ATTR_OTELHOOK_COMPACTION_TRIGGER]: event.trigger,\n ...(event.contextTokensBefore === undefined\n ? {}\n : { [ATTR_OTELHOOK_CONTEXT_TOKENS_BEFORE]: event.contextTokensBefore }),\n ...(event.contextTokensAfter === undefined\n ? {}\n : { [ATTR_OTELHOOK_CONTEXT_TOKENS_AFTER]: event.contextTokensAfter }),\n ...(event.droppedMessageCount === undefined\n ? {}\n : { [ATTR_OTELHOOK_DROPPED_MESSAGES]: event.droppedMessageCount }),\n ...usageAttributes(event.usage),\n };\n case \"error.raised\":\n return {\n [ATTR_ERROR_TYPE]: event.errorCode,\n [ATTR_OTELHOOK_ERROR_PHASE]: event.phase,\n [ATTR_OTELHOOK_ERROR_RETRYABLE]: event.retryable,\n [ATTR_OTELHOOK_ERROR_SEVERITY]: event.severity,\n };\n }\n};\n\nconst usageAttributes = (usage: CanonicalUsage | undefined): Attributes =>\n usage === undefined\n ? {}\n : {\n [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: usage.inputTokens,\n [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: usage.outputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: usage.cachedInputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: usage.cacheCreationInputTokens,\n ...usageTemporalityAttributes(usage),\n };\n\n/** Content facts an event carries, paired with the field they came from. */\nconst contentFactsOf = (event: CanonicalEvent): readonly ContentFact[] => {\n switch (event.type) {\n case \"prompt.submitted\":\n return event.content === undefined ? [] : [event.content];\n case \"generation.start\":\n return event.inputContent ?? [];\n case \"generation.end\":\n return event.outputContent ?? [];\n case \"tool.start\":\n return event.input === undefined ? [] : [event.input];\n case \"tool.end\":\n return event.output === undefined ? [] : [event.output];\n case \"error.raised\":\n return event.message === undefined ? [] : [event.message];\n default:\n return [];\n }\n};\n\ntype DisclosedBody =\n | { readonly text: string; readonly truncated: boolean }\n | { readonly withheld: ContentWithholdingReason }\n | { readonly metadataOnly: true };\n\nconst discloseBody = (fact: ContentFact, policy: LogContentPolicy): DisclosedBody => {\n if (fact.text === undefined && fact.characterLength === 0) {\n // The provider sent no text. Distinct from a privacy omit of real content:\n // there is nothing to withhold, and the record must say metadata_only.\n return { metadataOnly: true };\n }\n if (fact.text === undefined) {\n return { withheld: \"privacy-policy\" };\n }\n if (!policy.includeContent) {\n return { withheld: \"logs-content-disabled\" };\n }\n if (fact.disclosure === \"raw\" && !policy.allowRawContent) {\n // Belt to the privacy service's braces: `resolvePrivacyPolicy` already\n // downgrades `raw` without the opt-in, so reaching here means a fact was built\n // outside that path. Refusing rather than trusting it keeps the opt-in a\n // property of the wire, not of one code path.\n return { withheld: \"raw-not-permitted\" };\n }\n const length = codePointLength(fact.text);\n return length <= MAX_LOG_BODY_CHARACTERS\n ? { text: fact.text, truncated: false }\n : { text: sliceCodePoints(fact.text, MAX_LOG_BODY_CHARACTERS), truncated: true };\n};\n\nconst contentAttributes = (fact: ContentFact, body: DisclosedBody): Attributes => ({\n [ATTR_CONTENT_KIND]: fact.kind,\n ...(fact.role === undefined ? {} : { [ATTR_CONTENT_ROLE]: fact.role }),\n [ATTR_CONTENT_DISCLOSURE]: \"metadataOnly\" in body ? \"metadata_only\" : fact.disclosure,\n [ATTR_CONTENT_CHARACTER_LENGTH]: fact.characterLength,\n [ATTR_CONTENT_BYTE_LENGTH]: fact.byteLength,\n [ATTR_CONTENT_HASH]: fact.contentHash,\n [ATTR_CONTENT_TRUNCATED]: fact.truncated,\n [ATTR_CONTENT_SECRETS_REDACTED]: fact.secretsRedacted,\n ...(fact.label === undefined ? {} : { [ATTR_CONTENT_LABEL]: fact.label }),\n ...(\"withheld\" in body\n ? { [ATTR_CONTENT_WITHHELD]: body.withheld }\n : \"metadataOnly\" in body\n ? {}\n : { [ATTR_CONTENT_BODY_TRUNCATED]: body.truncated }),\n});\n\nexport type LogMappingOptions = {\n readonly resource: Resource;\n readonly instrumentationScope?: InstrumentationScope;\n /** Whether disclosed text may reach a body. Defaults to {@link NO_LOG_CONTENT}. */\n readonly content?: LogContentPolicy;\n /**\n * The same cross-process pairing facts the span mapping is given, so a record's\n * `spanContext` names the span id that batch actually exported.\n */\n readonly correlations?: readonly SpanCorrelation[];\n /** See `SemanticMappingOptions.correlationAvailable`. */\n readonly correlationAvailable?: boolean;\n};\n\nexport type LogMappingResult = {\n readonly records: readonly ReadableLogRecord[];\n /**\n * Content facts no record was produced for, because a bound was reached.\n *\n * Reported rather than truncated silently: a caller that logged \"N records\n * exported\" and nothing else would read a clipped batch as a complete one.\n */\n readonly droppedFacts: number;\n};\n\nconst buildRecord = (input: {\n readonly event: CanonicalEvent;\n readonly signal: LogSignal;\n readonly attributes: Attributes;\n readonly body?: string;\n readonly spanContext: SpanContext;\n readonly parentSpanId?: string;\n readonly resource: Resource;\n readonly scope: InstrumentationScope;\n}): ReadableLogRecord => {\n const severityNumber = severityFor(input.event);\n const hrTime = millisToHrTime(input.event.occurredAt);\n return {\n hrTime,\n // A hook observes an event that already happened, and this mapping is pure —\n // there is no clock here to read a real observation time from. Reporting the\n // occurrence time for both is the honest answer: it says \"this is when it\n // happened\" twice rather than inventing a second, wrong timestamp.\n hrTimeObserved: hrTime,\n spanContext: input.spanContext,\n severityNumber,\n severityText: SEVERITY_TEXT[severityNumber] ?? \"INFO\",\n ...(input.body === undefined ? {} : { body: input.body }),\n eventName: `otelhook.${input.event.type}`,\n resource: input.resource,\n instrumentationScope: input.scope,\n attributes: {\n ...identityAttributes(input.event, input.resource, {\n traceId: input.spanContext.traceId,\n spanId: input.spanContext.spanId,\n ...(input.parentSpanId === undefined ? {} : { parentSpanId: input.parentSpanId }),\n }),\n [ATTR_OTELHOOK_EVENT_TYPE]: input.event.type,\n [ATTR_OTELHOOK_EVENT_ID]: input.event.eventId,\n [ATTR_OTELHOOK_EVENT_SEQUENCE]: input.event.sequence,\n [ATTR_OTELHOOK_LOG_SIGNAL]: input.signal,\n [ATTR_OTELHOOK_LOG_MAPPING_VERSION]: LOG_MAPPING_VERSION,\n ...input.attributes,\n },\n droppedAttributesCount: 0,\n };\n};\n\n/**\n * Map one invocation's canonical event batch into OTLP-ready log records.\n *\n * One record per content fact, and one record per event that carries none, so an\n * event is never silently absent from the stream just because the provider\n * reported no text for it.\n */\nexport const canonicalEventsToLogRecords = (\n events: readonly CanonicalEvent[],\n options: LogMappingOptions,\n): LogMappingResult => {\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const content = options.content ?? NO_LOG_CONTENT;\n const identities = canonicalEventTraceIdentities(events, {\n ...(options.correlations === undefined ? {} : { correlations: options.correlations }),\n ...(options.correlationAvailable === undefined\n ? {}\n : { correlationAvailable: options.correlationAvailable }),\n });\n\n const records: ReadableLogRecord[] = [];\n let droppedFacts = 0;\n\n for (const event of events) {\n const identity = identities.get(event.eventId);\n if (identity === undefined) {\n // Unreachable: every event in the batch is given an identity above.\n continue;\n }\n const spanContext: SpanContext = {\n traceId: identity.traceId,\n spanId: identity.spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n };\n const shared = eventAttributes(event);\n const facts = contentFactsOf(event);\n\n if (facts.length === 0) {\n if (records.length >= MAX_LOG_RECORDS_PER_BATCH) {\n droppedFacts += 1;\n continue;\n }\n records.push(\n buildRecord({\n event,\n signal: logSignalOf(event),\n attributes:\n event.type === \"generation.end\"\n ? { ...shared, [ATTR_CONTENT_KIND]: \"response\", [ATTR_CONTENT_DISCLOSURE]: \"metadata_only\" }\n : shared,\n spanContext,\n ...(identity.parentSpanId === undefined ? {} : { parentSpanId: identity.parentSpanId }),\n resource: options.resource,\n scope,\n }),\n );\n continue;\n }\n\n let perEvent = 0;\n for (const fact of facts) {\n if (perEvent >= MAX_LOG_RECORDS_PER_EVENT || records.length >= MAX_LOG_RECORDS_PER_BATCH) {\n droppedFacts += 1;\n continue;\n }\n perEvent += 1;\n const body = discloseBody(fact, content);\n records.push(\n buildRecord({\n event,\n signal: logSignalOf(event, fact.kind),\n attributes: { ...shared, ...contentAttributes(fact, body) },\n ...(\"text\" in body ? { body: body.text } : {}),\n spanContext,\n ...(identity.parentSpanId === undefined ? {} : { parentSpanId: identity.parentSpanId }),\n resource: options.resource,\n scope,\n }),\n );\n }\n }\n\n return { records, droppedFacts };\n};\n","import type { Attributes } from \"@opentelemetry/api\";\n\nimport type { Clock, Logger } from \"../runtime/ports.js\";\nimport type { StoreNamespace } from \"../state/keys.js\";\nimport {\n createSpoolQueue,\n type SpoolDrainResult,\n type SpoolEnqueueResult,\n type SpoolValidation,\n type SpoolOverflowPolicy,\n type SpoolSendOutcome,\n type SpoolStats,\n} from \"./spool-queue.js\";\n\n/**\n * One log record, flattened to plain JSON so it survives a process exit.\n *\n * `body` is a string or absent, never a nested value: the mapping only ever\n * produces a disclosed text body, and admitting anything richer here would make a\n * spool file a route for a structure the live path would have refused.\n */\nexport type SerializedLogRecord = {\n readonly eventName: string;\n readonly severityNumber: number;\n readonly severityText?: string;\n readonly body?: string;\n readonly timeMillis: number;\n readonly observedTimeMillis: number;\n /** Absent only on a record that was mapped without trace correlation. */\n readonly traceId?: string;\n readonly spanId?: string;\n readonly attributes: Attributes;\n};\n\nexport type LogSpoolBatch = {\n readonly providerId: string;\n readonly installationId: string;\n readonly resourceAttributes: Attributes;\n readonly instrumentationScope: { readonly name: string; readonly version?: string };\n readonly records: readonly SerializedLogRecord[];\n readonly enqueuedAt: number;\n};\n\n/** Upper bounds on a replayed batch. A spool file is untrusted input. */\nexport const MAX_SPOOLED_LOG_RECORDS_PER_BATCH = 4_096;\nexport const MAX_SPOOLED_LOG_STRING_LENGTH = 8_192;\n/**\n * Longest replayed body.\n *\n * Matches the live mapping's `MAX_LOG_BODY_CHARACTERS`, because \"what the mapping\n * would have put on the wire\" and \"what is accepted back off disk\" diverging is\n * the whole vulnerability — a hand-edited spool file must not be able to export a\n * body the live path would have cut.\n */\nexport const MAX_SPOOLED_LOG_BODY_LENGTH = 8_192;\nconst MAX_SPOOLED_ATTRIBUTES_PER_RECORD = 256;\nconst TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;\nconst SPAN_ID_PATTERN = /^[0-9a-f]{16}$/;\n\nconst isFiniteNonNegative = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n\nconst isBoundedString = (value: unknown, maxLength = MAX_SPOOLED_LOG_STRING_LENGTH): value is string =>\n typeof value === \"string\" && value.length > 0 && value.length <= maxLength;\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isReplayableAttributeValue = (value: unknown): boolean => {\n if (Array.isArray(value)) {\n // OTLP permits homogeneous primitive arrays; anything nested is not an\n // attribute and would fail encoding.\n return value.every(\n (item) =>\n (typeof item === \"string\" && item.length <= MAX_SPOOLED_LOG_STRING_LENGTH) ||\n (typeof item === \"number\" && Number.isFinite(item)) ||\n typeof item === \"boolean\" ||\n item === null,\n );\n }\n return (\n (typeof value === \"string\" && value.length <= MAX_SPOOLED_LOG_STRING_LENGTH) ||\n (typeof value === \"number\" && Number.isFinite(value)) ||\n typeof value === \"boolean\" ||\n value === undefined\n );\n};\n\n/**\n * Whether one recorded log record can be replayed.\n *\n * Every field is checked, not just the ones a happy path reads. The rebuilt record\n * goes straight to the OTLP encoder, which assumes the shapes the type declares —\n * so a `severityNumber` of `null`, a nested object in `attributes`, or a trace id\n * of the wrong width becomes an encoder error deep inside the exporter rather than\n * a rejected file here. Trace and span ids are held to their hex forms because a\n * malformed id is not a correlation a collector can resolve.\n */\nconst isReplayableLogRecord = (value: unknown): value is SerializedLogRecord => {\n if (!isPlainObject(value)) {\n return false;\n }\n if (!isBoundedString(value.eventName)) {\n return false;\n }\n if (!isFiniteNonNegative(value.severityNumber)) {\n return false;\n }\n if (value.severityText !== undefined && typeof value.severityText !== \"string\") {\n return false;\n }\n if (\n value.body !== undefined &&\n (typeof value.body !== \"string\" || value.body.length > MAX_SPOOLED_LOG_BODY_LENGTH)\n ) {\n return false;\n }\n if (!isFiniteNonNegative(value.timeMillis) || !isFiniteNonNegative(value.observedTimeMillis)) {\n return false;\n }\n // Correlation is all-or-nothing: a trace id without a span id (or the reverse)\n // is not a span reference, and half of one would export as a record pointing at\n // span `0000000000000000`.\n const hasTrace = value.traceId !== undefined;\n const hasSpan = value.spanId !== undefined;\n if (hasTrace !== hasSpan) {\n return false;\n }\n if (hasTrace && (typeof value.traceId !== \"string\" || !TRACE_ID_PATTERN.test(value.traceId))) {\n return false;\n }\n if (hasSpan && (typeof value.spanId !== \"string\" || !SPAN_ID_PATTERN.test(value.spanId))) {\n return false;\n }\n if (!isPlainObject(value.attributes)) {\n return false;\n }\n const entries = Object.entries(value.attributes);\n if (entries.length > MAX_SPOOLED_ATTRIBUTES_PER_RECORD) {\n return false;\n }\n return entries.every(([, attribute]) => isReplayableAttributeValue(attribute));\n};\n\nexport type LogSpoolBatchRejection =\n | \"not-an-object\"\n | \"identity-mismatch\"\n | \"resource-attributes-invalid\"\n | \"instrumentation-scope-invalid\"\n | \"records-invalid\"\n | \"record-field-invalid\";\n\n/**\n * Validate a whole batch read back from disk, before any of it reaches an exporter.\n *\n * The identity check alone is not enough. `records` being anything other than an\n * array makes the sender's `records.map(...)` throw, and a throwing send is\n * indistinguishable from an unreachable collector — so the drain would treat a\n * permanently poisoned file as a transient failure and stop at it on every pass,\n * wedging the queue head and every batch behind it forever. Validation is what\n * turns that into a single quarantined file.\n */\nexport const validateLogSpoolBatch = (\n value: unknown,\n identity: StoreNamespace,\n): SpoolValidation<LogSpoolBatch> => {\n if (!isPlainObject(value)) {\n return { rejection: \"not-an-object\" satisfies LogSpoolBatchRejection };\n }\n if (\n value.providerId !== identity.providerId ||\n value.installationId !== identity.installationId\n ) {\n return { rejection: \"identity-mismatch\" satisfies LogSpoolBatchRejection };\n }\n if (!isPlainObject(value.resourceAttributes)) {\n // Not merely absent: the resource is rebuilt by iterating it, and a string or\n // an array would silently produce a resource built from its indices.\n return { rejection: \"resource-attributes-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (\n !isPlainObject(value.instrumentationScope) ||\n !isBoundedString(value.instrumentationScope.name)\n ) {\n return { rejection: \"instrumentation-scope-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (\n value.instrumentationScope.version !== undefined &&\n typeof value.instrumentationScope.version !== \"string\"\n ) {\n return { rejection: \"instrumentation-scope-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (!Array.isArray(value.records) || value.records.length === 0) {\n return { rejection: \"records-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (value.records.length > MAX_SPOOLED_LOG_RECORDS_PER_BATCH) {\n return { rejection: \"records-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (!value.records.every(isReplayableLogRecord)) {\n return { rejection: \"record-field-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (!isFiniteNonNegative(value.enqueuedAt)) {\n return { rejection: \"not-an-object\" satisfies LogSpoolBatchRejection };\n }\n return { batch: value as unknown as LogSpoolBatch };\n};\n\nexport type DurableLogSpoolOptions = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Refuses new entries once this many are queued. Default 500. */\n readonly maxSpoolFiles?: number;\n /**\n * Queue directory below the identity namespace. Default `spool-logs`; each\n * export destination other than `default` gets its own.\n */\n readonly queueName?: string;\n /** Bound on total queued bytes. Unbounded when absent. */\n readonly maxBytes?: number;\n /** Batches older than this are dropped rather than sent. No age bound when absent. */\n readonly maxAgeMillis?: number;\n /** Default `refuse-new`, the original behavior. */\n readonly overflow?: SpoolOverflowPolicy;\n};\n\n/**\n * Durable filesystem queue for log batches a collector could not accept.\n *\n * Rooted at `<rootDir>/<providerId>/<installationId>/spool-logs`, deliberately a\n * different directory from the trace spool: the two hold different encodings, so a\n * single mixed queue would have each signal's sender quarantining the other's\n * perfectly deliverable batches. Separate directories also mean a logs outage\n * cannot consume the trace spool's capacity, which is what keeps the primary\n * signal unaffected by a misconfigured logs endpoint.\n */\nexport interface DurableLogSpool {\n enqueue(batch: LogSpoolBatch): Promise<SpoolEnqueueResult>;\n /** Sequential, bounded drain: stops after the first failed send, or after `maxBatches`. */\n drain(\n send: (batch: LogSpoolBatch) => Promise<SpoolSendOutcome>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\n /**\n * Depth, bytes, and persisted drop counts. Optional so a host's own\n * implementation of this interface keeps compiling; the file-backed one has it.\n */\n stats?(): Promise<SpoolStats>;\n}\n\nexport const DEFAULT_MAX_LOG_SPOOL_FILES = 500;\n\nexport const createFileDurableLogSpool = (options: DurableLogSpoolOptions): DurableLogSpool =>\n createSpoolQueue<LogSpoolBatch>({\n rootDir: options.rootDir,\n providerId: options.providerId,\n installationId: options.installationId,\n clock: options.clock,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_LOG_SPOOL_FILES,\n queueName: options.queueName ?? \"spool-logs\",\n ...(options.maxBytes === undefined ? {} : { maxBytes: options.maxBytes }),\n ...(options.maxAgeMillis === undefined ? {} : { maxAgeMillis: options.maxAgeMillis }),\n ...(options.overflow === undefined ? {} : { overflow: options.overflow }),\n validate: validateLogSpoolBatch,\n });\n","import { TraceFlags, type AttributeValue, type Attributes, type SpanContext } from \"@opentelemetry/api\";\nimport { ExportResultCode, type ExportResult } from \"@opentelemetry/core\";\nimport { millisToHrTime, type InstrumentationScope } from \"@opentelemetry/core\";\nimport { OTLPLogExporter } from \"@opentelemetry/exporter-logs-otlp-proto\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport type { ReadableLogRecord } from \"@opentelemetry/sdk-logs\";\n\nimport { OTLP_LOGS_PATH, OTLP_TRACES_PATH, withoutTrailingSlashes } from \"../config/otlp-endpoint.js\";\nimport type { ExporterPolicy } from \"../config/schema.js\";\nimport { createHealthTracker, type DeliveryHealthSnapshot } from \"../diagnostics/health.js\";\nimport { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { Clock, Logger, TelemetryEmitResult, TelemetrySink } from \"../runtime/ports.js\";\nimport type { DurableLogSpool, LogSpoolBatch, SerializedLogRecord } from \"./durable-log-spool.js\";\nimport { isPermanentExportFailure } from \"./export-failure.js\";\nimport type { SpoolSendOutcome } from \"./spool-queue.js\";\nimport {\n agreedContextAttributes,\n replayResource,\n resourceFromExporterPolicy,\n resourceWithContext,\n} from \"./exporter-resource.js\";\nimport {\n canonicalEventsToLogRecords,\n NO_LOG_CONTENT,\n type LogContentPolicy,\n} from \"./log-records.js\";\nimport {\n DEFAULT_INSTRUMENTATION_SCOPE,\n type SpanCorrelation,\n type SpanCorrelationResolver,\n} from \"./semconv.js\";\n\n/**\n * OTLP HTTP/protobuf log sink.\n *\n * The logs counterpart of `otlp-sink.ts`, and deliberately its mirror image:\n * semantic mapping lives entirely in `log-records.ts`, and this module owns only\n * batching, delivery, bounded flush/shutdown, health tracking, and — when a spool\n * is configured — persisting what a down collector rejected. Every failure mode\n * (disabled config, missing or underivable endpoint, export failure, timeout,\n * spool write failure) degrades to a reported diagnostic rather than a thrown\n * error, preserving the hook's fail-open contract.\n *\n * The two sinks are separate objects rather than one exporter with two encoders\n * because they fail independently: a collector that has no logs receiver, or an\n * operator who pointed logs at the wrong port, must cost the logs signal and\n * nothing else. The trace pipeline is the one an installation already depends on.\n */\n\n/**\n * Where log records are posted.\n *\n * Resolution order, highest first:\n *\n * 1. `logs.endpoint` — stated outright, used verbatim.\n * 2. the trace endpoint with a trailing `/v1/traces` swapped for `/v1/logs`, which\n * is the shape a collector configured for both signals actually has.\n * 3. the trace endpoint treated as a base URL, with `/v1/logs` appended — the\n * convention the OTLP specification defines for a signal-less endpoint.\n *\n * Returned as a discriminated result rather than a bare string because \"no logs\n * endpoint could be derived\" has to be reportable: silently posting an\n * `ExportLogsServiceRequest` to a traces receiver produces a rejection whose cause\n * is a configuration mistake, and an operator reading \"collector rejected a batch\"\n * would go looking at the collector.\n */\nexport const resolveLogsEndpoint = (\n exporter: ExporterPolicy,\n): { readonly endpoint: string; readonly derived: boolean } | { readonly unresolvable: \"no-endpoint\" } => {\n if (exporter.logs.endpoint !== undefined) {\n return { endpoint: exporter.logs.endpoint, derived: false };\n }\n if (exporter.endpoint === undefined) {\n return { unresolvable: \"no-endpoint\" };\n }\n const trimmed = withoutTrailingSlashes(exporter.endpoint);\n if (trimmed.endsWith(OTLP_LOGS_PATH)) {\n return { endpoint: trimmed, derived: true };\n }\n if (trimmed.endsWith(OTLP_TRACES_PATH)) {\n return {\n endpoint: `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${OTLP_LOGS_PATH}`,\n derived: true,\n };\n }\n return { endpoint: `${trimmed}${OTLP_LOGS_PATH}`, derived: true };\n};\n\n/**\n * Narrow a log record's attributes to what a spool file can hold.\n *\n * Log attributes admit any value (`AnyValue` is `unknown` since api 1.10); the spool's own validator\n * does not, and neither does `assembleReadableSpan`'s sibling contract for traces.\n * This mapping only ever produces primitives, so the filter is unreachable in\n * practice — it is here so that \"what the live path emits\" and \"what survives a\n * spool round-trip\" cannot silently diverge if a future attribute is richer than\n * the queue's schema.\n */\nconst toSpoolAttributes = (attributes: Attributes): Attributes => {\n const safe: Record<string, AttributeValue> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n safe[key] = value;\n continue;\n }\n if (Array.isArray(value) && value.every((item) => typeof item === \"string\")) {\n safe[key] = value;\n }\n }\n return safe;\n};\n\nconst serializeRecord = (record: ReadableLogRecord): SerializedLogRecord => {\n const context = record.spanContext;\n return {\n eventName: record.eventName ?? \"otelhook.record\",\n severityNumber: record.severityNumber ?? 0,\n ...(record.severityText === undefined ? {} : { severityText: record.severityText }),\n ...(typeof record.body === \"string\" ? { body: record.body } : {}),\n timeMillis: record.hrTime[0] * 1000 + Math.round(record.hrTime[1] / 1e6),\n observedTimeMillis:\n record.hrTimeObserved[0] * 1000 + Math.round(record.hrTimeObserved[1] / 1e6),\n ...(context === undefined ? {} : { traceId: context.traceId, spanId: context.spanId }),\n attributes: toSpoolAttributes(record.attributes),\n };\n};\n\nconst deserializeRecord = (\n serialized: SerializedLogRecord,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableLogRecord => {\n const spanContext: SpanContext | undefined =\n serialized.traceId === undefined || serialized.spanId === undefined\n ? undefined\n : {\n traceId: serialized.traceId,\n spanId: serialized.spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n };\n return {\n hrTime: millisToHrTime(serialized.timeMillis),\n hrTimeObserved: millisToHrTime(serialized.observedTimeMillis),\n ...(spanContext === undefined ? {} : { spanContext }),\n severityNumber: serialized.severityNumber,\n ...(serialized.severityText === undefined ? {} : { severityText: serialized.severityText }),\n ...(serialized.body === undefined ? {} : { body: serialized.body }),\n eventName: serialized.eventName,\n resource,\n instrumentationScope: scope,\n attributes: serialized.attributes,\n droppedAttributesCount: 0,\n };\n};\n\nconst chunk = <T,>(items: readonly T[], size: number): readonly (readonly T[])[] => {\n if (size <= 0 || items.length <= size) {\n return [items];\n }\n const chunks: T[][] = [];\n for (let index = 0; index < items.length; index += size) {\n chunks.push(items.slice(index, index + size));\n }\n return chunks;\n};\n\nexport type OtlpLogSinkOptions = {\n readonly exporter: ExporterPolicy;\n /** Header values, kept out of the resolved-config snapshot (ADR: config carries only header *names*). */\n readonly headers?: Readonly<Record<string, string>>;\n readonly providerId: string;\n readonly installationId: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Persists batches an unreachable collector rejected, for a later retry. */\n readonly spool?: DurableLogSpool;\n readonly instrumentationScope?: InstrumentationScope;\n /**\n * Whether disclosed content text may reach a log body. Defaults to\n * {@link NO_LOG_CONTENT}, which is what an unconfigured installation gets.\n */\n readonly content?: LogContentPolicy;\n /**\n * Supplies cross-process pairing so a record correlates to the span id the trace\n * pipeline actually exported. Omitted, records still carry a derived trace and\n * span id, computed from the batch alone.\n *\n * Injected as a plain function rather than as a correlator so the telemetry layer\n * keeps no dependency on lifecycle or on the state store (ADR 0006). When both\n * sinks are wired, the fanout resolves correlation *once* and hands the same\n * answer to each — `correlateBatch` writes state, so calling it twice per batch\n * would record a start edge twice.\n */\n readonly correlate?: SpanCorrelationResolver;\n /** Export destination this sink delivers to; see `OtlpTraceSinkOptions.destination`. */\n readonly destination?: string;\n};\n\nexport interface OtlpLogTelemetrySink extends TelemetrySink {\n health(): DeliveryHealthSnapshot;\n /** Attempts to resend previously spooled batches, bounded by `maxBatches`. */\n drainSpool(\n maxBatches?: number,\n ): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }>;\n}\n\n/**\n * Sink that swallows every batch: logs disabled, or configured but unroutable.\n *\n * Reports **zero accepted and zero rejected**, which is the one place this differs\n * from the trace sink's disabled path — and it has to. The counts a sink returns are\n * what `classifyDurability` decides commit-or-retry from, and they are summed across\n * signals. A disabled signal that claimed to have accepted the batch would make a\n * *total* trace loss look like a partial delivery: `accepted > 0` from a sink that\n * sent nothing, `rejected > 0` from the sink that failed, so the callback would\n * commit as terminally-partial instead of releasing its claim for retry. Contributing\n * nothing is the truthful answer, and it leaves durability decided entirely by the\n * signals that actually tried — so an installation with logs off behaves exactly as\n * it did before logs existed.\n *\n * Health still records the batch as accepted: nothing failed, and a disabled signal\n * must not read as unhealthy.\n */\nconst createDisabledSink = (destination?: string): OtlpLogTelemetrySink => {\n const health = createHealthTracker(\n \"telemetry-log-sink\",\n destination === undefined ? {} : { destination },\n );\n return {\n emit: (events): Promise<TelemetryEmitResult> => {\n health.recordSuccess(events.length);\n return Promise.resolve({ accepted: 0, rejected: 0, errors: [] });\n },\n flush: (): Promise<void> => Promise.resolve(),\n shutdown: (): Promise<void> => Promise.resolve(),\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool: (): Promise<{\n readonly drained: number;\n readonly remaining: number;\n readonly failed: number;\n }> => Promise.resolve({ drained: 0, remaining: 0, failed: 0 }),\n };\n};\n\n/**\n * Whether this configuration can deliver logs at all.\n *\n * Separated from the constructor so `doctor` can report the same verdict without\n * building an exporter, and so each refusal names itself rather than collapsing\n * into one \"disabled\" state an operator then has to bisect.\n */\nexport type LogsDeliverability =\n | { readonly status: \"configured\"; readonly endpoint: string; readonly derivedEndpoint: boolean }\n | {\n readonly status: \"disabled\";\n readonly reason:\n | \"logs-disabled\"\n | \"exporter-disabled\"\n | \"protocol-none\"\n | \"protocol-unsupported\"\n | \"no-endpoint\";\n };\n\nexport const describeLogsDeliverability = (exporter: ExporterPolicy): LogsDeliverability => {\n if (!exporter.logs.enabled) {\n return { status: \"disabled\", reason: \"logs-disabled\" };\n }\n if (!exporter.enabled) {\n return { status: \"disabled\", reason: \"exporter-disabled\" };\n }\n if (exporter.protocol === \"none\") {\n return { status: \"disabled\", reason: \"protocol-none\" };\n }\n if (exporter.protocol !== \"http/protobuf\") {\n return { status: \"disabled\", reason: \"protocol-unsupported\" };\n }\n const resolved = resolveLogsEndpoint(exporter);\n if (\"unresolvable\" in resolved) {\n return { status: \"disabled\", reason: \"no-endpoint\" };\n }\n return { status: \"configured\", endpoint: resolved.endpoint, derivedEndpoint: resolved.derived };\n};\n\nconst DISABLED_DETAIL: Readonly<Record<Extract<LogsDeliverability, { status: \"disabled\" }>[\"reason\"], string>> =\n Object.freeze({\n \"logs-disabled\": \"otlp log sink disabled: exporter.logs.enabled is false\",\n \"exporter-disabled\": \"otlp log sink disabled: the exporter is disabled\",\n \"protocol-none\": \"otlp log sink disabled: protocol is none\",\n \"protocol-unsupported\":\n \"otlp log sink disabled: protocol not supported by this build, falling back to disabled\",\n \"no-endpoint\": \"otlp log sink disabled: no logs endpoint configured and none could be derived\",\n });\n\n/**\n * OTLP HTTP/protobuf {@link TelemetrySink} for the logs signal.\n *\n * A disabled sink never calls `correlate`: with nothing being exported there is no\n * span to correlate to, and writing correlation state anyway would leave a disabled\n * installation quietly accumulating files.\n */\nexport const createOtlpLogSink = (options: OtlpLogSinkOptions): OtlpLogTelemetrySink => {\n const destinationFields =\n options.destination === undefined ? {} : { \"export.destination\": options.destination };\n const deliverability = describeLogsDeliverability(options.exporter);\n if (deliverability.status === \"disabled\") {\n if (deliverability.reason !== \"logs-disabled\") {\n // `logs-disabled` is the default posture, not a misconfiguration, so it is\n // not worth a warning on every invocation. The rest are: somebody asked for\n // logs and will not get them.\n options.logger?.warn(DISABLED_DETAIL[deliverability.reason], {\n \"exporter.protocol\": options.exporter.protocol,\n ...destinationFields,\n });\n }\n return createDisabledSink(options.destination);\n }\n\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const resource = resourceFromExporterPolicy(options.exporter);\n const content = options.content ?? NO_LOG_CONTENT;\n const health = createHealthTracker(\n \"telemetry-log-sink\",\n options.destination === undefined ? {} : { destination: options.destination },\n );\n const exporter = new OTLPLogExporter({\n url: deliverability.endpoint,\n headers: { ...options.headers },\n timeoutMillis: options.exporter.timeoutMillis,\n });\n let shutdownCompleted = false;\n\n const exportRecords = (records: readonly ReadableLogRecord[]): Promise<ExportResult> =>\n new Promise((resolve) => {\n exporter.export([...records], (result: ExportResult) => resolve(result));\n });\n\n const toSpoolBatch = (records: readonly ReadableLogRecord[], batchResource: Resource): LogSpoolBatch => ({\n providerId: options.providerId,\n installationId: options.installationId,\n resourceAttributes: { ...batchResource.attributes },\n instrumentationScope: {\n name: scope.name,\n ...(scope.version === undefined ? {} : { version: scope.version }),\n },\n records: records.map(serializeRecord),\n enqueuedAt: options.clock.now(),\n });\n\n const sendSerializedBatch = async (batch: LogSpoolBatch): Promise<SpoolSendOutcome> => {\n const batchResource = replayResource(batch.resourceAttributes, options.exporter);\n const records = batch.records.map((record) =>\n deserializeRecord(record, batchResource, batch.instrumentationScope),\n );\n const result = await exportRecords(records);\n if (result.code === ExportResultCode.SUCCESS) {\n return true;\n }\n return isPermanentExportFailure(result) ? \"discard\" : false;\n };\n\n /**\n * Cross-process pairing is an enrichment, never a precondition: if state is\n * unreadable the batch still exports, with each record correlated from the batch\n * alone rather than dropped.\n */\n const resolveCorrelations = async (\n events: readonly CanonicalEvent[],\n ): Promise<{\n readonly correlations: readonly SpanCorrelation[];\n readonly available: boolean | undefined;\n }> => {\n if (options.correlate === undefined) {\n return { correlations: [], available: undefined };\n }\n try {\n return { correlations: await options.correlate(events), available: true };\n } catch {\n options.logger?.warn(\"span correlation unavailable; exporting uncorrelated log records\", {});\n return { correlations: [], available: false };\n }\n };\n\n const emit = async (events: Parameters<TelemetrySink[\"emit\"]>[0]): Promise<TelemetryEmitResult> => {\n if (events.length === 0) {\n return { accepted: 0, rejected: 0, errors: [] };\n }\n const resolved = await resolveCorrelations(events);\n // Session context overrides the same keys on the Resource for this batch.\n const batchResource = resourceWithContext(resource, agreedContextAttributes(events));\n const mapped = canonicalEventsToLogRecords(events, {\n resource: batchResource,\n instrumentationScope: scope,\n content,\n correlations: resolved.correlations,\n ...(resolved.available === undefined ? {} : { correlationAvailable: resolved.available }),\n });\n if (mapped.droppedFacts > 0) {\n // Said out loud rather than truncated silently: a caller that saw only\n // \"accepted\" would read a clipped batch as a complete one.\n options.logger?.warn(\"log records dropped: batch or per-event bound reached\", {\n \"logs.dropped_facts\": mapped.droppedFacts,\n });\n }\n const errors: OtelHookErrorInfo[] = [];\n let accepted = 0;\n let rejected = 0;\n\n for (const batch of chunk(mapped.records, options.exporter.logs.maxBatchSize)) {\n if (batch.length === 0) {\n continue;\n }\n let result: ExportResult;\n try {\n result = await exportRecords(batch);\n } catch (thrown) {\n result = {\n code: ExportResultCode.FAILED,\n error: thrown instanceof Error ? thrown : new Error(\"export threw\"),\n };\n }\n if (result.code === ExportResultCode.SUCCESS) {\n accepted += batch.length;\n health.recordSuccess(batch.length, options.clock.now());\n continue;\n }\n\n health.recordFailure(\"telemetry-export-failure\", batch.length, options.clock.now());\n const permanent = isPermanentExportFailure(result);\n if (options.spool !== undefined && !permanent) {\n const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({\n spooled: false as const,\n reason: \"capacity-exceeded\" as const,\n }));\n if (spoolResult.spooled) {\n accepted += batch.length;\n options.logger?.warn(\"log record batch not delivered; spooled for the next invocation\", {\n \"export.batch_size\": batch.length,\n ...destinationFields,\n });\n continue;\n }\n }\n rejected += batch.length;\n errors.push(\n createErrorInfo({\n code: \"telemetry-export-failure\",\n phase: \"export\",\n detail: permanent\n ? \"collector refused a log record batch with a non-retryable status\"\n : \"collector rejected or was unreachable for a log record batch\",\n details: {\n \"export.batch_size\": batch.length,\n \"export.signal\": \"logs\",\n ...destinationFields,\n },\n }),\n );\n }\n\n return { accepted, rejected, errors };\n };\n\n const drainSpool = async (\n maxBatches?: number,\n ): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }> => {\n if (options.spool === undefined) {\n return { drained: 0, remaining: 0, failed: 0 };\n }\n const result = await options.spool.drain(sendSerializedBatch, {\n ...(maxBatches === undefined ? {} : { maxBatches }),\n });\n if (result.drained > 0) {\n health.recordSuccess(result.drained, options.clock.now());\n }\n return result;\n };\n\n const flush = async (): Promise<void> => {\n try {\n await exporter.forceFlush();\n } catch {\n // Best-effort: flush failures are reported through health, never thrown.\n }\n await drainSpool().catch(() => undefined);\n };\n\n const shutdown = async (): Promise<void> => {\n if (shutdownCompleted) {\n return;\n }\n shutdownCompleted = true;\n await flush();\n try {\n await exporter.shutdown();\n } catch {\n // Idempotent, non-throwing per the TelemetrySink contract.\n }\n };\n\n return {\n emit,\n flush,\n shutdown,\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool,\n };\n};\n","/**\n * OTLP/HTTP endpoint URLs per signal, as the OpenTelemetry exporter\n * specification defines them.\n *\n * - `OTEL_EXPORTER_OTLP_ENDPOINT` is a **base** URL: the signal path\n * (`/v1/traces`, `/v1/logs`) is appended to it.\n * - `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` / `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`\n * are full URLs, used as they are.\n *\n * One compatibility rule: earlier releases read `OTEL_EXPORTER_OTLP_ENDPOINT`\n * as the full traces URL. A base URL that already ends in `/v1/traces` is\n * therefore taken to be that full URL, not a base to append to, so an existing\n * `…/v1/traces` value keeps posting where it did.\n */\n\n/**\n * The standard endpoint variables. `generic` and `logs` also appear in\n * `ENVIRONMENT_VARIABLES`; `traces` does not, because that list is guarded\n * against identity-looking (`TRACE`) names.\n */\nexport const OTLP_ENDPOINT_VARIABLES = Object.freeze({\n generic: \"OTEL_EXPORTER_OTLP_ENDPOINT\",\n traces: \"OTEL_EXPORTER_OTLP_TRACES_ENDPOINT\",\n logs: \"OTEL_EXPORTER_OTLP_LOGS_ENDPOINT\",\n metrics: \"OTEL_EXPORTER_OTLP_METRICS_ENDPOINT\",\n});\n\nexport const OTLP_TRACES_PATH = \"/v1/traces\";\nexport const OTLP_LOGS_PATH = \"/v1/logs\";\nexport const OTLP_METRICS_PATH = \"/v1/metrics\";\n\nexport type OtlpSignal = \"traces\" | \"logs\" | \"metrics\";\n\nconst SIGNAL_PATHS: Readonly<Record<OtlpSignal, string>> = Object.freeze({\n traces: OTLP_TRACES_PATH,\n logs: OTLP_LOGS_PATH,\n metrics: OTLP_METRICS_PATH,\n});\n\n/**\n * Strip trailing slashes, by scan rather than by regex.\n *\n * `/\\/+$/` is a polynomial-ReDoS on this input: an endpoint of many `/` followed by\n * anything else makes the engine retry the `+` from every position. The endpoint is\n * operator-supplied configuration bounded to 2048 characters, so the practical cost\n * is small — but a linear scan is just as short, and the bound is not the guarantee.\n */\nexport const withoutTrailingSlashes = (value: string): string => {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === 0x2f) {\n end -= 1;\n }\n return value.slice(0, end);\n};\n\n/**\n * The URL a signal posts to, given an `OTEL_EXPORTER_OTLP_ENDPOINT` base.\n *\n * Trailing slashes on the base are dropped before the signal path is appended,\n * so `https://host/otlp` and `https://host/otlp/` both give\n * `https://host/otlp/v1/traces`. A base ending in `/v1/traces` (the legacy\n * full-URL form) is used as-is for traces and has that suffix swapped for\n * `/v1/logs` for logs.\n */\nexport const otlpSignalEndpointFromBase = (base: string, signal: OtlpSignal): string => {\n const trimmed = withoutTrailingSlashes(base);\n if (trimmed.endsWith(OTLP_TRACES_PATH)) {\n return signal === \"traces\"\n ? trimmed\n : `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${SIGNAL_PATHS[signal]}`;\n }\n return `${trimmed}${SIGNAL_PATHS[signal]}`;\n};\n\n/**\n * A sibling signal's URL derived from a traces URL: a trailing `/v1/traces` (or\n * the target signal's own path) is swapped for the target path, and any other URL\n * is treated as a base and has the path appended. The rule logs have always used.\n */\nexport const siblingSignalEndpoint = (tracesEndpoint: string, signal: OtlpSignal): string => {\n const trimmed = withoutTrailingSlashes(tracesEndpoint);\n const target = SIGNAL_PATHS[signal];\n if (trimmed.endsWith(target)) {\n return trimmed;\n }\n if (trimmed.endsWith(OTLP_TRACES_PATH)) {\n return `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${target}`;\n }\n return `${trimmed}${target}`;\n};\n","import type { DeliveryHealthSnapshot } from \"../diagnostics/health.js\";\nimport type { OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { TelemetryEmitResult, TelemetrySink } from \"../runtime/ports.js\";\nimport type { OtlpLogTelemetrySink } from \"./otlp-log-sink.js\";\nimport type { OtlpTelemetrySink } from \"./otlp-sink.js\";\nimport type { SpanCorrelation, SpanCorrelationResolver } from \"./semconv.js\";\n\n/**\n * One canonical batch, two OTLP signals.\n *\n * A hook has a single {@link TelemetrySink} seam, and both signals map the *same*\n * canonical events — so this fans one batch out rather than making the orchestrator\n * aware that there is more than one destination.\n *\n * ## Durability adds up across signals\n *\n * The counts are summed rather than taken from the primary signal, because the\n * caller's question is \"may I commit this callback?\" and the answer turns on whether\n * *anything* reached a collector or a spool. Summing gives `classifyDurability`\n * exactly the right inputs:\n *\n * - both signals delivered → `delivered`\n * - neither delivered → `lost`, and the callback is safe to retry precisely because\n * there is nothing to duplicate\n * - one delivered and one did not → `partial`, which is terminal: retrying would\n * re-export what the healthy signal already delivered, and a duplicate silently\n * corrupts a total whereas a reported loss is a number somebody can act on\n *\n * A disabled sink accepts everything, so an installation with logs off behaves\n * exactly as it did before logs existed.\n *\n * ## Correlation must be resolved once per batch\n *\n * Both sinks want the same pairing facts, and `SpanCorrelator.correlateBatch` is not\n * a read — it records a start edge, marks a scope published, and takes the session\n * lock to do it. Wrap the correlator in {@link shareCorrelationPerBatch} and give\n * *the same wrapped function* to both sinks; `emit` here is sequential so the first\n * sink resolves it and the second is served the memoized answer.\n */\n\nexport type SignalFanoutOptions = {\n readonly traces: OtlpTelemetrySink;\n readonly logs: OtlpLogTelemetrySink;\n};\n\nexport interface SignalFanoutSink extends TelemetrySink {\n /** One snapshot per wired signal, in a stable order: traces, then logs. */\n health(): readonly DeliveryHealthSnapshot[];\n}\n\nexport const createSignalFanout = (options: SignalFanoutOptions): SignalFanoutSink => {\n const emit = async (events: readonly CanonicalEvent[]): Promise<TelemetryEmitResult> => {\n // Sequential, not concurrent: the first sink to ask resolves correlation, and\n // the second must be served that answer rather than race to start a second\n // resolution against the same state.\n const traces = await options.traces.emit(events);\n const logs = await options.logs.emit(events);\n const errors: readonly OtelHookErrorInfo[] = [...traces.errors, ...logs.errors];\n return {\n accepted: traces.accepted + logs.accepted,\n rejected: traces.rejected + logs.rejected,\n errors,\n };\n };\n\n const flush = async (): Promise<void> => {\n // Each signal's flush is already best-effort and non-throwing; awaiting both\n // unconditionally means a stuck logs endpoint cannot skip the trace flush.\n await options.traces.flush().catch(() => undefined);\n await options.logs.flush().catch(() => undefined);\n };\n\n const shutdown = async (): Promise<void> => {\n await options.traces.shutdown().catch(() => undefined);\n await options.logs.shutdown().catch(() => undefined);\n };\n\n return {\n emit,\n flush,\n shutdown,\n health: (): readonly DeliveryHealthSnapshot[] => [\n options.traces.health(),\n options.logs.health(),\n ],\n };\n};\n\n/**\n * Wrap a correlation resolver so one batch resolves at most once.\n *\n * Memoized on the identity of the `events` array, which is what makes it correct\n * without a reset: every batch is a distinct array, so a new batch cannot be served\n * a previous one's answer, and a retry of the *same* array deliberately is. The\n * promise is cached rather than its value, so two callers arriving before the first\n * resolution completes still share it.\n *\n * Exported because the one-call-per-batch property is a requirement of the\n * correlator, not a convenience of the fanout: a host wiring its own pair of sinks\n * needs to be able to express it too.\n */\nexport const shareCorrelationPerBatch = (\n correlate: SpanCorrelationResolver,\n): SpanCorrelationResolver => {\n let pending:\n | {\n readonly events: readonly CanonicalEvent[];\n readonly result: Promise<readonly SpanCorrelation[]>;\n }\n | undefined;\n return (events): Promise<readonly SpanCorrelation[]> => {\n if (pending?.events === events) {\n return pending.result;\n }\n const result = correlate(events);\n pending = { events, result };\n return result;\n };\n};\n","import { z } from \"zod\";\n\nimport { isUnsafeHeaderValue } from \"./header-value.js\";\nimport { MAX_OTLP_HEADERS } from \"./otlp-headers.js\";\nimport type { ExporterPolicy } from \"./schema.js\";\n\n/**\n * Export destinations: one batch, several OTLP endpoints.\n *\n * otel-hook is not a long-running process, so it cannot sit behind a proxy that\n * fans out for it. Instead every enabled destination is sent the same batch by the\n * same short-lived process, and what a destination could not take is kept in that\n * destination's own spool for the next invocation.\n *\n * ## The `default` destination\n *\n * The single-endpoint settings that predate this list — `exporter.endpoint`,\n * `exporter.logs.endpoint`, `exporter.protocol`, `--header`, and the standard\n * `OTEL_EXPORTER_OTLP_*` variables that feed them — describe one destination\n * named `default`. The name is therefore reserved: a `destinations[]` entry may\n * not take it, so there is exactly one place that destination is configured.\n *\n * A configuration with no `destinations` resolves to that one destination and\n * nothing else, exactly as before the list existed.\n */\n\nexport const DEFAULT_DESTINATION_NAME = \"default\";\n\n/**\n * Destination names become directory names (each destination spools on its own),\n * so they are held to a lowercase, filesystem-safe vocabulary rather than being\n * sanitized into something an operator would not recognize.\n */\nexport const DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;\n\nexport const MAX_EXPORT_DESTINATIONS = 16;\n/** The same bound `OTEL_EXPORTER_OTLP_*HEADERS` and `exporter.headerNames` have. */\nexport const MAX_DESTINATION_HEADERS = MAX_OTLP_HEADERS;\n\n/** Prefix of a header value that names an environment variable instead of holding a value. */\nexport const HEADER_ENV_REFERENCE_PREFIX = \"env:\";\n\n/** RFC 9110 `token`: the characters a header field name may use. */\nconst HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;\nconst ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;\nconst MAX_HEADER_VALUE_LENGTH = 8_192;\n\nexport const exportSignalSchema = z.enum([\"traces\", \"logs\", \"metrics\"]);\nexport type ExportSignal = z.infer<typeof exportSignalSchema>;\n\nconst headerValueSchema = z\n .string()\n .min(1)\n .max(MAX_HEADER_VALUE_LENGTH)\n // The rule `OTEL_EXPORTER_OTLP_*HEADERS` values are held to: a line break is a\n // request-splitting vector, and other controls or non-Latin-1 characters would\n // only make Node's HTTP client throw at send time.\n .refine(\n (value) => !isUnsafeHeaderValue(value),\n \"header values may not contain line breaks, control characters, or characters beyond Latin-1\",\n )\n .refine(\n (value) =>\n !value.startsWith(HEADER_ENV_REFERENCE_PREFIX) ||\n ENV_VARIABLE_NAME_PATTERN.test(value.slice(HEADER_ENV_REFERENCE_PREFIX.length)),\n \"an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN\",\n );\n\nconst endpointSchema = z.string().url().max(2048);\n\nexport const exportDestinationSchema = z\n .strictObject({\n /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */\n name: z\n .string()\n .regex(DESTINATION_NAME_PATTERN, \"destination names are lowercase letters, digits, _ and -\"),\n /** Default true. A disabled destination is neither sent to nor drained. */\n enabled: z.boolean().optional(),\n /**\n * Traces URL, with the same meaning as `exporter.endpoint`: the logs URL is\n * derived from it (`/v1/traces` becomes `/v1/logs`) unless `logsEndpoint` is set.\n */\n endpoint: endpointSchema.optional(),\n /** Per-signal override of `endpoint` for traces. */\n tracesEndpoint: endpointSchema.optional(),\n /** Per-signal override of the derived logs URL. */\n logsEndpoint: endpointSchema.optional(),\n /** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */\n metricsEndpoint: endpointSchema.optional(),\n /** Defaults to `exporter.protocol`. */\n protocol: z.enum([\"http/protobuf\", \"http/json\", \"none\"]).optional(),\n /**\n * Header name to value. A value of the form `env:NAME` is read from that\n * environment variable at send time, so a credential never has to be written\n * into the file. Values never appear in a snapshot, a diagnostic, or `doctor`.\n */\n headers: z\n .record(z.string().regex(HEADER_NAME_PATTERN, \"not a valid header name\"), headerValueSchema)\n .refine(\n (headers) => Object.keys(headers).length <= MAX_DESTINATION_HEADERS,\n `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`,\n )\n .optional(),\n /**\n * Which signals this destination receives. Default: traces and logs. The logs\n * signal is still governed by `exporter.logs.enabled`, which stays the one\n * opt-in for content-bearing records leaving the host. `metrics` is never on by\n * default: a destination receives hook-derived metrics only when it lists them.\n */\n signals: z.array(exportSignalSchema).min(1).max(3).readonly().optional(),\n })\n .refine(\n (destination) =>\n destination.endpoint !== undefined ||\n destination.tracesEndpoint !== undefined ||\n destination.logsEndpoint !== undefined ||\n destination.metricsEndpoint !== undefined,\n \"a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint\",\n );\nexport type ExportDestinationConfig = z.infer<typeof exportDestinationSchema>;\n\n/** Signals a destination receives when it does not list any: never metrics. */\nexport const DEFAULT_DESTINATION_SIGNALS: readonly ExportSignal[] = Object.freeze([\"traces\", \"logs\"]);\n\nexport const exportDestinationsSchema = z\n .array(exportDestinationSchema)\n .max(MAX_EXPORT_DESTINATIONS)\n .readonly()\n .superRefine((destinations, context) => {\n const seen = new Set<string>();\n destinations.forEach((destination, index) => {\n if (destination.name === DEFAULT_DESTINATION_NAME) {\n context.addIssue({\n code: \"custom\",\n path: [index, \"name\"],\n message:\n 'the name \"default\" is reserved for exporter.endpoint and the OTEL_EXPORTER_OTLP_* variables',\n });\n }\n if (seen.has(destination.name)) {\n context.addIssue({\n code: \"custom\",\n path: [index, \"name\"],\n message: `duplicate destination name \"${destination.name}\"`,\n });\n }\n seen.add(destination.name);\n });\n });\n\n/**\n * Bounds on each destination's retry spool, per signal.\n *\n * Every destination spools independently, so one long outage can only ever cost\n * its own budget. When a bound is reached the *oldest* batches are dropped first —\n * a recent batch is the one a reader is still likely to look for — and every drop\n * is counted on disk so `doctor` can report it.\n */\nexport const spoolPolicySchema = z.strictObject({\n /** Total bytes of queued batches. Default 16 MiB. */\n maxBytes: z.number().int().min(1_024).max(1_073_741_824),\n /** A batch older than this is dropped instead of sent. Default 72 hours. */\n maxAgeMillis: z.number().int().min(1_000).max(30 * 24 * 60 * 60 * 1000),\n /** Number of queued batches. Default 500. */\n maxBatches: z.number().int().min(1).max(65_536),\n});\nexport type SpoolPolicy = z.infer<typeof spoolPolicySchema>;\n\nexport const DEFAULT_SPOOL_POLICY: SpoolPolicy = Object.freeze({\n maxBytes: 16 * 1024 * 1024,\n maxAgeMillis: 72 * 60 * 60 * 1000,\n maxBatches: 500,\n});\n\n/** The spool policy in force, with defaults filled in for any bound left unset. */\nexport const effectiveSpoolPolicy = (exporter: ExporterPolicy): SpoolPolicy => ({\n maxBytes: exporter.spool?.maxBytes ?? DEFAULT_SPOOL_POLICY.maxBytes,\n maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,\n maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches,\n});\n\n/**\n * One destination as the runtime sends to it.\n *\n * `headers` holds what the configuration holds — literal values and `env:`\n * references, unresolved. Resolution against an environment happens only at the\n * point of sending ({@link resolveDestinationHeaders}), and the `default`\n * destination's header values never pass through configuration at all: they are\n * handed to the runtime separately, as they always have been.\n */\nexport type ExportDestination = {\n readonly name: string;\n /** `exporter` for the `default` destination, `destinations` for a list entry. */\n readonly source: \"exporter\" | \"destinations\";\n readonly protocol: ExporterPolicy[\"protocol\"];\n /** Traces URL as configured; for `default` this is `exporter.endpoint`. */\n readonly endpoint?: string;\n readonly tracesEndpoint?: string;\n readonly logsEndpoint?: string;\n readonly metricsEndpoint?: string;\n readonly signals: { readonly traces: boolean; readonly logs: boolean; readonly metrics: boolean };\n readonly headers: Readonly<Record<string, string>>;\n};\n\nconst legacyDestination = (exporter: ExporterPolicy): ExportDestination => ({\n name: DEFAULT_DESTINATION_NAME,\n source: \"exporter\",\n protocol: exporter.protocol,\n ...(exporter.endpoint === undefined ? {} : { endpoint: exporter.endpoint }),\n ...(exporter.logs.endpoint === undefined ? {} : { logsEndpoint: exporter.logs.endpoint }),\n ...(exporter.metrics?.endpoint === undefined ? {} : { metricsEndpoint: exporter.metrics.endpoint }),\n signals: { traces: true, logs: exporter.logs.enabled, metrics: exporter.metrics?.enabled === true },\n headers: {},\n});\n\n/** Whether a configuration uses the destination list at all. */\nexport const hasConfiguredDestinations = (exporter: ExporterPolicy): boolean =>\n exporter.destinations !== undefined && exporter.destinations.length > 0;\n\n/**\n * The destinations an exporter policy sends to, in a stable order: `default`\n * first when present, then the list in file order.\n *\n * - No `destinations`: exactly one `default` destination, even when it has no\n * endpoint — the sink then reports itself unconfigured, as it always has.\n * - With `destinations`: `default` is included only when a single-endpoint setting\n * actually names an endpoint, and disabled entries are left out.\n */\nexport const resolveExportDestinations = (\n exporter: ExporterPolicy,\n): readonly ExportDestination[] => {\n if (!hasConfiguredDestinations(exporter)) {\n return [legacyDestination(exporter)];\n }\n const resolved: ExportDestination[] = [];\n if (\n exporter.endpoint !== undefined ||\n exporter.logs.endpoint !== undefined ||\n exporter.metrics?.endpoint !== undefined\n ) {\n resolved.push(legacyDestination(exporter));\n }\n for (const destination of exporter.destinations ?? []) {\n if (destination.enabled === false) {\n continue;\n }\n const signals: readonly ExportSignal[] = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;\n resolved.push({\n name: destination.name,\n source: \"destinations\",\n protocol: destination.protocol ?? exporter.protocol,\n ...(destination.endpoint === undefined ? {} : { endpoint: destination.endpoint }),\n ...(destination.tracesEndpoint === undefined\n ? {}\n : { tracesEndpoint: destination.tracesEndpoint }),\n ...(destination.logsEndpoint === undefined ? {} : { logsEndpoint: destination.logsEndpoint }),\n ...(destination.metricsEndpoint === undefined\n ? {}\n : { metricsEndpoint: destination.metricsEndpoint }),\n signals: {\n traces: signals.includes(\"traces\"),\n logs: exporter.logs.enabled && signals.includes(\"logs\"),\n metrics: signals.includes(\"metrics\"),\n },\n headers: { ...(destination.headers ?? {}) },\n });\n }\n return resolved;\n};\n\n/** A header value's meaning, without its content. */\nexport type HeaderValueReference =\n | { readonly kind: \"literal\" }\n | { readonly kind: \"env\"; readonly variable: string };\n\nexport const parseHeaderValueReference = (value: string): HeaderValueReference =>\n value.startsWith(HEADER_ENV_REFERENCE_PREFIX)\n ? { kind: \"env\", variable: value.slice(HEADER_ENV_REFERENCE_PREFIX.length) }\n : { kind: \"literal\" };\n\nexport type ResolvedDestinationHeaders = {\n /** Header values ready to send. Never logged, never reported. */\n readonly values: Readonly<Record<string, string>>;\n /** Names of referenced environment variables that are unset or empty. */\n readonly missingVariables: readonly string[];\n};\n\n/**\n * Resolve `env:` references against an explicitly supplied environment.\n *\n * Pure: the process environment is never read implicitly. An unset or empty\n * variable is reported by *name* — the only part of a reference that is safe to\n * say out loud — and its header is left out of `values`.\n */\nexport const resolveDestinationHeaders = (\n headers: Readonly<Record<string, string>>,\n environment: Readonly<Record<string, string | undefined>> | undefined,\n): ResolvedDestinationHeaders => {\n const values: Record<string, string> = {};\n const missing: string[] = [];\n for (const [name, value] of Object.entries(headers)) {\n const reference = parseHeaderValueReference(value);\n if (reference.kind === \"literal\") {\n values[name] = value;\n continue;\n }\n const resolved = environment?.[reference.variable];\n if (resolved === undefined || resolved === \"\") {\n missing.push(reference.variable);\n continue;\n }\n values[name] = resolved;\n }\n return { values, missingVariables: [...new Set(missing)].sort() };\n};\n\n/**\n * Attribute-safe description of one destination: names, origins, and variable\n * names. Never a header value, and never an endpoint beyond its origin.\n */\nexport type DestinationDescription = {\n readonly name: string;\n readonly enabled: boolean;\n readonly protocol: ExporterPolicy[\"protocol\"];\n readonly signals: readonly ExportSignal[];\n readonly tracesEndpointOrigin?: string;\n readonly logsEndpointOrigin?: string;\n readonly metricsEndpointOrigin?: string;\n readonly headerNames: readonly string[];\n /** Environment variables this destination's headers reference. */\n readonly headerVariables: readonly string[];\n};\n\nexport const endpointOrigin = (endpoint: string | undefined): string | undefined => {\n if (endpoint === undefined) {\n return undefined;\n }\n try {\n return new URL(endpoint).origin;\n } catch {\n return \"<unparsable>\";\n }\n};\n\n/** Every configured destination, disabled ones included, for `doctor` and snapshots. */\nexport const describeExportDestinations = (\n exporter: ExporterPolicy,\n): readonly DestinationDescription[] => {\n const describe = (\n destination: ExportDestination,\n enabled: boolean,\n ): DestinationDescription => {\n const tracesOrigin = endpointOrigin(destination.tracesEndpoint ?? destination.endpoint);\n const logsOrigin = endpointOrigin(\n destination.logsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint,\n );\n const metricsOrigin = endpointOrigin(\n destination.metricsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint,\n );\n const variables = Object.values(destination.headers)\n .map(parseHeaderValueReference)\n .flatMap((reference) => (reference.kind === \"env\" ? [reference.variable] : []));\n return {\n name: destination.name,\n enabled,\n protocol: destination.protocol,\n signals: exportSignalSchema.options.filter((signal) => destination.signals[signal]),\n ...(tracesOrigin === undefined || !destination.signals.traces\n ? {}\n : { tracesEndpointOrigin: tracesOrigin }),\n ...(logsOrigin === undefined || !destination.signals.logs\n ? {}\n : { logsEndpointOrigin: logsOrigin }),\n ...(metricsOrigin === undefined || !destination.signals.metrics\n ? {}\n : { metricsEndpointOrigin: metricsOrigin }),\n headerNames:\n destination.source === \"exporter\"\n ? [...exporter.headerNames].sort()\n : Object.keys(destination.headers).sort(),\n headerVariables: [...new Set(variables)].sort(),\n };\n };\n const enabled = resolveExportDestinations(exporter).map((destination) =>\n describe(destination, true),\n );\n const disabled = (exporter.destinations ?? [])\n .filter((destination) => destination.enabled === false)\n .map((destination) =>\n describe(\n {\n name: destination.name,\n source: \"destinations\",\n protocol: destination.protocol ?? exporter.protocol,\n ...(destination.endpoint === undefined ? {} : { endpoint: destination.endpoint }),\n signals: { traces: false, logs: false, metrics: false },\n headers: { ...(destination.headers ?? {}) },\n },\n false,\n ),\n );\n return [...enabled, ...disabled];\n};\n","/**\n * Internal: shared by `OTEL_EXPORTER_OTLP_*HEADERS` parsing and the\n * `exporter.destinations[].headers` schema. Not re-exported from the package.\n */\n\n/**\n * Characters an HTTP field value must not contain once decoded. CR and LF would\n * split the request; the other controls and anything beyond Latin-1 are refused\n * by Node's HTTP client anyway, and refusing them here turns a failed export into\n * a reported, skipped entry.\n */\nexport const isUnsafeHeaderValue = (value: string): boolean =>\n [...value].some((char) => {\n const code = char.codePointAt(0) ?? 0;\n return (code < 0x20 && code !== 0x09) || code === 0x7f || code > 0xff;\n });\n","/**\n * The standard OTLP exporter header variables.\n *\n * `OTEL_EXPORTER_OTLP_HEADERS` applies to every signal;\n * `OTEL_EXPORTER_OTLP_TRACES_HEADERS` and `OTEL_EXPORTER_OTLP_LOGS_HEADERS`\n * apply to one signal each. They exist so a credential (`authorization=Basic …`)\n * can reach the exporter without being written on a command line, where `ps` and\n * `/proc/<pid>/cmdline` would show it to every local user.\n *\n * Header *values* never enter configuration. Parsing returns them to the caller,\n * which hands them straight to the sink at construction; configuration carries\n * header *names* only (`exporter.headerNames`), because a resolved-config\n * snapshot is logged and exported. Every diagnostic here names an entry by its\n * position and the variable by its name — never a key, never a value — because a\n * malformed entry may be the secret itself (`Basic abc` with no `=`).\n */\n\nimport { isUnsafeHeaderValue } from \"./header-value.js\";\n\n/** Upper bound on headers per variable, matching `exporter.headerNames`. */\nexport const MAX_OTLP_HEADERS = 32;\n\nexport const OTLP_HEADER_VARIABLES = Object.freeze({\n generic: \"OTEL_EXPORTER_OTLP_HEADERS\",\n traces: \"OTEL_EXPORTER_OTLP_TRACES_HEADERS\",\n logs: \"OTEL_EXPORTER_OTLP_LOGS_HEADERS\",\n});\n\n/** RFC 9110 `token`: the characters an HTTP field name may contain. */\nconst HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n\nexport type ParsedOtlpHeaders = {\n readonly headers: Readonly<Record<string, string>>;\n /** Position-only explanations; never a key or a value. */\n readonly warnings: readonly string[];\n};\n\nconst decode = (raw: string): string | undefined => {\n try {\n return decodeURIComponent(raw);\n } catch {\n return undefined;\n }\n};\n\n/**\n * Parse one `OTEL_EXPORTER_OTLP_*HEADERS` value.\n *\n * The OpenTelemetry exporter specification defines the format as W3C\n * Baggage-like: comma-separated `key=value` pairs, surrounding whitespace\n * trimmed, keys and values percent-decoded. So `authorization=Basic%20abc` is\n * the header `authorization: Basic abc`, and a `,` inside a value must be\n * written `%2C`. A malformed entry is skipped and reported; the rest of the\n * variable still applies. A repeated key takes its last value.\n */\nexport const parseOtlpHeadersValue = (raw: string): ParsedOtlpHeaders => {\n const headers: Record<string, string> = {};\n const warnings: string[] = [];\n let overflowed = false;\n\n for (const [index, rawEntry] of raw.split(\",\").entries()) {\n const position = String(index + 1);\n const entry = rawEntry.trim();\n if (entry === \"\") {\n continue;\n }\n const equals = entry.indexOf(\"=\");\n if (equals <= 0) {\n warnings.push(`entry ${position} is not a key=value pair; ignored`);\n continue;\n }\n const key = decode(entry.slice(0, equals).trim());\n // Split on the first `=` only: a base64 credential ends in `=` padding.\n const value = decode(entry.slice(equals + 1).trim());\n if (key === undefined || value === undefined) {\n warnings.push(`entry ${position} has malformed percent-encoding; ignored`);\n continue;\n }\n const name = key.trim();\n const trimmedValue = value.trim();\n if (!HEADER_NAME_PATTERN.test(name)) {\n warnings.push(`entry ${position} does not name a valid HTTP header; ignored`);\n continue;\n }\n if (trimmedValue === \"\") {\n warnings.push(`entry ${position} has an empty value; ignored`);\n continue;\n }\n if (isUnsafeHeaderValue(trimmedValue)) {\n warnings.push(`entry ${position} has a character not allowed in an HTTP header value; ignored`);\n continue;\n }\n const existing = findHeaderName(headers, name);\n if (existing === undefined && Object.keys(headers).length >= MAX_OTLP_HEADERS) {\n overflowed = true;\n continue;\n }\n if (existing !== undefined) {\n delete headers[existing];\n }\n headers[name] = trimmedValue;\n }\n\n if (overflowed) {\n warnings.push(`more than ${String(MAX_OTLP_HEADERS)} headers were supplied; the excess was ignored`);\n }\n return { headers, warnings };\n};\n\n/** HTTP field names are case-insensitive: `Authorization` and `authorization` are one header. */\nconst findHeaderName = (headers: Readonly<Record<string, string>>, name: string): string | undefined => {\n const lower = name.toLowerCase();\n return Object.keys(headers).find((candidate) => candidate.toLowerCase() === lower);\n};\n\n/**\n * Overlay header maps, lowest precedence first, per header name.\n *\n * A higher source replaces only the names it sets (case-insensitively), so a\n * signal-specific variable can override `authorization` while a generic tenant\n * header still applies — the same per-key merge the OpenTelemetry SDKs apply.\n */\nexport const mergeOtlpHeaders = (\n ...sources: readonly Readonly<Record<string, string>>[]\n): Readonly<Record<string, string>> => {\n const merged: Record<string, string> = {};\n for (const source of sources) {\n for (const [name, value] of Object.entries(source)) {\n const existing = findHeaderName(merged, name);\n if (existing !== undefined) {\n delete merged[existing];\n }\n merged[name] = value;\n }\n }\n return merged;\n};\n\nexport type ResolvedOtlpHeaders = {\n /** Headers for the traces exporter. */\n readonly traces: Readonly<Record<string, string>>;\n /** Headers for the logs exporter. */\n readonly logs: Readonly<Record<string, string>>;\n /** Variable-qualified, value-free explanations of skipped entries. */\n readonly warnings: readonly { readonly variable: string; readonly detail: string }[];\n};\n\n/**\n * Resolve exporter headers per signal.\n *\n * Precedence, per header name, highest first:\n *\n * ```\n * explicit headers (--header) > OTEL_EXPORTER_OTLP_{TRACES,LOGS}_HEADERS > OTEL_EXPORTER_OTLP_HEADERS\n * ```\n *\n * Pure: the environment is passed in, never read from `process.env`.\n */\nexport const resolveOtlpHeaders = (\n env: Readonly<Record<string, string | undefined>>,\n explicit: Readonly<Record<string, string>> = {},\n): ResolvedOtlpHeaders => {\n const warnings: { variable: string; detail: string }[] = [];\n const read = (variable: string): Readonly<Record<string, string>> => {\n const raw = env[variable];\n if (raw === undefined || raw.trim() === \"\") {\n return {};\n }\n const parsed = parseOtlpHeadersValue(raw);\n for (const detail of parsed.warnings) {\n warnings.push({ variable, detail });\n }\n return parsed.headers;\n };\n const generic = read(OTLP_HEADER_VARIABLES.generic);\n const traces = read(OTLP_HEADER_VARIABLES.traces);\n const logs = read(OTLP_HEADER_VARIABLES.logs);\n return {\n traces: mergeOtlpHeaders(generic, traces, explicit),\n logs: mergeOtlpHeaders(generic, logs, explicit),\n warnings,\n };\n};\n\n/**\n * Header names, deduplicated case-insensitively (first spelling kept), sorted\n * and bounded — the only part of a header that may enter configuration or a\n * diagnostic.\n */\nexport const unionOtlpHeaderNames = (...lists: readonly (readonly string[])[]): readonly string[] => {\n const names: string[] = [];\n const seen = new Set<string>();\n for (const name of lists.flat()) {\n if (!seen.has(name.toLowerCase())) {\n seen.add(name.toLowerCase());\n names.push(name);\n }\n }\n return names.sort().slice(0, MAX_OTLP_HEADERS);\n};\n\n/** {@link unionOtlpHeaderNames} over the names of header maps. */\nexport const describeOtlpHeaderNames = (\n ...sources: readonly Readonly<Record<string, string>>[]\n): readonly string[] => unionOtlpHeaderNames(...sources.map((source) => Object.keys(source)));\n","import { isAbsolute } from \"node:path\";\n\nimport { z } from \"zod\";\n\nimport { detectionConfidenceSchema, nonEmptyStringSchema } from \"../model/primitives.js\";\nimport {\n contentModeSchema,\n DEFAULT_PRIVACY_POLICY,\n privacyPolicySchema,\n} from \"../privacy/policy.js\";\nimport { exportDestinationsSchema, spoolPolicySchema } from \"./destinations.js\";\nimport { EMPTY_RESOURCE_ATTRIBUTES, resourceAttributesSchema } from \"./resource-attributes.js\";\n\n/**\n * Policy for the OTLP logs signal.\n *\n * Two switches rather than one, because they answer different questions and an\n * operator needs to be able to answer them differently:\n *\n * - `enabled` — whether a second signal leaves this host at all. Off by default:\n * an installation that upgrades must not silently start sending a new stream to a\n * collector whose receivers, quotas, and retention were sized for traces.\n * - `includeContent` — whether *disclosed* text may appear in a log body. Also off\n * by default, and deliberately not the same knob as `privacy.contentMode`: spans\n * carry no content in any content mode, so an installation that set\n * `contentMode` to get a hash and a length has never had content on the wire.\n * Reusing that setting to also mean \"publish prompts\" would change what an\n * existing configuration discloses without anybody editing it.\n *\n * `raw` content additionally requires the pre-existing `privacy.allowRawContent`\n * opt-in, which the privacy service enforces before a fact is ever built and the\n * log mapping re-checks at the wire.\n */\nexport const logsPolicySchema = z.strictObject({\n enabled: z.boolean(),\n /**\n * Full URL for the logs signal.\n *\n * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes\n * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.\n */\n endpoint: z.string().url().max(2048).optional(),\n includeContent: z.boolean(),\n maxBatchSize: z.number().int().min(1).max(4096),\n});\nexport type LogsPolicy = z.infer<typeof logsPolicySchema>;\n\nexport const DEFAULT_LOGS_POLICY: LogsPolicy = Object.freeze({\n enabled: false,\n includeContent: false,\n maxBatchSize: 128,\n});\n\n/**\n * Policy for hook-derived metrics (issue #69).\n *\n * Off by default, like logs: an upgrade must not start a new stream to a\n * collector nobody sized for it. `enabled` governs the `default` destination\n * (the single-endpoint settings); an `exporter.destinations[]` entry receives\n * metrics when its `signals` list names `metrics`. Metrics carry no content, so\n * listing the signal is the whole opt-in.\n *\n * - `temporality`: `cumulative` (default) exports running totals per series,\n * kept in the state store across hook processes, so a receiver that merges\n * counters by keeping the largest value stays correct. `delta` exports what one\n * callback observed and keeps no state.\n * - `includeSessionId`: put `session.id` on every data point (default true). Turn\n * it off where per-session series are too many for the backend.\n */\nexport const metricsPolicySchema = z.strictObject({\n enabled: z.boolean(),\n /** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */\n endpoint: z.string().url().max(2048).optional(),\n temporality: z.enum([\"cumulative\", \"delta\"]),\n includeSessionId: z.boolean(),\n});\nexport type MetricsPolicy = z.infer<typeof metricsPolicySchema>;\n\nexport const DEFAULT_METRICS_POLICY: MetricsPolicy = Object.freeze({\n enabled: false,\n temporality: \"cumulative\",\n includeSessionId: true,\n});\n\n/**\n * Runtime exporter policy.\n *\n * This describes *where and how* telemetry goes. It deliberately contains no\n * session, invocation, or workspace field: see ADR 0001. Mixing the two would\n * make identity globally reachable through configuration.\n */\nexport const exporterPolicySchema = z.strictObject({\n enabled: z.boolean(),\n protocol: z.enum([\"http/protobuf\", \"http/json\", \"none\"]),\n endpoint: z.string().url().max(2048).optional(),\n /**\n * Header names only. Values are supplied separately at construction time and\n * are never part of a resolved-config snapshot, which is logged and exported.\n */\n headerNames: z.array(nonEmptyStringSchema).max(32).readonly(),\n timeoutMillis: z.number().int().min(1).max(600_000),\n maxBatchSize: z.number().int().min(1).max(4096),\n maxQueueSize: z.number().int().min(1).max(65_536),\n maxRetryAttempts: z.number().int().min(0).max(10),\n serviceName: nonEmptyStringSchema,\n serviceNamespace: nonEmptyStringSchema.optional(),\n /**\n * Custom attributes merged into the exported OTLP Resource.\n *\n * Bounded and validated, and refusing `service.name`/`service.namespace`,\n * which are the two fields above. Distinct from an invocation's\n * `consumerAttributes`: this describes the emitting deployment, carries no\n * identity, and is the same for every span this process exports.\n */\n resourceAttributes: resourceAttributesSchema,\n /**\n * The logs signal. Nested under the exporter because it shares the endpoint,\n * headers, timeout, protocol, service identity, and resource attributes above —\n * a second top-level section would invite two of each to drift apart.\n */\n logs: logsPolicySchema,\n /**\n * Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before\n * metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.\n */\n metrics: metricsPolicySchema.optional(),\n /**\n * Additional OTLP destinations, each sent every batch in parallel.\n *\n * Absent (the default), the exporter has exactly one destination — the\n * single-endpoint settings above, named `default` — and behaves exactly as it\n * did before this list existed. See `destinations.ts`.\n *\n * Merged as one leaf: a higher layer that sets the list replaces it whole,\n * because \"the union of two partial lists\" has no answer an operator could\n * predict.\n */\n destinations: exportDestinationsSchema.optional(),\n /**\n * Per-destination retry spool bounds, each optional and merged per leaf; any\n * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.\n */\n spool: spoolPolicySchema.partial().optional(),\n});\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\n/**\n * Per-provider behaviour that is not part of an adapter's parse.\n *\n * `claudeCode.readTranscriptUsage` is the one sanctioned exception to \"no\n * transcript reads in the hook\" (docs/claude-code-usage-contract.md, finding 8).\n * When true, the hook runtime — never the adapter — reads the session transcript\n * named by a Claude Code `Stop` / `StopFailure` payload, bounded, and attaches the\n * turn's model and summed token usage before the adapter parses it. Off by\n * default: without it, otel-hook reads no file a hook payload names.\n */\nexport const providersPolicySchema = z.strictObject({\n claudeCode: z\n .strictObject({\n readTranscriptUsage: z.boolean(),\n })\n .optional(),\n});\nexport type ProvidersPolicy = z.infer<typeof providersPolicySchema>;\n\n/**\n * Session context (`docs/session-context.md`): a directory a harness writes one\n * JSON file per agent session into, laid out `<dir>/<agent-tool>/<session-id>.json`.\n * With `dir` set, the hook reads that one file on every event and stamps the\n * attributes of the segment in force on every span, log record and metric point.\n * Absent (the default), nothing is read.\n *\n * Set in the configuration file or with `--session-context-dir`, never through\n * the environment: some agents (Claude Code) strip `OTEL_*` variables from the\n * hook processes they start.\n */\nexport const sessionContextPolicySchema = z.strictObject({\n /** Absolute path of the context directory. */\n dir: z\n .string()\n .min(1)\n .max(4096)\n .refine((value) => isAbsolute(value), { message: \"must be an absolute path\" }),\n});\nexport type SessionContextPolicy = z.infer<typeof sessionContextPolicySchema>;\n\nexport const otelHookConfigSchema = z.strictObject({\n exporter: exporterPolicySchema,\n privacy: privacyPolicySchema,\n detection: detectionPolicySchema,\n diagnostics: diagnosticsPolicySchema,\n /** Optional so a hand-built configuration from before it existed stays valid. */\n providers: providersPolicySchema.optional(),\n /** Optional: absent means no session context is read. */\n sessionContext: sessionContextPolicySchema.optional(),\n});\nexport type OtelHookConfig = z.infer<typeof otelHookConfigSchema>;\n\n/** Partial overlay accepted from a configuration layer. */\nexport const otelHookConfigPatchSchema = z.strictObject({\n // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:\n // merging happens per leaf, so a layer must be able to set `logs.enabled` alone\n // without also restating the endpoint and the batch size.\n exporter: exporterPolicySchema\n .omit({ logs: true, metrics: true, spool: true })\n .partial()\n .extend({\n logs: logsPolicySchema.partial().optional(),\n metrics: metricsPolicySchema.partial().optional(),\n spool: spoolPolicySchema.partial().optional(),\n })\n .optional(),\n privacy: privacyPolicySchema\n .omit({ limits: true })\n .partial()\n .extend({ limits: privacyPolicySchema.shape.limits.partial().optional() })\n .optional(),\n detection: detectionPolicySchema.partial().optional(),\n diagnostics: diagnosticsPolicySchema.partial().optional(),\n providers: z\n .strictObject({\n claudeCode: z.strictObject({ readTranscriptUsage: z.boolean() }).partial().optional(),\n })\n .partial()\n .optional(),\n sessionContext: sessionContextPolicySchema.partial().optional(),\n});\nexport type OtelHookConfigPatch = z.infer<typeof otelHookConfigPatchSchema>;\n\nexport const DEFAULT_EXPORTER_POLICY: ExporterPolicy = Object.freeze({\n enabled: true,\n protocol: \"http/protobuf\",\n headerNames: Object.freeze([]),\n timeoutMillis: 10_000,\n maxBatchSize: 128,\n maxQueueSize: 2048,\n maxRetryAttempts: 2,\n serviceName: \"coding-agent\",\n resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,\n logs: DEFAULT_LOGS_POLICY,\n metrics: DEFAULT_METRICS_POLICY,\n});\n\nexport const DEFAULT_DETECTION_POLICY: DetectionPolicy = Object.freeze({\n minimumConfidence: \"strong\",\n allowAmbiguousFallback: true,\n allowedProviderIds: Object.freeze([]),\n});\n\nexport const DEFAULT_DIAGNOSTICS_POLICY: DiagnosticsPolicy = Object.freeze({\n logLevel: \"warn\",\n emitErrorEvents: true,\n});\n\nexport const DEFAULT_PROVIDERS_POLICY: ProvidersPolicy = Object.freeze({\n claudeCode: Object.freeze({ readTranscriptUsage: false }),\n});\n\nexport const DEFAULT_CONFIG: OtelHookConfig = Object.freeze({\n exporter: DEFAULT_EXPORTER_POLICY,\n privacy: DEFAULT_PRIVACY_POLICY,\n detection: DEFAULT_DETECTION_POLICY,\n diagnostics: DEFAULT_DIAGNOSTICS_POLICY,\n providers: DEFAULT_PROVIDERS_POLICY,\n});\n\n/** Whether the runtime may read Claude Code transcripts at `Stop` (default false). */\nexport const readsClaudeTranscriptUsage = (config: OtelHookConfig): boolean =>\n config.providers?.claudeCode?.readTranscriptUsage === true;\n\n/** The session context directory in force, or `undefined` when none is configured. */\nexport const sessionContextDir = (config: OtelHookConfig): string | undefined => config.sessionContext?.dir;\n\n/** Content mode is re-exported for callers building patches. */\nexport { contentModeSchema };\n\n/** The metrics policy in force, defaults filled in. */\nexport const effectiveMetricsPolicy = (exporter: ExporterPolicy): MetricsPolicy => ({\n ...DEFAULT_METRICS_POLICY,\n ...(exporter.metrics ?? {}),\n});\n","import type { Attributes } from \"@opentelemetry/api\";\nimport type { Resource } from \"@opentelemetry/resources\";\n\nimport type { CanonicalEvent, GenerationEndEvent } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\nimport { resolveExportedSessionId } from \"./export-identity.js\";\n\n/**\n * Metrics derived from hook events (issue #69).\n *\n * otel-hook already normalizes every provider's hook callbacks into canonical\n * events; this module turns one batch of those events into *observations* — a\n * value recorded against an instrument, with attributes. It is pure: it reads no\n * state and sends nothing. Aggregating observations into OTLP data points\n * (cumulative across processes, or delta per batch) and exporting them are the\n * jobs of `lifecycle/metric-series.ts` and `otlp-metric-sink.ts`.\n *\n * ## Why observations come from the runtime's accounting, not from the events alone\n *\n * Token usage is taken from the orchestrator's `UsageObservation` deltas rather than\n * from `generation.end.usage` directly. A provider that reports a session-wide\n * running total (Codex) stamps the *cumulative* figure on every turn; summing those\n * into a histogram would bill a three-turn session several times over. The\n * orchestrator already diffs them against a persisted baseline, exactly once per\n * delivery, so the metric reuses that answer.\n *\n * ## What is never on a metric\n *\n * Session context attributes (`docs/session-context.md`) are on every data point\n * of an event that has them, so a new context starts a new series.\n *\n * No account identity (`user.*`, `enduser.*`, `organization.id`), no content, no\n * paths, and no per-event ids (`otelhook.event.id`, tool-call ids, generation ids):\n * an id per data point is a new series per data point. `session.id` is the one\n * high-cardinality attribute, and it can be switched off.\n */\n\n/** Recommended bucket boundaries from the GenAI semantic conventions. */\nexport const TOKEN_USAGE_BUCKETS: readonly number[] = Object.freeze([\n 1, 4, 16, 64, 256, 1_024, 4_096, 16_384, 65_536, 262_144, 1_048_576, 4_194_304, 16_777_216,\n 67_108_864,\n]);\nexport const OPERATION_DURATION_BUCKETS: readonly number[] = Object.freeze([\n 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24, 20.48, 40.96, 81.92,\n]);\n\nexport const METRIC_TOKEN_USAGE = \"gen_ai.client.token.usage\";\nexport const METRIC_OPERATION_DURATION = \"gen_ai.client.operation.duration\";\nexport const METRIC_SESSIONS = \"otelhook.sessions\";\nexport const METRIC_TOOL_CALLS = \"otelhook.tool.calls\";\nexport const METRIC_COST_USAGE = \"otelhook.cost.usage\";\n\nexport type MetricInstrumentName =\n | typeof METRIC_TOKEN_USAGE\n | typeof METRIC_OPERATION_DURATION\n | typeof METRIC_SESSIONS\n | typeof METRIC_TOOL_CALLS\n | typeof METRIC_COST_USAGE;\n\nexport type MetricInstrument = {\n readonly name: MetricInstrumentName;\n readonly kind: \"histogram\" | \"counter\";\n readonly unit: string;\n readonly description: string;\n /** Integer values (`asInt`) or doubles. Histograms always carry a double sum. */\n readonly valueType: \"int\" | \"double\";\n /** Histograms only. */\n readonly boundaries?: readonly number[];\n};\n\nexport const METRIC_INSTRUMENTS: Readonly<Record<MetricInstrumentName, MetricInstrument>> = Object.freeze({\n [METRIC_TOKEN_USAGE]: {\n name: METRIC_TOKEN_USAGE,\n kind: \"histogram\",\n unit: \"{token}\",\n description: \"Tokens used per generation, by token type (hook-derived)\",\n valueType: \"int\",\n boundaries: TOKEN_USAGE_BUCKETS,\n },\n [METRIC_OPERATION_DURATION]: {\n name: METRIC_OPERATION_DURATION,\n kind: \"histogram\",\n unit: \"s\",\n description: \"Generation duration, from its start hook to its end hook (hook-derived)\",\n valueType: \"double\",\n boundaries: OPERATION_DURATION_BUCKETS,\n },\n [METRIC_SESSIONS]: {\n name: METRIC_SESSIONS,\n kind: \"counter\",\n unit: \"{session}\",\n description: \"Agent sessions started\",\n valueType: \"int\",\n },\n [METRIC_TOOL_CALLS]: {\n name: METRIC_TOOL_CALLS,\n kind: \"counter\",\n unit: \"{call}\",\n description: \"Completed tool calls, by tool name and outcome\",\n valueType: \"int\",\n },\n [METRIC_COST_USAGE]: {\n name: METRIC_COST_USAGE,\n kind: \"counter\",\n unit: \"USD\",\n description: \"Cost reported by the provider; never estimated\",\n valueType: \"double\",\n },\n});\n\nexport const isMetricInstrumentName = (value: unknown): value is MetricInstrumentName =>\n typeof value === \"string\" && Object.hasOwn(METRIC_INSTRUMENTS, value);\n\nexport const ATTR_GEN_AI_TOKEN_TYPE = \"gen_ai.token.type\";\nexport const ATTR_GEN_AI_PROVIDER_NAME = \"gen_ai.provider.name\";\nconst ATTR_GEN_AI_OPERATION_NAME = \"gen_ai.operation.name\";\nconst ATTR_GEN_AI_REQUEST_MODEL = \"gen_ai.request.model\";\nconst ATTR_GEN_AI_RESPONSE_MODEL = \"gen_ai.response.model\";\nconst ATTR_GEN_AI_TOOL_NAME = \"gen_ai.tool.name\";\nconst ATTR_ERROR_TYPE = \"error.type\";\nconst ATTR_SESSION_ID = \"session.id\";\nconst ATTR_OTELHOOK_PROVIDER_ID = \"otelhook.provider.id\";\nconst ATTR_OTELHOOK_OUTCOME = \"otelhook.outcome\";\nconst ATTR_OTELHOOK_SESSION_KIND = \"otelhook.session.kind\";\n\n/**\n * Token types on `gen_ai.client.token.usage`.\n *\n * `input` is inclusive of cache reads, as the GenAI conventions define\n * `gen_ai.usage.input_tokens`. `cache_read` and `cache_creation` are extra series\n * describing parts of the input; summing every token type double-counts.\n */\nexport type TokenType = \"input\" | \"output\" | \"cache_read\" | \"cache_creation\";\n\nexport type MetricsTemporality = \"cumulative\" | \"delta\";\n\n/** One recorded value. */\nexport type MetricObservation = {\n readonly instrument: MetricInstrumentName;\n readonly value: number;\n /** Data-point attributes. Primitives only. */\n readonly attributes: Readonly<Record<string, string | number | boolean>>;\n /** When the observed thing happened, in epoch milliseconds. */\n readonly timeMillis: number;\n /** Provider session the observation belongs to; scopes cumulative state. */\n readonly sessionId: string;\n};\n\n/** A start time recovered for a generation, by generation id. */\nexport type GenerationStart = {\n readonly startMillis: number;\n readonly requestModel?: string;\n};\n\n/** The usage delta the orchestrator derived for one usage-bearing event. */\nexport type MetricUsageInput = {\n readonly eventId: string;\n readonly scope: string;\n readonly delta: CanonicalUsage;\n};\n\nexport type DeriveMetricObservationsInput = {\n readonly events: readonly CanonicalEvent[];\n readonly usage: readonly MetricUsageInput[];\n /** The exported resource; supplies the launcher's `session.id` when it sets one. */\n readonly resource: Resource;\n /** Put `session.id` on every data point. Default true. */\n readonly includeSessionId?: boolean;\n /**\n * Start times for generations whose start edge is not in this batch (it was\n * recorded by an earlier hook process). Looked up by generation id.\n */\n readonly generationStarts?: (generationId: string) => GenerationStart | undefined;\n /**\n * When the session's current turn began: the last `prompt.submitted` recorded,\n * by an earlier callback or this one. The fallback duration source for\n * providers whose generation is a turn (Claude Code, Codex).\n */\n readonly turnStart?: (sessionId: string) => number | undefined;\n};\n\nconst commonAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n includeSessionId: boolean,\n): Record<string, string | number | boolean> => ({\n // Session context first, so the metric's own attributes always win; and never\n // anything account-shaped, whatever the context says.\n ...(event.contextAttributes === undefined\n ? {}\n : (withoutAccountIdentity(event.contextAttributes) as Record<string, string | number | boolean>)),\n [ATTR_OTELHOOK_PROVIDER_ID]: event.provenance.providerId,\n ...(includeSessionId\n ? { [ATTR_SESSION_ID]: resolveExportedSessionId(event.sessionId, resource).sessionId }\n : {}),\n});\n\nconst generationAttributes = (\n end: GenerationEndEvent,\n requestModel: string | undefined,\n): Record<string, string> => ({\n [ATTR_GEN_AI_OPERATION_NAME]: \"chat\",\n ...(end.model.vendor === undefined ? {} : { [ATTR_GEN_AI_PROVIDER_NAME]: end.model.vendor }),\n [ATTR_GEN_AI_REQUEST_MODEL]: requestModel ?? end.model.modelId,\n [ATTR_GEN_AI_RESPONSE_MODEL]: end.model.modelId,\n});\n\nconst TOKEN_FIELDS: readonly (readonly [TokenType, (usage: CanonicalUsage) => number])[] = [\n [\"input\", (usage) => usage.inputTokens],\n [\"output\", (usage) => usage.outputTokens],\n [\"cache_read\", (usage) => usage.cachedInputTokens],\n [\"cache_creation\", (usage) => usage.cacheCreationInputTokens],\n];\n\nconst isFailedOutcome = (outcome: string): boolean =>\n outcome !== \"ok\" && outcome !== \"unknown\" && outcome !== \"cancelled\";\n\n/**\n * Observations for one batch.\n *\n * - `otelhook.sessions`: one per `session.start`.\n * - `otelhook.tool.calls`: one per `tool.end`.\n * - `gen_ai.client.operation.duration`: one per `generation.end` whose duration is\n * known, from the first source that has it:\n * 1. the duration the provider stated (`durationMillis`);\n * 2. a `generation.start` recorded by an *earlier* callback;\n * 3. the turn's start: the last `prompt.submitted` of the session, no later than\n * the end. For Claude Code and Codex a generation is a turn, so this is the\n * turn's wall-clock time, tool calls included.\n * A `generation.start` in the *same* batch as its end is not a start: an\n * adapter that emits both from one callback (Claude Code's `Stop`) synthesized\n * it, and measuring from it would record a zero.\n * - `gen_ai.client.token.usage`: per generation-scoped usage delta, one per token\n * type. A zero `cache_read` / `cache_creation` is not recorded: a provider that\n * never reports cache tokens would otherwise fill the low bucket with zeros.\n * `input` and `output` are always recorded, zero included, so the count of a\n * token histogram is the number of generations with usage.\n * - `otelhook.cost.usage`: per `generation.end` with a provider-reported USD cost.\n */\nexport const deriveMetricObservations = (\n input: DeriveMetricObservationsInput,\n): readonly MetricObservation[] => {\n const includeSessionId = input.includeSessionId ?? true;\n const observations: MetricObservation[] = [];\n const byId = new Map<string, CanonicalEvent>();\n const startsInBatch = new Map<string, GenerationStart>();\n for (const event of input.events) {\n byId.set(event.eventId, event);\n if (event.type === \"generation.start\") {\n startsInBatch.set(event.generationId, {\n startMillis: event.occurredAt,\n requestModel: event.model.modelId,\n });\n }\n }\n // Request model only: a start in this batch says what was asked for, but not when.\n const requestModelOf = (generationId: string): string | undefined =>\n startsInBatch.get(generationId)?.requestModel ?? input.generationStarts?.(generationId)?.requestModel;\n let lastPromptInBatch: Map<string, number> | undefined;\n for (const event of input.events) {\n if (event.type === \"prompt.submitted\") {\n lastPromptInBatch ??= new Map();\n lastPromptInBatch.set(event.sessionId, Math.max(lastPromptInBatch.get(event.sessionId) ?? 0, event.occurredAt));\n }\n }\n const measuredDurationOf = (end: GenerationEndEvent): number | undefined => {\n if (end.durationMillis !== undefined) {\n return end.durationMillis;\n }\n const recovered = startsInBatch.has(end.generationId) ? undefined : input.generationStarts?.(end.generationId);\n if (recovered !== undefined) {\n return end.occurredAt - recovered.startMillis;\n }\n const turn = lastPromptInBatch?.get(end.sessionId) ?? input.turnStart?.(end.sessionId);\n return turn === undefined || turn > end.occurredAt ? undefined : end.occurredAt - turn;\n };\n\n const push = (\n event: CanonicalEvent,\n instrument: MetricInstrumentName,\n value: number,\n attributes: Record<string, string | number | boolean>,\n ): void => {\n if (!Number.isFinite(value) || value < 0) {\n return;\n }\n observations.push({\n instrument,\n value,\n attributes: { ...commonAttributes(event, input.resource, includeSessionId), ...attributes },\n timeMillis: event.occurredAt,\n sessionId: event.sessionId,\n });\n };\n\n for (const event of input.events) {\n switch (event.type) {\n case \"session.start\":\n push(event, METRIC_SESSIONS, 1, { [ATTR_OTELHOOK_SESSION_KIND]: event.sessionKind });\n break;\n case \"tool.end\":\n push(event, METRIC_TOOL_CALLS, 1, {\n [ATTR_GEN_AI_TOOL_NAME]: event.toolName,\n [ATTR_OTELHOOK_OUTCOME]: event.outcome,\n });\n break;\n case \"generation.end\": {\n const attributes = generationAttributes(event, requestModelOf(event.generationId));\n const durationMillis = measuredDurationOf(event);\n if (durationMillis !== undefined && durationMillis >= 0) {\n push(event, METRIC_OPERATION_DURATION, durationMillis / 1000, {\n ...attributes,\n ...(isFailedOutcome(event.outcome) ? { [ATTR_ERROR_TYPE]: event.outcome } : {}),\n });\n }\n if (\n event.cost !== undefined &&\n event.cost.source === \"provider-reported\" &&\n event.cost.currency === \"USD\"\n ) {\n push(event, METRIC_COST_USAGE, event.cost.amount, attributes);\n }\n break;\n }\n default:\n break;\n }\n }\n\n for (const observation of input.usage) {\n if (observation.scope !== \"generation\") {\n // Session totals and subagent rollups restate generation spend; counting them\n // too would double it.\n continue;\n }\n const event = byId.get(observation.eventId);\n if (event?.type !== \"generation.end\") {\n continue;\n }\n const attributes = generationAttributes(event, requestModelOf(event.generationId));\n for (const [tokenType, read] of TOKEN_FIELDS) {\n const value = read(observation.delta);\n if (value === 0 && (tokenType === \"cache_read\" || tokenType === \"cache_creation\")) {\n continue;\n }\n push(event, METRIC_TOKEN_USAGE, value, { ...attributes, [ATTR_GEN_AI_TOKEN_TYPE]: tokenType });\n }\n }\n return observations;\n};\n\n/** Accumulated histogram state for one series. */\nexport type HistogramState = {\n readonly count: number;\n readonly sum: number;\n readonly min: number;\n readonly max: number;\n /** One more entry than the instrument's boundaries. */\n readonly bucketCounts: readonly number[];\n};\n\n/**\n * One OTLP data point, as plain JSON so it can be spooled.\n *\n * A point is self-describing: the instrument, its temporality, and its interval.\n * A cumulative point is a snapshot of a running total, so resending one (from a\n * spool) restates a value rather than adding to it.\n */\nexport type MetricPoint = {\n readonly instrument: MetricInstrumentName;\n readonly temporality: MetricsTemporality;\n readonly attributes: Readonly<Record<string, string | number | boolean>>;\n readonly startTimeMillis: number;\n readonly timeMillis: number;\n /** Counters. */\n readonly value?: number;\n /** Histograms. */\n readonly histogram?: HistogramState;\n};\n\nexport const emptyHistogram = (boundaries: readonly number[]): HistogramState => ({\n count: 0,\n sum: 0,\n min: Number.POSITIVE_INFINITY,\n max: Number.NEGATIVE_INFINITY,\n bucketCounts: new Array<number>(boundaries.length + 1).fill(0),\n});\n\n/** OTLP explicit buckets: bucket `i` holds values in `(boundaries[i-1], boundaries[i]]`. */\nexport const bucketIndex = (boundaries: readonly number[], value: number): number => {\n for (let index = 0; index < boundaries.length; index += 1) {\n const bound = boundaries[index];\n if (bound !== undefined && value <= bound) {\n return index;\n }\n }\n return boundaries.length;\n};\n\nexport const recordIntoHistogram = (\n state: HistogramState,\n boundaries: readonly number[],\n value: number,\n): HistogramState => {\n const bucketCounts = [...state.bucketCounts];\n const index = bucketIndex(boundaries, value);\n bucketCounts[index] = (bucketCounts[index] ?? 0) + 1;\n return {\n count: state.count + 1,\n sum: state.sum + value,\n min: Math.min(state.min, value),\n max: Math.max(state.max, value),\n bucketCounts,\n };\n};\n\n/**\n * Stable identity of a series: instrument plus sorted attributes.\n *\n * Used as a map key and, digested, as a state key. JSON of sorted entries is\n * unambiguous where a joined string would not be.\n */\nexport const seriesIdentity = (\n instrument: MetricInstrumentName,\n attributes: Readonly<Record<string, string | number | boolean>>,\n): string =>\n JSON.stringify([\n instrument,\n Object.entries(attributes).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),\n ]);\n\n/**\n * Delta points for one batch: observations of the same series folded together,\n * over the interval from the earliest observation to `nowMillis`.\n */\nexport const aggregateDeltaPoints = (\n observations: readonly MetricObservation[],\n nowMillis: number,\n): readonly MetricPoint[] => {\n const series = new Map<\n string,\n { observation: MetricObservation; start: number; value: number; histogram?: HistogramState }\n >();\n for (const observation of observations) {\n const instrument = METRIC_INSTRUMENTS[observation.instrument];\n const key = seriesIdentity(observation.instrument, observation.attributes);\n const existing =\n series.get(key) ??\n ({\n observation,\n start: observation.timeMillis,\n value: 0,\n ...(instrument.boundaries === undefined ? {} : { histogram: emptyHistogram(instrument.boundaries) }),\n });\n existing.start = Math.min(existing.start, observation.timeMillis);\n if (existing.histogram !== undefined && instrument.boundaries !== undefined) {\n existing.histogram = recordIntoHistogram(existing.histogram, instrument.boundaries, observation.value);\n } else {\n existing.value += observation.value;\n }\n series.set(key, existing);\n }\n return [...series.values()].map((entry) => ({\n instrument: entry.observation.instrument,\n temporality: \"delta\",\n attributes: entry.observation.attributes,\n startTimeMillis: Math.min(entry.start, nowMillis),\n timeMillis: Math.max(nowMillis, entry.start),\n ...(entry.histogram === undefined ? { value: entry.value } : { histogram: entry.histogram }),\n }));\n};\n\n/** Data-point attribute keys that must never appear on a metric. */\nexport const FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES: readonly string[] = Object.freeze([\n \"user.\",\n \"enduser.\",\n \"organization.\",\n]);\n\n/** Strip anything account-shaped from attributes, as a last line of defence. */\nexport const withoutAccountIdentity = (attributes: Attributes): Attributes =>\n Object.fromEntries(\n Object.entries(attributes).filter(\n ([key]) => !FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES.some((prefix) => key.startsWith(prefix)),\n ),\n );\n","import type { Attributes } from \"@opentelemetry/api\";\n\nimport type { Clock, Logger } from \"../runtime/ports.js\";\nimport type { StoreNamespace } from \"../state/keys.js\";\nimport { isMetricInstrumentName, METRIC_INSTRUMENTS, type MetricPoint } from \"./metric-model.js\";\nimport {\n createSpoolQueue,\n type SpoolDrainResult,\n type SpoolEnqueueResult,\n type SpoolOverflowPolicy,\n type SpoolSendOutcome,\n type SpoolStats,\n type SpoolValidation,\n} from \"./spool-queue.js\";\n\n/**\n * A batch of metric points a destination could not take, kept for the next\n * invocation.\n *\n * Points are plain JSON (`MetricPoint`), so a batch replays without the process\n * that recorded it. A cumulative point is a snapshot of a running total: replaying\n * an old one after a newer one was delivered restates an earlier value with an\n * earlier timestamp, which a receiver orders by time rather than adding.\n */\nexport type MetricSpoolBatch = {\n readonly providerId: string;\n readonly installationId: string;\n readonly resourceAttributes: Attributes;\n readonly instrumentationScope: { readonly name: string; readonly version?: string };\n readonly points: readonly MetricPoint[];\n readonly enqueuedAt: number;\n};\n\nexport const MAX_SPOOLED_METRIC_POINTS_PER_BATCH = 4_096;\nconst MAX_STRING_LENGTH = 8_192;\nconst MAX_ATTRIBUTES_PER_POINT = 64;\nconst MAX_BUCKETS = 64;\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isFiniteNonNegative = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n\nconst isBoundedString = (value: unknown): value is string =>\n typeof value === \"string\" && value.length > 0 && value.length <= MAX_STRING_LENGTH;\n\nconst isPrimitiveAttribute = (value: unknown): boolean =>\n (typeof value === \"string\" && value.length <= MAX_STRING_LENGTH) ||\n (typeof value === \"number\" && Number.isFinite(value)) ||\n typeof value === \"boolean\";\n\n/**\n * Whether one spooled point can be replayed. A spool file is untrusted input, and\n * a malformed point would otherwise fail inside the OTLP encoder, where it reads\n * as an unreachable collector and wedges the queue head.\n */\nconst isReplayablePoint = (value: unknown): value is MetricPoint => {\n if (!isPlainObject(value) || !isMetricInstrumentName(value.instrument)) {\n return false;\n }\n if (value.temporality !== \"cumulative\" && value.temporality !== \"delta\") {\n return false;\n }\n if (!isFiniteNonNegative(value.startTimeMillis) || !isFiniteNonNegative(value.timeMillis)) {\n return false;\n }\n if (!isPlainObject(value.attributes)) {\n return false;\n }\n const entries = Object.entries(value.attributes);\n if (entries.length > MAX_ATTRIBUTES_PER_POINT || !entries.every(([, item]) => isPrimitiveAttribute(item))) {\n return false;\n }\n const instrument = METRIC_INSTRUMENTS[value.instrument];\n if (instrument.kind === \"counter\") {\n return isFiniteNonNegative(value.value) && value.histogram === undefined;\n }\n const histogram = value.histogram;\n if (!isPlainObject(histogram) || value.value !== undefined) {\n return false;\n }\n const buckets = histogram.bucketCounts;\n return (\n isFiniteNonNegative(histogram.count) &&\n Number.isInteger(histogram.count) &&\n isFiniteNonNegative(histogram.sum) &&\n typeof histogram.min === \"number\" &&\n typeof histogram.max === \"number\" &&\n Array.isArray(buckets) &&\n buckets.length <= MAX_BUCKETS &&\n buckets.length === (instrument.boundaries?.length ?? 0) + 1 &&\n buckets.every((count) => isFiniteNonNegative(count) && Number.isInteger(count))\n );\n};\n\nexport const validateMetricSpoolBatch = (\n value: unknown,\n identity: StoreNamespace,\n): SpoolValidation<MetricSpoolBatch> => {\n if (!isPlainObject(value)) {\n return { rejection: \"not-an-object\" };\n }\n if (value.providerId !== identity.providerId || value.installationId !== identity.installationId) {\n return { rejection: \"identity-mismatch\" };\n }\n if (!isPlainObject(value.resourceAttributes)) {\n return { rejection: \"resource-attributes-invalid\" };\n }\n if (!isPlainObject(value.instrumentationScope) || !isBoundedString(value.instrumentationScope.name)) {\n return { rejection: \"instrumentation-scope-invalid\" };\n }\n if (\n value.instrumentationScope.version !== undefined &&\n typeof value.instrumentationScope.version !== \"string\"\n ) {\n return { rejection: \"instrumentation-scope-invalid\" };\n }\n if (\n !Array.isArray(value.points) ||\n value.points.length === 0 ||\n value.points.length > MAX_SPOOLED_METRIC_POINTS_PER_BATCH\n ) {\n return { rejection: \"points-invalid\" };\n }\n if (!value.points.every(isReplayablePoint)) {\n return { rejection: \"point-field-invalid\" };\n }\n if (!isFiniteNonNegative(value.enqueuedAt)) {\n return { rejection: \"not-an-object\" };\n }\n return { batch: value as unknown as MetricSpoolBatch };\n};\n\nexport interface DurableMetricSpool {\n enqueue(batch: MetricSpoolBatch): Promise<SpoolEnqueueResult>;\n drain(\n send: (batch: MetricSpoolBatch) => Promise<SpoolSendOutcome>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\n stats?(): Promise<SpoolStats>;\n}\n\nexport type DurableMetricSpoolOptions = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n readonly maxSpoolFiles?: number;\n /** Queue directory below the identity namespace. Default `spool-metrics`. */\n readonly queueName?: string;\n readonly maxBytes?: number;\n readonly maxAgeMillis?: number;\n readonly overflow?: SpoolOverflowPolicy;\n};\n\nexport const DEFAULT_MAX_METRIC_SPOOL_FILES = 500;\n\n/** Durable queue for metric batches, in its own directory beside the trace and log spools. */\nexport const createFileDurableMetricSpool = (options: DurableMetricSpoolOptions): DurableMetricSpool =>\n createSpoolQueue<MetricSpoolBatch>({\n rootDir: options.rootDir,\n providerId: options.providerId,\n installationId: options.installationId,\n clock: options.clock,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_METRIC_SPOOL_FILES,\n queueName: options.queueName ?? \"spool-metrics\",\n ...(options.maxBytes === undefined ? {} : { maxBytes: options.maxBytes }),\n ...(options.maxAgeMillis === undefined ? {} : { maxAgeMillis: options.maxAgeMillis }),\n ...(options.overflow === undefined ? {} : { overflow: options.overflow }),\n validate: validateMetricSpoolBatch,\n });\n","import { ValueType } from \"@opentelemetry/api\";\nimport { ExportResultCode, millisToHrTime, type ExportResult, type InstrumentationScope } from \"@opentelemetry/core\";\nimport { OTLPMetricExporter } from \"@opentelemetry/exporter-metrics-otlp-proto\";\nimport { resourceFromAttributes, type Resource } from \"@opentelemetry/resources\";\nimport {\n AggregationTemporality,\n DataPointType,\n type MetricData,\n type ResourceMetrics,\n} from \"@opentelemetry/sdk-metrics\";\n\nimport { siblingSignalEndpoint } from \"../config/otlp-endpoint.js\";\nimport type { ExporterPolicy } from \"../config/schema.js\";\nimport { createHealthTracker, type DeliveryHealthSnapshot } from \"../diagnostics/health.js\";\nimport { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { Clock, Logger } from \"../runtime/ports.js\";\nimport type { DurableMetricSpool, MetricSpoolBatch } from \"./durable-metric-spool.js\";\nimport { isPermanentExportFailure } from \"./export-failure.js\";\nimport { replayResource, resourceFromExporterPolicy, resourceWithContext } from \"./exporter-resource.js\";\nimport { METRIC_INSTRUMENTS, withoutAccountIdentity, type MetricPoint } from \"./metric-model.js\";\nimport { DEFAULT_INSTRUMENTATION_SCOPE } from \"./semconv.js\";\nimport type { SpoolSendOutcome } from \"./spool-queue.js\";\n\n/**\n * OTLP HTTP/protobuf sink for hook-derived metrics (issue #69).\n *\n * Unlike the trace and log sinks, it does not take canonical events: the points it\n * sends are already aggregated (see `metric-model.ts` and\n * `lifecycle/metric-series.ts`), because cumulative aggregation needs state the\n * telemetry layer must not own. This module only encodes, sends, spools what a\n * destination could not take, and replays the spool on flush.\n *\n * There is deliberately no `MeterProvider` and no periodic reader. A hook process\n * lives for one callback; a reader that collects on an interval would either never\n * fire or hold the process open. Points are exported once, right after the\n * callback's telemetry, inside the same bounded flush window.\n *\n * Fails open like the other sinks: every failure is a diagnostic, never a throw.\n */\n\nexport type MetricsEndpointResolution =\n | { readonly endpoint: string; readonly derived: boolean }\n | { readonly unresolvable: \"no-endpoint\" };\n\n/**\n * Where metric points are posted: `metrics.endpoint` as stated, else the traces\n * endpoint with `/v1/traces` swapped for `/v1/metrics` (or `/v1/metrics` appended\n * to a base URL).\n */\nexport const resolveMetricsEndpoint = (exporter: ExporterPolicy): MetricsEndpointResolution => {\n const stated = exporter.metrics?.endpoint;\n if (stated !== undefined) {\n return { endpoint: stated, derived: false };\n }\n if (exporter.endpoint === undefined) {\n return { unresolvable: \"no-endpoint\" };\n }\n return { endpoint: siblingSignalEndpoint(exporter.endpoint, \"metrics\"), derived: true };\n};\n\nexport type MetricsDeliverability =\n | { readonly status: \"configured\"; readonly endpoint: string; readonly derivedEndpoint: boolean }\n | {\n readonly status: \"disabled\";\n readonly reason:\n | \"metrics-disabled\"\n | \"exporter-disabled\"\n | \"protocol-none\"\n | \"protocol-unsupported\"\n | \"no-endpoint\";\n };\n\nexport const describeMetricsDeliverability = (exporter: ExporterPolicy): MetricsDeliverability => {\n if (exporter.metrics?.enabled !== true) {\n return { status: \"disabled\", reason: \"metrics-disabled\" };\n }\n if (!exporter.enabled) {\n return { status: \"disabled\", reason: \"exporter-disabled\" };\n }\n if (exporter.protocol === \"none\") {\n return { status: \"disabled\", reason: \"protocol-none\" };\n }\n if (exporter.protocol !== \"http/protobuf\") {\n return { status: \"disabled\", reason: \"protocol-unsupported\" };\n }\n const resolved = resolveMetricsEndpoint(exporter);\n if (\"unresolvable\" in resolved) {\n return { status: \"disabled\", reason: \"no-endpoint\" };\n }\n return { status: \"configured\", endpoint: resolved.endpoint, derivedEndpoint: resolved.derived };\n};\n\nconst DISABLED_DETAIL: Readonly<\n Record<Exclude<Extract<MetricsDeliverability, { status: \"disabled\" }>[\"reason\"], \"metrics-disabled\">, string>\n> = Object.freeze({\n \"exporter-disabled\": \"otlp metric sink disabled: the exporter is disabled\",\n \"protocol-none\": \"otlp metric sink disabled: protocol is none\",\n \"protocol-unsupported\": \"otlp metric sink disabled: protocol not supported by this build\",\n \"no-endpoint\": \"otlp metric sink disabled: no metrics endpoint configured and none could be derived\",\n});\n\nexport type MetricExportResult = {\n /** Points delivered or spooled. */\n readonly accepted: number;\n readonly rejected: number;\n readonly errors: readonly OtelHookErrorInfo[];\n};\n\nexport interface OtlpMetricTelemetrySink {\n /** Whether this sink sends anything. A disabled sink accepts nothing and reports nothing. */\n readonly enabled: boolean;\n /**\n * `context`: the session context the points' events agree on (see\n * `agreedContextAttributes`). It overrides the same keys on the Resource for\n * this export, as the trace and log sinks do; the points carry it already.\n */\n exportPoints(\n points: readonly MetricPoint[],\n context?: Readonly<Record<string, string | number | boolean>>,\n ): Promise<MetricExportResult>;\n /** Replays spooled batches; bounded, best-effort, never throws. */\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n health(): DeliveryHealthSnapshot;\n drainSpool(\n maxBatches?: number,\n ): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }>;\n}\n\nexport type OtlpMetricSinkOptions = {\n readonly exporter: ExporterPolicy;\n readonly headers?: Readonly<Record<string, string>>;\n readonly providerId: string;\n readonly installationId: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n readonly spool?: DurableMetricSpool;\n readonly instrumentationScope?: InstrumentationScope;\n /** Export destination this sink delivers to. */\n readonly destination?: string;\n};\n\nconst createDisabledMetricSink = (destination?: string): OtlpMetricTelemetrySink => {\n const health = createHealthTracker(\n \"telemetry-metric-sink\",\n destination === undefined ? {} : { destination },\n );\n return {\n enabled: false,\n exportPoints: (): Promise<MetricExportResult> => Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),\n flush: (): Promise<void> => Promise.resolve(),\n shutdown: (): Promise<void> => Promise.resolve(),\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool: (): Promise<{\n readonly drained: number;\n readonly remaining: number;\n readonly failed: number;\n }> => Promise.resolve({ drained: 0, remaining: 0, failed: 0 }),\n };\n};\n\n/** A sink for a destination that does not take metrics, or a build with metrics off. */\nexport const createDisabledOtlpMetricSink = createDisabledMetricSink;\n\nconst toMetricData = (points: readonly MetricPoint[]): MetricData[] => {\n const byInstrument = new Map<string, MetricPoint[]>();\n for (const point of points) {\n const key = `${point.instrument}|${point.temporality}`;\n const group = byInstrument.get(key) ?? [];\n group.push(point);\n byInstrument.set(key, group);\n }\n const metrics: MetricData[] = [];\n for (const group of byInstrument.values()) {\n const first = group[0];\n if (first === undefined) {\n continue;\n }\n const instrument = METRIC_INSTRUMENTS[first.instrument];\n const descriptor = {\n name: instrument.name,\n description: instrument.description,\n unit: instrument.unit,\n valueType: instrument.valueType === \"int\" ? ValueType.INT : ValueType.DOUBLE,\n };\n const aggregationTemporality =\n first.temporality === \"cumulative\" ? AggregationTemporality.CUMULATIVE : AggregationTemporality.DELTA;\n const times = (point: MetricPoint): { startTime: [number, number]; endTime: [number, number] } => ({\n startTime: millisToHrTime(point.startTimeMillis),\n endTime: millisToHrTime(point.timeMillis),\n });\n if (instrument.kind === \"counter\") {\n metrics.push({\n descriptor,\n aggregationTemporality,\n dataPointType: DataPointType.SUM,\n isMonotonic: true,\n dataPoints: group.map((point) => ({\n ...times(point),\n attributes: { ...point.attributes },\n value: point.value ?? 0,\n })),\n });\n continue;\n }\n metrics.push({\n descriptor,\n aggregationTemporality,\n dataPointType: DataPointType.HISTOGRAM,\n dataPoints: group.map((point) => {\n const histogram = point.histogram;\n return {\n ...times(point),\n attributes: { ...point.attributes },\n value: {\n buckets: {\n boundaries: [...(instrument.boundaries ?? [])],\n counts: [...(histogram?.bucketCounts ?? [])],\n },\n count: histogram?.count ?? 0,\n sum: histogram?.sum ?? 0,\n ...(histogram === undefined || histogram.count === 0\n ? {}\n : { min: histogram.min, max: histogram.max }),\n },\n };\n }),\n });\n }\n return metrics;\n};\n\nexport const createOtlpMetricSink = (options: OtlpMetricSinkOptions): OtlpMetricTelemetrySink => {\n const destinationFields =\n options.destination === undefined ? {} : { \"export.destination\": options.destination };\n const deliverability = describeMetricsDeliverability(options.exporter);\n if (deliverability.status === \"disabled\") {\n if (deliverability.reason !== \"metrics-disabled\") {\n options.logger?.warn(DISABLED_DETAIL[deliverability.reason], {\n \"exporter.protocol\": options.exporter.protocol,\n ...destinationFields,\n });\n }\n return createDisabledMetricSink(options.destination);\n }\n\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n // No account identity on any metric, even if an operator put it on the resource.\n const resource = resourceFromAttributes(\n withoutAccountIdentity(resourceFromExporterPolicy(options.exporter).attributes),\n );\n const health = createHealthTracker(\n \"telemetry-metric-sink\",\n options.destination === undefined ? {} : { destination: options.destination },\n );\n const exporter = new OTLPMetricExporter({\n url: deliverability.endpoint,\n headers: { ...options.headers },\n timeoutMillis: options.exporter.timeoutMillis,\n });\n let shutdownCompleted = false;\n\n const exportResourceMetrics = (\n points: readonly MetricPoint[],\n batchResource: Resource,\n batchScope: InstrumentationScope,\n ): Promise<ExportResult> =>\n new Promise((resolve) => {\n const payload: ResourceMetrics = {\n resource: batchResource,\n scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }],\n };\n try {\n exporter.export(payload, (result: ExportResult) => resolve(result));\n } catch (thrown) {\n resolve({\n code: ExportResultCode.FAILED,\n error: thrown instanceof Error ? thrown : new Error(\"export threw\"),\n });\n }\n });\n\n const toSpoolBatch = (points: readonly MetricPoint[], batchResource: Resource): MetricSpoolBatch => ({\n providerId: options.providerId,\n installationId: options.installationId,\n resourceAttributes: { ...batchResource.attributes },\n instrumentationScope: {\n name: scope.name,\n ...(scope.version === undefined ? {} : { version: scope.version }),\n },\n points: points.map((point) => ({ ...point })),\n enqueuedAt: options.clock.now(),\n });\n\n const sendSerializedBatch = async (batch: MetricSpoolBatch): Promise<SpoolSendOutcome> => {\n const batchResource = resourceFromAttributes(\n withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes),\n );\n const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);\n if (result.code === ExportResultCode.SUCCESS) {\n return true;\n }\n return isPermanentExportFailure(result) ? \"discard\" : false;\n };\n\n const exportPoints = async (\n points: readonly MetricPoint[],\n context?: Readonly<Record<string, string | number | boolean>>,\n ): Promise<MetricExportResult> => {\n if (points.length === 0) {\n return { accepted: 0, rejected: 0, errors: [] };\n }\n const batchResource = context === undefined ? resource : resourceWithContext(resource, context);\n const result = await exportResourceMetrics(points, batchResource, scope);\n if (result.code === ExportResultCode.SUCCESS) {\n health.recordSuccess(points.length, options.clock.now());\n return { accepted: points.length, rejected: 0, errors: [] };\n }\n health.recordFailure(\"telemetry-export-failure\", points.length, options.clock.now());\n const permanent = isPermanentExportFailure(result);\n if (options.spool !== undefined && !permanent) {\n const spooled = await options.spool.enqueue(toSpoolBatch(points, batchResource)).catch(() => ({\n spooled: false as const,\n reason: \"capacity-exceeded\" as const,\n }));\n if (spooled.spooled) {\n options.logger?.warn(\"metric batch not delivered; spooled for the next invocation\", {\n \"export.batch_size\": points.length,\n ...destinationFields,\n });\n return { accepted: points.length, rejected: 0, errors: [] };\n }\n }\n return {\n accepted: 0,\n rejected: points.length,\n errors: [\n createErrorInfo({\n code: \"telemetry-export-failure\",\n phase: \"export\",\n detail: permanent\n ? \"collector refused a metric batch with a non-retryable status\"\n : \"collector rejected or was unreachable for a metric batch\",\n details: {\n \"export.batch_size\": points.length,\n \"export.signal\": \"metrics\",\n ...destinationFields,\n },\n }),\n ],\n };\n };\n\n const drainSpool = async (\n maxBatches?: number,\n ): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }> => {\n if (options.spool === undefined) {\n return { drained: 0, remaining: 0, failed: 0 };\n }\n const result = await options.spool.drain(sendSerializedBatch, {\n ...(maxBatches === undefined ? {} : { maxBatches }),\n });\n if (result.drained > 0) {\n health.recordSuccess(result.drained, options.clock.now());\n }\n return result;\n };\n\n const flush = async (): Promise<void> => {\n try {\n await exporter.forceFlush();\n } catch {\n // Best-effort; reported through health.\n }\n await drainSpool().catch(() => undefined);\n };\n\n const shutdown = async (): Promise<void> => {\n if (shutdownCompleted) {\n return;\n }\n shutdownCompleted = true;\n await flush();\n try {\n await exporter.shutdown();\n } catch {\n // Idempotent and non-throwing.\n }\n };\n\n return {\n enabled: true,\n exportPoints,\n flush,\n shutdown,\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool,\n };\n};\n","import {\n DEFAULT_DESTINATION_NAME,\n effectiveSpoolPolicy,\n hasConfiguredDestinations,\n resolveDestinationHeaders,\n resolveExportDestinations,\n type ExportDestination,\n} from \"../config/destinations.js\";\nimport { siblingSignalEndpoint } from \"../config/otlp-endpoint.js\";\nimport { effectiveMetricsPolicy, type ExporterPolicy } from \"../config/schema.js\";\nimport type { DeliveryHealthSnapshot } from \"../diagnostics/health.js\";\nimport { createHealthTracker } from \"../diagnostics/health.js\";\nimport { errorInfoFromThrown, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { Clock, Logger, TelemetryEmitResult } from \"../runtime/ports.js\";\nimport { createFileDurableLogSpool, type DurableLogSpool } from \"./durable-log-spool.js\";\nimport { createFileDurableMetricSpool, type DurableMetricSpool } from \"./durable-metric-spool.js\";\nimport { createFileDurableSpool, type DurableSpool } from \"./durable-spool.js\";\nimport type { LogContentPolicy } from \"./log-records.js\";\nimport {\n createOtlpLogSink,\n resolveLogsEndpoint,\n type OtlpLogTelemetrySink,\n} from \"./otlp-log-sink.js\";\nimport {\n createDisabledOtlpMetricSink,\n createOtlpMetricSink,\n type OtlpMetricTelemetrySink,\n} from \"./otlp-metric-sink.js\";\nimport { createOtlpTraceSink, type OtlpTelemetrySink } from \"./otlp-sink.js\";\nimport type { SpanCorrelationResolver } from \"./semconv.js\";\nimport { createSignalFanout, type SignalFanoutSink } from \"./signal-fanout.js\";\n\n/**\n * Spool queue directories for one destination, below the identity namespace.\n *\n * `default` keeps the directories it has always had, so batches an earlier\n * version queued are still drained after an upgrade. Every other destination\n * queues under `destinations/<name>/`, so one destination's outage can never\n * consume another's budget or be drained by another's sender.\n */\nexport const spoolQueueNamesFor = (\n destination: string,\n): { readonly traces: string; readonly logs: string; readonly metrics: string } =>\n destination === DEFAULT_DESTINATION_NAME\n ? { traces: \"spool\", logs: \"spool-logs\", metrics: \"spool-metrics\" }\n : {\n traces: `destinations/${destination}/spool`,\n logs: `destinations/${destination}/spool-logs`,\n metrics: `destinations/${destination}/spool-metrics`,\n };\n\n/**\n * The exporter policy one destination's sinks are built from.\n *\n * Everything but where and how to send — timeout, batch sizes, service identity,\n * resource attributes, log content policy — is shared, so every destination\n * receives the same spans. The `default` destination gets the policy unchanged.\n */\nexport const exporterPolicyForDestination = (\n exporter: ExporterPolicy,\n destination: ExportDestination,\n): ExporterPolicy => {\n if (destination.source === \"exporter\") {\n return exporter;\n }\n const { destinations, endpoint, logs, ...shared } = exporter;\n void destinations;\n void endpoint;\n const tracesEndpoint = destination.tracesEndpoint ?? destination.endpoint;\n // An explicit logs URL wins; otherwise derive from `endpoint` (not from a\n // traces-only override), and failing that let the sink derive from the traces URL.\n const derivedLogs =\n destination.logsEndpoint ??\n (destination.endpoint === undefined\n ? undefined\n : (() => {\n const derived = resolveLogsEndpoint({\n ...exporter,\n endpoint: destination.endpoint,\n logs: { enabled: true, includeContent: false, maxBatchSize: logs.maxBatchSize },\n });\n return \"endpoint\" in derived ? derived.endpoint : undefined;\n })());\n const { metrics: sharedMetrics, ...rest } = shared;\n // Like logs: an explicit metrics URL wins; otherwise derive from `endpoint`, and\n // failing that let the sink derive from the traces URL.\n const derivedMetrics =\n destination.metricsEndpoint ??\n (destination.endpoint === undefined\n ? undefined\n : siblingSignalEndpoint(destination.endpoint, \"metrics\"));\n return {\n ...rest,\n protocol: destination.protocol,\n ...(tracesEndpoint === undefined ? {} : { endpoint: tracesEndpoint }),\n headerNames: Object.keys(destination.headers).sort(),\n logs: {\n ...logs,\n enabled: destination.signals.logs,\n ...(derivedLogs === undefined ? {} : { endpoint: derivedLogs }),\n },\n metrics: {\n ...effectiveMetricsPolicy({ ...exporter, metrics: sharedMetrics }),\n enabled: destination.signals.metrics,\n ...(derivedMetrics === undefined ? {} : { endpoint: derivedMetrics }),\n },\n };\n};\n\n/** The pair of sinks, and their spools, serving one destination. */\nexport type ExportDestinationSinks = {\n readonly name: string;\n readonly traces: OtlpTelemetrySink;\n readonly logs: OtlpLogTelemetrySink;\n readonly spool?: DurableSpool;\n readonly logSpool?: DurableLogSpool;\n /** Hook-derived metrics; a disabled sink unless this destination takes `metrics`. */\n readonly metrics: OtlpMetricTelemetrySink;\n readonly metricSpool?: DurableMetricSpool;\n};\n\n/** A destination left out of this invocation, and why — by name only. */\nexport type SkippedExportDestination = {\n readonly name: string;\n readonly reason: \"header-variable-missing\";\n /** Environment variable *names*; never a value. */\n readonly missingVariables: readonly string[];\n};\n\nexport type ExportDestinationsOptions = {\n readonly exporter: ExporterPolicy;\n /**\n * Header values for the `default` destination's traces: `--header` over\n * `OTEL_EXPORTER_OTLP_TRACES_HEADERS` over `OTEL_EXPORTER_OTLP_HEADERS`, as\n * resolved by `resolveOtlpHeaders`.\n */\n readonly defaultHeaders?: Readonly<Record<string, string>>;\n /**\n * Header values for the `default` destination's logs, when they differ from\n * its traces' (`OTEL_EXPORTER_OTLP_LOGS_HEADERS`). Defaults to {@link defaultHeaders}.\n */\n readonly defaultLogHeaders?: Readonly<Record<string, string>>;\n /**\n * The environment `env:` header references resolve against. Never read\n * implicitly; without it, a destination whose headers reference a variable is\n * skipped and reported.\n */\n readonly headerEnvironment?: Readonly<Record<string, string | undefined>>;\n readonly providerId: string;\n readonly installationId: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Root of the spool trees. Absent, nothing is spooled. */\n readonly spoolRootDir?: string;\n /** Whether the logs signal gets a spool at all; it is only built when logs are on. */\n readonly logContent: LogContentPolicy;\n readonly correlate?: SpanCorrelationResolver;\n};\n\n/**\n * A trace sink for a destination that does not take the traces signal.\n *\n * Contributes zero accepted and zero rejected — unlike a *disabled exporter*,\n * which accepts everything — because the counts decide commit-or-retry and a\n * signal that never tried must not make a real loss elsewhere look delivered.\n */\nconst createOptedOutTraceSink = (destination: string | undefined): OtlpTelemetrySink => {\n const health = createHealthTracker(\n \"telemetry-sink\",\n destination === undefined ? {} : { destination },\n );\n return {\n emit: (): Promise<TelemetryEmitResult> =>\n Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),\n flush: (): Promise<void> => Promise.resolve(),\n shutdown: (): Promise<void> => Promise.resolve(),\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool: (): Promise<{\n readonly drained: number;\n readonly remaining: number;\n readonly failed: number;\n }> => Promise.resolve({ drained: 0, remaining: 0, failed: 0 }),\n };\n};\n\n/**\n * Build one sink pair per enabled destination.\n *\n * With no `exporter.destinations`, this is exactly the single `default`\n * destination the runtime has always built: the same policy, the same header\n * values, the same spool directories.\n */\nexport const createExportDestinationSinks = (\n options: ExportDestinationsOptions,\n): {\n readonly destinations: readonly ExportDestinationSinks[];\n readonly skipped: readonly SkippedExportDestination[];\n} => {\n const labelled = hasConfiguredDestinations(options.exporter);\n const spoolPolicy = effectiveSpoolPolicy(options.exporter);\n const destinations: ExportDestinationSinks[] = [];\n const skipped: SkippedExportDestination[] = [];\n\n for (const destination of resolveExportDestinations(options.exporter)) {\n let headers: Readonly<Record<string, string>> | undefined;\n let logHeaders: Readonly<Record<string, string>> | undefined;\n if (destination.source === \"exporter\") {\n headers = options.defaultHeaders;\n logHeaders = options.defaultLogHeaders ?? options.defaultHeaders;\n } else {\n const resolved = resolveDestinationHeaders(destination.headers, options.headerEnvironment);\n if (resolved.missingVariables.length > 0) {\n // Sending without the header would be refused at best, and at worst\n // accepted into somebody else's unauthenticated tenant. So the destination\n // sits this invocation out, and says which variable it is waiting for.\n options.logger?.warn(\"export destination skipped: a header references an unset environment variable\", {\n \"export.destination\": destination.name,\n \"config.variables\": [...resolved.missingVariables],\n });\n skipped.push({\n name: destination.name,\n reason: \"header-variable-missing\",\n missingVariables: resolved.missingVariables,\n });\n continue;\n }\n headers = resolved.values;\n logHeaders = resolved.values;\n }\n\n const label = labelled ? destination.name : undefined;\n const policy = exporterPolicyForDestination(options.exporter, destination);\n const queues = spoolQueueNamesFor(destination.name);\n const bounds = {\n maxSpoolFiles: spoolPolicy.maxBatches,\n maxBytes: spoolPolicy.maxBytes,\n maxAgeMillis: spoolPolicy.maxAgeMillis,\n overflow: \"drop-oldest\" as const,\n };\n const shared = {\n providerId: options.providerId,\n installationId: options.installationId,\n clock: options.clock,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n };\n const spool =\n options.spoolRootDir === undefined || !destination.signals.traces\n ? undefined\n : createFileDurableSpool({\n rootDir: options.spoolRootDir,\n ...shared,\n ...bounds,\n queueName: queues.traces,\n });\n // Only built when logs are on: a default installation must not create a\n // directory for a signal it never emits.\n const logSpool =\n options.spoolRootDir === undefined || !destination.signals.logs\n ? undefined\n : createFileDurableLogSpool({\n rootDir: options.spoolRootDir,\n ...shared,\n ...bounds,\n queueName: queues.logs,\n });\n\n const metricSpool =\n options.spoolRootDir === undefined || !destination.signals.metrics\n ? undefined\n : createFileDurableMetricSpool({\n rootDir: options.spoolRootDir,\n ...shared,\n ...bounds,\n queueName: queues.metrics,\n });\n\n const sinkShared = {\n exporter: policy,\n ...shared,\n ...(options.correlate === undefined ? {} : { correlate: options.correlate }),\n ...(label === undefined ? {} : { destination: label }),\n };\n const traces = destination.signals.traces\n ? createOtlpTraceSink({\n ...sinkShared,\n ...(headers === undefined || Object.keys(headers).length === 0 ? {} : { headers }),\n ...(spool === undefined ? {} : { spool }),\n })\n : createOptedOutTraceSink(label);\n const logs = createOtlpLogSink({\n ...sinkShared,\n ...(logHeaders === undefined || Object.keys(logHeaders).length === 0\n ? {}\n : { headers: logHeaders }),\n ...(logSpool === undefined ? {} : { spool: logSpool }),\n content: options.logContent,\n });\n const metrics = destination.signals.metrics\n ? createOtlpMetricSink({\n exporter: policy,\n ...shared,\n ...(label === undefined ? {} : { destination: label }),\n ...(headers === undefined || Object.keys(headers).length === 0 ? {} : { headers }),\n ...(metricSpool === undefined ? {} : { spool: metricSpool }),\n })\n : createDisabledOtlpMetricSink(label);\n destinations.push({\n name: destination.name,\n traces,\n logs,\n metrics,\n ...(spool === undefined ? {} : { spool }),\n ...(logSpool === undefined ? {} : { logSpool }),\n ...(metricSpool === undefined ? {} : { metricSpool }),\n });\n }\n return { destinations, skipped };\n};\n\n/**\n * One canonical batch, every destination, in parallel.\n *\n * Each destination is its own {@link createSignalFanout} (traces then logs, which\n * must stay sequential so they share one correlation resolution); destinations run\n * concurrently, each bounded by the exporter's own timeout, so a slow or dead\n * destination costs at most that timeout and never another destination's delivery.\n * A destination that throws is contained to a rejection of its own share.\n *\n * Counts are summed across destinations, which gives the durability decision the\n * right inputs: everything delivered or spooled → `delivered`; nothing → `lost`\n * and safe to retry; some → `partial`, terminal, because retrying would re-export\n * to the destinations that already accepted.\n *\n * With one destination this returns that destination's fanout unchanged.\n */\nexport const createDestinationFanout = (\n destinations: readonly ExportDestinationSinks[],\n): SignalFanoutSink => {\n const fanouts = destinations.map((destination) => ({\n name: destination.name,\n sink: createSignalFanout({ traces: destination.traces, logs: destination.logs }),\n }));\n const only = fanouts.length === 1 ? fanouts[0] : undefined;\n if (only !== undefined) {\n return only.sink;\n }\n\n const emit = async (events: readonly CanonicalEvent[]): Promise<TelemetryEmitResult> => {\n const results = await Promise.all(\n fanouts.map((fanout) =>\n fanout.sink.emit(events).catch(\n (thrown: unknown): TelemetryEmitResult => ({\n accepted: 0,\n rejected: events.length,\n errors: [errorInfoFromThrown(thrown, { code: \"telemetry-export-failure\", phase: \"export\" })],\n }),\n ),\n ),\n );\n const errors: OtelHookErrorInfo[] = results.flatMap((result) => result.errors);\n return {\n accepted: results.reduce((sum, result) => sum + result.accepted, 0),\n rejected: results.reduce((sum, result) => sum + result.rejected, 0),\n errors,\n };\n };\n\n const settleAll = async (run: (sink: SignalFanoutSink) => Promise<void>): Promise<void> => {\n await Promise.all(fanouts.map((fanout) => run(fanout.sink).catch(() => undefined)));\n };\n\n return {\n emit,\n // Each destination drains its own spool in its flush; in parallel, so one\n // unreachable destination's drain cannot use up the others' flush window.\n flush: () => settleAll((sink) => sink.flush()),\n shutdown: () => settleAll((sink) => sink.shutdown()),\n health: (): readonly DeliveryHealthSnapshot[] => fanouts.flatMap((fanout) => fanout.sink.health()),\n };\n};\n"],"mappings":";AAAA,SAAS,kBAAkB;AAE3B,SAAS,UAAU,gBAAgB,kBAAsE;AACzG,SAAS,sBAAsB;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AI,CAAC,WAAW,IAAI,OAAO,IAAI,EAAE,MAAM,MAAM,MAAS,CAAC,CAAC;AAAA,EACpF;AAEA,SAAO;AAAA,IACL;AAAA;AAAA;AAAA,IAGA,OAAO,MAAM,UAAU,CAAC,SAAS,KAAK,MAAM,CAAC;AAAA,IAC7C,UAAU,MAAM,UAAU,CAAC,SAAS,KAAK,SAAS,CAAC;AAAA,IACnD,QAAQ,MAAyC,QAAQ,QAAQ,CAAC,WAAW,OAAO,KAAK,OAAO,CAAC;AAAA,EACnG;AACF;","names":["z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","event","event","event","parent","createHash","z","z","z","z","z","event","TraceFlags","millisToHrTime","ATTR_ERROR_TYPE","ATTR_GEN_AI_OPERATION_NAME","ATTR_GEN_AI_REQUEST_MODEL","ATTR_GEN_AI_RESPONSE_MODEL","ATTR_GEN_AI_SYSTEM","ATTR_GEN_AI_TOOL_CALL_ID","ATTR_GEN_AI_TOOL_NAME","ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS","ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS","ATTR_GEN_AI_USAGE_INPUT_TOKENS","ATTR_GEN_AI_USAGE_OUTPUT_TOKENS","ATTR_OTELHOOK_OUTCOME","ATTR_OTELHOOK_TOOL_KIND","ATTR_OTELHOOK_DELEGATION_DEPTH","ATTR_OTELHOOK_AGENT_NAME","ATTR_OTELHOOK_AGENT_VERSION","ATTR_OTELHOOK_GENERATION_ID","ATTR_OTELHOOK_COMPACTION_TRIGGER","event","identityAttributes","ATTR_GEN_AI_REQUEST_MODEL","usageAttributes","ATTR_GEN_AI_OPERATION_NAME","ATTR_GEN_AI_SYSTEM","ATTR_GEN_AI_RESPONSE_MODEL","ATTR_GEN_AI_TOOL_NAME","ATTR_GEN_AI_TOOL_CALL_ID","ATTR_ERROR_TYPE","ATTR_GEN_AI_USAGE_INPUT_TOKENS","ATTR_GEN_AI_USAGE_OUTPUT_TOKENS","ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS","ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS","millisToHrTime","TraceFlags","TRACE_ID_PATTERN","SPAN_ID_PATTERN","isFiniteNonNegative","isBoundedString","isPlainObject","TraceFlags","ExportResultCode","millisToHrTime","TraceFlags","millisToHrTime","chunk","createDisabledSink","ExportResultCode","z","z","z","z","ATTR_GEN_AI_OPERATION_NAME","ATTR_GEN_AI_REQUEST_MODEL","ATTR_GEN_AI_RESPONSE_MODEL","ATTR_GEN_AI_TOOL_NAME","ATTR_ERROR_TYPE","ATTR_SESSION_ID","ATTR_OTELHOOK_PROVIDER_ID","ATTR_OTELHOOK_OUTCOME","ATTR_OTELHOOK_SESSION_KIND","event","isPlainObject","isFiniteNonNegative","isBoundedString","isPrimitiveAttribute","ExportResultCode","millisToHrTime","resourceFromAttributes","DISABLED_DETAIL","millisToHrTime","resourceFromAttributes","ExportResultCode"]}
|
|
1
|
+
{"version":3,"sources":["../src/telemetry/semconv.ts","../src/version.ts","../src/telemetry/export-identity.ts","../src/model/events.ts","../src/errors/taxonomy.ts","../src/model/content.ts","../src/model/primitives.ts","../src/model/extensions.ts","../src/model/identity.ts","../src/model/target.ts","../src/model/usage.ts","../src/model/version.ts","../src/telemetry/spool-queue.ts","../src/state/keys.ts","../src/telemetry/durable-spool.ts","../src/telemetry/otlp-sink.ts","../src/errors/index.ts","../src/diagnostics/health.ts","../src/telemetry/export-failure.ts","../src/telemetry/exporter-resource.ts","../src/config/resource-attributes.ts","../src/privacy/policy.ts","../src/telemetry/log-records.ts","../src/telemetry/durable-log-spool.ts","../src/telemetry/otlp-log-sink.ts","../src/config/otlp-endpoint.ts","../src/telemetry/signal-fanout.ts","../src/config/destinations.ts","../src/config/header-value.ts","../src/config/otlp-headers.ts","../src/config/schema.ts","../src/telemetry/metric-model.ts","../src/telemetry/durable-metric-spool.ts","../src/telemetry/otlp-metric-sink.ts","../src/telemetry/export-destinations.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\n\nimport { SpanKind, SpanStatusCode, TraceFlags, type Attributes, type SpanContext, type SpanStatus } from \"@opentelemetry/api\";\nimport { millisToHrTime } from \"@opentelemetry/core\";\nimport type { InstrumentationScope } from \"@opentelemetry/core\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport type { ReadableSpan } from \"@opentelemetry/sdk-trace\";\nimport {\n ATTR_ERROR_TYPE,\n ATTR_GEN_AI_OPERATION_NAME,\n ATTR_GEN_AI_REQUEST_MODEL,\n ATTR_GEN_AI_RESPONSE_MODEL,\n ATTR_GEN_AI_SYSTEM,\n ATTR_GEN_AI_TOOL_CALL_ID,\n ATTR_GEN_AI_TOOL_NAME,\n ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n} from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport type { CanonicalEvent, CanonicalEventType } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\nimport { VERSION } from \"../version.js\";\nimport {\n ATTR_OTELHOOK_TARGET_REPOSITORY_ID,\n ATTR_OTELHOOK_TARGET_SOURCE,\n ATTR_OTELHOOK_TARGET_WORKSPACE_ID,\n ATTR_OTELHOOK_TARGET_WORKTREE_KIND,\n ATTR_VCS_REF_HEAD_NAME,\n exportIdentityAttributes,\n profileAttributes,\n targetAttributes,\n usageTemporalityAttributes,\n} from \"./export-identity.js\";\n\nconst SCOPE_NAME = \"@osfactory/otel-hook\";\n\nexport const DEFAULT_INSTRUMENTATION_SCOPE: InstrumentationScope = Object.freeze({\n name: SCOPE_NAME,\n version: VERSION,\n});\n\nconst ATTR_OTELHOOK_SPAN_PAIRED = \"otelhook.span.paired\";\nconst ATTR_OTELHOOK_SPAN_PAIRING = \"otelhook.span.pairing\";\nconst ATTR_OTELHOOK_SPAN_ORPHAN = \"otelhook.span.orphan\";\nconst ATTR_OTELHOOK_OUTCOME = \"otelhook.outcome\";\nconst ATTR_OTELHOOK_RESET_DETECTED = \"otelhook.usage.reset_detected\";\n/** True when a generation's usage covers only part of it; see `generation.end.usagePartial`. */\nexport const ATTR_OTELHOOK_USAGE_PARTIAL = \"otelhook.usage.partial\";\nconst ATTR_OTELHOOK_TOOL_KIND = \"otelhook.tool.kind\";\nconst ATTR_OTELHOOK_DELEGATION_DEPTH = \"otelhook.delegation_depth\";\nconst ATTR_OTELHOOK_COMPACTION_TRIGGER = \"otelhook.compaction.trigger\";\nconst ATTR_OTELHOOK_AGENT_NAME = \"otelhook.agent.name\";\nconst ATTR_OTELHOOK_AGENT_VERSION = \"otelhook.agent.version\";\nconst ATTR_OTELHOOK_GENERATION_ID = \"otelhook.generation.id\";\n\n/**\n * Pure, stateless canonical-event-to-span mapping.\n *\n * Isolated in one module so every other piece of the telemetry pipeline\n * — batching, retry, spooling — can change without touching what an attribute\n * means. Two edges of the same lifecycle scope are merged into one span when\n * they appear in the same batch; when they arrive in *different* short-lived\n * hook processes they are merged through a {@link SpanCorrelation} the caller\n * resolved from persisted state. Either way the mapping itself stays a pure\n * function: state is read by the correlator, never by this module.\n *\n * ## Identity of a span\n *\n * Trace and span ids are derived, never random, so two processes that never\n * meet still agree on them:\n *\n * - `traceId = H(providerId, sessionId)` — one trace per session per provider.\n * Deriving it from the session rather than the invocation is what lets a\n * `tool.end` emitted minutes later land in the same trace as its `tool.start`;\n * including the provider is what stops two providers that happen to reuse a\n * session id from being stitched into one trace.\n * - `spanId = H(providerId, sessionId, family, scopeKey)` — stable across\n * processes and idempotent under redelivery, so a collector that sees a\n * start-only span and later the completed span treats them as one span\n * rather than two.\n */\n// NUL, so joined parts cannot collide across a different split: no identifier\n// this library accepts can contain one, which a printable separator cannot\n// promise. Never emitted — only hashed, or used as an in-memory map key.\nconst FIELD_SEPARATOR = \"\\u0000\";\n\nconst digestHex = (parts: readonly string[], length: number): string =>\n createHash(\"sha256\").update(parts.join(FIELD_SEPARATOR)).digest(\"hex\").slice(0, length);\n\n/** Lifecycle scopes that pair a `*.start` edge with a later `*.end` edge. */\nexport type SpanFamily = \"session\" | \"generation\" | \"tool\" | \"subagent\";\n\n/** Identifies one lifecycle span within a session. */\nexport type SpanScopeRef = {\n readonly family: SpanFamily;\n readonly scopeKey: string;\n};\n\n/**\n * Why a lifecycle span is, or is not, a complete pair.\n *\n * Deliberately explicit rather than a bare boolean: \"we never saw the start\",\n * \"we saw it but it aged out of state\", and \"state could not be read at all\"\n * are different operational facts, and a dashboard that cannot tell them apart\n * cannot tell a broken host from a broken exporter.\n */\nexport type SpanOrphanClassification =\n /** Both edges are known — from this batch, or from persisted state. */\n | \"none\"\n /** The start is known; its end has not arrived yet. */\n | \"missing-end\"\n /** An end arrived and no start was ever recorded for this scope. */\n | \"missing-start\"\n /** A start was recorded but aged past the retention window before the end arrived. */\n | \"expired-start\"\n /** A start exists but was recorded by a different provider; pairing it would be a guess. */\n | \"provider-mismatch\"\n /** A second, distinct end arrived for a scope that was already closed. */\n | \"already-closed\"\n /** The persisted record was written by an incompatible version and was discarded. */\n | \"state-incompatible\"\n /** The persisted record could not be understood. */\n | \"state-corrupt\"\n /** State could not be consulted at all; the mapping degraded rather than failing. */\n | \"state-unavailable\";\n\nexport type SpanPairing =\n /** Both edges were present in this batch. */\n | \"in-batch\"\n /** The other edge came from state written by an earlier process. */\n | \"cross-process\"\n | \"unpaired\";\n\n/**\n * Whether this scope should produce an OTLP record now.\n *\n * OTLP has no notion of updating a span: a span is exported once, when it ends,\n * and a second record carrying the same trace and span id is not a revision of\n * the first — it is a duplicate that backends variously drop, keep the older of,\n * or display twice. Since every lifecycle span id here is *derived* from\n * `(provider, session, family, scopeKey)`, a `*.start` edge and its later `*.end`\n * edge compute the identical id, so exporting on both is precisely that\n * duplicate.\n *\n * `defer` is therefore the answer for a start whose end has not arrived: the\n * start is durable in the state store, and the end edge exports the one complete\n * span using the times recovered from it. Nothing is lost by waiting, and what is\n * gained is that the record a collector receives has a real duration.\n */\nexport type SpanDisposition =\n /** Export a record for this scope now. */\n | \"emit\"\n /** Hold: the start is recorded, and the end edge will export the complete span. */\n | \"defer\";\n\n/**\n * One scope's correlation facts, resolved from persisted state by the caller.\n *\n * Plain data on purpose: the telemetry layer must not reach into the state\n * store itself (ADR 0006), so it declares what it needs and the lifecycle layer\n * supplies it.\n */\nexport type SpanCorrelation = {\n readonly providerId: string;\n readonly sessionId: string;\n readonly ref: SpanScopeRef;\n readonly pairing: SpanPairing;\n readonly orphan: SpanOrphanClassification;\n /**\n * Whether to export a record for this scope now. Defaults to `emit` when a\n * correlation is supplied without one.\n */\n readonly disposition?: SpanDisposition;\n /**\n * Extra component mixed into the derived span id.\n *\n * Set only when this record is a genuinely *additional* observation of a scope\n * that has already been exported once — a second, distinct end for a scope that\n * was already closed. Both records are real, so neither is dropped, and the\n * discriminator keeps them from claiming the same span id.\n */\n readonly spanIdDiscriminator?: string;\n /**\n * Set for a later *run* of a scope whose first run was already exported (a\n * resumed session): mixed into the span id of this run's record, on the\n * deferred start as well as on the end, so both edges agree and the id differs\n * from the first run's. A resumed session span hangs under the first run's\n * session span, so the trace stays one tree.\n */\n readonly runSpanIdDiscriminator?: string;\n /** Start recovered from state; authoritative over the batch's own start edge. */\n readonly startMillis?: number;\n /** End recovered from state; authoritative so a redelivered end re-exports an identical span. */\n readonly endMillis?: number;\n /** Parent recorded at start time, so an end-only process hangs the span in the same place. */\n readonly parent?: SpanScopeRef;\n /** Attributes only the start edge could supply, recovered for an end-only span. */\n readonly attributes?: Attributes;\n};\n\n/**\n * Resolves persisted correlation for one batch.\n *\n * Must never reject: a state failure is a degraded span, never a lost export.\n */\nexport type SpanCorrelationResolver = (\n events: readonly CanonicalEvent[],\n) => Promise<readonly SpanCorrelation[]>;\n\n/**\n * Upper bound on how many start-edge attributes the correlator may carry\n * forward, so persisted state cannot grow with provider-controlled input.\n */\nexport const MAX_RECOVERED_START_ATTRIBUTES = 16;\n\nconst familyOf = (type: CanonicalEventType): SpanFamily | undefined => {\n switch (type) {\n case \"session.start\":\n case \"session.end\":\n return \"session\";\n case \"generation.start\":\n case \"generation.end\":\n return \"generation\";\n case \"tool.start\":\n case \"tool.end\":\n return \"tool\";\n case \"subagent.start\":\n case \"subagent.end\":\n return \"subagent\";\n default:\n return undefined;\n }\n};\n\n/** The lifecycle span an event is an edge of, or undefined for a point-in-time event. */\nexport const spanScopeRefOf = (event: CanonicalEvent): SpanScopeRef | undefined => {\n const family = familyOf(event.type);\n if (family === undefined) {\n return undefined;\n }\n switch (event.type) {\n case \"session.start\":\n case \"session.end\":\n return { family, scopeKey: event.sessionId };\n case \"generation.start\":\n case \"generation.end\":\n return { family, scopeKey: event.generationId };\n case \"tool.start\":\n case \"tool.end\":\n return { family, scopeKey: event.toolCallId };\n case \"subagent.start\":\n case \"subagent.end\":\n return { family, scopeKey: event.subagentInvocationId };\n default:\n return undefined;\n }\n};\n\n/**\n * Where a span hangs in the trace, judged from this event alone.\n *\n * Everything in a session descends from the session span. A tool call names its\n * generation only on `tool.start`, which is exactly why the correlator persists\n * the parent: the `tool.end` process would otherwise reparent the same span to\n * the session and produce a tree whose shape depends on which edge happened to\n * be exported last.\n */\nexport const parentScopeRefOf = (event: CanonicalEvent): SpanScopeRef | undefined => {\n if (event.type === \"session.start\" || event.type === \"session.end\") {\n return undefined;\n }\n if (event.type === \"tool.start\" && event.generationId !== undefined) {\n return { family: \"generation\", scopeKey: event.generationId };\n }\n return { family: \"session\", scopeKey: event.sessionId };\n};\n\n/**\n * Span attributes that only a `*.start` edge can supply.\n *\n * The correlator persists these verbatim so an end-only span in a later process\n * still carries the tool kind, requested model, delegation depth, or agent name\n * the start process saw. An allowlist, and bounded, so persisted state can\n * never become a second route for provider payload content to escape.\n */\nexport const startOnlySpanAttributes = (event: CanonicalEvent): Attributes => {\n switch (event.type) {\n // The session's own worktree is carried forward like a tool's target, so\n // the session span a later `session.end` process exports still names it.\n case \"session.start\":\n return {\n ...(event.agentName === undefined ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: event.agentName }),\n ...(event.agentVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_AGENT_VERSION]: event.agentVersion }),\n ...targetAttributes(event),\n };\n case \"generation.start\":\n return {\n [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId,\n ...(event.model.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: event.model.vendor }),\n };\n // `toolName` and `toolCallId` are on both tool edges, so they are not\n // start-only and persisting them would just pad every record.\n // The target is carried forward too: an end-only process may see a payload\n // with less to go on (no tool input), and the start's evidence still holds.\n case \"tool.start\":\n return { [ATTR_OTELHOOK_TOOL_KIND]: event.toolKind, ...targetAttributes(event) };\n case \"subagent.start\":\n return { [ATTR_OTELHOOK_DELEGATION_DEPTH]: event.delegationDepth };\n default:\n return {};\n }\n};\n\nconst deriveTraceId = (providerId: string, sessionId: string): string =>\n digestHex([\"otelhook/trace\", providerId, sessionId], 32);\n\nconst deriveSpanId = (providerId: string, sessionId: string, ref: SpanScopeRef): string =>\n digestHex([\"otelhook/span\", providerId, sessionId, ref.family, ref.scopeKey], 16);\n\nconst deriveStandaloneSpanId = (\n providerId: string,\n sessionId: string,\n eventType: string,\n eventId: string,\n): string => digestHex([\"otelhook/span\", providerId, sessionId, \"event\", eventType, eventId], 16);\n\nconst correlationKey = (providerId: string, sessionId: string, ref: SpanScopeRef): string =>\n [providerId, sessionId, ref.family, ref.scopeKey].join(FIELD_SEPARATOR);\n\nconst outcomeStatus = (outcome: string | undefined): SpanStatus => {\n if (outcome === undefined || outcome === \"ok\" || outcome === \"unknown\") {\n return { code: SpanStatusCode.UNSET };\n }\n if (outcome === \"cancelled\") {\n return { code: SpanStatusCode.UNSET };\n }\n return { code: SpanStatusCode.ERROR, message: outcome };\n};\n\nconst identityAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n ids: { readonly traceId: string; readonly spanId: string; readonly parentSpanId?: string },\n): Attributes => exportIdentityAttributes(event, resource, ids);\n\nconst usageAttributes = (usage: CanonicalUsage | undefined, resetDetected: boolean): Attributes => {\n if (usage === undefined) {\n return {};\n }\n return {\n [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: usage.inputTokens,\n [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: usage.outputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: usage.cachedInputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: usage.cacheCreationInputTokens,\n [ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]: usage.reasoningOutputTokens,\n ...usageTemporalityAttributes(usage),\n ...(resetDetected ? { [ATTR_OTELHOOK_RESET_DETECTED]: true } : {}),\n };\n};\n\n/** Evidence strength of a target source; see `targetSourceSchema`. */\nconst TARGET_SOURCE_RANK: Readonly<Record<string, number>> = Object.freeze({\n \"tool-path\": 3,\n \"shell-cwd\": 2,\n \"session-cwd\": 1,\n});\n\nconst TARGET_KEYS = [\n ATTR_OTELHOOK_TARGET_WORKSPACE_ID,\n ATTR_OTELHOOK_TARGET_SOURCE,\n ATTR_VCS_REF_HEAD_NAME,\n ATTR_OTELHOOK_TARGET_REPOSITORY_ID,\n ATTR_OTELHOOK_TARGET_WORKTREE_KIND,\n] as const;\n\nconst pickTarget = (attributes: Attributes): Attributes => {\n const picked: Attributes = {};\n for (const key of TARGET_KEYS) {\n if (attributes[key] !== undefined) {\n picked[key] = attributes[key];\n }\n }\n return picked;\n};\n\n/**\n * Drop the target keys so they can be re-chosen as one unit, keeping only what\n * the launcher put on the Resource or the session context named (a\n * `vcs.ref.head.name` passed through by `exportIdentityAttributes`) as the\n * fallback beneath the chosen target.\n */\nconst withoutTarget = (attributes: Attributes, resource: Resource, event: CanonicalEvent): Attributes => {\n const rest: Attributes = { ...attributes };\n for (const key of TARGET_KEYS) {\n delete rest[key];\n }\n return { ...rest, ...pickTarget(profileAttributes(event, resource)) };\n};\n\nconst rankOf = (candidate: Attributes): number => {\n const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];\n return typeof source === \"string\" && Object.hasOwn(TARGET_SOURCE_RANK, source)\n ? (TARGET_SOURCE_RANK[source] ?? 0)\n : 0;\n};\n\n/**\n * One span, one target: the strongest evidence among the recovered start,\n * the live start, and the live end — later wins a tie. A Cursor shell call's\n * start knows its `cwd` and its end does not; the span must keep the former,\n * not be downgraded to the workspace root by whichever edge exported last.\n */\nconst strongestTarget = (candidates: readonly Attributes[]): Attributes => {\n let best: Attributes = {};\n let bestRank = 0;\n for (const candidate of candidates) {\n const rank = rankOf(candidate);\n if (rank > 0 && rank >= bestRank) {\n best = candidate;\n bestRank = rank;\n }\n }\n return best;\n};\n\ntype SpanGroup = {\n readonly ref: SpanScopeRef;\n start?: CanonicalEvent;\n end?: CanonicalEvent;\n};\n\nconst buildSpanContext = (traceId: string, spanId: string): SpanContext => ({\n traceId,\n spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n});\n\nexport type ReadableSpanInput = {\n readonly name: string;\n readonly kind: SpanKind;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly attributes: Attributes;\n readonly status: SpanStatus;\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n};\n\n/** Reconstructs a {@link ReadableSpan} from plain, serializable fields. Used by the durable spool to replay a span it persisted earlier. */\nexport const assembleReadableSpan = (input: ReadableSpanInput): ReadableSpan => toReadableSpan(input);\n\nconst toReadableSpan = (input: ReadableSpanInput): ReadableSpan => {\n const startTime = millisToHrTime(input.startMillis);\n const endTime = millisToHrTime(Math.max(input.startMillis, input.endMillis));\n const duration = millisToHrTime(Math.max(0, input.endMillis - input.startMillis));\n return {\n name: input.name,\n kind: input.kind,\n spanContext: (): SpanContext => buildSpanContext(input.traceId, input.spanId),\n ...(input.parentSpanId === undefined\n ? {}\n : { parentSpanContext: buildSpanContext(input.traceId, input.parentSpanId) }),\n startTime,\n endTime,\n status: input.status,\n attributes: input.attributes,\n links: [],\n events: [],\n duration,\n ended: true,\n resource: input.resource,\n instrumentationScope: input.instrumentationScope,\n droppedAttributesCount: 0,\n droppedEventsCount: 0,\n droppedLinksCount: 0,\n };\n};\n\ntype ResolvedPairing = {\n readonly pairing: SpanPairing;\n readonly orphan: SpanOrphanClassification;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly parent: SpanScopeRef | undefined;\n readonly recovered: Attributes;\n};\n\nconst resolvePairing = (\n group: SpanGroup,\n anchor: CanonicalEvent,\n correlation: SpanCorrelation | undefined,\n): ResolvedPairing => {\n const inBatch = group.start !== undefined && group.end !== undefined;\n const batchStart = group.start?.occurredAt ?? anchor.occurredAt;\n const batchEnd = group.end?.occurredAt ?? anchor.occurredAt;\n\n if (correlation === undefined) {\n return {\n pairing: inBatch ? \"in-batch\" : \"unpaired\",\n orphan: inBatch ? \"none\" : group.start === undefined ? \"missing-start\" : \"missing-end\",\n startMillis: batchStart,\n endMillis: inBatch ? batchEnd : batchStart,\n parent: parentScopeRefOf(anchor),\n recovered: {},\n };\n }\n\n // A correlation that reports no start (an orphaned end) must not fabricate\n // one: the span collapses onto the end instant rather than claiming a\n // duration measured from an event nobody ever saw.\n const startMillis = correlation.startMillis ?? (inBatch ? batchStart : batchEnd);\n const endMillis = correlation.endMillis ?? (group.end === undefined ? startMillis : batchEnd);\n return {\n pairing: correlation.pairing,\n orphan: correlation.orphan,\n startMillis,\n endMillis,\n parent: correlation.parent ?? parentScopeRefOf(anchor),\n recovered: correlation.attributes ?? {},\n };\n};\n\nconst buildLifecycleSpan = (\n plan: GroupPlan,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan => {\n const group = plan.group;\n const anchor = plan.anchor;\n const correlation = plan.correlation;\n const providerId = anchor.provenance.providerId;\n const sessionId = anchor.sessionId;\n const resolved = resolvePairing(group, anchor, correlation);\n const traceId = plan.traceId;\n const spanId = plan.spanId;\n const parentRef = resolved.parent ?? resumedSessionParent(group.ref, correlation);\n const parentSpanId =\n parentRef === undefined ? undefined : deriveSpanId(providerId, sessionId, parentRef);\n\n let name: string = group.ref.family;\n let kind: SpanKind = SpanKind.INTERNAL;\n let status: SpanStatus = { code: SpanStatusCode.UNSET };\n // Attributes recovered from the start process sit *beneath* whatever this\n // batch observed: a live edge always wins over a remembered one.\n let attributes: Attributes = {\n ...identityAttributes(anchor, resource, {\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n }),\n ...resolved.recovered,\n [ATTR_OTELHOOK_SPAN_PAIRED]: resolved.pairing !== \"unpaired\",\n [ATTR_OTELHOOK_SPAN_PAIRING]: resolved.pairing,\n [ATTR_OTELHOOK_SPAN_ORPHAN]: resolved.orphan,\n };\n\n switch (group.ref.family) {\n case \"session\": {\n const end = group.end?.type === \"session.end\" ? group.end : undefined;\n const start = group.start?.type === \"session.start\" ? group.start : undefined;\n name = \"session\";\n kind = SpanKind.INTERNAL;\n attributes = {\n ...withoutTarget(attributes, resource, anchor),\n ...strongestTarget([pickTarget(resolved.recovered), start === undefined ? {} : targetAttributes(start)]),\n ...(start?.agentName === undefined ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName }),\n ...(start?.agentVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion }),\n ...(end === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.reason }),\n ...usageAttributes(end?.usage, false),\n };\n if (end?.reason === \"error\" || end?.reason === \"timeout\") {\n status = { code: SpanStatusCode.ERROR, message: end.reason };\n }\n break;\n }\n case \"generation\": {\n const start = group.start?.type === \"generation.start\" ? group.start : undefined;\n const end = group.end?.type === \"generation.end\" ? group.end : undefined;\n const model = end?.model ?? start?.model;\n name = model === undefined ? \"generation\" : `generation ${model.modelId}`;\n kind = SpanKind.CLIENT;\n attributes = {\n ...attributes,\n [ATTR_GEN_AI_OPERATION_NAME]: \"chat\",\n ...(model?.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: model.vendor }),\n ...(start?.model?.modelId === undefined ? {} : { [ATTR_GEN_AI_REQUEST_MODEL]: start.model.modelId }),\n ...(end?.model?.modelId === undefined ? {} : { [ATTR_GEN_AI_RESPONSE_MODEL]: end.model.modelId }),\n // The provider's own id for this unit of work (Cursor generation,\n // Codex turn): the key a consumer stores a usage observation under.\n [ATTR_OTELHOOK_GENERATION_ID]: group.ref.scopeKey,\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...usageAttributes(end?.usage, false),\n ...(end?.usage === undefined || end.usagePartial === undefined\n ? {}\n : { [ATTR_OTELHOOK_USAGE_PARTIAL]: end.usagePartial }),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n case \"tool\": {\n const start = group.start?.type === \"tool.start\" ? group.start : undefined;\n const end = group.end?.type === \"tool.end\" ? group.end : undefined;\n const toolName = start?.toolName ?? end?.toolName ?? \"unknown\";\n name = `tool ${toolName}`;\n kind = SpanKind.CLIENT;\n attributes = {\n // Target keys are re-chosen below as one unit, never mixed across edges.\n ...withoutTarget(attributes, resource, anchor),\n [ATTR_GEN_AI_TOOL_NAME]: toolName,\n [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,\n ...(start?.toolKind === undefined ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind }),\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...strongestTarget([\n pickTarget(resolved.recovered),\n start === undefined ? {} : targetAttributes(start),\n end === undefined ? {} : targetAttributes(end),\n ]),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n case \"subagent\": {\n const start = group.start?.type === \"subagent.start\" ? group.start : undefined;\n const end = group.end?.type === \"subagent.end\" ? group.end : undefined;\n name = \"subagent\";\n kind = SpanKind.INTERNAL;\n attributes = {\n ...attributes,\n ...(start?.delegationDepth === undefined\n ? {}\n : { [ATTR_OTELHOOK_DELEGATION_DEPTH]: start.delegationDepth }),\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...usageAttributes(end?.usage, false),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n }\n\n if (status.code === SpanStatusCode.ERROR) {\n attributes = { ...attributes, [ATTR_ERROR_TYPE]: status.message ?? \"error\" };\n }\n\n return toReadableSpan({\n name,\n kind,\n startMillis: resolved.startMillis,\n endMillis: resolved.endMillis,\n attributes,\n status,\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n resource,\n instrumentationScope: scope,\n });\n};\n\nconst buildStandaloneSpan = (\n event: CanonicalEvent,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan => {\n const providerId = event.provenance.providerId;\n const traceId = deriveTraceId(providerId, event.sessionId);\n const spanId = deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId);\n const parent = parentScopeRefOf(event);\n const parentSpanId =\n parent === undefined ? undefined : deriveSpanId(providerId, event.sessionId, parent);\n let attributes: Attributes = {\n ...identityAttributes(event, resource, {\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n }),\n [ATTR_OTELHOOK_SPAN_PAIRED]: true,\n };\n let status: SpanStatus = { code: SpanStatusCode.UNSET };\n let name: string = event.type;\n\n switch (event.type) {\n case \"prompt.submitted\":\n name = \"prompt\";\n attributes = { ...attributes, \"otelhook.prompt.source\": event.promptSource, ...targetAttributes(event) };\n break;\n case \"compaction.performed\":\n name = \"compaction\";\n attributes = {\n ...attributes,\n [ATTR_OTELHOOK_COMPACTION_TRIGGER]: event.trigger,\n ...usageAttributes(event.usage, false),\n };\n break;\n case \"error.raised\":\n name = \"error\";\n status = { code: SpanStatusCode.ERROR, message: event.errorCode };\n attributes = {\n ...attributes,\n [ATTR_ERROR_TYPE]: event.errorCode,\n \"otelhook.error.phase\": event.phase,\n \"otelhook.error.retryable\": event.retryable,\n };\n break;\n default:\n break;\n }\n\n return toReadableSpan({\n name,\n kind: SpanKind.INTERNAL,\n startMillis: event.occurredAt,\n endMillis: event.occurredAt,\n attributes,\n status,\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n resource,\n instrumentationScope: scope,\n });\n};\n\nexport type SemanticMappingOptions = {\n readonly resource: Resource;\n readonly instrumentationScope?: InstrumentationScope;\n /**\n * Cross-process pairing facts, at most one entry per lifecycle scope in\n * `events`. Omitted entirely, the mapping degrades to in-batch pairing only —\n * the behavior of a host that wired no state store.\n */\n readonly correlations?: readonly SpanCorrelation[];\n /**\n * Whether a correlator was consulted at all, and whether it answered.\n *\n * This is what separates \"the state store is holding this start, so the end edge\n * will publish it\" from \"nothing recorded this start\". Both look like an empty\n * `correlations` list, and only the first is safe to drop — dropping the second\n * would discard an observation that was neither persisted nor exported, while a\n * caller that saw zero rejections went on to mark the callback handled.\n *\n * - `true` — the correlator ran; an absent or non-`defer` entry means emit.\n * - `false` — the correlator failed; every unpaired start is emitted as an\n * explicitly labelled, uniquely identified fallback.\n * - omitted — no correlator is wired, so cross-process pairing was never on\n * offer and an unpaired start is deferred (the documented no-state-root\n * degradation).\n */\n readonly correlationAvailable?: boolean;\n};\n\n/**\n * Fill in a correlation for an unpaired start that nothing recorded.\n *\n * Reached when a correlator was consulted and either failed outright or reported\n * nothing for this scope. The synthesized entry says what is true — the state was\n * not consulted successfully, so this span is unpaired and no end can complete it\n * — and carries a discriminator so the record cannot claim the span id a later end\n * will publish for the same scope.\n */\nconst effectiveCorrelation = (\n group: SpanGroup,\n correlation: SpanCorrelation | undefined,\n): SpanCorrelation | undefined => {\n if (correlation !== undefined || group.end !== undefined || group.start === undefined) {\n return correlation;\n }\n return {\n providerId: group.start.provenance.providerId,\n sessionId: group.start.sessionId,\n ref: group.ref,\n pairing: \"unpaired\",\n orphan: \"state-unavailable\",\n disposition: \"emit\",\n spanIdDiscriminator: group.start.eventId,\n };\n};\n\n/** How one batch's events distribute over the lifecycle scopes they are edges of. */\ntype BatchLayout = {\n readonly groups: ReadonlyMap<string, SpanGroup>;\n readonly standalone: readonly CanonicalEvent[];\n /** Event id of each lifecycle edge, mapped to the group key it belongs to. */\n readonly groupOf: ReadonlyMap<string, string>;\n};\n\nconst layoutBatch = (events: readonly CanonicalEvent[]): BatchLayout => {\n const groups = new Map<string, SpanGroup>();\n const standalone: CanonicalEvent[] = [];\n const groupOf = new Map<string, string>();\n\n for (const event of events) {\n const ref = spanScopeRefOf(event);\n if (ref === undefined) {\n standalone.push(event);\n continue;\n }\n const groupKey = correlationKey(event.provenance.providerId, event.sessionId, ref);\n const group: SpanGroup = groups.get(groupKey) ?? { ref };\n if (event.type.endsWith(\".start\")) {\n group.start = event;\n } else {\n group.end = event;\n }\n groups.set(groupKey, group);\n groupOf.set(event.eventId, groupKey);\n }\n return { groups, standalone, groupOf };\n};\n\nconst indexCorrelations = (\n correlations: readonly SpanCorrelation[] | undefined,\n): ReadonlyMap<string, SpanCorrelation> => {\n const indexed = new Map<string, SpanCorrelation>();\n for (const correlation of correlations ?? []) {\n indexed.set(\n correlationKey(correlation.providerId, correlation.sessionId, correlation.ref),\n correlation,\n );\n }\n return indexed;\n};\n\n/**\n * What this batch does with one lifecycle scope, decided once.\n *\n * Both the span mapping and the log mapping need the *same* answer to \"which\n * span id identifies this scope, and is a record for it going out now?\" — a log\n * record whose `spanContext` names a span id the exporter never published would\n * dangle at the collector. Computing it in one place is what keeps the two\n * signals pointing at the same span rather than at two plausible derivations of\n * it.\n */\ntype GroupPlan = {\n readonly group: SpanGroup;\n /** The event the span's identity and provenance are read from. */\n readonly anchor: CanonicalEvent;\n /**\n * False when the start is deferred: the state store is holding it and the end\n * edge will publish the one complete span, so nothing is exported for it now.\n */\n readonly emits: boolean;\n readonly correlation: SpanCorrelation | undefined;\n readonly traceId: string;\n readonly spanId: string;\n};\n\nconst planGroup = (\n group: SpanGroup,\n correlation: SpanCorrelation | undefined,\n correlationAvailable: boolean | undefined,\n): GroupPlan | undefined => {\n const anchor = group.start ?? group.end;\n if (anchor === undefined) {\n // Unreachable: a group exists only because an event was filed into it.\n return undefined;\n }\n const providerId = anchor.provenance.providerId;\n const sessionId = anchor.sessionId;\n\n // A start with no end in this batch is dropped **only** when something states\n // that it is durably recorded, because its span id is a pure function of the\n // scope: emitting here and again at the end edge would put two records with one\n // id on the wire, and OTLP has no update operation.\n //\n // `defer` is that statement, and it is the correlator's to make — it just wrote\n // the record. Anything else means nothing is holding this start, so dropping it\n // would lose an observation that was neither persisted nor exported, while the\n // caller saw zero rejections and marked the callback handled. Those are exported\n // under a discriminated span id instead.\n const durablyRecorded =\n group.end === undefined &&\n (correlation?.disposition === \"defer\" ||\n // No correlator wired at all: cross-process pairing was never on offer, so\n // this is the documented no-state-root degradation rather than a failure to\n // persist something that should have been persisted.\n (correlation === undefined && correlationAvailable === undefined));\n\n // A deferred start keeps the scope's *plain* span id, because that is the id the\n // end edge will publish. Only a record actually going out now may claim a\n // discriminated one.\n const effective = durablyRecorded ? correlation : effectiveCorrelation(group, correlation);\n const discriminator = durablyRecorded\n ? runDiscriminatorOf(correlation)\n : (effective?.spanIdDiscriminator ?? runDiscriminatorOf(effective));\n\n return {\n group,\n anchor,\n emits: !durablyRecorded,\n correlation: effective,\n traceId: deriveTraceId(providerId, sessionId),\n spanId:\n discriminator === undefined\n ? deriveSpanId(providerId, sessionId, group.ref)\n : digestHex(\n [\n \"otelhook/span\",\n providerId,\n sessionId,\n group.ref.family,\n group.ref.scopeKey,\n discriminator,\n ],\n 16,\n ),\n };\n};\n\nconst runDiscriminatorOf = (correlation: SpanCorrelation | undefined): string | undefined =>\n correlation?.runSpanIdDiscriminator === undefined ? undefined : `run:${correlation.runSpanIdDiscriminator}`;\n\n/**\n * The parent of a later run of a session (see `runSpanIdDiscriminator`): the\n * session's first-run span, which children of every run already point at.\n */\nconst resumedSessionParent = (\n ref: SpanScopeRef,\n correlation: SpanCorrelation | undefined,\n): SpanScopeRef | undefined =>\n ref.family === \"session\" && correlation?.runSpanIdDiscriminator !== undefined ? ref : undefined;\n\n/** Trace and span a record derived from one canonical event belongs to. */\nexport type EventTraceIdentity = {\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n};\n\n/**\n * Resolve the trace and span identity of every event in one batch.\n *\n * Exposed for signals other than traces — a log record correlates by carrying\n * the *same* derived ids the span mapping would compute, including the deferred\n * and discriminated cases. Whole batch at once because a start's identity\n * depends on whether its end is in the same batch.\n *\n * Both ids come from the event's own `(providerId, sessionId)`, never from a\n * batch-level or module-level value, which is what makes cross-session\n * contamination structurally impossible: two sessions in one batch derive two\n * different trace ids.\n */\nexport const canonicalEventTraceIdentities = (\n events: readonly CanonicalEvent[],\n options: {\n readonly correlations?: readonly SpanCorrelation[];\n readonly correlationAvailable?: boolean;\n } = {},\n): ReadonlyMap<string, EventTraceIdentity> => {\n const layout = layoutBatch(events);\n const correlations = indexCorrelations(options.correlations);\n const plans = new Map<string, GroupPlan>();\n for (const [groupKey, group] of layout.groups) {\n const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);\n if (plan !== undefined) {\n plans.set(groupKey, plan);\n }\n }\n\n const identities = new Map<string, EventTraceIdentity>();\n for (const event of events) {\n const providerId = event.provenance.providerId;\n const groupKey = layout.groupOf.get(event.eventId);\n const plan = groupKey === undefined ? undefined : plans.get(groupKey);\n if (plan === undefined) {\n const parent = parentScopeRefOf(event);\n identities.set(event.eventId, {\n traceId: deriveTraceId(providerId, event.sessionId),\n spanId: deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId),\n ...(parent === undefined\n ? {}\n : { parentSpanId: deriveSpanId(providerId, event.sessionId, parent) }),\n });\n continue;\n }\n const parent =\n plan.correlation?.parent ?? parentScopeRefOf(event) ?? resumedSessionParent(plan.group.ref, plan.correlation);\n identities.set(event.eventId, {\n traceId: plan.traceId,\n spanId: plan.spanId,\n ...(parent === undefined\n ? {}\n : { parentSpanId: deriveSpanId(providerId, event.sessionId, parent) }),\n });\n }\n return identities;\n};\n\n/** Maps one invocation's canonical event batch into OTLP-ready spans. */\nexport const canonicalEventsToReadableSpans = (\n events: readonly CanonicalEvent[],\n options: SemanticMappingOptions,\n): readonly ReadableSpan[] => {\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const layout = layoutBatch(events);\n const correlations = indexCorrelations(options.correlations);\n\n const spans: ReadableSpan[] = [];\n for (const [groupKey, group] of layout.groups) {\n const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);\n if (plan === undefined || !plan.emits) {\n continue;\n }\n spans.push(buildLifecycleSpan(plan, options.resource, scope));\n }\n for (const event of layout.standalone) {\n spans.push(buildStandaloneSpan(event, options.resource, scope));\n }\n return spans;\n};\n","/**\n * Package version, kept in its own module so the CLI can report it without\n * importing the whole library barrel (and every provider adapter with it).\n *\n * Updated by `scripts/release/sync-version.mjs` during semantic-release.\n */\nexport const VERSION = \"0.13.1\";\n","import type { Attributes } from \"@opentelemetry/api\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport { ATTR_SESSION_ID } from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport { isTargetedEvent, type CanonicalEvent } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\n\n/**\n * W3C hex identity attributes on every log and span.\n *\n * Mission Control (and any consumer that decodes OTLP protobuf with a JSON\n * `toObject` that stringifies bytes as UTF-8) cannot recover a usable id from\n * the protobuf `trace_id` / `span_id` fields. These attributes are already hex\n * in the OpenTelemetry JS API; they are copied onto the attribute map so a\n * consumer never has to stringify binary ids.\n */\nexport const ATTR_TRACE_ID = \"trace_id\";\nexport const ATTR_SPAN_ID = \"span_id\";\nexport const ATTR_PARENT_SPAN_ID = \"parent_span_id\";\n\n/** Provider session id, kept when `session.id` is an externally supplied key. */\nexport const ATTR_OTELHOOK_SESSION_ID = \"otelhook.session.id\";\n/** Same provider session id under the gen_ai conversation attribute. */\nexport const ATTR_GEN_AI_CONVERSATION_ID = \"gen_ai.conversation.id\";\n\nexport const TRACE_ID_HEX_PATTERN = /^[0-9a-f]{32}$/;\nexport const SPAN_ID_HEX_PATTERN = /^[0-9a-f]{16}$/;\n\nconst ATTR_OTELHOOK_INVOCATION_ID = \"otelhook.invocation.id\";\nconst ATTR_OTELHOOK_PROVIDER_ID = \"otelhook.provider.id\";\nconst ATTR_OTELHOOK_PROVIDER_VERSION = \"otelhook.provider.version\";\nconst ATTR_OTELHOOK_WORKSPACE_ID = \"otelhook.workspace.id\";\n\n/**\n * Resource attributes a launcher may set to supply the session key, in\n * preference order: the OpenTelemetry semantic-convention `session.id`, then the\n * legacy `har.session_key` that earlier launchers still send.\n */\nexport const EXTERNAL_SESSION_KEY_ATTRIBUTES: readonly string[] = Object.freeze([\n ATTR_SESSION_ID,\n \"har.session_key\",\n]);\n\n/**\n * The provider's own subagent id (Claude Code `agent_id`), on every record of an\n * event emitted inside a subagent. Same class as `session.id`: a provider-minted\n * opaque identifier, exported verbatim so a consumer can join it to the\n * provider's own per-subagent records.\n */\nexport const ATTR_OTELHOOK_SUBAGENT_ID = \"otelhook.subagent.id\";\n\n/**\n * Worktree an event targeted (ADR 0008): the one a tool call touched, or the one\n * a session runs in on its start and prompts. Branch under the OTel VCS\n * attribute; the worktree root, and its repository's main worktree root, only\n * as salted `git-root` handles.\n */\nexport const ATTR_VCS_REF_HEAD_NAME = \"vcs.ref.head.name\";\nexport const ATTR_OTELHOOK_TARGET_WORKSPACE_ID = \"otelhook.target.workspace.id\";\nexport const ATTR_OTELHOOK_TARGET_SOURCE = \"otelhook.target.source\";\nexport const ATTR_OTELHOOK_TARGET_REPOSITORY_ID = \"otelhook.target.repository.id\";\nexport const ATTR_OTELHOOK_TARGET_WORKTREE_KIND = \"otelhook.target.worktree.kind\";\n\n/** Whether `gen_ai.usage.*` on this record is a delta or a running total. */\nexport const ATTR_OTELHOOK_USAGE_TEMPORALITY = \"otelhook.usage.temporality\";\n\n/** Target attributes for a targeted event; empty when the core resolved none. */\nexport const targetAttributes = (event: CanonicalEvent): Attributes => {\n if (!isTargetedEvent(event) || event.target === undefined) {\n return {};\n }\n const { target } = event;\n return {\n [ATTR_OTELHOOK_TARGET_WORKSPACE_ID]: target.workspaceId,\n [ATTR_OTELHOOK_TARGET_SOURCE]: target.source,\n ...(target.vcsBranchName === undefined ? {} : { [ATTR_VCS_REF_HEAD_NAME]: target.vcsBranchName }),\n ...(target.repositoryId === undefined\n ? {}\n : { [ATTR_OTELHOOK_TARGET_REPOSITORY_ID]: target.repositoryId }),\n ...(target.worktreeKind === undefined\n ? {}\n : { [ATTR_OTELHOOK_TARGET_WORKTREE_KIND]: target.worktreeKind }),\n };\n};\n\n/** Temporality of reported usage, so a consumer never sums running totals. */\nexport const usageTemporalityAttributes = (usage: CanonicalUsage | undefined): Attributes =>\n usage === undefined ? {} : { [ATTR_OTELHOOK_USAGE_TEMPORALITY]: usage.temporality };\n\nconst isPrimitiveAttribute = (value: unknown): value is string | number | boolean =>\n typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\";\n\n/**\n * Resource attribute namespaces a launcher puts on the process that are also\n * copied onto every span and log record.\n *\n * Many backends index only record attributes (filters, search, dashboards), so a\n * value that exists only on the Resource is invisible there. Copied:\n *\n * - `har.*` — attributes earlier launchers send;\n * - `factory.*` — the Factory Commits telemetry profile (work unit, slot, …),\n * **except** `factory.local.*`, which the profile defines as local-only: it\n * stays on the Resource and never reaches a record;\n * - `vcs.*` — OpenTelemetry VCS attributes. An event's own resolved target\n * (ADR 0008) still wins for the keys it sets, such as `vcs.ref.head.name`.\n *\n * `session.id` is not copied: it is resolved separately (see\n * `resolveExportedSessionId`), so a resource value cannot overwrite the\n * trimmed, resolved one.\n */\nexport const PASSTHROUGH_RESOURCE_PREFIXES: readonly string[] = Object.freeze([\"har.\", \"factory.\", \"vcs.\"]);\n/** Local-only profile namespace: never copied from the Resource onto records. */\nexport const LOCAL_ONLY_RESOURCE_PREFIX = \"factory.local.\";\n\nconst isPassthroughKey = (key: string): boolean =>\n PASSTHROUGH_RESOURCE_PREFIXES.some((prefix) => key.startsWith(prefix)) &&\n !key.startsWith(LOCAL_ONLY_RESOURCE_PREFIX) &&\n key !== \"factory.local\";\n\n/**\n * Primitive resource attributes to copy onto every log and span record.\n *\n * Only the namespaces in `PASSTHROUGH_RESOURCE_PREFIXES` are forwarded, minus\n * `factory.local.*`; nothing is invented when they are absent.\n */\nexport const passthroughResourceAttributes = (resource: Resource): Attributes => {\n const attributes: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(resource.attributes)) {\n if (isPassthroughKey(key) && isPrimitiveAttribute(value)) {\n attributes[key] = value;\n }\n }\n return attributes;\n};\n\n/**\n * Session context attributes the core stamped on this event\n * (`docs/session-context.md`); empty when none applies.\n */\nexport const contextAttributesOf = (event: CanonicalEvent): Attributes =>\n event.contextAttributes === undefined ? {} : { ...event.contextAttributes };\n\n/**\n * The profile layer of a record: the Resource's passthrough namespaces,\n * overridden key by key by the event's session context.\n *\n * Context wins because it is the more specific and more recent statement: a\n * session that moved from one attempt to another still has the first one in its\n * process environment (and so on the Resource), but its context names the\n * second. Everything otel-hook derives for the event itself — `session.id`,\n * `otelhook.*`, `gen_ai.*`, trace ids, and a resolved worktree target — is\n * layered above this and is never overridden by it.\n */\nexport const profileAttributes = (event: CanonicalEvent, resource: Resource): Attributes => ({\n ...passthroughResourceAttributes(resource),\n ...contextAttributesOf(event),\n});\n\n/**\n * Session id to put on `session.id`, preferring an externally supplied key.\n *\n * A launcher supplies the key as a resource attribute (usually through\n * `OTEL_RESOURCE_ATTRIBUTES`): `session.id` first, then the legacy\n * `har.session_key`, then the provider's own session id. The provider's id is\n * never discarded: it is returned separately so callers can emit it as\n * `otelhook.session.id` / `gen_ai.conversation.id`.\n */\nexport const resolveExportedSessionId = (\n eventSessionId: string,\n resource: Resource,\n): { readonly sessionId: string; readonly providerSessionId: string } => {\n for (const key of EXTERNAL_SESSION_KEY_ATTRIBUTES) {\n const supplied = resource.attributes[key];\n if (typeof supplied === \"string\") {\n const trimmed = supplied.trim();\n if (trimmed.length > 0) {\n return { sessionId: trimmed, providerSessionId: eventSessionId };\n }\n }\n }\n return { sessionId: eventSessionId, providerSessionId: eventSessionId };\n};\n\nexport type ExportedTraceIds = {\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n};\n\n/**\n * Hex-only trace/span attributes. A value that is not W3C hex is omitted\n * rather than stringified — binary blobs must never appear in id fields.\n */\nexport const hexTraceAttributes = (ids: ExportedTraceIds): Attributes => ({\n ...(TRACE_ID_HEX_PATTERN.test(ids.traceId) ? { [ATTR_TRACE_ID]: ids.traceId } : {}),\n ...(SPAN_ID_HEX_PATTERN.test(ids.spanId) ? { [ATTR_SPAN_ID]: ids.spanId } : {}),\n ...(ids.parentSpanId !== undefined && SPAN_ID_HEX_PATTERN.test(ids.parentSpanId)\n ? { [ATTR_PARENT_SPAN_ID]: ids.parentSpanId }\n : {}),\n});\n\n/**\n * Identity attributes shared by the log and span mappings.\n *\n * `session.id` is the externally supplied session key when the resource carries\n * one (`session.id`, then `har.session_key`), otherwise the provider session id.\n * The provider id is always also emitted under `otelhook.session.id` and\n * `gen_ai.conversation.id`. Profile resource attributes and the event's session\n * context are copied on too, beneath them (see `profileAttributes`).\n */\nexport const exportIdentityAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n ids: ExportedTraceIds,\n): Attributes => {\n const { sessionId, providerSessionId } = resolveExportedSessionId(event.sessionId, resource);\n return {\n // First, so nothing in the profile layer can replace an identity attribute.\n ...profileAttributes(event, resource),\n [ATTR_SESSION_ID]: sessionId,\n [ATTR_OTELHOOK_SESSION_ID]: providerSessionId,\n [ATTR_GEN_AI_CONVERSATION_ID]: providerSessionId,\n [ATTR_OTELHOOK_INVOCATION_ID]: event.invocationId,\n [ATTR_OTELHOOK_PROVIDER_ID]: event.provenance.providerId,\n ...(event.provenance.providerVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event.provenance.providerVersion }),\n [ATTR_OTELHOOK_WORKSPACE_ID]: event.workspace.workspaceId,\n ...(event.subagentId === undefined ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event.subagentId }),\n ...hexTraceAttributes(ids),\n };\n};\n","import { z } from \"zod\";\n\nimport {\n errorPhaseSchema,\n errorSeveritySchema,\n otelHookErrorCodeSchema,\n} from \"../errors/taxonomy.js\";\nimport { contentFactSchema, contentFactsSchema } from \"./content.js\";\nimport { extensionsSchema, emptyExtensions } from \"./extensions.js\";\nimport { sourceProvenanceSchema, workspaceIdentitySchema } from \"./identity.js\";\nimport { subagentIdSchema, workspaceTargetSchema } from \"./target.js\";\nimport {\n durationMillisSchema,\n epochMillisSchema,\n eventIdSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n sequenceNumberSchema,\n sessionIdSchema,\n tokenCountSchema,\n} from \"./primitives.js\";\nimport { canonicalUsageSchema, type CanonicalUsage } from \"./usage.js\";\nimport { canonicalSchemaVersionSchema } from \"./version.js\";\n\n/** Model being invoked. Model identifiers are not treated as sensitive. */\nexport const modelDescriptorSchema = z.strictObject({\n modelId: nonEmptyStringSchema,\n /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */\n vendor: nonEmptyStringSchema.optional(),\n family: nonEmptyStringSchema.optional(),\n});\nexport type ModelDescriptor = z.infer<typeof modelDescriptorSchema>;\n\nexport const costFactsSchema = z.strictObject({\n /** ISO 4217 code. */\n currency: z.string().length(3),\n amount: z.number().min(0).finite(),\n source: z.enum([\"provider-reported\", \"computed\"]),\n});\nexport type CostFacts = z.infer<typeof costFactsSchema>;\n\nexport const canonicalEventTypeSchema = z.enum([\n \"session.start\",\n \"session.end\",\n \"prompt.submitted\",\n \"generation.start\",\n \"generation.end\",\n \"tool.start\",\n \"tool.end\",\n \"subagent.start\",\n \"subagent.end\",\n \"compaction.performed\",\n \"error.raised\",\n]);\nexport type CanonicalEventType = z.infer<typeof canonicalEventTypeSchema>;\n\nexport const CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;\n\nconst outcomeSchema = z.enum([\"ok\", \"error\", \"cancelled\", \"timeout\", \"denied\", \"unknown\"]);\nexport type EventOutcome = z.infer<typeof outcomeSchema>;\n\n/**\n * Fields present on every canonical event.\n *\n * Identity fields are duplicated onto each event rather than referenced through\n * shared state, so an event is self-describing once it leaves the process.\n */\nconst baseEventFields = {\n schemaVersion: canonicalSchemaVersionSchema,\n eventId: eventIdSchema,\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Per-invocation ordering key. Stable across replays of the same input. */\n sequence: sequenceNumberSchema,\n occurredAt: epochMillisSchema,\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n /**\n * The provider's own id for the subagent this event was emitted inside (e.g.\n * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event\n * factory, never by hand.\n */\n subagentId: subagentIdSchema.optional(),\n extensions: extensionsSchema.default(emptyExtensions),\n /**\n * Attributes of the session context segment in force when the event\n * occurred (`docs/session-context.md`), stamped by the core from a file a\n * harness wrote. Exported on every record of the event, over the same keys\n * from the Resource. Absent when no context applies. Set by the core only,\n * never by an adapter.\n */\n contextAttributes: z.record(z.string().min(1).max(255), z.union([z.string(), z.number(), z.boolean()])).optional(),\n} as const;\n\nconst event = <TShape extends z.ZodRawShape>(shape: TShape) =>\n z.strictObject({ ...baseEventFields, ...shape });\n\nexport const sessionStartEventSchema = event({\n type: z.literal(\"session.start\"),\n sessionKind: z.enum([\"interactive\", \"non-interactive\", \"unknown\"]),\n agentName: nonEmptyStringSchema.optional(),\n agentVersion: nonEmptyStringSchema.optional(),\n model: modelDescriptorSchema.optional(),\n /** The git worktree the session runs in, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const sessionEndEventSchema = event({\n type: z.literal(\"session.end\"),\n reason: z.enum([\"completed\", \"aborted\", \"error\", \"timeout\", \"unknown\"]),\n durationMillis: durationMillisSchema.optional(),\n /** Session totals, typically cumulative. */\n usage: canonicalUsageSchema.optional(),\n cost: costFactsSchema.optional(),\n});\n\nexport const promptSubmittedEventSchema = event({\n type: z.literal(\"prompt.submitted\"),\n promptSource: z.enum([\"user\", \"automation\", \"resumed\", \"unknown\"]),\n content: contentFactSchema.optional(),\n turnIndex: z.number().int().min(0).optional(),\n /** The git worktree the session runs in, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const generationStartEventSchema = event({\n type: z.literal(\"generation.start\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n requestedMaxOutputTokens: tokenCountSchema.optional(),\n inputContent: contentFactsSchema.optional(),\n});\n\nexport const generationEndEventSchema = event({\n type: z.literal(\"generation.end\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n outcome: outcomeSchema,\n stopReason: nonEmptyStringSchema.optional(),\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n /**\n * True when `usage` is known to cover only part of the generation (for\n * example the last model request of a multi-request turn); false when the\n * provider or harness said it is the whole. Absent: not stated. Meaningless\n * without `usage`.\n */\n usagePartial: z.boolean().optional(),\n cost: costFactsSchema.optional(),\n outputContent: contentFactsSchema.optional(),\n});\n\nexport const toolKindSchema = z.enum([\n \"read\",\n \"write\",\n \"execute\",\n \"search\",\n \"network\",\n \"delegate\",\n \"other\",\n \"unknown\",\n]);\nexport type ToolKind = z.infer<typeof toolKindSchema>;\n\nexport const toolStartEventSchema = event({\n type: z.literal(\"tool.start\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n toolKind: toolKindSchema,\n generationId: nonEmptyStringSchema.optional(),\n input: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const toolEndEventSchema = event({\n type: z.literal(\"tool.end\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n /** Present when the host asked for or recorded a permission decision. */\n permissionDecision: z.enum([\"allowed\", \"denied\", \"deferred\", \"not-required\"]).optional(),\n output: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const subagentStartEventSchema = event({\n type: z.literal(\"subagent.start\"),\n subagentInvocationId: invocationIdSchema,\n subagentType: nonEmptyStringSchema.optional(),\n /** 0 for the top-level agent; 1 for its direct children. */\n delegationDepth: z.number().int().min(0).max(64),\n model: modelDescriptorSchema.optional(),\n});\n\nexport const subagentEndEventSchema = event({\n type: z.literal(\"subagent.end\"),\n subagentInvocationId: invocationIdSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const compactionPerformedEventSchema = event({\n type: z.literal(\"compaction.performed\"),\n trigger: z.enum([\"automatic\", \"manual\", \"unknown\"]),\n /** Provider-reported context size before and after compaction, if known. */\n contextTokensBefore: tokenCountSchema.optional(),\n contextTokensAfter: tokenCountSchema.optional(),\n droppedMessageCount: z.number().int().min(0).optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const errorRaisedEventSchema = event({\n type: z.literal(\"error.raised\"),\n errorCode: otelHookErrorCodeSchema,\n severity: errorSeveritySchema,\n phase: errorPhaseSchema,\n retryable: z.boolean(),\n /** Error text is content: it is described, never embedded verbatim by default. */\n message: contentFactSchema.optional(),\n /** Non-sensitive, provider-agnostic short label. */\n detail: nonEmptyStringSchema.optional(),\n});\n\nexport const canonicalEventSchema = z.discriminatedUnion(\"type\", [\n sessionStartEventSchema,\n sessionEndEventSchema,\n promptSubmittedEventSchema,\n generationStartEventSchema,\n generationEndEventSchema,\n toolStartEventSchema,\n toolEndEventSchema,\n subagentStartEventSchema,\n subagentEndEventSchema,\n compactionPerformedEventSchema,\n errorRaisedEventSchema,\n]);\n\nexport type CanonicalEvent = z.infer<typeof canonicalEventSchema>;\nexport type CanonicalEventInput = z.input<typeof canonicalEventSchema>;\n\nexport type SessionStartEvent = z.infer<typeof sessionStartEventSchema>;\nexport type SessionEndEvent = z.infer<typeof sessionEndEventSchema>;\nexport type PromptSubmittedEvent = z.infer<typeof promptSubmittedEventSchema>;\nexport type GenerationStartEvent = z.infer<typeof generationStartEventSchema>;\nexport type GenerationEndEvent = z.infer<typeof generationEndEventSchema>;\nexport type ToolStartEvent = z.infer<typeof toolStartEventSchema>;\nexport type ToolEndEvent = z.infer<typeof toolEndEventSchema>;\nexport type SubagentStartEvent = z.infer<typeof subagentStartEventSchema>;\nexport type SubagentEndEvent = z.infer<typeof subagentEndEventSchema>;\nexport type CompactionPerformedEvent = z.infer<typeof compactionPerformedEventSchema>;\nexport type ErrorRaisedEvent = z.infer<typeof errorRaisedEventSchema>;\n\nexport type CanonicalEventOfType<TType extends CanonicalEventType> = Extract<\n CanonicalEvent,\n { type: TType }\n>;\n\n/**\n * The event types that may carry a resolved `target` (ADR 0008): a tool call\n * names the worktree it touched; a session start and a prompt name the one the\n * session runs in, so a consumer knows the session's place before its first\n * tool call.\n */\nexport const TARGETED_EVENT_TYPES = [\"session.start\", \"prompt.submitted\", \"tool.start\", \"tool.end\"] as const;\nexport type TargetedEventType = (typeof TARGETED_EVENT_TYPES)[number];\nexport type TargetedEvent = CanonicalEventOfType<TargetedEventType>;\n\nconst TARGETED: ReadonlySet<string> = new Set(TARGETED_EVENT_TYPES);\nexport const isTargetedEvent = (event: CanonicalEvent): event is TargetedEvent => TARGETED.has(event.type);\n\nexport type EventValidationResult =\n | { readonly status: \"ok\"; readonly event: CanonicalEvent }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nexport const validateCanonicalEvent = (value: unknown): EventValidationResult => {\n const parsed = canonicalEventSchema.safeParse(value);\n if (parsed.success) {\n return { status: \"ok\", event: parsed.data };\n }\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n};\n\n/** Parse or throw. Intended for fixtures and tests, not the hook path. */\nexport const parseCanonicalEvent = (value: unknown): CanonicalEvent =>\n canonicalEventSchema.parse(value);\n\n/** Usage carried by an event, if the event type can carry any. */\nexport const eventUsage = (event: CanonicalEvent): CanonicalUsage | undefined =>\n \"usage\" in event ? event.usage : undefined;\n\n/** Stable ordering: by sequence, then by timestamp, then by event id. */\nexport const compareEvents = (a: CanonicalEvent, b: CanonicalEvent): number =>\n a.sequence - b.sequence || a.occurredAt - b.occurredAt || a.eventId.localeCompare(b.eventId);\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 { z } from \"zod\";\n\nimport { nonEmptyStringSchema } from \"./primitives.js\";\n\n/** What kind of conversational or tool content a fact describes. */\nexport const contentKindSchema = z.enum([\n \"prompt\",\n \"response\",\n \"reasoning\",\n \"tool-input\",\n \"tool-output\",\n \"error-message\",\n \"system-instruction\",\n \"attachment\",\n]);\nexport type ContentKind = z.infer<typeof contentKindSchema>;\n\nexport const contentRoleSchema = z.enum([\"user\", \"assistant\", \"system\", \"tool\", \"unknown\"]);\nexport type ContentRole = z.infer<typeof contentRoleSchema>;\n\n/**\n * How much of the original content this fact discloses.\n *\n * - `omitted`: no text at all (the default posture).\n * - `masked`: a shape-preserving mask; non-whitespace characters replaced.\n * - `redacted`: text with secret-looking spans replaced by a placeholder.\n * - `raw`: verbatim text. Only reachable through explicit opt-in.\n */\nexport const contentDisclosureSchema = z.enum([\"omitted\", \"masked\", \"redacted\", \"raw\"]);\nexport type ContentDisclosure = z.infer<typeof contentDisclosureSchema>;\n\nexport const CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;\n\n/**\n * A privacy-safe description of content.\n *\n * Lengths and a stable hash are always present so consumers can measure and\n * correlate volume without receiving the content itself. `text` is present only\n * when the resolved privacy policy allows disclosure, and is produced solely by\n * the central privacy service.\n */\nexport const contentFactSchema = z.strictObject({\n kind: contentKindSchema,\n role: contentRoleSchema.optional(),\n /** Unicode code point count of the original content. */\n characterLength: z.number().int().min(0),\n /** UTF-8 byte length of the original content. */\n byteLength: z.number().int().min(0),\n /** Stable salted digest of the original content. */\n contentHash: z.string().regex(CONTENT_HASH_PATTERN),\n disclosure: contentDisclosureSchema,\n /** Disclosed text, bounded by the privacy policy. Absent when omitted. */\n text: z.string().optional(),\n /** True when `text` was cut short by the configured string bound. */\n truncated: z.boolean(),\n /** Number of secret-looking spans replaced while producing `text`. */\n secretsRedacted: z.number().int().min(0),\n /** Optional non-sensitive label, e.g. a MIME type or tool name. */\n label: nonEmptyStringSchema.optional(),\n});\nexport type ContentFact = z.infer<typeof contentFactSchema>;\n\nexport const contentFactsSchema = z.array(contentFactSchema).max(64);\n\n/**\n * Guard used in tests and at the sink boundary: an omitted fact must not carry\n * text, and a disclosing fact must carry it.\n */\nexport const isContentFactConsistent = (fact: ContentFact): boolean =>\n fact.disclosure === \"omitted\" ? fact.text === undefined : fact.text !== undefined;\n\n/**\n * A fact for a content kind the event can carry when the provider sent no text.\n *\n * Always `omitted` with zero length, regardless of the installation's content\n * mode: there is nothing to mask, redact, or export.\n */\nexport const isUnavailableContentFact = (fact: ContentFact): boolean =>\n fact.disclosure === \"omitted\" &&\n fact.text === undefined &&\n fact.characterLength === 0 &&\n fact.byteLength === 0;\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 { attributeValueSchema, type AttributeValue } from \"./primitives.js\";\n\n/**\n * Extension keys must be namespaced: at least one dot-separated segment before\n * the leaf, e.g. `acme.deployment-tier`. Namespacing keeps provider- and\n * consumer-specific fields from colliding with core fields or each other.\n */\nexport const EXTENSION_KEY_PATTERN =\n /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;\n\n/** Namespaces owned by the core model; extensions may not use them. */\nexport const RESERVED_EXTENSION_NAMESPACES: readonly string[] = Object.freeze([\n \"otelhook\",\n \"otel\",\n \"telemetry\",\n]);\n\nexport const MAX_EXTENSION_ENTRIES = 64;\n\nexport const extensionKeyNamespace = (key: string): string => key.slice(0, key.indexOf(\".\"));\n\nexport const isReservedExtensionNamespace = (key: string): boolean =>\n RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));\n\nexport const isValidExtensionKey = (key: string): boolean =>\n EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);\n\n/**\n * Namespaced extension bag.\n *\n * Values are restricted to attribute primitives, so extensions cannot carry\n * nested provider payloads.\n */\nexport const extensionsSchema = z\n .record(z.string(), attributeValueSchema)\n .check((ctx) => {\n const keys = Object.keys(ctx.value);\n if (keys.length > MAX_EXTENSION_ENTRIES) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`,\n });\n }\n for (const key of keys) {\n if (!EXTENSION_KEY_PATTERN.test(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. \"acme.tier\"`,\n });\n continue;\n }\n if (isReservedExtensionNamespace(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`,\n });\n }\n }\n });\n\nexport type Extensions = Record<string, AttributeValue>;\n\nexport const EMPTY_EXTENSIONS: Extensions = Object.freeze({});\n\nexport const emptyExtensions = (): Extensions => ({});\n","import { z } from \"zod\";\n\nimport {\n attributesSchema,\n detectionConfidenceSchema,\n DETECTION_CONFIDENCE_RANK,\n epochMillisSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n resolvedProviderIdSchema,\n sessionIdSchema,\n sourceTransportSchema,\n workspaceIdSchema,\n type DetectionConfidence,\n type InvocationId,\n type SessionId,\n type WorkspaceId,\n} from \"./primitives.js\";\n\n/**\n * Where a workspace identifier came from.\n *\n * Ordered from most to least stable. The source is recorded so consumers can\n * tell a repository-scoped identity from a directory-scoped one instead of\n * assuming they are comparable.\n */\nexport const workspaceKeySourceSchema = z.enum([\n \"git-remote\",\n \"git-root\",\n \"working-directory\",\n \"explicit\",\n \"unknown\",\n]);\nexport type WorkspaceKeySource = z.infer<typeof workspaceKeySourceSchema>;\n\n/**\n * Privacy-safe workspace identity.\n *\n * Only opaque handles and explicitly allowed labels are modelled. There is no\n * field for a filesystem path, so paths cannot be exported through this type.\n */\nexport const workspaceIdentitySchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n keySource: workspaceKeySourceSchema,\n /** Repository name only; never an owner path or URL with credentials. */\n repositoryName: nonEmptyStringSchema.optional(),\n vcsBranchName: nonEmptyStringSchema.optional(),\n /** Opaque handle for the checked-out revision. */\n vcsRevisionId: nonEmptyStringSchema.optional(),\n })\n .readonly();\nexport type WorkspaceIdentity = z.infer<typeof workspaceIdentitySchema>;\n\nexport const UNKNOWN_WORKSPACE_ID = \"unknown:0000000000000000\" as WorkspaceId;\n\nexport const unknownWorkspaceIdentity = (): WorkspaceIdentity =>\n workspaceIdentitySchema.parse({\n workspaceId: UNKNOWN_WORKSPACE_ID,\n keySource: \"unknown\",\n });\n\n/**\n * Provenance of an observation: which provider produced it and which adapter\n * interpreted it, with the confidence of that attribution.\n */\nexport const sourceProvenanceSchema = z\n .strictObject({\n providerId: resolvedProviderIdSchema,\n providerVersion: nonEmptyStringSchema.optional(),\n adapterId: nonEmptyStringSchema,\n adapterVersion: nonEmptyStringSchema,\n detectionConfidence: detectionConfidenceSchema,\n /** The provider's own name for the source event, e.g. a hook event name. */\n sourceEventName: nonEmptyStringSchema.optional(),\n transport: sourceTransportSchema,\n })\n .readonly();\nexport type SourceProvenance = z.infer<typeof sourceProvenanceSchema>;\n\n/**\n * Opaque, immutable metadata supplied by the embedding consumer.\n *\n * The library never interprets these values; it only carries and exports them.\n */\nexport const consumerAttributesSchema = attributesSchema.readonly();\nexport type ConsumerAttributes = z.infer<typeof consumerAttributesSchema>;\n\n/**\n * Immutable identity of a single hook invocation.\n *\n * Frozen on parse. There is deliberately no setter, no builder that mutates in\n * place, and no module-level instance: identity is passed explicitly so two\n * concurrent invocations can never observe each other's fields.\n */\nexport const invocationIdentitySchema = z\n .strictObject({\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Set when this invocation runs beneath another agent invocation. */\n parentInvocationId: invocationIdSchema.optional(),\n /** Root of the session tree when the provider exposes one. */\n rootSessionId: sessionIdSchema.optional(),\n /** Stable handle for the agent process/instance, when available. */\n agentInstanceId: nonEmptyStringSchema.optional(),\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n startedAt: epochMillisSchema,\n consumerAttributes: consumerAttributesSchema,\n })\n .readonly();\nexport type InvocationIdentity = z.infer<typeof invocationIdentitySchema>;\n\n/** Fields an identity claim may contribute. */\nexport const identityClaimFieldsSchema = z.strictObject({\n invocationId: invocationIdSchema.optional(),\n sessionId: sessionIdSchema.optional(),\n parentInvocationId: invocationIdSchema.optional(),\n rootSessionId: sessionIdSchema.optional(),\n agentInstanceId: nonEmptyStringSchema.optional(),\n workspace: workspaceIdentitySchema.optional(),\n startedAt: epochMillisSchema.optional(),\n});\nexport type IdentityClaimFields = z.infer<typeof identityClaimFieldsSchema>;\n\n/**\n * A claim about invocation identity from one source.\n *\n * Claims are evidence, not truth. Resolution keeps the highest-confidence claim\n * per field and refuses to merge disagreeing peers.\n */\nexport const identityClaimSchema = z.strictObject({\n /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */\n source: nonEmptyStringSchema,\n confidence: detectionConfidenceSchema,\n fields: identityClaimFieldsSchema,\n});\nexport type IdentityClaim = z.infer<typeof identityClaimSchema>;\n\nexport type IdentityConflict = {\n readonly field: keyof IdentityClaimFields;\n readonly confidence: DetectionConfidence;\n /** Rendered, non-sensitive representations of the disagreeing values. */\n readonly values: readonly string[];\n readonly sources: readonly string[];\n};\n\nexport type IdentityResolution =\n | { readonly status: \"resolved\"; readonly identity: InvocationIdentity }\n | {\n readonly status: \"conflict\";\n readonly conflicts: readonly IdentityConflict[];\n }\n | {\n readonly status: \"incomplete\";\n readonly missing: readonly (keyof IdentityClaimFields)[];\n }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nconst CLAIM_FIELDS = [\n \"invocationId\",\n \"sessionId\",\n \"parentInvocationId\",\n \"rootSessionId\",\n \"agentInstanceId\",\n \"workspace\",\n \"startedAt\",\n] as const satisfies readonly (keyof IdentityClaimFields)[];\n\nconst renderClaimValue = (value: unknown): string => {\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (value !== null && typeof value === \"object\" && \"workspaceId\" in value) {\n const { workspaceId } = value;\n return typeof workspaceId === \"string\" ? workspaceId : \"<workspace>\";\n }\n return \"<opaque>\";\n};\n\nexport type ResolveIdentityInput = {\n readonly claims: readonly IdentityClaim[];\n readonly provenance: SourceProvenance;\n /** Used only for fields no claim provides and that have a safe default. */\n readonly fallback?: {\n readonly startedAt?: number;\n readonly workspace?: WorkspaceIdentity;\n };\n readonly consumerAttributes?: Readonly<Record<string, unknown>>;\n};\n\n/**\n * Resolve identity from claims, failing closed.\n *\n * Rules:\n * 1. For each field, only claims at the highest confidence that provided it are\n * considered. Lower-confidence claims never fill in or override.\n * 2. Two distinct values at that highest confidence produce a `conflict`. The\n * invocation is then not attributed at all — a mislabelled session is worse\n * than a missing one.\n * 3. `invocationId` and `sessionId` are mandatory. Missing either yields\n * `incomplete`; neither is invented here.\n * 4. `startedAt` and `workspace` may come from an explicit fallback, because a\n * clock reading and an `unknown` workspace handle assert nothing false.\n */\nexport const resolveInvocationIdentity = (input: ResolveIdentityInput): IdentityResolution => {\n const parsedClaims: IdentityClaim[] = [];\n const issues: string[] = [];\n for (const [index, claim] of input.claims.entries()) {\n const parsed = identityClaimSchema.safeParse(claim);\n if (parsed.success) {\n parsedClaims.push(parsed.data);\n } else {\n issues.push(\n `claim[${index}]: ${parsed.error.issues.map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`).join(\", \")}`,\n );\n }\n }\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const conflicts: IdentityConflict[] = [];\n const selected: Record<string, unknown> = {};\n\n for (const field of CLAIM_FIELDS) {\n const contributors = parsedClaims.filter((claim) => claim.fields[field] !== undefined);\n if (contributors.length === 0) {\n continue;\n }\n const bestRank = Math.max(\n ...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence]),\n );\n const best = contributors.filter(\n (claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank,\n );\n const rendered = new Map<string, string[]>();\n for (const claim of best) {\n const key = JSON.stringify(claim.fields[field]);\n const sources = rendered.get(key) ?? [];\n sources.push(claim.source);\n rendered.set(key, sources);\n }\n if (rendered.size > 1) {\n const [firstBest] = best;\n conflicts.push({\n field,\n confidence: firstBest?.confidence ?? \"none\",\n values: best.map((claim) => renderClaimValue(claim.fields[field])),\n sources: best.map((claim) => claim.source),\n });\n continue;\n }\n const [winner] = best;\n if (winner !== undefined) {\n selected[field] = winner.fields[field];\n }\n }\n\n if (conflicts.length > 0) {\n return { status: \"conflict\", conflicts };\n }\n\n const missing: (keyof IdentityClaimFields)[] = [];\n if (selected.invocationId === undefined) {\n missing.push(\"invocationId\");\n }\n if (selected.sessionId === undefined) {\n missing.push(\"sessionId\");\n }\n if (missing.length > 0) {\n return { status: \"incomplete\", missing };\n }\n\n const startedAt = (selected.startedAt as number | undefined) ?? input.fallback?.startedAt;\n if (startedAt === undefined) {\n return { status: \"incomplete\", missing: [\"startedAt\"] };\n }\n const workspace =\n (selected.workspace as WorkspaceIdentity | undefined) ??\n input.fallback?.workspace ??\n unknownWorkspaceIdentity();\n\n const candidate = {\n invocationId: selected.invocationId as InvocationId,\n sessionId: selected.sessionId as SessionId,\n ...(selected.parentInvocationId === undefined\n ? {}\n : { parentInvocationId: selected.parentInvocationId as InvocationId }),\n ...(selected.rootSessionId === undefined\n ? {}\n : { rootSessionId: selected.rootSessionId as SessionId }),\n ...(selected.agentInstanceId === undefined\n ? {}\n : { agentInstanceId: selected.agentInstanceId as string }),\n provenance: input.provenance,\n workspace,\n startedAt,\n consumerAttributes: input.consumerAttributes ?? {},\n };\n\n const parsed = invocationIdentitySchema.safeParse(candidate);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n }\n return { status: \"resolved\", identity: parsed.data };\n};\n","import { z } from \"zod\";\n\nimport { nonEmptyStringSchema, workspaceIdSchema } from \"./primitives.js\";\n\n/**\n * Per-event workspace targeting (ADR 0008).\n *\n * A session's `workspace` is where the agent was *started*. An agent routinely\n * works somewhere else — in a linked git worktree beside the checkout it was\n * launched from — and the session-level identity cannot show that. A tool event\n * can: the file it edited, or the directory its shell command ran in, names the\n * worktree it actually touched.\n *\n * Two values model that, and the split between them is the privacy boundary:\n *\n * - {@link TargetHint} is what an adapter observed — local paths. It is an\n * in-process value only: it is never part of a {@link CanonicalEvent}, never\n * persisted, never exported. The core resolves it and drops it.\n * - {@link WorkspaceTarget} is what the core resolved — salted handles of the\n * worktree and its repository, the worktree's kind, the checked-out branch, and\n * what the evidence was. It travels on the event.\n */\n\n/**\n * What a target was derived from, strongest evidence first.\n *\n * - `tool-path` — a path the tool call itself named (an edited or read file, a\n * patch header).\n * - `shell-cwd` — the working directory the provider reports a shell command ran in.\n * - `session-cwd` — only the session's own directory was known; the event may\n * have reached elsewhere (e.g. a shell `cd`) without the provider saying so.\n */\nexport const targetSourceSchema = z.enum([\"tool-path\", \"shell-cwd\", \"session-cwd\"]);\nexport type TargetSource = z.infer<typeof targetSourceSchema>;\n\n/** Most paths one hint may name; a bound, not a sampling rule (all must agree). */\nexport const MAX_TARGET_HINT_PATHS = 8;\n\n/** Longest local path a hint may carry. Longer input is dropped, never truncated. */\nexport const MAX_TARGET_PATH_LENGTH = 4096;\n\nconst localPathSchema = z\n .string()\n .min(1)\n .max(MAX_TARGET_PATH_LENGTH)\n .refine((value) => !value.includes(\"\\u0000\"), \"path must not contain NUL\");\n\n/**\n * An adapter's observation of where a tool event pointed. **Carries local paths**\n * — in-process only, see the module note.\n *\n * Every path in one hint must resolve to the same worktree, or the event gets no\n * target at all: a patch touching two worktrees did not target either of them.\n */\nexport const targetHintSchema = z\n .strictObject({\n source: targetSourceSchema,\n paths: z.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),\n /** Absolute directory that relative `paths` resolve against. */\n baseDirectory: localPathSchema.optional(),\n })\n .readonly();\nexport type TargetHint = z.infer<typeof targetHintSchema>;\n\n/**\n * The weakest hint: the session's own directory. Every adapter gives it to a\n * session start and a prompt, and to a tool call that names no path.\n */\nexport const sessionCwdHint = (cwd: string | undefined): TargetHint | undefined =>\n cwd === undefined || cwd.length === 0 ? undefined : { source: \"session-cwd\", paths: [cwd] };\n\n/**\n * Whether a worktree is its repository's main checkout (`main`) or one added\n * beside it with `git worktree add` (`linked`).\n */\nexport const worktreeKindSchema = z.enum([\"main\", \"linked\"]);\nexport type WorktreeKind = z.infer<typeof worktreeKindSchema>;\n\n/**\n * The git worktree a tool event targeted. Exported; carries no path.\n *\n * `workspaceId` is derived exactly like a `git-root` workspace identity, so a\n * consumer holding the same salt can match it against one it derived itself.\n * `repositoryId` is the same derivation applied to the repository's main\n * worktree, so every worktree of one repository shares it — and for a main\n * worktree it equals `workspaceId`.\n */\nexport const workspaceTargetSchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n /** Branch checked out in that worktree; absent on a detached HEAD. */\n vcsBranchName: nonEmptyStringSchema.optional(),\n source: targetSourceSchema,\n /** `git-root` handle of the repository's main worktree; absent when there is none to name. */\n repositoryId: workspaceIdSchema.optional(),\n worktreeKind: worktreeKindSchema.optional(),\n })\n .readonly();\nexport type WorkspaceTarget = z.infer<typeof workspaceTargetSchema>;\n\n/**\n * Shape a provider's own subagent identifier must have to be exported.\n *\n * Identifier-shaped on purpose — no whitespace, no path separators — so a\n * malformed payload field cannot carry prose or a path onto the wire under an id\n * attribute. A value that does not fit is dropped, not repaired.\n */\nexport const SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;\nexport const subagentIdSchema = z.string().regex(SUBAGENT_ID_PATTERN);\nexport type SubagentId = z.infer<typeof subagentIdSchema>;\n","import { z } from \"zod\";\n\nimport { tokenCountSchema } from \"./primitives.js\";\n\n/**\n * Whether an observation reports the change since the previous observation\n * (`delta`) or the running total for the session/generation (`cumulative`).\n *\n * The canonical model keeps temporality explicit rather than assuming one:\n * summing cumulative observations double-counts, and diffing delta observations\n * silently loses tokens.\n */\nexport const usageTemporalitySchema = z.enum([\"delta\", \"cumulative\"]);\nexport type UsageTemporality = z.infer<typeof usageTemporalitySchema>;\n\n/**\n * Whether the provider counts cache-creation tokens inside its input total or\n * reports them as a disjoint bucket.\n *\n * - `included-in-input`: `cacheCreationInputTokens` is a subset of `inputTokens`.\n * - `disjoint-from-input`: cache-creation tokens are billed in addition to\n * `inputTokens` and must be added when computing a total.\n * - `not-reported`: the provider exposes no cache-creation counter; the field is\n * pinned to zero.\n */\nexport const cacheCreationAccountingSchema = z.enum([\n \"included-in-input\",\n \"disjoint-from-input\",\n \"not-reported\",\n]);\nexport type CacheCreationAccounting = z.infer<typeof cacheCreationAccountingSchema>;\n\n/** Whether a provider-reported total agrees with the canonical computation. */\nexport const providerTotalAgreementSchema = z.enum([\"unreported\", \"agrees\", \"disagrees\"]);\nexport type ProviderTotalAgreement = z.infer<typeof providerTotalAgreementSchema>;\n\n/**\n * What an adapter reports, before normalization.\n *\n * `inputTokens` is *inclusive*: it counts every input token the provider\n * attributes to the call, including cache reads (and cache creation when the\n * provider folds it in). `outputTokens` is likewise inclusive of reasoning\n * output. Subset fields describe portions of those totals, never additions.\n */\nexport const usageReportSchema = z.strictObject({\n temporality: usageTemporalitySchema,\n /** Inclusive input tokens. */\n inputTokens: tokenCountSchema.optional(),\n /** Subset of `inputTokens` served from a prompt cache. */\n cachedInputTokens: tokenCountSchema.optional(),\n /** Tokens written to a prompt cache. */\n cacheCreationInputTokens: tokenCountSchema.optional(),\n /** Required when `cacheCreationInputTokens` is present and non-zero. */\n cacheCreationAccounting: cacheCreationAccountingSchema.optional(),\n /** Inclusive output tokens. */\n outputTokens: tokenCountSchema.optional(),\n /** Subset of `outputTokens` spent on reasoning. */\n reasoningOutputTokens: tokenCountSchema.optional(),\n /** Total exactly as the provider reported it, if it reported one. */\n providerTotalTokens: tokenCountSchema.optional(),\n});\nexport type UsageReport = z.infer<typeof usageReportSchema>;\n\n/**\n * Fully normalized usage.\n *\n * Derived fields (`uncachedInputTokens`, `totalTokens`,\n * `providerTotalAgreement`) are part of the schema and are re-checked on parse,\n * so an inconsistent object cannot exist. Construct values with\n * {@link normalizeUsage} rather than by hand.\n */\nexport const canonicalUsageSchema = z\n .strictObject({\n temporality: usageTemporalitySchema,\n inputTokens: tokenCountSchema,\n cachedInputTokens: tokenCountSchema,\n cacheCreationInputTokens: tokenCountSchema,\n cacheCreationAccounting: cacheCreationAccountingSchema,\n outputTokens: tokenCountSchema,\n reasoningOutputTokens: tokenCountSchema,\n /** Derived: input tokens that were neither cache reads nor cache writes. */\n uncachedInputTokens: tokenCountSchema,\n /** Derived: canonical billable total. */\n totalTokens: tokenCountSchema,\n providerTotalTokens: tokenCountSchema.optional(),\n providerTotalAgreement: providerTotalAgreementSchema,\n })\n .check((ctx) => {\n const usage = ctx.value;\n const push = (message: string): void => {\n ctx.issues.push({ code: \"custom\", input: usage, message });\n };\n\n if (usage.cachedInputTokens > usage.inputTokens) {\n push(\"cachedInputTokens must not exceed inputTokens (it is a subset)\");\n }\n if (usage.reasoningOutputTokens > usage.outputTokens) {\n push(\"reasoningOutputTokens must not exceed outputTokens (it is a subset)\");\n }\n if (usage.cacheCreationAccounting === \"not-reported\" && usage.cacheCreationInputTokens !== 0) {\n push(\"cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported\");\n }\n const creationInsideInput =\n usage.cacheCreationAccounting === \"included-in-input\" ? usage.cacheCreationInputTokens : 0;\n if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {\n push(\n \"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input\",\n );\n }\n const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;\n if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {\n push(`uncachedInputTokens must equal ${expectedUncached}`);\n }\n const creationOutsideInput =\n usage.cacheCreationAccounting === \"disjoint-from-input\" ? usage.cacheCreationInputTokens : 0;\n const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;\n if (usage.totalTokens !== expectedTotal) {\n push(`totalTokens must equal ${expectedTotal}`);\n }\n const expectedAgreement: ProviderTotalAgreement =\n usage.providerTotalTokens === undefined\n ? \"unreported\"\n : usage.providerTotalTokens === expectedTotal\n ? \"agrees\"\n : \"disagrees\";\n if (usage.providerTotalAgreement !== expectedAgreement) {\n push(`providerTotalAgreement must be ${expectedAgreement}`);\n }\n });\nexport type CanonicalUsage = z.infer<typeof canonicalUsageSchema>;\n\nexport type UsageNormalizationIssue = {\n readonly code:\n | \"invalid-report\"\n | \"cached-exceeds-input\"\n | \"reasoning-exceeds-output\"\n | \"cache-creation-exceeds-input\"\n | \"cache-creation-accounting-missing\";\n readonly message: string;\n};\n\nexport type UsageNormalizationResult =\n | { readonly status: \"ok\"; readonly usage: CanonicalUsage; readonly notes: readonly string[] }\n | { readonly status: \"invalid\"; readonly issues: readonly UsageNormalizationIssue[] };\n\n/**\n * Normalize a provider usage report into canonical usage.\n *\n * Deterministic rules:\n * 1. Absent counters default to `0`; `providerTotalTokens` stays absent.\n * 2. Non-integer, negative, or non-finite counters are rejected.\n * 3. A subset exceeding its total is rejected — never clamped — because\n * clamping would silently invent a billing story.\n * 4. `cacheCreationAccounting` defaults to `not-reported` when no cache-creation\n * tokens are reported, and is *required* when they are: guessing whether the\n * bucket is disjoint would mis-total every downstream cost calculation.\n * 5. A provider total that disagrees with the canonical total is preserved as\n * reported and flagged `disagrees`. Both numbers survive; neither is edited.\n */\nexport const normalizeUsage = (report: unknown): UsageNormalizationResult => {\n const parsed = usageReportSchema.safeParse(report);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map((issue) => ({\n code: \"invalid-report\" as const,\n message: `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n })),\n };\n }\n\n const input = parsed.data;\n const issues: UsageNormalizationIssue[] = [];\n const notes: string[] = [];\n\n const inputTokens = input.inputTokens ?? 0;\n const cachedInputTokens = input.cachedInputTokens ?? 0;\n const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;\n const outputTokens = input.outputTokens ?? 0;\n const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;\n\n let accounting: CacheCreationAccounting;\n if (cacheCreationInputTokens === 0) {\n accounting = input.cacheCreationAccounting ?? \"not-reported\";\n if (accounting !== \"not-reported\") {\n notes.push(\n `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`,\n );\n }\n } else if (input.cacheCreationAccounting === undefined) {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message:\n \"cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred\",\n });\n accounting = \"not-reported\";\n } else if (input.cacheCreationAccounting === \"not-reported\") {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message: \"cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens\",\n });\n accounting = \"not-reported\";\n } else {\n accounting = input.cacheCreationAccounting;\n }\n\n if (cachedInputTokens > inputTokens) {\n issues.push({\n code: \"cached-exceeds-input\",\n message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n if (reasoningOutputTokens > outputTokens) {\n issues.push({\n code: \"reasoning-exceeds-output\",\n message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`,\n });\n }\n\n const creationInsideInput = accounting === \"included-in-input\" ? cacheCreationInputTokens : 0;\n if (cachedInputTokens + creationInsideInput > inputTokens) {\n issues.push({\n code: \"cache-creation-exceeds-input\",\n message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const creationOutsideInput = accounting === \"disjoint-from-input\" ? cacheCreationInputTokens : 0;\n const totalTokens = inputTokens + creationOutsideInput + outputTokens;\n const providerTotalAgreement: ProviderTotalAgreement =\n input.providerTotalTokens === undefined\n ? \"unreported\"\n : input.providerTotalTokens === totalTokens\n ? \"agrees\"\n : \"disagrees\";\n\n if (providerTotalAgreement === \"disagrees\") {\n notes.push(\n `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`,\n );\n }\n\n const usage: CanonicalUsage = {\n temporality: input.temporality,\n inputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens,\n reasoningOutputTokens,\n uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,\n totalTokens,\n ...(input.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: input.providerTotalTokens }),\n providerTotalAgreement,\n };\n\n return { status: \"ok\", usage, notes };\n};\n\nexport class UsageNormalizationError extends Error {\n public readonly issues: readonly UsageNormalizationIssue[];\n\n public constructor(issues: readonly UsageNormalizationIssue[]) {\n super(`invalid usage report: ${issues.map((issue) => issue.message).join(\"; \")}`);\n this.name = \"UsageNormalizationError\";\n this.issues = issues;\n }\n}\n\n/** Convenience wrapper for call sites that treat invalid usage as a bug. */\nexport const normalizeUsageOrThrow = (report: unknown): CanonicalUsage => {\n const result = normalizeUsage(report);\n if (result.status === \"invalid\") {\n throw new UsageNormalizationError(result.issues);\n }\n return result.usage;\n};\n\nexport const EMPTY_DELTA_USAGE: CanonicalUsage = Object.freeze(\n normalizeUsageOrThrow({ temporality: \"delta\" }),\n);\n\nexport type UsageDeltaResult = {\n readonly usage: CanonicalUsage;\n /**\n * True when the current snapshot is smaller than the previous one on any\n * counter. That means the cumulative series restarted (new session, replayed\n * transcript, provider reset), so the current snapshot is emitted as the delta\n * instead of a negative difference.\n */\n readonly resetDetected: boolean;\n};\n\nconst requireCumulative = (usage: CanonicalUsage, label: string): void => {\n if (usage.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: `${label} must have cumulative temporality` },\n ]);\n }\n};\n\n/**\n * Convert two cumulative snapshots into a delta observation.\n *\n * Replay safety: re-processing the same snapshot yields an all-zero delta, and a\n * decreasing series is reported as a reset rather than a negative delta.\n * Accounting mode must match; mixing modes would make the subtraction meaningless.\n */\nexport const cumulativeToDelta = (\n previous: CanonicalUsage,\n current: CanonicalUsage,\n): UsageDeltaResult => {\n requireCumulative(previous, \"previous usage\");\n requireCumulative(current, \"current usage\");\n\n if (\n previous.cacheCreationAccounting !== current.cacheCreationAccounting &&\n previous.cacheCreationInputTokens !== 0 &&\n current.cacheCreationInputTokens !== 0\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot diff cumulative usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const resetDetected =\n current.inputTokens < previous.inputTokens ||\n current.cachedInputTokens < previous.cachedInputTokens ||\n current.cacheCreationInputTokens < previous.cacheCreationInputTokens ||\n current.outputTokens < previous.outputTokens ||\n current.reasoningOutputTokens < previous.reasoningOutputTokens;\n\n if (resetDetected) {\n return {\n usage: normalizeUsageOrThrow({ ...toReport(current), temporality: \"delta\" }),\n resetDetected: true,\n };\n }\n\n const usage = normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: current.inputTokens - previous.inputTokens,\n cachedInputTokens: current.cachedInputTokens - previous.cachedInputTokens,\n cacheCreationInputTokens:\n current.cacheCreationInputTokens - previous.cacheCreationInputTokens,\n cacheCreationAccounting: current.cacheCreationAccounting,\n outputTokens: current.outputTokens - previous.outputTokens,\n reasoningOutputTokens: current.reasoningOutputTokens - previous.reasoningOutputTokens,\n });\n\n return { usage, resetDetected: false };\n};\n\n/** Project canonical usage back onto the reported shape. */\nexport const toReport = (usage: CanonicalUsage): UsageReport => ({\n temporality: usage.temporality,\n inputTokens: usage.inputTokens,\n cachedInputTokens: usage.cachedInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n cacheCreationAccounting: usage.cacheCreationAccounting,\n outputTokens: usage.outputTokens,\n reasoningOutputTokens: usage.reasoningOutputTokens,\n ...(usage.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: usage.providerTotalTokens }),\n});\n\n/**\n * Add two delta observations. Cumulative usage is never summed, because two\n * running totals do not compose.\n */\nexport const addUsage = (a: CanonicalUsage, b: CanonicalUsage): CanonicalUsage => {\n if (a.temporality !== \"delta\" || b.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"only delta usage may be summed\" },\n ]);\n }\n const accounting =\n a.cacheCreationInputTokens === 0 && a.cacheCreationAccounting === \"not-reported\"\n ? b.cacheCreationAccounting\n : b.cacheCreationInputTokens === 0 && b.cacheCreationAccounting === \"not-reported\"\n ? a.cacheCreationAccounting\n : a.cacheCreationAccounting;\n\n if (\n a.cacheCreationInputTokens !== 0 &&\n b.cacheCreationInputTokens !== 0 &&\n a.cacheCreationAccounting !== b.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot sum usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n a.providerTotalTokens === undefined && b.providerTotalTokens === undefined\n ? undefined\n : (a.providerTotalTokens ?? 0) + (b.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: a.inputTokens + b.inputTokens,\n cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,\n cacheCreationInputTokens: a.cacheCreationInputTokens + b.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: a.outputTokens + b.outputTokens,\n reasoningOutputTokens: a.reasoningOutputTokens + b.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n","import { z } from \"zod\";\n\n/**\n * Version of the canonical event model.\n *\n * Every emitted event carries this value. Consumers must treat an unknown\n * version as unreadable rather than guessing field semantics.\n *\n * Compatibility rules:\n * - Additive optional fields do not change the version.\n * - Renaming, removing, or re-interpreting a field increments the version.\n */\nexport const CANONICAL_SCHEMA_VERSION = 1 as const;\n\nexport type CanonicalSchemaVersion = typeof CANONICAL_SCHEMA_VERSION;\n\nexport const canonicalSchemaVersionSchema = z.literal(CANONICAL_SCHEMA_VERSION);\n","import { randomBytes } from \"node:crypto\";\nimport { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport type { Clock, Logger } from \"../runtime/ports.js\";\nimport { namespaceSegments, type StoreNamespace } from \"../state/keys.js\";\n\nexport type SpoolEnqueueResult =\n | { readonly spooled: true }\n | { readonly spooled: false; readonly reason: \"capacity-exceeded\" };\n\nexport type SpoolDrainResult = {\n readonly drained: number;\n readonly remaining: number;\n readonly failed: number;\n /**\n * Batches removed from the queue because they were unusable rather than\n * undeliverable.\n *\n * Distinct from `failed`, which means \"the collector would not take it, try\n * later\". A quarantined batch will never become deliverable, so counting it\n * separately is what stops a permanent problem from reading as transient.\n */\n readonly quarantined: number;\n};\n\n/**\n * Why a queued batch was dropped rather than delivered.\n *\n * - `age` — older than the queue's `maxAgeMillis`.\n * - `size` — evicted (or refused) to stay within `maxBytes`.\n * - `count` — evicted (or refused) to stay within the batch-count bound.\n * - `rejected` — the destination answered with a non-retryable status on replay,\n * so sending it again could never succeed.\n */\nexport type SpoolDropReason = \"age\" | \"size\" | \"count\" | \"rejected\";\n\n/** Drop counts, persisted beside the queue so they outlive the process that dropped. */\nexport type SpoolDropCounts = {\n readonly total: number;\n readonly age: number;\n readonly size: number;\n readonly count: number;\n readonly rejected: number;\n readonly lastDroppedAt?: number;\n};\n\nexport type SpoolStats = {\n readonly batches: number;\n readonly bytes: number;\n /** Enqueue time of the oldest queued batch. Absent when the queue is empty. */\n readonly oldestEnqueuedAt?: number;\n readonly dropped: SpoolDropCounts;\n};\n\n/**\n * What a queue does when a new batch would exceed a bound.\n *\n * `refuse-new` keeps what is queued and reports the new batch as lost — the\n * original behavior, still the default for a queue built directly. `drop-oldest`\n * evicts from the head until the new batch fits, which is what the runtime's\n * per-destination spools use.\n */\nexport type SpoolOverflowPolicy = \"refuse-new\" | \"drop-oldest\";\n\n/**\n * What a drain's sender reports for one batch: delivered (`true`), still\n * undeliverable and worth retrying (`false`), or permanently undeliverable\n * (`\"discard\"`), which removes it and counts it as a `rejected` drop instead of\n * stopping the drain behind it.\n */\nexport type SpoolSendOutcome = boolean | \"discard\";\n\nexport const EMPTY_SPOOL_DROP_COUNTS: SpoolDropCounts = Object.freeze({\n total: 0,\n age: 0,\n size: 0,\n count: 0,\n rejected: 0,\n});\n\n/** Outcome of validating one batch read back from a queue file. */\nexport type SpoolValidation<TBatch> =\n | { readonly batch: TBatch }\n | { readonly rejection: string };\n\nexport type SpoolQueueOptions<TBatch> = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Bound on the number of queued batches. */\n readonly maxFiles: number;\n /** Bound on the total bytes of queued batches. Unbounded when absent. */\n readonly maxBytes?: number;\n /** A batch older than this is dropped, at enqueue and at drain. No age bound when absent. */\n readonly maxAgeMillis?: number;\n /** Default `refuse-new`. */\n readonly overflow?: SpoolOverflowPolicy;\n /** Age after which a claim left by a dead drain is put back. Default {@link SPOOL_CLAIM_STALE_MILLIS}. */\n readonly claimStaleMillis?: number;\n /**\n * Directory holding the queue, under the identity namespace. One name per\n * signal, so a batch of one signal can never be drained by the other's sender —\n * the two encode different payloads and a mixed queue would quarantine\n * perfectly good batches.\n */\n readonly queueName: string;\n /** Re-validates a batch read back from disk, before any of it reaches a sender. */\n readonly validate: (value: unknown, identity: StoreNamespace) => SpoolValidation<TBatch>;\n};\n\n/**\n * Durable filesystem queue for export batches a collector could not accept.\n *\n * A hook process is short-lived, so \"retry later\" means \"persist and let a later\n * invocation retry\" rather than an in-process backoff loop. Each instance is\n * rooted at `<rootDir>/<providerId>/<installationId>/<queueName>`; two queues for\n * different providers, installations, or signals never share a directory, so a\n * batch from one identity cannot physically land in another's drain — batches\n * cannot mix identities by construction, not by a runtime check alone (the check\n * inside {@link SpoolQueue.drain} is defense in depth for a hand-edited or\n * misplaced file).\n *\n * Shared by the trace and log spools rather than written twice: the drain's\n * quarantine-and-continue behavior is the subtle part, and a second copy of it is\n * a second place for the head-of-queue-blocking bug to come back.\n */\nexport interface SpoolQueue<TBatch> {\n enqueue(batch: TBatch): Promise<SpoolEnqueueResult>;\n /** Sequential, bounded drain: stops after the first failed send, or after `maxBatches`. */\n drain(\n send: (batch: TBatch) => Promise<SpoolSendOutcome>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\n /** Depth, bytes, and persisted drop counts. Read-only: creates no directory. */\n stats(): Promise<SpoolStats>;\n}\n\n/** Name of the drop-count file, inside the queue directory and outside its `*.json` listing. */\nexport const SPOOL_DROPS_FILE = \".drops\";\n\n/** Enqueue time encoded in a queue file name, or undefined for a foreign name. */\nconst enqueuedAtOf = (fileName: string): number | undefined => {\n const match = /^(\\d{16})-/.exec(fileName);\n return match?.[1] === undefined ? undefined : Number(match[1]);\n};\n\nconst isCount = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isInteger(value) && value >= 0;\n\n/** Read a queue directory's drop counts. Missing or unreadable reads as zero. */\nexport const readSpoolDropCounts = async (queueDir: string): Promise<SpoolDropCounts> => {\n try {\n const parsed = JSON.parse(await readFile(path.join(queueDir, SPOOL_DROPS_FILE), \"utf8\")) as unknown;\n if (typeof parsed !== \"object\" || parsed === null) {\n return EMPTY_SPOOL_DROP_COUNTS;\n }\n const record = parsed as Record<string, unknown>;\n const field = (name: string): number => (isCount(record[name]) ? record[name] : 0);\n return {\n total: field(\"total\"),\n age: field(\"age\"),\n size: field(\"size\"),\n count: field(\"count\"),\n rejected: field(\"rejected\"),\n ...(isCount(record.lastDroppedAt) ? { lastDroppedAt: record.lastDroppedAt } : {}),\n };\n } catch {\n return EMPTY_SPOOL_DROP_COUNTS;\n }\n};\n\n/**\n * Depth, bytes, and drop counts of one queue directory, without creating it.\n *\n * Exported for `doctor`, which inspects queues on disk without constructing the\n * sinks that own them.\n */\nexport const readSpoolQueueStats = async (queueDir: string): Promise<SpoolStats> => {\n let entries: string[];\n try {\n entries = await readdir(queueDir);\n } catch {\n return { batches: 0, bytes: 0, dropped: await readSpoolDropCounts(queueDir) };\n }\n const files = entries.filter((entry) => entry.endsWith(\".json\") && !entry.startsWith(\".tmp-\")).sort();\n let bytes = 0;\n for (const file of files) {\n try {\n bytes += (await stat(path.join(queueDir, file))).size;\n } catch {\n // Drained by a peer between the listing and the stat.\n }\n }\n const oldest = files[0] === undefined ? undefined : enqueuedAtOf(files[0]);\n return {\n batches: files.length,\n bytes,\n ...(oldest === undefined ? {} : { oldestEnqueuedAt: oldest }),\n dropped: await readSpoolDropCounts(queueDir),\n };\n};\n\n/** Default bound on a single drain pass, so one invocation's flush stays short. */\nexport const DEFAULT_DRAIN_MAX_BATCHES = 20;\n\n/**\n * A drain claims a batch (renames it out of the queue) before sending it, so two\n * hook processes draining one queue at once — many sessions on one machine —\n * never deliver the same batch twice. The claim names its process: a claim whose\n * process is gone (a hook that exited at its flush deadline mid-send) is put back\n * by the next drain; one whose process cannot be checked is put back once it is\n * this old.\n */\nexport const SPOOL_CLAIM_STALE_MILLIS = 5 * 60 * 1000;\nconst CLAIM_MARKER = \".claimed-\";\n\n/** Whether the process that made a claim still runs; unknown counts as alive. */\nconst isClaimOwnerAlive = (pid: number): boolean => {\n if (!Number.isSafeInteger(pid) || pid <= 0) {\n return true;\n }\n if (pid === process.pid) {\n return true;\n }\n try {\n process.kill(pid, 0);\n return true;\n } catch (thrown) {\n return (thrown as NodeJS.ErrnoException | undefined)?.code !== \"ESRCH\";\n }\n};\n\nconst isErrnoException = (thrown: unknown, code: string): boolean =>\n thrown instanceof Error && (thrown as NodeJS.ErrnoException).code === code;\n\nexport const createSpoolQueue = <TBatch>(\n options: SpoolQueueOptions<TBatch>,\n): SpoolQueue<TBatch> => {\n const [providerSegment, installationSegment] = namespaceSegments(options);\n const queueDir = path.join(options.rootDir, providerSegment, installationSegment, options.queueName);\n const corruptDir = path.join(\n options.rootDir,\n providerSegment,\n installationSegment,\n `${options.queueName}-corrupt`,\n );\n\n let dirsReady: Promise<void> | undefined;\n const ensureDirs = async (): Promise<void> => {\n if (dirsReady !== undefined) {\n return dirsReady;\n }\n const promise = (async (): Promise<void> => {\n await mkdir(queueDir, { recursive: true });\n await mkdir(corruptDir, { recursive: true });\n })();\n dirsReady = promise;\n try {\n await promise;\n } catch (thrown) {\n dirsReady = undefined;\n throw thrown;\n }\n };\n\n const listSorted = async (): Promise<readonly string[]> => {\n let entries: string[];\n try {\n entries = await readdir(queueDir);\n } catch (thrown) {\n if (isErrnoException(thrown, \"ENOENT\")) {\n return [];\n }\n throw thrown;\n }\n return entries.filter((entry) => entry.endsWith(\".json\") && !entry.startsWith(\".tmp-\")).sort();\n };\n\n /**\n * Add drops to the persisted counts.\n *\n * A read-modify-write without a lock: two processes dropping at the same moment\n * can lose one increment. The counts are a diagnostic, not an invoice, and a\n * lock here would put a second contention point on the failure path.\n */\n const recordDrops = async (reason: SpoolDropReason, dropped: number): Promise<void> => {\n if (dropped <= 0) {\n return;\n }\n try {\n const current = await readSpoolDropCounts(queueDir);\n const next: SpoolDropCounts = {\n ...current,\n total: current.total + dropped,\n [reason]: current[reason] + dropped,\n lastDroppedAt: options.clock.now(),\n };\n const tmp = path.join(queueDir, `.tmp-${randomBytes(6).toString(\"hex\")}.drops`);\n await writeFile(tmp, JSON.stringify(next), \"utf8\");\n await rename(tmp, path.join(queueDir, SPOOL_DROPS_FILE));\n } catch {\n // Counting is best-effort; the drop itself already happened.\n }\n options.logger?.warn(\"durable spool dropped batches\", {\n \"spool.queue\": options.queueName,\n \"spool.drop_reason\": reason,\n \"spool.dropped\": dropped,\n });\n };\n\n type QueuedFile = { readonly name: string; readonly enqueuedAt?: number; readonly bytes: number };\n\n const listWithSizes = async (): Promise<QueuedFile[]> => {\n const names = await listSorted();\n const files: QueuedFile[] = [];\n for (const name of names) {\n let bytes = 0;\n if (options.maxBytes !== undefined) {\n try {\n bytes = (await stat(path.join(queueDir, name))).size;\n } catch {\n continue;\n }\n }\n const enqueuedAt = enqueuedAtOf(name);\n files.push({ name, bytes, ...(enqueuedAt === undefined ? {} : { enqueuedAt }) });\n }\n return files;\n };\n\n /** Remove queued files; the count is what actually left the queue. */\n const evict = async (files: readonly QueuedFile[]): Promise<number> => {\n let removed = 0;\n for (const file of files) {\n try {\n await unlink(path.join(queueDir, file.name));\n removed += 1;\n } catch {\n // Already drained or evicted by a peer: it left the queue either way, but\n // not because of this process, so it is not counted here.\n }\n }\n return removed;\n };\n\n const isExpired = (file: QueuedFile, now: number): boolean =>\n options.maxAgeMillis !== undefined &&\n file.enqueuedAt !== undefined &&\n now - file.enqueuedAt > options.maxAgeMillis;\n\n const enqueue = async (batch: TBatch): Promise<SpoolEnqueueResult> => {\n await ensureDirs();\n const serialized = JSON.stringify(batch);\n const bytes = Buffer.byteLength(serialized, \"utf8\");\n const refuse = async (reason: \"size\" | \"count\"): Promise<SpoolEnqueueResult> => {\n options.logger?.warn(\"durable spool at capacity; batch dropped\", {\n \"spool.max_files\": options.maxFiles,\n ...(options.maxBytes === undefined ? {} : { \"spool.max_bytes\": options.maxBytes }),\n \"spool.queue\": options.queueName,\n });\n await recordDrops(reason, 1);\n return { spooled: false, reason: \"capacity-exceeded\" };\n };\n\n if (options.maxBytes !== undefined && bytes > options.maxBytes) {\n // Larger than the whole budget: evicting everything else still would not\n // make room, so it is the one batch that is refused under either policy.\n return refuse(\"size\");\n }\n\n let queued = await listWithSizes();\n const now = options.clock.now();\n const expired = queued.filter((file) => isExpired(file, now));\n if (expired.length > 0) {\n await recordDrops(\"age\", await evict(expired));\n queued = queued.filter((file) => !isExpired(file, now));\n }\n\n const overflow = options.overflow ?? \"refuse-new\";\n const totalBytes = (): number => queued.reduce((sum, file) => sum + file.bytes, 0);\n if (overflow === \"refuse-new\") {\n if (queued.length >= options.maxFiles) {\n return refuse(\"count\");\n }\n if (options.maxBytes !== undefined && totalBytes() + bytes > options.maxBytes) {\n return refuse(\"size\");\n }\n } else {\n // Oldest first: the listing is sorted by enqueue time.\n const overCount = Math.max(0, queued.length + 1 - options.maxFiles);\n if (overCount > 0) {\n await recordDrops(\"count\", await evict(queued.slice(0, overCount)));\n queued = queued.slice(overCount);\n }\n if (options.maxBytes !== undefined) {\n let excess = totalBytes() + bytes - options.maxBytes;\n let cut = 0;\n while (excess > 0 && cut < queued.length) {\n excess -= queued[cut]?.bytes ?? 0;\n cut += 1;\n }\n if (cut > 0) {\n await recordDrops(\"size\", await evict(queued.slice(0, cut)));\n queued = queued.slice(cut);\n }\n }\n }\n\n const fileName = `${String(now).padStart(16, \"0\")}-${randomBytes(6).toString(\"hex\")}.json`;\n const target = path.join(queueDir, fileName);\n const tmp = path.join(queueDir, `.tmp-${randomBytes(6).toString(\"hex\")}.json`);\n await writeFile(tmp, serialized, \"utf8\");\n await rename(tmp, target);\n return { spooled: true };\n };\n\n /** Put back claims a crashed drain left behind (rename sets ctime: the claim's age). */\n const releaseStaleClaims = async (): Promise<void> => {\n let entries: string[];\n try {\n entries = await readdir(queueDir);\n } catch {\n return;\n }\n const now = Date.now();\n for (const entry of entries) {\n const marker = entry.lastIndexOf(CLAIM_MARKER);\n if (marker <= 0) {\n continue;\n }\n const claimPath = path.join(queueDir, entry);\n const owner = Number.parseInt(entry.slice(marker + CLAIM_MARKER.length), 10);\n try {\n if (\n !isClaimOwnerAlive(owner) ||\n now - (await stat(claimPath)).ctimeMs > (options.claimStaleMillis ?? SPOOL_CLAIM_STALE_MILLIS)\n ) {\n await rename(claimPath, path.join(queueDir, entry.slice(0, marker)));\n }\n } catch {\n // released or finished by its owner meanwhile\n }\n }\n };\n\n const drain = async (\n send: (batch: TBatch) => Promise<SpoolSendOutcome>,\n drainOptions?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult> => {\n await ensureDirs();\n const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;\n await releaseStaleClaims();\n let files = await listSorted();\n if (options.maxAgeMillis !== undefined) {\n // Expired batches are dropped, not sent: a collector would place them far in\n // the past, and they would spend this invocation's short flush window.\n const now = options.clock.now();\n const expired = files\n .map((name): QueuedFile => {\n const enqueuedAt = enqueuedAtOf(name);\n return { name, bytes: 0, ...(enqueuedAt === undefined ? {} : { enqueuedAt }) };\n })\n .filter((file) => isExpired(file, now));\n if (expired.length > 0) {\n await recordDrops(\"age\", await evict(expired));\n const gone = new Set(expired.map((file) => file.name));\n files = files.filter((name) => !gone.has(name));\n }\n }\n let drained = 0;\n let failed = 0;\n let quarantined = 0;\n let index = 0;\n\n for (; index < files.length && index < cap; index += 1) {\n const fileName = files[index];\n if (fileName === undefined) {\n break;\n }\n const queuedPath = path.join(queueDir, fileName);\n const filePath = path.join(\n queueDir,\n `${fileName}${CLAIM_MARKER}${String(process.pid)}-${randomBytes(4).toString(\"hex\")}`,\n );\n try {\n await rename(queuedPath, filePath);\n } catch {\n // Claimed, drained or evicted by a concurrent process: not ours to send.\n continue;\n }\n\n /**\n * Move a file out of the queue, or delete it if quarantine is unavailable.\n *\n * Getting it *out of the queue* is the part that matters. A file the drain\n * cannot use and cannot move would be re-read on every pass, and because the\n * head is processed first it would block every healthy batch behind it — the\n * one failure mode a retry queue must not have. So a failed quarantine falls\n * back to deleting: losing one unusable batch beats losing all the usable\n * ones queued behind it.\n */\n const quarantine = async (rejection: string): Promise<void> => {\n quarantined += 1;\n options.logger?.error(\"durable spool quarantined an unusable batch\", {\n \"spool.rejection\": rejection,\n \"spool.file\": fileName,\n \"spool.queue\": options.queueName,\n });\n try {\n await rename(filePath, path.join(corruptDir, fileName));\n } catch {\n await unlink(filePath).catch(() => undefined);\n }\n };\n\n let text: string;\n try {\n text = await readFile(filePath, \"utf8\");\n } catch (thrown) {\n if ((thrown as NodeJS.ErrnoException | undefined)?.code === \"ENOENT\") {\n // A concurrent hook process drained (or evicted) it between our listing\n // and this read: it already left the queue, nothing to quarantine.\n continue;\n }\n await quarantine(\"unreadable\");\n continue;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(text) as unknown;\n } catch {\n await quarantine(\"unparseable-json\");\n continue;\n }\n\n const validation = options.validate(parsed, {\n providerId: options.providerId,\n installationId: options.installationId,\n });\n if (\"rejection\" in validation) {\n await quarantine(validation.rejection);\n continue;\n }\n\n let delivered: SpoolSendOutcome;\n try {\n delivered = await send(validation.batch);\n } catch {\n delivered = false;\n }\n if (delivered === \"discard\") {\n // Permanently refused: retrying can never succeed, and stopping here would\n // wedge every batch queued behind it.\n if (await unlink(filePath).then(() => true, () => false)) {\n await recordDrops(\"rejected\", 1);\n }\n continue;\n }\n if (delivered) {\n await unlink(filePath).catch(() => undefined);\n drained += 1;\n } else {\n // Back in the queue, under its own name, for the next drain.\n await rename(filePath, queuedPath).catch(() => undefined);\n failed += 1;\n break;\n }\n }\n\n const remaining = (await listSorted()).length;\n return { drained, remaining, failed, quarantined };\n };\n\n return {\n enqueue,\n drain,\n size: async (): Promise<number> => {\n await ensureDirs();\n return (await listSorted()).length;\n },\n stats: (): Promise<SpoolStats> => readSpoolQueueStats(queueDir),\n };\n};\n","import { createHash } from \"node:crypto\";\n\n/**\n * Segments derived from arbitrary strings must be safe path components on any\n * filesystem: no separators, no traversal, no reserved characters. Anything\n * that already looks safe is kept as-is (for readable directory names);\n * anything else is replaced by a stable hash so no input can escape its\n * namespace directory or collide with a sibling by accident.\n */\nconst SAFE_SEGMENT_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;\n\nexport const isSafeSegment = (segment: string): boolean => SAFE_SEGMENT_PATTERN.test(segment);\n\nexport const sanitizeSegment = (segment: string): string => {\n if (isSafeSegment(segment)) {\n return segment;\n }\n return `h_${createHash(\"sha256\").update(segment, \"utf8\").digest(\"hex\").slice(0, 32)}`;\n};\n\n/** Scopes a state store to one provider deployed under one installation. */\nexport type StoreNamespace = {\n readonly providerId: string;\n readonly installationId: string;\n};\n\nexport const namespaceSegments = (namespace: StoreNamespace): readonly [string, string] => [\n sanitizeSegment(namespace.providerId),\n sanitizeSegment(namespace.installationId),\n];\n\n/** Stable, collision-resistant digest of a logical state key. */\nexport const keyDigest = (key: string): string =>\n createHash(\"sha256\").update(key, \"utf8\").digest(\"hex\");\n","import type { Attributes } from \"@opentelemetry/api\";\n\nimport type { Clock, Logger } from \"../runtime/ports.js\";\nimport type { StoreNamespace } from \"../state/keys.js\";\n// Deliberately not re-exported: `spool-queue.js` is their one home, and a second\n// `export *` path to the same names makes them ambiguous in the barrel below.\nimport {\n createSpoolQueue,\n type SpoolDrainResult,\n type SpoolEnqueueResult,\n type SpoolOverflowPolicy,\n type SpoolSendOutcome,\n type SpoolStats,\n} from \"./spool-queue.js\";\n\nexport type SerializedSpan = {\n readonly name: string;\n readonly kind: number;\n readonly traceId: string;\n readonly spanId: string;\n /** Absent on batches spooled before cross-process parenting existed, and on root spans. */\n readonly parentSpanId?: string;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly attributes: Attributes;\n readonly statusCode: number;\n readonly statusMessage?: string;\n};\n\nexport type SpoolBatch = {\n readonly providerId: string;\n readonly installationId: string;\n readonly resourceAttributes: Attributes;\n readonly instrumentationScope: { readonly name: string; readonly version?: string };\n readonly spans: readonly SerializedSpan[];\n readonly enqueuedAt: number;\n};\n\n/** Upper bounds on a replayed batch. A spool file is untrusted input. */\nexport const MAX_SPOOLED_SPANS_PER_BATCH = 4_096;\nexport const MAX_SPOOLED_STRING_LENGTH = 8_192;\nconst MAX_SPOOLED_ATTRIBUTES_PER_SPAN = 256;\nconst TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;\nconst SPAN_ID_PATTERN = /^[0-9a-f]{16}$/;\n\nconst isFiniteNonNegative = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n\nconst isBoundedString = (value: unknown, maxLength = MAX_SPOOLED_STRING_LENGTH): value is string =>\n typeof value === \"string\" && value.length > 0 && value.length <= maxLength;\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * Whether one recorded span can be replayed.\n *\n * Every field is checked, not just the ones a happy path reads. `assembleReadableSpan`\n * hands its output straight to the OTLP encoder, which assumes the shapes the type\n * declares — so a `spanId` of the wrong length, a `startMillis` of `null`, or an\n * `attributes` value holding a nested object becomes an encoder error deep inside\n * the exporter rather than a rejected file here. Trace and span ids are further held\n * to their hex forms, because a malformed id is not a span a collector can place.\n */\nconst isReplayableSpan = (value: unknown): value is SerializedSpan => {\n if (!isPlainObject(value)) {\n return false;\n }\n if (!isBoundedString(value.name) || !isFiniteNonNegative(value.kind)) {\n return false;\n }\n if (typeof value.traceId !== \"string\" || !TRACE_ID_PATTERN.test(value.traceId)) {\n return false;\n }\n if (typeof value.spanId !== \"string\" || !SPAN_ID_PATTERN.test(value.spanId)) {\n return false;\n }\n if (\n value.parentSpanId !== undefined &&\n (typeof value.parentSpanId !== \"string\" || !SPAN_ID_PATTERN.test(value.parentSpanId))\n ) {\n return false;\n }\n if (!isFiniteNonNegative(value.startMillis) || !isFiniteNonNegative(value.endMillis)) {\n return false;\n }\n if (!isFiniteNonNegative(value.statusCode)) {\n return false;\n }\n if (\n value.statusMessage !== undefined &&\n typeof value.statusMessage !== \"string\"\n ) {\n return false;\n }\n if (!isPlainObject(value.attributes)) {\n return false;\n }\n const entries = Object.entries(value.attributes);\n if (entries.length > MAX_SPOOLED_ATTRIBUTES_PER_SPAN) {\n return false;\n }\n return entries.every(([, attribute]) => {\n if (Array.isArray(attribute)) {\n // OTLP permits homogeneous primitive arrays; anything nested is not a span\n // attribute and would fail encoding.\n return attribute.every(\n (item) =>\n (typeof item === \"string\" && item.length <= MAX_SPOOLED_STRING_LENGTH) ||\n (typeof item === \"number\" && Number.isFinite(item)) ||\n typeof item === \"boolean\" ||\n item === null,\n );\n }\n return (\n (typeof attribute === \"string\" && attribute.length <= MAX_SPOOLED_STRING_LENGTH) ||\n (typeof attribute === \"number\" && Number.isFinite(attribute)) ||\n typeof attribute === \"boolean\" ||\n attribute === undefined\n );\n });\n};\n\nexport type SpoolBatchRejection =\n | \"not-an-object\"\n | \"identity-mismatch\"\n | \"resource-attributes-invalid\"\n | \"instrumentation-scope-invalid\"\n | \"spans-invalid\"\n | \"span-field-invalid\";\n\n/**\n * Validate a whole batch read back from disk, before any of it reaches an exporter.\n *\n * The identity check alone is not enough. `spans` being anything other than an array\n * makes the sink's `spans.map(...)` throw, and a throwing send is indistinguishable\n * from an unreachable collector — so the drain would treat a permanently poisoned\n * file as a transient failure and stop at it on every pass, wedging the queue head\n * and every batch behind it forever. Validation is what turns that into a single\n * quarantined file.\n */\nexport const validateSpoolBatch = (\n value: unknown,\n identity: StoreNamespace,\n): { readonly batch: SpoolBatch } | { readonly rejection: SpoolBatchRejection } => {\n if (!isPlainObject(value)) {\n return { rejection: \"not-an-object\" };\n }\n if (\n value.providerId !== identity.providerId ||\n value.installationId !== identity.installationId\n ) {\n return { rejection: \"identity-mismatch\" };\n }\n if (!isPlainObject(value.resourceAttributes)) {\n // Not merely absent: `replayResource` iterates it, and a string or an array\n // would silently produce a resource built from its indices.\n return { rejection: \"resource-attributes-invalid\" };\n }\n if (!isPlainObject(value.instrumentationScope) || !isBoundedString(value.instrumentationScope.name)) {\n return { rejection: \"instrumentation-scope-invalid\" };\n }\n if (\n value.instrumentationScope.version !== undefined &&\n typeof value.instrumentationScope.version !== \"string\"\n ) {\n return { rejection: \"instrumentation-scope-invalid\" };\n }\n if (!Array.isArray(value.spans) || value.spans.length === 0) {\n return { rejection: \"spans-invalid\" };\n }\n if (value.spans.length > MAX_SPOOLED_SPANS_PER_BATCH) {\n return { rejection: \"spans-invalid\" };\n }\n if (!value.spans.every(isReplayableSpan)) {\n return { rejection: \"span-field-invalid\" };\n }\n if (!isFiniteNonNegative(value.enqueuedAt)) {\n return { rejection: \"not-an-object\" };\n }\n return { batch: value as unknown as SpoolBatch };\n};\n\nexport type DurableSpoolOptions = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Refuses new entries once this many are queued, rather than growing without bound. Default 500. */\n readonly maxSpoolFiles?: number;\n /**\n * Queue directory below the identity namespace. Default `spool`; each\n * export destination other than `default` gets its own.\n */\n readonly queueName?: string;\n /** Bound on total queued bytes. Unbounded when absent. */\n readonly maxBytes?: number;\n /** Batches older than this are dropped rather than sent. No age bound when absent. */\n readonly maxAgeMillis?: number;\n /** Default `refuse-new`, the original behavior. */\n readonly overflow?: SpoolOverflowPolicy;\n};\n\n/**\n * Durable filesystem queue for export batches a collector could not accept.\n *\n * A hook process is short-lived, so \"retry later\" means \"persist and let a\n * later invocation retry\" rather than an in-process backoff loop. Each\n * instance is rooted at `<rootDir>/<providerId>/<installationId>/spool`; two\n * spools for different providers or installations never share a directory,\n * so a batch from one identity cannot physically land in another's drain —\n * batches cannot mix identities by construction, not by a runtime check\n * alone (the check in {@link DurableSpool.drain} is defense in depth for a\n * hand-edited or misplaced file).\n */\nexport interface DurableSpool {\n enqueue(batch: SpoolBatch): Promise<SpoolEnqueueResult>;\n /** Sequential, bounded drain: stops after the first failed send, or after `maxBatches`. */\n drain(\n send: (batch: SpoolBatch) => Promise<SpoolSendOutcome>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\n /**\n * Depth, bytes, and persisted drop counts. Optional so a host's own\n * implementation of this interface keeps compiling; the file-backed one has it.\n */\n stats?(): Promise<SpoolStats>;\n}\n\n/** Default bound on queued trace batches, so the spool cannot grow without limit. */\nexport const DEFAULT_MAX_SPOOL_FILES = 500;\n\nexport const createFileDurableSpool = (options: DurableSpoolOptions): DurableSpool =>\n createSpoolQueue<SpoolBatch>({\n rootDir: options.rootDir,\n providerId: options.providerId,\n installationId: options.installationId,\n clock: options.clock,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_SPOOL_FILES,\n queueName: options.queueName ?? \"spool\",\n ...(options.maxBytes === undefined ? {} : { maxBytes: options.maxBytes }),\n ...(options.maxAgeMillis === undefined ? {} : { maxAgeMillis: options.maxAgeMillis }),\n ...(options.overflow === undefined ? {} : { overflow: options.overflow }),\n validate: validateSpoolBatch,\n });\n","import { ExportResultCode, type ExportResult } from \"@opentelemetry/core\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-proto\";\nimport type { InstrumentationScope } from \"@opentelemetry/core\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport type { ReadableSpan } from \"@opentelemetry/sdk-trace\";\n\nimport type { ExporterPolicy } from \"../config/schema.js\";\nimport { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport { createHealthTracker, type DeliveryHealthSnapshot } from \"../diagnostics/health.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { Clock, Logger, TelemetryEmitResult, TelemetrySink } from \"../runtime/ports.js\";\nimport type { DurableSpool, SerializedSpan, SpoolBatch } from \"./durable-spool.js\";\nimport { isPermanentExportFailure } from \"./export-failure.js\";\nimport type { SpoolSendOutcome } from \"./spool-queue.js\";\nimport {\n agreedContextAttributes,\n replayResource,\n resourceFromExporterPolicy,\n resourceWithContext,\n} from \"./exporter-resource.js\";\nimport {\n assembleReadableSpan,\n canonicalEventsToReadableSpans,\n DEFAULT_INSTRUMENTATION_SCOPE,\n type SpanCorrelation,\n type SpanCorrelationResolver,\n} from \"./semconv.js\";\n\nconst chunk = <T,>(items: readonly T[], size: number): readonly (readonly T[])[] => {\n if (size <= 0 || items.length <= size) {\n return [items];\n }\n const chunks: T[][] = [];\n for (let index = 0; index < items.length; index += size) {\n chunks.push(items.slice(index, index + size));\n }\n return chunks;\n};\n\nconst serializeSpan = (span: ReadableSpan): SerializedSpan => ({\n name: span.name,\n kind: span.kind,\n traceId: span.spanContext().traceId,\n spanId: span.spanContext().spanId,\n ...(span.parentSpanContext === undefined\n ? {}\n : { parentSpanId: span.parentSpanContext.spanId }),\n startMillis: span.startTime[0] * 1000 + Math.round(span.startTime[1] / 1e6),\n endMillis: span.endTime[0] * 1000 + Math.round(span.endTime[1] / 1e6),\n attributes: { ...span.attributes },\n statusCode: span.status.code,\n ...(span.status.message === undefined ? {} : { statusMessage: span.status.message }),\n});\n\nconst deserializeSpan = (\n serialized: SerializedSpan,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan =>\n assembleReadableSpan({\n name: serialized.name,\n kind: serialized.kind,\n startMillis: serialized.startMillis,\n endMillis: serialized.endMillis,\n attributes: serialized.attributes,\n status: { code: serialized.statusCode, ...(serialized.statusMessage === undefined ? {} : { message: serialized.statusMessage }) },\n traceId: serialized.traceId,\n spanId: serialized.spanId,\n ...(serialized.parentSpanId === undefined ? {} : { parentSpanId: serialized.parentSpanId }),\n resource,\n instrumentationScope: scope,\n });\n\nexport type OtlpTraceSinkOptions = {\n readonly exporter: ExporterPolicy;\n /** Header values, kept out of the resolved-config snapshot (ADR: config carries only header *names*). */\n readonly headers?: Readonly<Record<string, string>>;\n readonly providerId: string;\n readonly installationId: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Persists batches an unreachable collector rejected, for a later retry. */\n readonly spool?: DurableSpool;\n readonly instrumentationScope?: InstrumentationScope;\n /**\n * Supplies cross-process pairing for lifecycle spans, normally the\n * {@link SpanCorrelator}. Omitted, the sink pairs only within a batch.\n *\n * Injected as a plain function rather than as a correlator so the telemetry\n * layer keeps no dependency on lifecycle or on the state store (ADR 0006).\n */\n readonly correlate?: SpanCorrelationResolver;\n /**\n * Export destination this sink delivers to, when `exporter.destinations` is in\n * use. Labels health snapshots, diagnostics, and log lines; absent, all three are\n * exactly what a single-destination installation has always produced.\n */\n readonly destination?: string;\n};\n\nexport interface OtlpTelemetrySink extends TelemetrySink {\n health(): DeliveryHealthSnapshot;\n /** Attempts to resend previously spooled batches, bounded by `maxBatches`. */\n drainSpool(maxBatches?: number): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }>;\n}\n\n/** Sink that accepts every batch and does nothing else: exporter disabled or protocol `none`. */\nconst createDisabledSink = (destination?: string): OtlpTelemetrySink => {\n const health = createHealthTracker(\n \"telemetry-sink\",\n destination === undefined ? {} : { destination },\n );\n return {\n emit: (events): Promise<TelemetryEmitResult> => {\n health.recordSuccess(events.length);\n return Promise.resolve({ accepted: events.length, rejected: 0, errors: [] });\n },\n flush: (): Promise<void> => Promise.resolve(),\n shutdown: (): Promise<void> => Promise.resolve(),\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool: (): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }> =>\n Promise.resolve({ drained: 0, remaining: 0, failed: 0 }),\n };\n};\n\n/**\n * OTLP HTTP/protobuf {@link TelemetrySink}.\n *\n * Semantic mapping lives entirely in `semconv.ts`; this module only owns\n * batching, delivery, bounded flush/shutdown, health tracking, and — when a\n * spool is configured — persisting what a down collector rejected. Every\n * failure mode (disabled config, missing endpoint, export failure, timeout,\n * spool write failure, unreadable correlation state) degrades to a reported\n * diagnostic rather than a thrown error, preserving the hook's fail-open\n * contract.\n *\n * A disabled sink never calls `correlate`: with nothing being exported there is\n * no span to pair, and writing correlation state anyway would leave a disabled\n * installation quietly accumulating files.\n */\nexport const createOtlpTraceSink = (options: OtlpTraceSinkOptions): OtlpTelemetrySink => {\n const destinationFields =\n options.destination === undefined ? {} : { \"export.destination\": options.destination };\n if (!options.exporter.enabled || options.exporter.protocol === \"none\") {\n return createDisabledSink(options.destination);\n }\n if (options.exporter.endpoint === undefined) {\n options.logger?.warn(\"otlp sink disabled: no endpoint configured\", destinationFields);\n return createDisabledSink(options.destination);\n }\n if (options.exporter.protocol !== \"http/protobuf\") {\n options.logger?.warn(\"otlp sink: protocol not supported by this build, falling back to disabled\", {\n \"exporter.protocol\": options.exporter.protocol,\n ...destinationFields,\n });\n return createDisabledSink(options.destination);\n }\n\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const resource = resourceFromExporterPolicy(options.exporter);\n const health = createHealthTracker(\n \"telemetry-sink\",\n options.destination === undefined ? {} : { destination: options.destination },\n );\n const exporter = new OTLPTraceExporter({\n url: options.exporter.endpoint,\n headers: { ...options.headers },\n timeoutMillis: options.exporter.timeoutMillis,\n });\n let shutdownCompleted = false;\n\n const exportSpans = (spans: readonly ReadableSpan[]): Promise<ExportResult> =>\n new Promise((resolve) => {\n exporter.export([...spans], (result: ExportResult) => resolve(result));\n });\n\n const toSpoolBatch = (spans: readonly ReadableSpan[], batchResource: Resource): SpoolBatch => ({\n providerId: options.providerId,\n installationId: options.installationId,\n resourceAttributes: { ...batchResource.attributes },\n instrumentationScope: { name: scope.name, ...(scope.version === undefined ? {} : { version: scope.version }) },\n spans: spans.map(serializeSpan),\n enqueuedAt: options.clock.now(),\n });\n\n const sendSerializedBatch = async (batch: SpoolBatch): Promise<SpoolSendOutcome> => {\n const batchResource = replayResource(batch.resourceAttributes, options.exporter);\n const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));\n const result = await exportSpans(spans);\n if (result.code === ExportResultCode.SUCCESS) {\n return true;\n }\n return isPermanentExportFailure(result) ? \"discard\" : false;\n };\n\n /**\n * Cross-process pairing is an enrichment, never a precondition: if state is\n * unreadable the batch still exports, with each lifecycle span flagged\n * unpaired rather than dropped.\n *\n * `available` is reported separately from the (possibly empty) list because the\n * mapping needs the two apart. An empty list from a healthy correlator and an\n * empty list from a correlator that threw look identical, and only the first\n * means \"the state store is holding these starts\". Conflating them would drop an\n * unpaired start that nothing recorded, and the export would then report zero\n * rejections — so a caller would commit a callback whose telemetry went nowhere.\n */\n const resolveCorrelations = async (\n events: readonly CanonicalEvent[],\n ): Promise<{\n readonly correlations: readonly SpanCorrelation[];\n readonly available: boolean | undefined;\n }> => {\n if (options.correlate === undefined) {\n return { correlations: [], available: undefined };\n }\n try {\n return { correlations: await options.correlate(events), available: true };\n } catch {\n options.logger?.warn(\"span correlation unavailable; exporting unpaired spans\", {});\n return { correlations: [], available: false };\n }\n };\n\n const emit = async (events: Parameters<TelemetrySink[\"emit\"]>[0]): Promise<TelemetryEmitResult> => {\n if (events.length === 0) {\n return { accepted: 0, rejected: 0, errors: [] };\n }\n const resolved = await resolveCorrelations(events);\n // Session context overrides the same keys on the Resource for this batch, so\n // a backend reading the Resource sees what the records say.\n const batchResource = resourceWithContext(resource, agreedContextAttributes(events));\n const spans = canonicalEventsToReadableSpans(events, {\n resource: batchResource,\n instrumentationScope: scope,\n correlations: resolved.correlations,\n ...(resolved.available === undefined ? {} : { correlationAvailable: resolved.available }),\n });\n const errors: OtelHookErrorInfo[] = [];\n let accepted = 0;\n let rejected = 0;\n\n for (const batch of chunk(spans, options.exporter.maxBatchSize)) {\n if (batch.length === 0) {\n // A batch of only start edges maps to no span at all: a lone `*.start` is\n // held for its end rather than exported. Sending it anyway POSTed an\n // `ExportTraceServiceRequest` with no resource spans — an empty body at the\n // collector — and, against a down collector, spooled an empty batch that\n // the drain could only quarantine.\n continue;\n }\n let result: ExportResult;\n try {\n result = await exportSpans(batch);\n } catch (thrown) {\n result = { code: ExportResultCode.FAILED, error: thrown instanceof Error ? thrown : new Error(\"export threw\") };\n }\n if (result.code === ExportResultCode.SUCCESS) {\n accepted += batch.length;\n health.recordSuccess(batch.length, options.clock.now());\n continue;\n }\n\n health.recordFailure(\"telemetry-export-failure\", batch.length, options.clock.now());\n const permanent = isPermanentExportFailure(result);\n if (options.spool !== undefined && !permanent) {\n const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({\n spooled: false as const,\n reason: \"capacity-exceeded\" as const,\n }));\n if (spoolResult.spooled) {\n accepted += batch.length;\n options.logger?.warn(\"span batch not delivered; spooled for the next invocation\", {\n \"export.batch_size\": batch.length,\n ...destinationFields,\n });\n continue;\n }\n }\n rejected += batch.length;\n errors.push(\n createErrorInfo({\n code: \"telemetry-export-failure\",\n phase: \"export\",\n detail: permanent\n ? \"collector refused a span batch with a non-retryable status\"\n : \"collector rejected or was unreachable for a span batch\",\n details: { \"export.batch_size\": batch.length, ...destinationFields },\n }),\n );\n }\n\n return { accepted, rejected, errors };\n };\n\n const drainSpool = async (\n maxBatches?: number,\n ): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }> => {\n if (options.spool === undefined) {\n return { drained: 0, remaining: 0, failed: 0 };\n }\n const result = await options.spool.drain(sendSerializedBatch, { ...(maxBatches === undefined ? {} : { maxBatches }) });\n if (result.drained > 0) {\n health.recordSuccess(result.drained, options.clock.now());\n }\n return result;\n };\n\n const flush = async (): Promise<void> => {\n try {\n await exporter.forceFlush();\n } catch {\n // Best-effort: flush failures are reported through health, never thrown.\n }\n await drainSpool().catch(() => undefined);\n };\n\n const shutdown = async (): Promise<void> => {\n if (shutdownCompleted) {\n return;\n }\n shutdownCompleted = true;\n await flush();\n try {\n await exporter.shutdown();\n } catch {\n // Idempotent, non-throwing per the TelemetrySink contract.\n }\n };\n\n return {\n emit,\n flush,\n shutdown,\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool,\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 type { OtelHookErrorCode } from \"../errors/index.js\";\nimport type { EpochMillis } from \"../model/primitives.js\";\n\n/**\n * One tracked delivery path.\n *\n * The two telemetry signals are separate subsystems because they fail\n * independently — a collector with no logs receiver leaves traces perfectly\n * healthy — and a single combined verdict would make an operator bisect which one\n * is broken. `telemetry-sink` remains the traces signal, unrenamed, so an existing\n * `doctor --json` consumer keeps reading the same field.\n */\nexport type DeliverySubsystem =\n | \"state-store\"\n | \"telemetry-sink\"\n | \"telemetry-log-sink\"\n | \"telemetry-metric-sink\"\n | \"lifecycle\";\n\n/**\n * Sanitized delivery health.\n *\n * Every field is a count, a timestamp, a boolean, or a closed-vocabulary error\n * code — the same restriction the privacy service applies to everything else\n * that might reach a sink, so a health snapshot is itself safe to export or log\n * without a second review.\n */\nexport type DeliveryHealthSnapshot = {\n readonly subsystem: DeliverySubsystem;\n readonly healthy: boolean;\n readonly totalAccepted: number;\n readonly totalRejected: number;\n readonly consecutiveFailures: number;\n readonly lastSuccessAt?: EpochMillis;\n readonly lastFailureAt?: EpochMillis;\n readonly lastErrorCode?: OtelHookErrorCode;\n /**\n * Export destination this snapshot describes. Present only when\n * `exporter.destinations` is in use, so a single-destination snapshot is\n * unchanged.\n */\n readonly destination?: string;\n};\n\nexport type HealthTrackerOptions = {\n /** Consecutive failures at or beyond this count flip `healthy` to false. Default 3. */\n readonly unhealthyAfterConsecutiveFailures?: number;\n /** Labels every snapshot with an export destination name. */\n readonly destination?: string;\n};\n\n/**\n * Accumulates success/failure counts for one subsystem instance.\n *\n * Deliberately per-instance rather than a module-level registry: a store or\n * sink constructs its own tracker and exposes a `health()` accessor, so two\n * instances in one process never share counters (see ADR 0001 on module-level\n * identity).\n */\nexport interface HealthTracker {\n recordSuccess(count?: number, at?: number): void;\n recordFailure(code: OtelHookErrorCode, count?: number, at?: number): void;\n snapshot(): DeliveryHealthSnapshot;\n}\n\nexport const createHealthTracker = (\n subsystem: DeliverySubsystem,\n options: HealthTrackerOptions = {},\n): HealthTracker => {\n const unhealthyThreshold = options.unhealthyAfterConsecutiveFailures ?? 3;\n let totalAccepted = 0;\n let totalRejected = 0;\n let consecutiveFailures = 0;\n let lastSuccessAt: number | undefined;\n let lastFailureAt: number | undefined;\n let lastErrorCode: OtelHookErrorCode | undefined;\n\n return {\n recordSuccess: (count = 1, at?: number): void => {\n totalAccepted += count;\n consecutiveFailures = 0;\n if (at !== undefined) {\n lastSuccessAt = at;\n }\n },\n recordFailure: (code: OtelHookErrorCode, count = 1, at?: number): void => {\n totalRejected += count;\n consecutiveFailures += 1;\n lastErrorCode = code;\n if (at !== undefined) {\n lastFailureAt = at;\n }\n },\n snapshot: (): DeliveryHealthSnapshot => ({\n subsystem,\n healthy: consecutiveFailures < unhealthyThreshold,\n totalAccepted,\n totalRejected,\n consecutiveFailures,\n ...(lastSuccessAt === undefined ? {} : { lastSuccessAt }),\n ...(lastFailureAt === undefined ? {} : { lastFailureAt }),\n ...(lastErrorCode === undefined ? {} : { lastErrorCode }),\n ...(options.destination === undefined ? {} : { destination: options.destination }),\n }),\n };\n};\n\nexport type OverallHealth = {\n readonly healthy: boolean;\n readonly subsystems: readonly DeliveryHealthSnapshot[];\n};\n\n/** Combines snapshots from every configured subsystem into one overall verdict. */\nexport const summarizeHealth = (snapshots: readonly DeliveryHealthSnapshot[]): OverallHealth => ({\n healthy: snapshots.every((snapshot) => snapshot.healthy),\n subsystems: [...snapshots],\n});\n","import type { ExportResult } from \"@opentelemetry/core\";\n\n/**\n * HTTP statuses that mean \"try again later\" rather than \"never send this\".\n *\n * The OTLP specification's retryable set (429, 502, 503, 504), plus:\n *\n * - 408, which is a timeout by another name;\n * - 500, by decision for this project: a backend that is restarting, overloaded,\n * or briefly broken commonly answers 500, and losing those batches costs more\n * than retrying them. A backend that answers 500 *forever* cannot pin a batch\n * in the spool: every spooled batch is still subject to the spool's age,\n * size, and count bounds (`exporter.spool`), and is dropped and counted when\n * it exceeds them.\n *\n * Anything else the server answered with a status for is a refusal of *this\n * batch*: replaying it can only fail the same way, and a spool that kept it would\n * retry it on every invocation and stop behind it.\n */\nexport const RETRYABLE_HTTP_STATUSES: ReadonlySet<number> = new Set([408, 429, 500, 502, 503, 504]);\n\n/**\n * Whether a failed export was a permanent refusal.\n *\n * With `@opentelemetry/otlp-exporter-base` (OpenTelemetry JS 3.x), the HTTP\n * transport reports a status outside its own retryable set (429, 502, 503, 504)\n * as an `OTLPExporterError` whose numeric `code` is the HTTP status — so 400,\n * 401, 408, 413, and 500 all arrive with a `code`, and 408 and 500 are then held\n * retryable here. Its retryable statuses are retried inside the exporter and,\n * once retries or the timeout run out, arrive without a `code`, as do a refused\n * connection, a timeout, and an oversized response. Those are exactly the \"never\n * reached it, or asked us to come back\" failures a spool is for.\n */\nexport const isPermanentExportFailure = (result: ExportResult): boolean => {\n const code = (result.error as { readonly code?: unknown } | undefined)?.code;\n return (\n typeof code === \"number\" &&\n Number.isInteger(code) &&\n code >= 400 &&\n code < 600 &&\n !RETRYABLE_HTTP_STATUSES.has(code)\n );\n};\n","import { resourceFromAttributes, type Resource } from \"@opentelemetry/resources\";\nimport type { Attributes } from \"@opentelemetry/api\";\n\nimport {\n checkResourceAttributeKey,\n isReservedResourceAttributeKey,\n MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH,\n MAX_RESOURCE_ATTRIBUTES,\n sanitizeResourceAttributes,\n} from \"../config/resource-attributes.js\";\nimport type { ExporterPolicy } from \"../config/schema.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport { MAX_IDENTIFIER_LENGTH } from \"../model/primitives.js\";\n\n/**\n * The OTLP `Resource` every record of a signal is exported under.\n *\n * Shared by the trace and log sinks rather than written twice: a resource carries\n * the service identity, so two sinks disagreeing about how it is built or\n * re-validated would attribute the same installation's two signals to two\n * services — and the divergence would only be visible in a backend, long after.\n */\n\n/**\n * Resource for the live path, from exporter policy.\n *\n * Custom attributes first, then service identity: spread order makes the policy\n * fields structurally unoverridable. `sanitizeResourceAttributes` already drops\n * the reserved keys, so this is belt-and-braces for a caller who hand-built an\n * `ExporterPolicy` without running it through the schema — but between them,\n * `service.name` can only ever come from policy.\n */\nexport const resourceFromExporterPolicy = (policy: ExporterPolicy): Resource =>\n resourceFromAttributes({\n ...sanitizeResourceAttributes(policy.resourceAttributes),\n \"service.name\": policy.serviceName,\n ...(policy.serviceNamespace === undefined\n ? {}\n : { \"service.namespace\": policy.serviceNamespace }),\n });\n\n/**\n * A spool file is a plain JSON file in a state directory, so everything read back\n * out of one is untrusted input — it can be hand-edited, truncated, or written by\n * an older release with a different schema. These bounds mirror the live path's,\n * because \"what the exporter would have refused from a flag\" and \"what it accepts\n * from disk\" diverging is the whole vulnerability.\n */\nconst isReplayableValue = (value: unknown): value is string | number | boolean =>\n (typeof value === \"string\" && value.length <= MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) ||\n (typeof value === \"number\" && Number.isFinite(value)) ||\n typeof value === \"boolean\";\n\n/**\n * Validate a service identity read back from a spool file.\n *\n * `service.name` decides which service every replayed record is attributed to, so\n * a spool that could set it freely could attribute this installation's telemetry\n * to somebody else's service — the one resource field where a forged value is a\n * reporting-integrity problem rather than a cosmetic one. It is therefore held to\n * the same contract as the typed policy field: a non-empty string within\n * {@link MAX_IDENTIFIER_LENGTH}. Anything else is not \"replayed as recorded\", it is\n * discarded in favour of the draining process's own policy.\n */\nconst replayableServiceIdentity = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 && value.length <= MAX_IDENTIFIER_LENGTH\n ? value\n : undefined;\n\n/**\n * Rebuild the resource a spooled batch was recorded with.\n *\n * A recorded `service.name` is a fact about the process that made the observation,\n * not about the one draining the spool, so a *valid* one is replayed as recorded.\n * But every field is re-validated on the way out, at the same bounds the live path\n * enforces: custom keys must pass {@link checkResourceAttributeKey} (which refuses\n * reserved and secret-looking names), values must be primitives within the length\n * bound, the custom count is capped, and the two reserved service fields must look\n * like the identifiers they are. A batch that fails the service check falls back to\n * the live policy rather than exporting with no service identity, because a resource\n * without `service.name` is rejected or bucketed as \"unknown_service\" by most\n * collectors — losing the batch to a tampered byte would make the validation itself\n * the outage.\n */\nexport const replayResource = (attributes: Attributes, policy: ExporterPolicy): Resource => {\n const safe: Record<string, string | number | boolean> = {};\n let customCount = 0;\n for (const [key, value] of Object.entries(attributes)) {\n if (isReservedResourceAttributeKey(key)) {\n // Handled below against the policy fallback, never copied verbatim.\n continue;\n }\n if (!isReplayableValue(value)) {\n continue;\n }\n if (checkResourceAttributeKey(key) !== undefined || customCount >= MAX_RESOURCE_ATTRIBUTES) {\n continue;\n }\n customCount += 1;\n safe[key] = value;\n }\n\n // Reserved keys last and unconditionally, so a spooled custom attribute can\n // never occupy the slot a service field is about to be written into.\n const recordedName = replayableServiceIdentity(attributes[\"service.name\"]);\n const recordedNamespace = replayableServiceIdentity(attributes[\"service.namespace\"]);\n safe[\"service.name\"] = recordedName ?? policy.serviceName;\n const namespace = recordedNamespace ?? policy.serviceNamespace;\n if (namespace !== undefined) {\n safe[\"service.namespace\"] = namespace;\n }\n\n return resourceFromAttributes(safe);\n};\n\n/**\n * The session context attributes every event of a batch agrees on.\n *\n * The core stamps one invocation's events from one context file, so a batch\n * normally agrees on everything. Should two events disagree on a key (a segment\n * boundary inside one callback), or one event lack it, the key is left out: the\n * Resource is shared by the whole batch and must not state a value one of its\n * records contradicts. Each record still carries its own value.\n */\nexport const agreedContextAttributes = (\n events: readonly CanonicalEvent[],\n): Readonly<Record<string, string | number | boolean>> => {\n const [first, ...rest] = events;\n if (first?.contextAttributes === undefined) {\n return {};\n }\n const agreed: Record<string, string | number | boolean> = { ...first.contextAttributes };\n for (const event of rest) {\n for (const key of Object.keys(agreed)) {\n if (event.contextAttributes?.[key] !== agreed[key]) {\n delete agreed[key];\n }\n }\n }\n return agreed;\n};\n\n/**\n * The Resource a batch is exported under, with session context applied.\n *\n * Context overrides only keys the Resource already carries — a stale\n * `factory.attempt.id` from the process environment, say — so the Resource and\n * the records say the same thing to a backend that reads either. It adds no new\n * key: the Resource describes the producer, and the context's own keys are on\n * every record already. Service identity is never touched (context cannot carry\n * it). Returns the input unchanged when nothing applies.\n */\nexport const resourceWithContext = (\n resource: Resource,\n context: Readonly<Record<string, string | number | boolean>>,\n): Resource => {\n const overrides: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(context)) {\n if (\n Object.hasOwn(resource.attributes, key) &&\n !isReservedResourceAttributeKey(key) &&\n resource.attributes[key] !== value\n ) {\n overrides[key] = value;\n }\n }\n if (Object.keys(overrides).length === 0) {\n return resource;\n }\n return resourceFromAttributes({ ...resource.attributes, ...overrides });\n};\n","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\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 { SeverityNumber, TraceFlags, type Attributes, type SpanContext } from \"@opentelemetry/api\";\nimport { millisToHrTime, type InstrumentationScope } from \"@opentelemetry/core\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport type { ReadableLogRecord } from \"@opentelemetry/sdk-logs\";\nimport {\n ATTR_ERROR_TYPE,\n ATTR_GEN_AI_OPERATION_NAME,\n ATTR_GEN_AI_REQUEST_MODEL,\n ATTR_GEN_AI_RESPONSE_MODEL,\n ATTR_GEN_AI_SYSTEM,\n ATTR_GEN_AI_TOOL_CALL_ID,\n ATTR_GEN_AI_TOOL_NAME,\n ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n} from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport type { ContentFact } from \"../model/content.js\";\nimport type { CanonicalEvent, CanonicalEventType } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\nimport {\n exportIdentityAttributes,\n targetAttributes,\n usageTemporalityAttributes,\n} from \"./export-identity.js\";\nimport {\n ATTR_OTELHOOK_USAGE_PARTIAL,\n canonicalEventTraceIdentities,\n DEFAULT_INSTRUMENTATION_SCOPE,\n type SpanCorrelation,\n} from \"./semconv.js\";\n\n/**\n * Pure, stateless canonical-event-to-OTLP-log-record mapping.\n *\n * The counterpart of `semconv.ts` for the logs signal, and deliberately the same\n * shape: no state is read here, no clock is consulted, and the only inputs are\n * the batch plus the correlations the caller already resolved. Batching, retry,\n * spooling, and delivery live in `otlp-log-sink.ts`.\n *\n * ## Why logs at all, when traces already exist\n *\n * A span reports that a tool call happened, how long it took, and whether it\n * failed. It does not report *what was in it*, and it cannot: span attributes are\n * a flat bounded map, one record per span, exported once. A conversation turn is a\n * sequence of distinct pieces of content — a prompt, a response, reasoning, a tool\n * input, a tool output — each with its own role, its own length, and its own\n * disclosure decision. That is a log stream, and OTLP has one.\n *\n * So this mapping emits **one record per content fact**, plus one record per event\n * that carries no content, and correlates every record to the span the same batch\n * produced (or will produce). Nothing here decides *whether* content is\n * disclosed — the privacy service already did that, upstream, once — but the\n * gate is re-checked here because this is the last boundary before the wire.\n *\n * ## Identity and correlation\n *\n * Every record carries the same identity attributes a span does, and a\n * `spanContext` built from {@link canonicalEventTraceIdentities}: the trace id and\n * span id are derived from the event's own `(providerId, sessionId)` and its\n * lifecycle scope, so a record lands in the same trace as its span without either\n * signal knowing about the other. Two sessions in one batch derive two trace ids;\n * there is no batch-level or module-level trace state to contaminate.\n */\n\n/**\n * Version of this mapping.\n *\n * Consumers pin it. Bumped on any change to what an existing attribute or signal\n * *means*; adding a new attribute or a new signal value does not bump it, on the\n * same additive-compatibility rule the canonical model follows\n * (`CANONICAL_SCHEMA_VERSION`). Every record carries it as\n * `otelhook.log.mapping_version`, so a consumer never has to infer which\n * vocabulary it is reading.\n */\nexport const LOG_MAPPING_VERSION = 1 as const;\n\n/**\n * Coarse routing key for one log record.\n *\n * The fact's own `otelhook.content.kind` states precisely what the content is;\n * this states which *pipeline* it belongs to, so an operator can route or drop a\n * whole class (\"no tool output off this host\") with one collector rule rather\n * than an enumeration of event types.\n */\nexport const LOG_SIGNALS = [\n \"session\",\n \"prompt\",\n \"response\",\n \"reasoning\",\n \"tool\",\n \"shell\",\n \"file-operation\",\n \"mcp\",\n \"delegation\",\n \"compaction\",\n \"error\",\n] as const;\nexport type LogSignal = (typeof LOG_SIGNALS)[number];\n\n/**\n * Naming convention that marks a tool call as MCP-mediated.\n *\n * The canonical model has no \"this went through MCP\" field, because no provider\n * contract this package has verified carries one: what they carry is a *tool\n * name*, and three of the four non-synthetic contracts (Claude Code, Codex,\n * Gemini CLI) name MCP tools `mcp__<server>__<tool>`. So the convention is the\n * evidence, matched on the canonical tool name rather than on any provider's\n * payload.\n *\n * This deliberately **under-reports**: a provider whose MCP tool names do not\n * follow the convention classifies as `tool`, which is true but less specific.\n * The alternative — per-provider branching in the canonical layer, or a canonical\n * field no adapter can populate from a verified contract — would either leak\n * provider knowledge across the boundary or invent a contract. See\n * `docs/canonical-log-mapping.md`.\n */\nexport const MCP_TOOL_NAME_PATTERN = /^mcp__/i;\n\n/**\n * Most records one event may produce.\n *\n * Matches `contentFactsSchema`'s own cap, so in practice the mapping never drops\n * a fact an adapter produced; it is the backstop for a hand-built event, not a\n * routine truncation.\n */\nexport const MAX_LOG_RECORDS_PER_EVENT = 64;\n\n/** Most records one batch may produce, whatever the batch contains. */\nexport const MAX_LOG_RECORDS_PER_BATCH = 2_048;\n\n/**\n * Longest disclosed body this mapping will put on the wire.\n *\n * Separate from, and stricter than, the privacy policy's `maxStringLength` (which\n * may be configured up to 64Ki characters): a policy bound is about *disclosure*,\n * this is about the size of one OTLP record. A body cut here is reported as\n * `otelhook.content.body_truncated` rather than as the fact's own `truncated`\n * flag, so \"the privacy policy shortened this\" and \"the log record shortened\n * this\" stay distinguishable.\n */\nexport const MAX_LOG_BODY_CHARACTERS = 8_192;\n\nconst ATTR_OTELHOOK_EVENT_TYPE = \"otelhook.event.type\";\nconst ATTR_OTELHOOK_EVENT_ID = \"otelhook.event.id\";\nconst ATTR_OTELHOOK_EVENT_SEQUENCE = \"otelhook.event.sequence\";\nconst ATTR_OTELHOOK_LOG_SIGNAL = \"otelhook.log.signal\";\nconst ATTR_OTELHOOK_LOG_MAPPING_VERSION = \"otelhook.log.mapping_version\";\nconst ATTR_OTELHOOK_OUTCOME = \"otelhook.outcome\";\nconst ATTR_OTELHOOK_TOOL_KIND = \"otelhook.tool.kind\";\nconst ATTR_OTELHOOK_TOOL_PERMISSION = \"otelhook.tool.permission_decision\";\nconst ATTR_OTELHOOK_DELEGATION_DEPTH = \"otelhook.delegation_depth\";\nconst ATTR_OTELHOOK_SUBAGENT_TYPE = \"otelhook.subagent.type\";\nconst ATTR_OTELHOOK_AGENT_NAME = \"otelhook.agent.name\";\nconst ATTR_OTELHOOK_AGENT_VERSION = \"otelhook.agent.version\";\nconst ATTR_OTELHOOK_SESSION_KIND = \"otelhook.session.kind\";\nconst ATTR_OTELHOOK_PROMPT_SOURCE = \"otelhook.prompt.source\";\nconst ATTR_OTELHOOK_PROMPT_TURN_INDEX = \"otelhook.prompt.turn_index\";\nconst ATTR_OTELHOOK_GENERATION_ID = \"otelhook.generation.id\";\nconst ATTR_OTELHOOK_STOP_REASON = \"otelhook.generation.stop_reason\";\nconst ATTR_OTELHOOK_COMPACTION_TRIGGER = \"otelhook.compaction.trigger\";\nconst ATTR_OTELHOOK_CONTEXT_TOKENS_BEFORE = \"otelhook.compaction.context_tokens_before\";\nconst ATTR_OTELHOOK_CONTEXT_TOKENS_AFTER = \"otelhook.compaction.context_tokens_after\";\nconst ATTR_OTELHOOK_DROPPED_MESSAGES = \"otelhook.compaction.dropped_message_count\";\nconst ATTR_OTELHOOK_ERROR_PHASE = \"otelhook.error.phase\";\nconst ATTR_OTELHOOK_ERROR_RETRYABLE = \"otelhook.error.retryable\";\nconst ATTR_OTELHOOK_ERROR_SEVERITY = \"otelhook.error.severity\";\n\nconst ATTR_CONTENT_KIND = \"otelhook.content.kind\";\nconst ATTR_CONTENT_ROLE = \"otelhook.content.role\";\nconst ATTR_CONTENT_DISCLOSURE = \"otelhook.content.disclosure\";\nconst ATTR_CONTENT_CHARACTER_LENGTH = \"otelhook.content.character_length\";\nconst ATTR_CONTENT_BYTE_LENGTH = \"otelhook.content.byte_length\";\nconst ATTR_CONTENT_HASH = \"otelhook.content.hash\";\nconst ATTR_CONTENT_TRUNCATED = \"otelhook.content.truncated\";\nconst ATTR_CONTENT_SECRETS_REDACTED = \"otelhook.content.secrets_redacted\";\nconst ATTR_CONTENT_LABEL = \"otelhook.content.label\";\nconst ATTR_CONTENT_WITHHELD = \"otelhook.content.withheld\";\nconst ATTR_CONTENT_BODY_TRUNCATED = \"otelhook.content.body_truncated\";\n\n/**\n * Why a content fact reached the wire without its text.\n *\n * Stated rather than left as an absence, because \"this prompt was empty\", \"this\n * deployment omits content\", and \"this deployment discloses content but not to\n * the logs pipeline\" are three different operational facts that all look like a\n * missing body.\n */\nexport type ContentWithholdingReason =\n /** The privacy policy produced no text at all — the default `omit` posture. */\n | \"privacy-policy\"\n /** Content is disclosed elsewhere, but the logs pipeline is not permitted it. */\n | \"logs-content-disabled\"\n /** The fact carries verbatim text and `allowRawContent` is not set. */\n | \"raw-not-permitted\";\n\n/**\n * Whether disclosed content text may reach a log body.\n *\n * Two gates rather than one, and both must open. `includeContent` is the logs\n * pipeline's own switch, and it exists because spans carry no content in *any*\n * content mode: without it, turning on `privacy.contentMode` to get a hash and a\n * length — which is all it ever bought before — would start putting prompts on\n * the wire. `allowRawContent` is the pre-existing verbatim-content opt-in,\n * re-checked here because the sink is the last boundary before the wire and a\n * hand-built fact could otherwise carry `disclosure: \"raw\"` past a policy that\n * never permitted it.\n */\nexport type LogContentPolicy = {\n readonly includeContent: boolean;\n readonly allowRawContent: boolean;\n};\n\n/** Content disabled, which is what an unconfigured installation gets. */\nexport const NO_LOG_CONTENT: LogContentPolicy = Object.freeze({\n includeContent: false,\n allowRawContent: false,\n});\n\nconst codePointLength = (value: string): number => [...value].length;\n\nconst sliceCodePoints = (value: string, max: number): string => {\n let result = \"\";\n let count = 0;\n for (const char of value) {\n if (count >= max) {\n break;\n }\n result += char;\n count += 1;\n }\n return result;\n};\n\n/**\n * Which pipeline an event's records belong to.\n *\n * `factKind` refines the answer where one event type carries more than one kind\n * of content: a `generation.end` holds the response *and*, on providers that\n * report it, the reasoning that produced it, and collapsing those into one signal\n * would make \"drop reasoning, keep responses\" unexpressible.\n */\nexport const logSignalOf = (event: CanonicalEvent, factKind?: ContentFact[\"kind\"]): LogSignal => {\n switch (event.type) {\n case \"session.start\":\n case \"session.end\":\n return \"session\";\n case \"prompt.submitted\":\n return \"prompt\";\n case \"generation.start\":\n return factKind === \"reasoning\" ? \"reasoning\" : \"prompt\";\n case \"generation.end\":\n return factKind === \"reasoning\" ? \"reasoning\" : \"response\";\n case \"subagent.start\":\n case \"subagent.end\":\n return \"delegation\";\n case \"compaction.performed\":\n return \"compaction\";\n case \"error.raised\":\n return \"error\";\n case \"tool.start\":\n return toolSignal(event.toolName, event.toolKind);\n case \"tool.end\":\n // A `tool.end` carries no `toolKind`: only the start edge does. Classifying\n // from the name alone is what the canonical model permits here, so a shell\n // or file operation whose name does not say so lands on `tool` — and the\n // span for the same scope, which *did* recover the kind from state, is where\n // that detail is authoritative.\n return toolSignal(event.toolName, undefined);\n }\n};\n\nconst toolSignal = (\n toolName: string,\n toolKind: Extract<CanonicalEvent, { type: \"tool.start\" }>[\"toolKind\"] | undefined,\n): LogSignal => {\n if (MCP_TOOL_NAME_PATTERN.test(toolName)) {\n return \"mcp\";\n }\n switch (toolKind) {\n case \"execute\":\n return \"shell\";\n case \"read\":\n case \"write\":\n return \"file-operation\";\n case \"delegate\":\n return \"delegation\";\n default:\n return \"tool\";\n }\n};\n\n/**\n * Log signals an adapter declaring these lifecycle events can produce.\n *\n * Derived from the adapter's existing `lifecycleEvents` declaration rather than\n * declared separately, which is the whole point: a hand-maintained second list\n * can disagree with the first, and a capability declaration that has gone stale is\n * worse than none — a consumer cannot tell \"this provider reports no tool output\"\n * from \"this declaration was never updated\".\n *\n * The tool refinements (`shell`, `file-operation`, `mcp`) are reported whenever\n * the adapter emits tool events at all, because which of them a given callback\n * produces depends on the payload, not on the adapter. So this is a statement\n * about what *may* appear, not what always will.\n */\nexport const logSignalsForLifecycleEvents = (\n lifecycleEvents: readonly CanonicalEventType[],\n): readonly LogSignal[] => {\n const signals = new Set<LogSignal>();\n const add = (...values: readonly LogSignal[]): void => {\n for (const value of values) {\n signals.add(value);\n }\n };\n for (const type of lifecycleEvents) {\n switch (type) {\n case \"session.start\":\n case \"session.end\":\n add(\"session\");\n break;\n case \"prompt.submitted\":\n add(\"prompt\");\n break;\n case \"generation.start\":\n add(\"prompt\");\n break;\n case \"generation.end\":\n add(\"response\", \"reasoning\");\n break;\n case \"tool.start\":\n case \"tool.end\":\n add(\"tool\", \"shell\", \"file-operation\", \"mcp\", \"delegation\");\n break;\n case \"subagent.start\":\n case \"subagent.end\":\n add(\"delegation\");\n break;\n case \"compaction.performed\":\n add(\"compaction\");\n break;\n case \"error.raised\":\n add(\"error\");\n break;\n }\n }\n return LOG_SIGNALS.filter((signal) => signals.has(signal));\n};\n\nconst severityFor = (event: CanonicalEvent): SeverityNumber => {\n switch (event.type) {\n case \"error.raised\":\n return event.severity === \"error\" ? SeverityNumber.ERROR : SeverityNumber.WARN;\n case \"session.end\":\n return event.reason === \"error\" || event.reason === \"timeout\"\n ? SeverityNumber.ERROR\n : event.reason === \"aborted\"\n ? SeverityNumber.WARN\n : SeverityNumber.INFO;\n case \"generation.end\":\n case \"tool.end\":\n case \"subagent.end\":\n return event.outcome === \"error\" || event.outcome === \"timeout\"\n ? SeverityNumber.ERROR\n : event.outcome === \"denied\" || event.outcome === \"cancelled\"\n ? SeverityNumber.WARN\n : SeverityNumber.INFO;\n default:\n return SeverityNumber.INFO;\n }\n};\n\nconst SEVERITY_TEXT: Readonly<Record<number, string>> = Object.freeze({\n [SeverityNumber.INFO]: \"INFO\",\n [SeverityNumber.WARN]: \"WARN\",\n [SeverityNumber.ERROR]: \"ERROR\",\n});\n\nconst identityAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n ids: { readonly traceId: string; readonly spanId: string; readonly parentSpanId?: string },\n): Attributes => exportIdentityAttributes(event, resource, ids);\n\n/**\n * Attributes describing the event itself, independent of any content it carries.\n *\n * Every attribute here is a closed vocabulary, an identifier this library\n * derived, a count, or a boolean — the same restriction the privacy service\n * applies everywhere else, so an attribute can never become a second disclosure\n * path alongside the body.\n */\nconst eventAttributes = (event: CanonicalEvent): Attributes => {\n switch (event.type) {\n case \"session.start\":\n return {\n [ATTR_OTELHOOK_SESSION_KIND]: event.sessionKind,\n ...(event.agentName === undefined ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: event.agentName }),\n ...(event.agentVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_AGENT_VERSION]: event.agentVersion }),\n ...(event.model === undefined\n ? {}\n : { [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId }),\n ...targetAttributes(event),\n };\n case \"session.end\":\n return {\n [ATTR_OTELHOOK_OUTCOME]: event.reason,\n ...usageAttributes(event.usage),\n };\n case \"prompt.submitted\":\n return {\n [ATTR_OTELHOOK_PROMPT_SOURCE]: event.promptSource,\n ...(event.turnIndex === undefined\n ? {}\n : { [ATTR_OTELHOOK_PROMPT_TURN_INDEX]: event.turnIndex }),\n ...targetAttributes(event),\n };\n case \"generation.start\":\n return {\n [ATTR_GEN_AI_OPERATION_NAME]: \"chat\",\n [ATTR_OTELHOOK_GENERATION_ID]: event.generationId,\n [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId,\n ...(event.model.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: event.model.vendor }),\n };\n case \"generation.end\":\n return {\n [ATTR_GEN_AI_OPERATION_NAME]: \"chat\",\n [ATTR_OTELHOOK_GENERATION_ID]: event.generationId,\n [ATTR_GEN_AI_RESPONSE_MODEL]: event.model.modelId,\n ...(event.model.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: event.model.vendor }),\n [ATTR_OTELHOOK_OUTCOME]: event.outcome,\n ...(event.stopReason === undefined ? {} : { [ATTR_OTELHOOK_STOP_REASON]: event.stopReason }),\n ...usageAttributes(event.usage),\n ...(event.usage === undefined || event.usagePartial === undefined\n ? {}\n : { [ATTR_OTELHOOK_USAGE_PARTIAL]: event.usagePartial }),\n };\n case \"tool.start\":\n return {\n [ATTR_GEN_AI_TOOL_NAME]: event.toolName,\n [ATTR_GEN_AI_TOOL_CALL_ID]: event.toolCallId,\n [ATTR_OTELHOOK_TOOL_KIND]: event.toolKind,\n ...(event.generationId === undefined\n ? {}\n : { [ATTR_OTELHOOK_GENERATION_ID]: event.generationId }),\n ...targetAttributes(event),\n };\n case \"tool.end\":\n return {\n [ATTR_GEN_AI_TOOL_NAME]: event.toolName,\n [ATTR_GEN_AI_TOOL_CALL_ID]: event.toolCallId,\n [ATTR_OTELHOOK_OUTCOME]: event.outcome,\n ...(event.permissionDecision === undefined\n ? {}\n : { [ATTR_OTELHOOK_TOOL_PERMISSION]: event.permissionDecision }),\n ...targetAttributes(event),\n };\n case \"subagent.start\":\n return {\n [ATTR_OTELHOOK_DELEGATION_DEPTH]: event.delegationDepth,\n ...(event.subagentType === undefined\n ? {}\n : { [ATTR_OTELHOOK_SUBAGENT_TYPE]: event.subagentType }),\n ...(event.model === undefined ? {} : { [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId }),\n };\n case \"subagent.end\":\n return {\n [ATTR_OTELHOOK_OUTCOME]: event.outcome,\n ...usageAttributes(event.usage),\n };\n case \"compaction.performed\":\n return {\n [ATTR_OTELHOOK_COMPACTION_TRIGGER]: event.trigger,\n ...(event.contextTokensBefore === undefined\n ? {}\n : { [ATTR_OTELHOOK_CONTEXT_TOKENS_BEFORE]: event.contextTokensBefore }),\n ...(event.contextTokensAfter === undefined\n ? {}\n : { [ATTR_OTELHOOK_CONTEXT_TOKENS_AFTER]: event.contextTokensAfter }),\n ...(event.droppedMessageCount === undefined\n ? {}\n : { [ATTR_OTELHOOK_DROPPED_MESSAGES]: event.droppedMessageCount }),\n ...usageAttributes(event.usage),\n };\n case \"error.raised\":\n return {\n [ATTR_ERROR_TYPE]: event.errorCode,\n [ATTR_OTELHOOK_ERROR_PHASE]: event.phase,\n [ATTR_OTELHOOK_ERROR_RETRYABLE]: event.retryable,\n [ATTR_OTELHOOK_ERROR_SEVERITY]: event.severity,\n };\n }\n};\n\nconst usageAttributes = (usage: CanonicalUsage | undefined): Attributes =>\n usage === undefined\n ? {}\n : {\n [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: usage.inputTokens,\n [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: usage.outputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: usage.cachedInputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: usage.cacheCreationInputTokens,\n ...usageTemporalityAttributes(usage),\n };\n\n/** Content facts an event carries, paired with the field they came from. */\nconst contentFactsOf = (event: CanonicalEvent): readonly ContentFact[] => {\n switch (event.type) {\n case \"prompt.submitted\":\n return event.content === undefined ? [] : [event.content];\n case \"generation.start\":\n return event.inputContent ?? [];\n case \"generation.end\":\n return event.outputContent ?? [];\n case \"tool.start\":\n return event.input === undefined ? [] : [event.input];\n case \"tool.end\":\n return event.output === undefined ? [] : [event.output];\n case \"error.raised\":\n return event.message === undefined ? [] : [event.message];\n default:\n return [];\n }\n};\n\ntype DisclosedBody =\n | { readonly text: string; readonly truncated: boolean }\n | { readonly withheld: ContentWithholdingReason }\n | { readonly metadataOnly: true };\n\nconst discloseBody = (fact: ContentFact, policy: LogContentPolicy): DisclosedBody => {\n if (fact.text === undefined && fact.characterLength === 0) {\n // The provider sent no text. Distinct from a privacy omit of real content:\n // there is nothing to withhold, and the record must say metadata_only.\n return { metadataOnly: true };\n }\n if (fact.text === undefined) {\n return { withheld: \"privacy-policy\" };\n }\n if (!policy.includeContent) {\n return { withheld: \"logs-content-disabled\" };\n }\n if (fact.disclosure === \"raw\" && !policy.allowRawContent) {\n // Belt to the privacy service's braces: `resolvePrivacyPolicy` already\n // downgrades `raw` without the opt-in, so reaching here means a fact was built\n // outside that path. Refusing rather than trusting it keeps the opt-in a\n // property of the wire, not of one code path.\n return { withheld: \"raw-not-permitted\" };\n }\n const length = codePointLength(fact.text);\n return length <= MAX_LOG_BODY_CHARACTERS\n ? { text: fact.text, truncated: false }\n : { text: sliceCodePoints(fact.text, MAX_LOG_BODY_CHARACTERS), truncated: true };\n};\n\nconst contentAttributes = (fact: ContentFact, body: DisclosedBody): Attributes => ({\n [ATTR_CONTENT_KIND]: fact.kind,\n ...(fact.role === undefined ? {} : { [ATTR_CONTENT_ROLE]: fact.role }),\n [ATTR_CONTENT_DISCLOSURE]: \"metadataOnly\" in body ? \"metadata_only\" : fact.disclosure,\n [ATTR_CONTENT_CHARACTER_LENGTH]: fact.characterLength,\n [ATTR_CONTENT_BYTE_LENGTH]: fact.byteLength,\n [ATTR_CONTENT_HASH]: fact.contentHash,\n [ATTR_CONTENT_TRUNCATED]: fact.truncated,\n [ATTR_CONTENT_SECRETS_REDACTED]: fact.secretsRedacted,\n ...(fact.label === undefined ? {} : { [ATTR_CONTENT_LABEL]: fact.label }),\n ...(\"withheld\" in body\n ? { [ATTR_CONTENT_WITHHELD]: body.withheld }\n : \"metadataOnly\" in body\n ? {}\n : { [ATTR_CONTENT_BODY_TRUNCATED]: body.truncated }),\n});\n\nexport type LogMappingOptions = {\n readonly resource: Resource;\n readonly instrumentationScope?: InstrumentationScope;\n /** Whether disclosed text may reach a body. Defaults to {@link NO_LOG_CONTENT}. */\n readonly content?: LogContentPolicy;\n /**\n * The same cross-process pairing facts the span mapping is given, so a record's\n * `spanContext` names the span id that batch actually exported.\n */\n readonly correlations?: readonly SpanCorrelation[];\n /** See `SemanticMappingOptions.correlationAvailable`. */\n readonly correlationAvailable?: boolean;\n};\n\nexport type LogMappingResult = {\n readonly records: readonly ReadableLogRecord[];\n /**\n * Content facts no record was produced for, because a bound was reached.\n *\n * Reported rather than truncated silently: a caller that logged \"N records\n * exported\" and nothing else would read a clipped batch as a complete one.\n */\n readonly droppedFacts: number;\n};\n\nconst buildRecord = (input: {\n readonly event: CanonicalEvent;\n readonly signal: LogSignal;\n readonly attributes: Attributes;\n readonly body?: string;\n readonly spanContext: SpanContext;\n readonly parentSpanId?: string;\n readonly resource: Resource;\n readonly scope: InstrumentationScope;\n}): ReadableLogRecord => {\n const severityNumber = severityFor(input.event);\n const hrTime = millisToHrTime(input.event.occurredAt);\n return {\n hrTime,\n // A hook observes an event that already happened, and this mapping is pure —\n // there is no clock here to read a real observation time from. Reporting the\n // occurrence time for both is the honest answer: it says \"this is when it\n // happened\" twice rather than inventing a second, wrong timestamp.\n hrTimeObserved: hrTime,\n spanContext: input.spanContext,\n severityNumber,\n severityText: SEVERITY_TEXT[severityNumber] ?? \"INFO\",\n ...(input.body === undefined ? {} : { body: input.body }),\n eventName: `otelhook.${input.event.type}`,\n resource: input.resource,\n instrumentationScope: input.scope,\n attributes: {\n ...identityAttributes(input.event, input.resource, {\n traceId: input.spanContext.traceId,\n spanId: input.spanContext.spanId,\n ...(input.parentSpanId === undefined ? {} : { parentSpanId: input.parentSpanId }),\n }),\n [ATTR_OTELHOOK_EVENT_TYPE]: input.event.type,\n [ATTR_OTELHOOK_EVENT_ID]: input.event.eventId,\n [ATTR_OTELHOOK_EVENT_SEQUENCE]: input.event.sequence,\n [ATTR_OTELHOOK_LOG_SIGNAL]: input.signal,\n [ATTR_OTELHOOK_LOG_MAPPING_VERSION]: LOG_MAPPING_VERSION,\n ...input.attributes,\n },\n droppedAttributesCount: 0,\n };\n};\n\n/**\n * Map one invocation's canonical event batch into OTLP-ready log records.\n *\n * One record per content fact, and one record per event that carries none, so an\n * event is never silently absent from the stream just because the provider\n * reported no text for it.\n */\nexport const canonicalEventsToLogRecords = (\n events: readonly CanonicalEvent[],\n options: LogMappingOptions,\n): LogMappingResult => {\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const content = options.content ?? NO_LOG_CONTENT;\n const identities = canonicalEventTraceIdentities(events, {\n ...(options.correlations === undefined ? {} : { correlations: options.correlations }),\n ...(options.correlationAvailable === undefined\n ? {}\n : { correlationAvailable: options.correlationAvailable }),\n });\n\n const records: ReadableLogRecord[] = [];\n let droppedFacts = 0;\n\n for (const event of events) {\n const identity = identities.get(event.eventId);\n if (identity === undefined) {\n // Unreachable: every event in the batch is given an identity above.\n continue;\n }\n const spanContext: SpanContext = {\n traceId: identity.traceId,\n spanId: identity.spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n };\n const shared = eventAttributes(event);\n const facts = contentFactsOf(event);\n\n if (facts.length === 0) {\n if (records.length >= MAX_LOG_RECORDS_PER_BATCH) {\n droppedFacts += 1;\n continue;\n }\n records.push(\n buildRecord({\n event,\n signal: logSignalOf(event),\n attributes:\n event.type === \"generation.end\"\n ? { ...shared, [ATTR_CONTENT_KIND]: \"response\", [ATTR_CONTENT_DISCLOSURE]: \"metadata_only\" }\n : shared,\n spanContext,\n ...(identity.parentSpanId === undefined ? {} : { parentSpanId: identity.parentSpanId }),\n resource: options.resource,\n scope,\n }),\n );\n continue;\n }\n\n let perEvent = 0;\n for (const fact of facts) {\n if (perEvent >= MAX_LOG_RECORDS_PER_EVENT || records.length >= MAX_LOG_RECORDS_PER_BATCH) {\n droppedFacts += 1;\n continue;\n }\n perEvent += 1;\n const body = discloseBody(fact, content);\n records.push(\n buildRecord({\n event,\n signal: logSignalOf(event, fact.kind),\n attributes: { ...shared, ...contentAttributes(fact, body) },\n ...(\"text\" in body ? { body: body.text } : {}),\n spanContext,\n ...(identity.parentSpanId === undefined ? {} : { parentSpanId: identity.parentSpanId }),\n resource: options.resource,\n scope,\n }),\n );\n }\n }\n\n return { records, droppedFacts };\n};\n","import type { Attributes } from \"@opentelemetry/api\";\n\nimport type { Clock, Logger } from \"../runtime/ports.js\";\nimport type { StoreNamespace } from \"../state/keys.js\";\nimport {\n createSpoolQueue,\n type SpoolDrainResult,\n type SpoolEnqueueResult,\n type SpoolValidation,\n type SpoolOverflowPolicy,\n type SpoolSendOutcome,\n type SpoolStats,\n} from \"./spool-queue.js\";\n\n/**\n * One log record, flattened to plain JSON so it survives a process exit.\n *\n * `body` is a string or absent, never a nested value: the mapping only ever\n * produces a disclosed text body, and admitting anything richer here would make a\n * spool file a route for a structure the live path would have refused.\n */\nexport type SerializedLogRecord = {\n readonly eventName: string;\n readonly severityNumber: number;\n readonly severityText?: string;\n readonly body?: string;\n readonly timeMillis: number;\n readonly observedTimeMillis: number;\n /** Absent only on a record that was mapped without trace correlation. */\n readonly traceId?: string;\n readonly spanId?: string;\n readonly attributes: Attributes;\n};\n\nexport type LogSpoolBatch = {\n readonly providerId: string;\n readonly installationId: string;\n readonly resourceAttributes: Attributes;\n readonly instrumentationScope: { readonly name: string; readonly version?: string };\n readonly records: readonly SerializedLogRecord[];\n readonly enqueuedAt: number;\n};\n\n/** Upper bounds on a replayed batch. A spool file is untrusted input. */\nexport const MAX_SPOOLED_LOG_RECORDS_PER_BATCH = 4_096;\nexport const MAX_SPOOLED_LOG_STRING_LENGTH = 8_192;\n/**\n * Longest replayed body.\n *\n * Matches the live mapping's `MAX_LOG_BODY_CHARACTERS`, because \"what the mapping\n * would have put on the wire\" and \"what is accepted back off disk\" diverging is\n * the whole vulnerability — a hand-edited spool file must not be able to export a\n * body the live path would have cut.\n */\nexport const MAX_SPOOLED_LOG_BODY_LENGTH = 8_192;\nconst MAX_SPOOLED_ATTRIBUTES_PER_RECORD = 256;\nconst TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;\nconst SPAN_ID_PATTERN = /^[0-9a-f]{16}$/;\n\nconst isFiniteNonNegative = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n\nconst isBoundedString = (value: unknown, maxLength = MAX_SPOOLED_LOG_STRING_LENGTH): value is string =>\n typeof value === \"string\" && value.length > 0 && value.length <= maxLength;\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isReplayableAttributeValue = (value: unknown): boolean => {\n if (Array.isArray(value)) {\n // OTLP permits homogeneous primitive arrays; anything nested is not an\n // attribute and would fail encoding.\n return value.every(\n (item) =>\n (typeof item === \"string\" && item.length <= MAX_SPOOLED_LOG_STRING_LENGTH) ||\n (typeof item === \"number\" && Number.isFinite(item)) ||\n typeof item === \"boolean\" ||\n item === null,\n );\n }\n return (\n (typeof value === \"string\" && value.length <= MAX_SPOOLED_LOG_STRING_LENGTH) ||\n (typeof value === \"number\" && Number.isFinite(value)) ||\n typeof value === \"boolean\" ||\n value === undefined\n );\n};\n\n/**\n * Whether one recorded log record can be replayed.\n *\n * Every field is checked, not just the ones a happy path reads. The rebuilt record\n * goes straight to the OTLP encoder, which assumes the shapes the type declares —\n * so a `severityNumber` of `null`, a nested object in `attributes`, or a trace id\n * of the wrong width becomes an encoder error deep inside the exporter rather than\n * a rejected file here. Trace and span ids are held to their hex forms because a\n * malformed id is not a correlation a collector can resolve.\n */\nconst isReplayableLogRecord = (value: unknown): value is SerializedLogRecord => {\n if (!isPlainObject(value)) {\n return false;\n }\n if (!isBoundedString(value.eventName)) {\n return false;\n }\n if (!isFiniteNonNegative(value.severityNumber)) {\n return false;\n }\n if (value.severityText !== undefined && typeof value.severityText !== \"string\") {\n return false;\n }\n if (\n value.body !== undefined &&\n (typeof value.body !== \"string\" || value.body.length > MAX_SPOOLED_LOG_BODY_LENGTH)\n ) {\n return false;\n }\n if (!isFiniteNonNegative(value.timeMillis) || !isFiniteNonNegative(value.observedTimeMillis)) {\n return false;\n }\n // Correlation is all-or-nothing: a trace id without a span id (or the reverse)\n // is not a span reference, and half of one would export as a record pointing at\n // span `0000000000000000`.\n const hasTrace = value.traceId !== undefined;\n const hasSpan = value.spanId !== undefined;\n if (hasTrace !== hasSpan) {\n return false;\n }\n if (hasTrace && (typeof value.traceId !== \"string\" || !TRACE_ID_PATTERN.test(value.traceId))) {\n return false;\n }\n if (hasSpan && (typeof value.spanId !== \"string\" || !SPAN_ID_PATTERN.test(value.spanId))) {\n return false;\n }\n if (!isPlainObject(value.attributes)) {\n return false;\n }\n const entries = Object.entries(value.attributes);\n if (entries.length > MAX_SPOOLED_ATTRIBUTES_PER_RECORD) {\n return false;\n }\n return entries.every(([, attribute]) => isReplayableAttributeValue(attribute));\n};\n\nexport type LogSpoolBatchRejection =\n | \"not-an-object\"\n | \"identity-mismatch\"\n | \"resource-attributes-invalid\"\n | \"instrumentation-scope-invalid\"\n | \"records-invalid\"\n | \"record-field-invalid\";\n\n/**\n * Validate a whole batch read back from disk, before any of it reaches an exporter.\n *\n * The identity check alone is not enough. `records` being anything other than an\n * array makes the sender's `records.map(...)` throw, and a throwing send is\n * indistinguishable from an unreachable collector — so the drain would treat a\n * permanently poisoned file as a transient failure and stop at it on every pass,\n * wedging the queue head and every batch behind it forever. Validation is what\n * turns that into a single quarantined file.\n */\nexport const validateLogSpoolBatch = (\n value: unknown,\n identity: StoreNamespace,\n): SpoolValidation<LogSpoolBatch> => {\n if (!isPlainObject(value)) {\n return { rejection: \"not-an-object\" satisfies LogSpoolBatchRejection };\n }\n if (\n value.providerId !== identity.providerId ||\n value.installationId !== identity.installationId\n ) {\n return { rejection: \"identity-mismatch\" satisfies LogSpoolBatchRejection };\n }\n if (!isPlainObject(value.resourceAttributes)) {\n // Not merely absent: the resource is rebuilt by iterating it, and a string or\n // an array would silently produce a resource built from its indices.\n return { rejection: \"resource-attributes-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (\n !isPlainObject(value.instrumentationScope) ||\n !isBoundedString(value.instrumentationScope.name)\n ) {\n return { rejection: \"instrumentation-scope-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (\n value.instrumentationScope.version !== undefined &&\n typeof value.instrumentationScope.version !== \"string\"\n ) {\n return { rejection: \"instrumentation-scope-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (!Array.isArray(value.records) || value.records.length === 0) {\n return { rejection: \"records-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (value.records.length > MAX_SPOOLED_LOG_RECORDS_PER_BATCH) {\n return { rejection: \"records-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (!value.records.every(isReplayableLogRecord)) {\n return { rejection: \"record-field-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (!isFiniteNonNegative(value.enqueuedAt)) {\n return { rejection: \"not-an-object\" satisfies LogSpoolBatchRejection };\n }\n return { batch: value as unknown as LogSpoolBatch };\n};\n\nexport type DurableLogSpoolOptions = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Refuses new entries once this many are queued. Default 500. */\n readonly maxSpoolFiles?: number;\n /**\n * Queue directory below the identity namespace. Default `spool-logs`; each\n * export destination other than `default` gets its own.\n */\n readonly queueName?: string;\n /** Bound on total queued bytes. Unbounded when absent. */\n readonly maxBytes?: number;\n /** Batches older than this are dropped rather than sent. No age bound when absent. */\n readonly maxAgeMillis?: number;\n /** Default `refuse-new`, the original behavior. */\n readonly overflow?: SpoolOverflowPolicy;\n};\n\n/**\n * Durable filesystem queue for log batches a collector could not accept.\n *\n * Rooted at `<rootDir>/<providerId>/<installationId>/spool-logs`, deliberately a\n * different directory from the trace spool: the two hold different encodings, so a\n * single mixed queue would have each signal's sender quarantining the other's\n * perfectly deliverable batches. Separate directories also mean a logs outage\n * cannot consume the trace spool's capacity, which is what keeps the primary\n * signal unaffected by a misconfigured logs endpoint.\n */\nexport interface DurableLogSpool {\n enqueue(batch: LogSpoolBatch): Promise<SpoolEnqueueResult>;\n /** Sequential, bounded drain: stops after the first failed send, or after `maxBatches`. */\n drain(\n send: (batch: LogSpoolBatch) => Promise<SpoolSendOutcome>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\n /**\n * Depth, bytes, and persisted drop counts. Optional so a host's own\n * implementation of this interface keeps compiling; the file-backed one has it.\n */\n stats?(): Promise<SpoolStats>;\n}\n\nexport const DEFAULT_MAX_LOG_SPOOL_FILES = 500;\n\nexport const createFileDurableLogSpool = (options: DurableLogSpoolOptions): DurableLogSpool =>\n createSpoolQueue<LogSpoolBatch>({\n rootDir: options.rootDir,\n providerId: options.providerId,\n installationId: options.installationId,\n clock: options.clock,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_LOG_SPOOL_FILES,\n queueName: options.queueName ?? \"spool-logs\",\n ...(options.maxBytes === undefined ? {} : { maxBytes: options.maxBytes }),\n ...(options.maxAgeMillis === undefined ? {} : { maxAgeMillis: options.maxAgeMillis }),\n ...(options.overflow === undefined ? {} : { overflow: options.overflow }),\n validate: validateLogSpoolBatch,\n });\n","import { TraceFlags, type AttributeValue, type Attributes, type SpanContext } from \"@opentelemetry/api\";\nimport { ExportResultCode, type ExportResult } from \"@opentelemetry/core\";\nimport { millisToHrTime, type InstrumentationScope } from \"@opentelemetry/core\";\nimport { OTLPLogExporter } from \"@opentelemetry/exporter-logs-otlp-proto\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport type { ReadableLogRecord } from \"@opentelemetry/sdk-logs\";\n\nimport { OTLP_LOGS_PATH, OTLP_TRACES_PATH, withoutTrailingSlashes } from \"../config/otlp-endpoint.js\";\nimport type { ExporterPolicy } from \"../config/schema.js\";\nimport { createHealthTracker, type DeliveryHealthSnapshot } from \"../diagnostics/health.js\";\nimport { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { Clock, Logger, TelemetryEmitResult, TelemetrySink } from \"../runtime/ports.js\";\nimport type { DurableLogSpool, LogSpoolBatch, SerializedLogRecord } from \"./durable-log-spool.js\";\nimport { isPermanentExportFailure } from \"./export-failure.js\";\nimport type { SpoolSendOutcome } from \"./spool-queue.js\";\nimport {\n agreedContextAttributes,\n replayResource,\n resourceFromExporterPolicy,\n resourceWithContext,\n} from \"./exporter-resource.js\";\nimport {\n canonicalEventsToLogRecords,\n NO_LOG_CONTENT,\n type LogContentPolicy,\n} from \"./log-records.js\";\nimport {\n DEFAULT_INSTRUMENTATION_SCOPE,\n type SpanCorrelation,\n type SpanCorrelationResolver,\n} from \"./semconv.js\";\n\n/**\n * OTLP HTTP/protobuf log sink.\n *\n * The logs counterpart of `otlp-sink.ts`, and deliberately its mirror image:\n * semantic mapping lives entirely in `log-records.ts`, and this module owns only\n * batching, delivery, bounded flush/shutdown, health tracking, and — when a spool\n * is configured — persisting what a down collector rejected. Every failure mode\n * (disabled config, missing or underivable endpoint, export failure, timeout,\n * spool write failure) degrades to a reported diagnostic rather than a thrown\n * error, preserving the hook's fail-open contract.\n *\n * The two sinks are separate objects rather than one exporter with two encoders\n * because they fail independently: a collector that has no logs receiver, or an\n * operator who pointed logs at the wrong port, must cost the logs signal and\n * nothing else. The trace pipeline is the one an installation already depends on.\n */\n\n/**\n * Where log records are posted.\n *\n * Resolution order, highest first:\n *\n * 1. `logs.endpoint` — stated outright, used verbatim.\n * 2. the trace endpoint with a trailing `/v1/traces` swapped for `/v1/logs`, which\n * is the shape a collector configured for both signals actually has.\n * 3. the trace endpoint treated as a base URL, with `/v1/logs` appended — the\n * convention the OTLP specification defines for a signal-less endpoint.\n *\n * Returned as a discriminated result rather than a bare string because \"no logs\n * endpoint could be derived\" has to be reportable: silently posting an\n * `ExportLogsServiceRequest` to a traces receiver produces a rejection whose cause\n * is a configuration mistake, and an operator reading \"collector rejected a batch\"\n * would go looking at the collector.\n */\nexport const resolveLogsEndpoint = (\n exporter: ExporterPolicy,\n): { readonly endpoint: string; readonly derived: boolean } | { readonly unresolvable: \"no-endpoint\" } => {\n if (exporter.logs.endpoint !== undefined) {\n return { endpoint: exporter.logs.endpoint, derived: false };\n }\n if (exporter.endpoint === undefined) {\n return { unresolvable: \"no-endpoint\" };\n }\n const trimmed = withoutTrailingSlashes(exporter.endpoint);\n if (trimmed.endsWith(OTLP_LOGS_PATH)) {\n return { endpoint: trimmed, derived: true };\n }\n if (trimmed.endsWith(OTLP_TRACES_PATH)) {\n return {\n endpoint: `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${OTLP_LOGS_PATH}`,\n derived: true,\n };\n }\n return { endpoint: `${trimmed}${OTLP_LOGS_PATH}`, derived: true };\n};\n\n/**\n * Narrow a log record's attributes to what a spool file can hold.\n *\n * Log attributes admit any value (`AnyValue` is `unknown` since api 1.10); the spool's own validator\n * does not, and neither does `assembleReadableSpan`'s sibling contract for traces.\n * This mapping only ever produces primitives, so the filter is unreachable in\n * practice — it is here so that \"what the live path emits\" and \"what survives a\n * spool round-trip\" cannot silently diverge if a future attribute is richer than\n * the queue's schema.\n */\nconst toSpoolAttributes = (attributes: Attributes): Attributes => {\n const safe: Record<string, AttributeValue> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n safe[key] = value;\n continue;\n }\n if (Array.isArray(value) && value.every((item) => typeof item === \"string\")) {\n safe[key] = value;\n }\n }\n return safe;\n};\n\nconst serializeRecord = (record: ReadableLogRecord): SerializedLogRecord => {\n const context = record.spanContext;\n return {\n eventName: record.eventName ?? \"otelhook.record\",\n severityNumber: record.severityNumber ?? 0,\n ...(record.severityText === undefined ? {} : { severityText: record.severityText }),\n ...(typeof record.body === \"string\" ? { body: record.body } : {}),\n timeMillis: record.hrTime[0] * 1000 + Math.round(record.hrTime[1] / 1e6),\n observedTimeMillis:\n record.hrTimeObserved[0] * 1000 + Math.round(record.hrTimeObserved[1] / 1e6),\n ...(context === undefined ? {} : { traceId: context.traceId, spanId: context.spanId }),\n attributes: toSpoolAttributes(record.attributes),\n };\n};\n\nconst deserializeRecord = (\n serialized: SerializedLogRecord,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableLogRecord => {\n const spanContext: SpanContext | undefined =\n serialized.traceId === undefined || serialized.spanId === undefined\n ? undefined\n : {\n traceId: serialized.traceId,\n spanId: serialized.spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n };\n return {\n hrTime: millisToHrTime(serialized.timeMillis),\n hrTimeObserved: millisToHrTime(serialized.observedTimeMillis),\n ...(spanContext === undefined ? {} : { spanContext }),\n severityNumber: serialized.severityNumber,\n ...(serialized.severityText === undefined ? {} : { severityText: serialized.severityText }),\n ...(serialized.body === undefined ? {} : { body: serialized.body }),\n eventName: serialized.eventName,\n resource,\n instrumentationScope: scope,\n attributes: serialized.attributes,\n droppedAttributesCount: 0,\n };\n};\n\nconst chunk = <T,>(items: readonly T[], size: number): readonly (readonly T[])[] => {\n if (size <= 0 || items.length <= size) {\n return [items];\n }\n const chunks: T[][] = [];\n for (let index = 0; index < items.length; index += size) {\n chunks.push(items.slice(index, index + size));\n }\n return chunks;\n};\n\nexport type OtlpLogSinkOptions = {\n readonly exporter: ExporterPolicy;\n /** Header values, kept out of the resolved-config snapshot (ADR: config carries only header *names*). */\n readonly headers?: Readonly<Record<string, string>>;\n readonly providerId: string;\n readonly installationId: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Persists batches an unreachable collector rejected, for a later retry. */\n readonly spool?: DurableLogSpool;\n readonly instrumentationScope?: InstrumentationScope;\n /**\n * Whether disclosed content text may reach a log body. Defaults to\n * {@link NO_LOG_CONTENT}, which is what an unconfigured installation gets.\n */\n readonly content?: LogContentPolicy;\n /**\n * Supplies cross-process pairing so a record correlates to the span id the trace\n * pipeline actually exported. Omitted, records still carry a derived trace and\n * span id, computed from the batch alone.\n *\n * Injected as a plain function rather than as a correlator so the telemetry layer\n * keeps no dependency on lifecycle or on the state store (ADR 0006). When both\n * sinks are wired, the fanout resolves correlation *once* and hands the same\n * answer to each — `correlateBatch` writes state, so calling it twice per batch\n * would record a start edge twice.\n */\n readonly correlate?: SpanCorrelationResolver;\n /** Export destination this sink delivers to; see `OtlpTraceSinkOptions.destination`. */\n readonly destination?: string;\n};\n\nexport interface OtlpLogTelemetrySink extends TelemetrySink {\n health(): DeliveryHealthSnapshot;\n /** Attempts to resend previously spooled batches, bounded by `maxBatches`. */\n drainSpool(\n maxBatches?: number,\n ): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }>;\n}\n\n/**\n * Sink that swallows every batch: logs disabled, or configured but unroutable.\n *\n * Reports **zero accepted and zero rejected**, which is the one place this differs\n * from the trace sink's disabled path — and it has to. The counts a sink returns are\n * what `classifyDurability` decides commit-or-retry from, and they are summed across\n * signals. A disabled signal that claimed to have accepted the batch would make a\n * *total* trace loss look like a partial delivery: `accepted > 0` from a sink that\n * sent nothing, `rejected > 0` from the sink that failed, so the callback would\n * commit as terminally-partial instead of releasing its claim for retry. Contributing\n * nothing is the truthful answer, and it leaves durability decided entirely by the\n * signals that actually tried — so an installation with logs off behaves exactly as\n * it did before logs existed.\n *\n * Health still records the batch as accepted: nothing failed, and a disabled signal\n * must not read as unhealthy.\n */\nconst createDisabledSink = (destination?: string): OtlpLogTelemetrySink => {\n const health = createHealthTracker(\n \"telemetry-log-sink\",\n destination === undefined ? {} : { destination },\n );\n return {\n emit: (events): Promise<TelemetryEmitResult> => {\n health.recordSuccess(events.length);\n return Promise.resolve({ accepted: 0, rejected: 0, errors: [] });\n },\n flush: (): Promise<void> => Promise.resolve(),\n shutdown: (): Promise<void> => Promise.resolve(),\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool: (): Promise<{\n readonly drained: number;\n readonly remaining: number;\n readonly failed: number;\n }> => Promise.resolve({ drained: 0, remaining: 0, failed: 0 }),\n };\n};\n\n/**\n * Whether this configuration can deliver logs at all.\n *\n * Separated from the constructor so `doctor` can report the same verdict without\n * building an exporter, and so each refusal names itself rather than collapsing\n * into one \"disabled\" state an operator then has to bisect.\n */\nexport type LogsDeliverability =\n | { readonly status: \"configured\"; readonly endpoint: string; readonly derivedEndpoint: boolean }\n | {\n readonly status: \"disabled\";\n readonly reason:\n | \"logs-disabled\"\n | \"exporter-disabled\"\n | \"protocol-none\"\n | \"protocol-unsupported\"\n | \"no-endpoint\";\n };\n\nexport const describeLogsDeliverability = (exporter: ExporterPolicy): LogsDeliverability => {\n if (!exporter.logs.enabled) {\n return { status: \"disabled\", reason: \"logs-disabled\" };\n }\n if (!exporter.enabled) {\n return { status: \"disabled\", reason: \"exporter-disabled\" };\n }\n if (exporter.protocol === \"none\") {\n return { status: \"disabled\", reason: \"protocol-none\" };\n }\n if (exporter.protocol !== \"http/protobuf\") {\n return { status: \"disabled\", reason: \"protocol-unsupported\" };\n }\n const resolved = resolveLogsEndpoint(exporter);\n if (\"unresolvable\" in resolved) {\n return { status: \"disabled\", reason: \"no-endpoint\" };\n }\n return { status: \"configured\", endpoint: resolved.endpoint, derivedEndpoint: resolved.derived };\n};\n\nconst DISABLED_DETAIL: Readonly<Record<Extract<LogsDeliverability, { status: \"disabled\" }>[\"reason\"], string>> =\n Object.freeze({\n \"logs-disabled\": \"otlp log sink disabled: exporter.logs.enabled is false\",\n \"exporter-disabled\": \"otlp log sink disabled: the exporter is disabled\",\n \"protocol-none\": \"otlp log sink disabled: protocol is none\",\n \"protocol-unsupported\":\n \"otlp log sink disabled: protocol not supported by this build, falling back to disabled\",\n \"no-endpoint\": \"otlp log sink disabled: no logs endpoint configured and none could be derived\",\n });\n\n/**\n * OTLP HTTP/protobuf {@link TelemetrySink} for the logs signal.\n *\n * A disabled sink never calls `correlate`: with nothing being exported there is no\n * span to correlate to, and writing correlation state anyway would leave a disabled\n * installation quietly accumulating files.\n */\nexport const createOtlpLogSink = (options: OtlpLogSinkOptions): OtlpLogTelemetrySink => {\n const destinationFields =\n options.destination === undefined ? {} : { \"export.destination\": options.destination };\n const deliverability = describeLogsDeliverability(options.exporter);\n if (deliverability.status === \"disabled\") {\n if (deliverability.reason !== \"logs-disabled\") {\n // `logs-disabled` is the default posture, not a misconfiguration, so it is\n // not worth a warning on every invocation. The rest are: somebody asked for\n // logs and will not get them.\n options.logger?.warn(DISABLED_DETAIL[deliverability.reason], {\n \"exporter.protocol\": options.exporter.protocol,\n ...destinationFields,\n });\n }\n return createDisabledSink(options.destination);\n }\n\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const resource = resourceFromExporterPolicy(options.exporter);\n const content = options.content ?? NO_LOG_CONTENT;\n const health = createHealthTracker(\n \"telemetry-log-sink\",\n options.destination === undefined ? {} : { destination: options.destination },\n );\n const exporter = new OTLPLogExporter({\n url: deliverability.endpoint,\n headers: { ...options.headers },\n timeoutMillis: options.exporter.timeoutMillis,\n });\n let shutdownCompleted = false;\n\n const exportRecords = (records: readonly ReadableLogRecord[]): Promise<ExportResult> =>\n new Promise((resolve) => {\n exporter.export([...records], (result: ExportResult) => resolve(result));\n });\n\n const toSpoolBatch = (records: readonly ReadableLogRecord[], batchResource: Resource): LogSpoolBatch => ({\n providerId: options.providerId,\n installationId: options.installationId,\n resourceAttributes: { ...batchResource.attributes },\n instrumentationScope: {\n name: scope.name,\n ...(scope.version === undefined ? {} : { version: scope.version }),\n },\n records: records.map(serializeRecord),\n enqueuedAt: options.clock.now(),\n });\n\n const sendSerializedBatch = async (batch: LogSpoolBatch): Promise<SpoolSendOutcome> => {\n const batchResource = replayResource(batch.resourceAttributes, options.exporter);\n const records = batch.records.map((record) =>\n deserializeRecord(record, batchResource, batch.instrumentationScope),\n );\n const result = await exportRecords(records);\n if (result.code === ExportResultCode.SUCCESS) {\n return true;\n }\n return isPermanentExportFailure(result) ? \"discard\" : false;\n };\n\n /**\n * Cross-process pairing is an enrichment, never a precondition: if state is\n * unreadable the batch still exports, with each record correlated from the batch\n * alone rather than dropped.\n */\n const resolveCorrelations = async (\n events: readonly CanonicalEvent[],\n ): Promise<{\n readonly correlations: readonly SpanCorrelation[];\n readonly available: boolean | undefined;\n }> => {\n if (options.correlate === undefined) {\n return { correlations: [], available: undefined };\n }\n try {\n return { correlations: await options.correlate(events), available: true };\n } catch {\n options.logger?.warn(\"span correlation unavailable; exporting uncorrelated log records\", {});\n return { correlations: [], available: false };\n }\n };\n\n const emit = async (events: Parameters<TelemetrySink[\"emit\"]>[0]): Promise<TelemetryEmitResult> => {\n if (events.length === 0) {\n return { accepted: 0, rejected: 0, errors: [] };\n }\n const resolved = await resolveCorrelations(events);\n // Session context overrides the same keys on the Resource for this batch.\n const batchResource = resourceWithContext(resource, agreedContextAttributes(events));\n const mapped = canonicalEventsToLogRecords(events, {\n resource: batchResource,\n instrumentationScope: scope,\n content,\n correlations: resolved.correlations,\n ...(resolved.available === undefined ? {} : { correlationAvailable: resolved.available }),\n });\n if (mapped.droppedFacts > 0) {\n // Said out loud rather than truncated silently: a caller that saw only\n // \"accepted\" would read a clipped batch as a complete one.\n options.logger?.warn(\"log records dropped: batch or per-event bound reached\", {\n \"logs.dropped_facts\": mapped.droppedFacts,\n });\n }\n const errors: OtelHookErrorInfo[] = [];\n let accepted = 0;\n let rejected = 0;\n\n for (const batch of chunk(mapped.records, options.exporter.logs.maxBatchSize)) {\n if (batch.length === 0) {\n continue;\n }\n let result: ExportResult;\n try {\n result = await exportRecords(batch);\n } catch (thrown) {\n result = {\n code: ExportResultCode.FAILED,\n error: thrown instanceof Error ? thrown : new Error(\"export threw\"),\n };\n }\n if (result.code === ExportResultCode.SUCCESS) {\n accepted += batch.length;\n health.recordSuccess(batch.length, options.clock.now());\n continue;\n }\n\n health.recordFailure(\"telemetry-export-failure\", batch.length, options.clock.now());\n const permanent = isPermanentExportFailure(result);\n if (options.spool !== undefined && !permanent) {\n const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({\n spooled: false as const,\n reason: \"capacity-exceeded\" as const,\n }));\n if (spoolResult.spooled) {\n accepted += batch.length;\n options.logger?.warn(\"log record batch not delivered; spooled for the next invocation\", {\n \"export.batch_size\": batch.length,\n ...destinationFields,\n });\n continue;\n }\n }\n rejected += batch.length;\n errors.push(\n createErrorInfo({\n code: \"telemetry-export-failure\",\n phase: \"export\",\n detail: permanent\n ? \"collector refused a log record batch with a non-retryable status\"\n : \"collector rejected or was unreachable for a log record batch\",\n details: {\n \"export.batch_size\": batch.length,\n \"export.signal\": \"logs\",\n ...destinationFields,\n },\n }),\n );\n }\n\n return { accepted, rejected, errors };\n };\n\n const drainSpool = async (\n maxBatches?: number,\n ): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }> => {\n if (options.spool === undefined) {\n return { drained: 0, remaining: 0, failed: 0 };\n }\n const result = await options.spool.drain(sendSerializedBatch, {\n ...(maxBatches === undefined ? {} : { maxBatches }),\n });\n if (result.drained > 0) {\n health.recordSuccess(result.drained, options.clock.now());\n }\n return result;\n };\n\n const flush = async (): Promise<void> => {\n try {\n await exporter.forceFlush();\n } catch {\n // Best-effort: flush failures are reported through health, never thrown.\n }\n await drainSpool().catch(() => undefined);\n };\n\n const shutdown = async (): Promise<void> => {\n if (shutdownCompleted) {\n return;\n }\n shutdownCompleted = true;\n await flush();\n try {\n await exporter.shutdown();\n } catch {\n // Idempotent, non-throwing per the TelemetrySink contract.\n }\n };\n\n return {\n emit,\n flush,\n shutdown,\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool,\n };\n};\n","/**\n * OTLP/HTTP endpoint URLs per signal, as the OpenTelemetry exporter\n * specification defines them.\n *\n * - `OTEL_EXPORTER_OTLP_ENDPOINT` is a **base** URL: the signal path\n * (`/v1/traces`, `/v1/logs`) is appended to it.\n * - `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` / `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`\n * are full URLs, used as they are.\n *\n * One compatibility rule: earlier releases read `OTEL_EXPORTER_OTLP_ENDPOINT`\n * as the full traces URL. A base URL that already ends in `/v1/traces` is\n * therefore taken to be that full URL, not a base to append to, so an existing\n * `…/v1/traces` value keeps posting where it did.\n */\n\n/**\n * The standard endpoint variables. `generic` and `logs` also appear in\n * `ENVIRONMENT_VARIABLES`; `traces` does not, because that list is guarded\n * against identity-looking (`TRACE`) names.\n */\nexport const OTLP_ENDPOINT_VARIABLES = Object.freeze({\n generic: \"OTEL_EXPORTER_OTLP_ENDPOINT\",\n traces: \"OTEL_EXPORTER_OTLP_TRACES_ENDPOINT\",\n logs: \"OTEL_EXPORTER_OTLP_LOGS_ENDPOINT\",\n metrics: \"OTEL_EXPORTER_OTLP_METRICS_ENDPOINT\",\n});\n\nexport const OTLP_TRACES_PATH = \"/v1/traces\";\nexport const OTLP_LOGS_PATH = \"/v1/logs\";\nexport const OTLP_METRICS_PATH = \"/v1/metrics\";\n\nexport type OtlpSignal = \"traces\" | \"logs\" | \"metrics\";\n\nconst SIGNAL_PATHS: Readonly<Record<OtlpSignal, string>> = Object.freeze({\n traces: OTLP_TRACES_PATH,\n logs: OTLP_LOGS_PATH,\n metrics: OTLP_METRICS_PATH,\n});\n\n/**\n * Strip trailing slashes, by scan rather than by regex.\n *\n * `/\\/+$/` is a polynomial-ReDoS on this input: an endpoint of many `/` followed by\n * anything else makes the engine retry the `+` from every position. The endpoint is\n * operator-supplied configuration bounded to 2048 characters, so the practical cost\n * is small — but a linear scan is just as short, and the bound is not the guarantee.\n */\nexport const withoutTrailingSlashes = (value: string): string => {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === 0x2f) {\n end -= 1;\n }\n return value.slice(0, end);\n};\n\n/**\n * The URL a signal posts to, given an `OTEL_EXPORTER_OTLP_ENDPOINT` base.\n *\n * Trailing slashes on the base are dropped before the signal path is appended,\n * so `https://host/otlp` and `https://host/otlp/` both give\n * `https://host/otlp/v1/traces`. A base ending in `/v1/traces` (the legacy\n * full-URL form) is used as-is for traces and has that suffix swapped for\n * `/v1/logs` for logs.\n */\nexport const otlpSignalEndpointFromBase = (base: string, signal: OtlpSignal): string => {\n const trimmed = withoutTrailingSlashes(base);\n if (trimmed.endsWith(OTLP_TRACES_PATH)) {\n return signal === \"traces\"\n ? trimmed\n : `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${SIGNAL_PATHS[signal]}`;\n }\n return `${trimmed}${SIGNAL_PATHS[signal]}`;\n};\n\n/**\n * A sibling signal's URL derived from a traces URL: a trailing `/v1/traces` (or\n * the target signal's own path) is swapped for the target path, and any other URL\n * is treated as a base and has the path appended. The rule logs have always used.\n */\nexport const siblingSignalEndpoint = (tracesEndpoint: string, signal: OtlpSignal): string => {\n const trimmed = withoutTrailingSlashes(tracesEndpoint);\n const target = SIGNAL_PATHS[signal];\n if (trimmed.endsWith(target)) {\n return trimmed;\n }\n if (trimmed.endsWith(OTLP_TRACES_PATH)) {\n return `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${target}`;\n }\n return `${trimmed}${target}`;\n};\n","import type { DeliveryHealthSnapshot } from \"../diagnostics/health.js\";\nimport type { OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { TelemetryEmitResult, TelemetrySink } from \"../runtime/ports.js\";\nimport type { OtlpLogTelemetrySink } from \"./otlp-log-sink.js\";\nimport type { OtlpTelemetrySink } from \"./otlp-sink.js\";\nimport type { SpanCorrelation, SpanCorrelationResolver } from \"./semconv.js\";\n\n/**\n * One canonical batch, two OTLP signals.\n *\n * A hook has a single {@link TelemetrySink} seam, and both signals map the *same*\n * canonical events — so this fans one batch out rather than making the orchestrator\n * aware that there is more than one destination.\n *\n * ## Durability adds up across signals\n *\n * The counts are summed rather than taken from the primary signal, because the\n * caller's question is \"may I commit this callback?\" and the answer turns on whether\n * *anything* reached a collector or a spool. Summing gives `classifyDurability`\n * exactly the right inputs:\n *\n * - both signals delivered → `delivered`\n * - neither delivered → `lost`, and the callback is safe to retry precisely because\n * there is nothing to duplicate\n * - one delivered and one did not → `partial`, which is terminal: retrying would\n * re-export what the healthy signal already delivered, and a duplicate silently\n * corrupts a total whereas a reported loss is a number somebody can act on\n *\n * A disabled sink accepts everything, so an installation with logs off behaves\n * exactly as it did before logs existed.\n *\n * ## Correlation must be resolved once per batch\n *\n * Both sinks want the same pairing facts, and `SpanCorrelator.correlateBatch` is not\n * a read — it records a start edge, marks a scope published, and takes the session\n * lock to do it. Wrap the correlator in {@link shareCorrelationPerBatch} and give\n * *the same wrapped function* to both sinks; `emit` here is sequential so the first\n * sink resolves it and the second is served the memoized answer.\n */\n\nexport type SignalFanoutOptions = {\n readonly traces: OtlpTelemetrySink;\n readonly logs: OtlpLogTelemetrySink;\n};\n\nexport interface SignalFanoutSink extends TelemetrySink {\n /** One snapshot per wired signal, in a stable order: traces, then logs. */\n health(): readonly DeliveryHealthSnapshot[];\n}\n\nexport const createSignalFanout = (options: SignalFanoutOptions): SignalFanoutSink => {\n const emit = async (events: readonly CanonicalEvent[]): Promise<TelemetryEmitResult> => {\n // Sequential, not concurrent: the first sink to ask resolves correlation, and\n // the second must be served that answer rather than race to start a second\n // resolution against the same state.\n const traces = await options.traces.emit(events);\n const logs = await options.logs.emit(events);\n const errors: readonly OtelHookErrorInfo[] = [...traces.errors, ...logs.errors];\n return {\n accepted: traces.accepted + logs.accepted,\n rejected: traces.rejected + logs.rejected,\n errors,\n };\n };\n\n const flush = async (): Promise<void> => {\n // Each signal's flush is already best-effort and non-throwing; awaiting both\n // unconditionally means a stuck logs endpoint cannot skip the trace flush.\n await options.traces.flush().catch(() => undefined);\n await options.logs.flush().catch(() => undefined);\n };\n\n const shutdown = async (): Promise<void> => {\n await options.traces.shutdown().catch(() => undefined);\n await options.logs.shutdown().catch(() => undefined);\n };\n\n return {\n emit,\n flush,\n shutdown,\n health: (): readonly DeliveryHealthSnapshot[] => [\n options.traces.health(),\n options.logs.health(),\n ],\n };\n};\n\n/**\n * Wrap a correlation resolver so one batch resolves at most once.\n *\n * Memoized on the identity of the `events` array, which is what makes it correct\n * without a reset: every batch is a distinct array, so a new batch cannot be served\n * a previous one's answer, and a retry of the *same* array deliberately is. The\n * promise is cached rather than its value, so two callers arriving before the first\n * resolution completes still share it.\n *\n * Exported because the one-call-per-batch property is a requirement of the\n * correlator, not a convenience of the fanout: a host wiring its own pair of sinks\n * needs to be able to express it too.\n */\nexport const shareCorrelationPerBatch = (\n correlate: SpanCorrelationResolver,\n): SpanCorrelationResolver => {\n let pending:\n | {\n readonly events: readonly CanonicalEvent[];\n readonly result: Promise<readonly SpanCorrelation[]>;\n }\n | undefined;\n return (events): Promise<readonly SpanCorrelation[]> => {\n if (pending?.events === events) {\n return pending.result;\n }\n const result = correlate(events);\n pending = { events, result };\n return result;\n };\n};\n","import { z } from \"zod\";\n\nimport { isUnsafeHeaderValue } from \"./header-value.js\";\nimport { MAX_OTLP_HEADERS } from \"./otlp-headers.js\";\nimport type { ExporterPolicy } from \"./schema.js\";\n\n/**\n * Export destinations: one batch, several OTLP endpoints.\n *\n * otel-hook is not a long-running process, so it cannot sit behind a proxy that\n * fans out for it. Instead every enabled destination is sent the same batch by the\n * same short-lived process, and what a destination could not take is kept in that\n * destination's own spool for the next invocation.\n *\n * ## The `default` destination\n *\n * The single-endpoint settings that predate this list — `exporter.endpoint`,\n * `exporter.logs.endpoint`, `exporter.protocol`, `--header`, and the standard\n * `OTEL_EXPORTER_OTLP_*` variables that feed them — describe one destination\n * named `default`. The name is therefore reserved: a `destinations[]` entry may\n * not take it, so there is exactly one place that destination is configured.\n *\n * A configuration with no `destinations` resolves to that one destination and\n * nothing else, exactly as before the list existed.\n */\n\nexport const DEFAULT_DESTINATION_NAME = \"default\";\n\n/**\n * Destination names become directory names (each destination spools on its own),\n * so they are held to a lowercase, filesystem-safe vocabulary rather than being\n * sanitized into something an operator would not recognize.\n */\nexport const DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;\n\nexport const MAX_EXPORT_DESTINATIONS = 16;\n/** The same bound `OTEL_EXPORTER_OTLP_*HEADERS` and `exporter.headerNames` have. */\nexport const MAX_DESTINATION_HEADERS = MAX_OTLP_HEADERS;\n\n/** Prefix of a header value that names an environment variable instead of holding a value. */\nexport const HEADER_ENV_REFERENCE_PREFIX = \"env:\";\n\n/** RFC 9110 `token`: the characters a header field name may use. */\nconst HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;\nconst ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;\nconst MAX_HEADER_VALUE_LENGTH = 8_192;\n\nexport const exportSignalSchema = z.enum([\"traces\", \"logs\", \"metrics\"]);\nexport type ExportSignal = z.infer<typeof exportSignalSchema>;\n\nconst headerValueSchema = z\n .string()\n .min(1)\n .max(MAX_HEADER_VALUE_LENGTH)\n // The rule `OTEL_EXPORTER_OTLP_*HEADERS` values are held to: a line break is a\n // request-splitting vector, and other controls or non-Latin-1 characters would\n // only make Node's HTTP client throw at send time.\n .refine(\n (value) => !isUnsafeHeaderValue(value),\n \"header values may not contain line breaks, control characters, or characters beyond Latin-1\",\n )\n .refine(\n (value) =>\n !value.startsWith(HEADER_ENV_REFERENCE_PREFIX) ||\n ENV_VARIABLE_NAME_PATTERN.test(value.slice(HEADER_ENV_REFERENCE_PREFIX.length)),\n \"an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN\",\n );\n\nconst endpointSchema = z.string().url().max(2048);\n\nexport const exportDestinationSchema = z\n .strictObject({\n /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */\n name: z\n .string()\n .regex(DESTINATION_NAME_PATTERN, \"destination names are lowercase letters, digits, _ and -\"),\n /** Default true. A disabled destination is neither sent to nor drained. */\n enabled: z.boolean().optional(),\n /**\n * Traces URL, with the same meaning as `exporter.endpoint`: the logs URL is\n * derived from it (`/v1/traces` becomes `/v1/logs`) unless `logsEndpoint` is set.\n */\n endpoint: endpointSchema.optional(),\n /** Per-signal override of `endpoint` for traces. */\n tracesEndpoint: endpointSchema.optional(),\n /** Per-signal override of the derived logs URL. */\n logsEndpoint: endpointSchema.optional(),\n /** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */\n metricsEndpoint: endpointSchema.optional(),\n /** Defaults to `exporter.protocol`. */\n protocol: z.enum([\"http/protobuf\", \"http/json\", \"none\"]).optional(),\n /**\n * Header name to value. A value of the form `env:NAME` is read from that\n * environment variable at send time, so a credential never has to be written\n * into the file. Values never appear in a snapshot, a diagnostic, or `doctor`.\n */\n headers: z\n .record(z.string().regex(HEADER_NAME_PATTERN, \"not a valid header name\"), headerValueSchema)\n .refine(\n (headers) => Object.keys(headers).length <= MAX_DESTINATION_HEADERS,\n `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`,\n )\n .optional(),\n /**\n * Which signals this destination receives. Default: traces and logs. The logs\n * signal is still governed by `exporter.logs.enabled`, which stays the one\n * opt-in for content-bearing records leaving the host. `metrics` is never on by\n * default: a destination receives hook-derived metrics only when it lists them.\n */\n signals: z.array(exportSignalSchema).min(1).max(3).readonly().optional(),\n })\n .refine(\n (destination) =>\n destination.endpoint !== undefined ||\n destination.tracesEndpoint !== undefined ||\n destination.logsEndpoint !== undefined ||\n destination.metricsEndpoint !== undefined,\n \"a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint\",\n );\nexport type ExportDestinationConfig = z.infer<typeof exportDestinationSchema>;\n\n/** Signals a destination receives when it does not list any: never metrics. */\nexport const DEFAULT_DESTINATION_SIGNALS: readonly ExportSignal[] = Object.freeze([\"traces\", \"logs\"]);\n\nexport const exportDestinationsSchema = z\n .array(exportDestinationSchema)\n .max(MAX_EXPORT_DESTINATIONS)\n .readonly()\n .superRefine((destinations, context) => {\n const seen = new Set<string>();\n destinations.forEach((destination, index) => {\n if (destination.name === DEFAULT_DESTINATION_NAME) {\n context.addIssue({\n code: \"custom\",\n path: [index, \"name\"],\n message:\n 'the name \"default\" is reserved for exporter.endpoint and the OTEL_EXPORTER_OTLP_* variables',\n });\n }\n if (seen.has(destination.name)) {\n context.addIssue({\n code: \"custom\",\n path: [index, \"name\"],\n message: `duplicate destination name \"${destination.name}\"`,\n });\n }\n seen.add(destination.name);\n });\n });\n\n/**\n * Bounds on each destination's retry spool, per signal.\n *\n * Every destination spools independently, so one long outage can only ever cost\n * its own budget. When a bound is reached the *oldest* batches are dropped first —\n * a recent batch is the one a reader is still likely to look for — and every drop\n * is counted on disk so `doctor` can report it.\n */\nexport const spoolPolicySchema = z.strictObject({\n /** Total bytes of queued batches. Default 16 MiB. */\n maxBytes: z.number().int().min(1_024).max(1_073_741_824),\n /** A batch older than this is dropped instead of sent. Default 72 hours. */\n maxAgeMillis: z.number().int().min(1_000).max(30 * 24 * 60 * 60 * 1000),\n /** Number of queued batches. Default 500. */\n maxBatches: z.number().int().min(1).max(65_536),\n});\nexport type SpoolPolicy = z.infer<typeof spoolPolicySchema>;\n\nexport const DEFAULT_SPOOL_POLICY: SpoolPolicy = Object.freeze({\n maxBytes: 16 * 1024 * 1024,\n maxAgeMillis: 72 * 60 * 60 * 1000,\n maxBatches: 500,\n});\n\n/** The spool policy in force, with defaults filled in for any bound left unset. */\nexport const effectiveSpoolPolicy = (exporter: ExporterPolicy): SpoolPolicy => ({\n maxBytes: exporter.spool?.maxBytes ?? DEFAULT_SPOOL_POLICY.maxBytes,\n maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,\n maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches,\n});\n\n/**\n * One destination as the runtime sends to it.\n *\n * `headers` holds what the configuration holds — literal values and `env:`\n * references, unresolved. Resolution against an environment happens only at the\n * point of sending ({@link resolveDestinationHeaders}), and the `default`\n * destination's header values never pass through configuration at all: they are\n * handed to the runtime separately, as they always have been.\n */\nexport type ExportDestination = {\n readonly name: string;\n /** `exporter` for the `default` destination, `destinations` for a list entry. */\n readonly source: \"exporter\" | \"destinations\";\n readonly protocol: ExporterPolicy[\"protocol\"];\n /** Traces URL as configured; for `default` this is `exporter.endpoint`. */\n readonly endpoint?: string;\n readonly tracesEndpoint?: string;\n readonly logsEndpoint?: string;\n readonly metricsEndpoint?: string;\n readonly signals: { readonly traces: boolean; readonly logs: boolean; readonly metrics: boolean };\n readonly headers: Readonly<Record<string, string>>;\n};\n\nconst legacyDestination = (exporter: ExporterPolicy): ExportDestination => ({\n name: DEFAULT_DESTINATION_NAME,\n source: \"exporter\",\n protocol: exporter.protocol,\n ...(exporter.endpoint === undefined ? {} : { endpoint: exporter.endpoint }),\n ...(exporter.logs.endpoint === undefined ? {} : { logsEndpoint: exporter.logs.endpoint }),\n ...(exporter.metrics?.endpoint === undefined ? {} : { metricsEndpoint: exporter.metrics.endpoint }),\n signals: { traces: true, logs: exporter.logs.enabled, metrics: exporter.metrics?.enabled === true },\n headers: {},\n});\n\n/** Whether a configuration uses the destination list at all. */\nexport const hasConfiguredDestinations = (exporter: ExporterPolicy): boolean =>\n exporter.destinations !== undefined && exporter.destinations.length > 0;\n\n/**\n * The destinations an exporter policy sends to, in a stable order: `default`\n * first when present, then the list in file order.\n *\n * - No `destinations`: exactly one `default` destination, even when it has no\n * endpoint — the sink then reports itself unconfigured, as it always has.\n * - With `destinations`: `default` is included only when a single-endpoint setting\n * actually names an endpoint, and disabled entries are left out.\n */\nexport const resolveExportDestinations = (\n exporter: ExporterPolicy,\n): readonly ExportDestination[] => {\n if (!hasConfiguredDestinations(exporter)) {\n return [legacyDestination(exporter)];\n }\n const resolved: ExportDestination[] = [];\n if (\n exporter.endpoint !== undefined ||\n exporter.logs.endpoint !== undefined ||\n exporter.metrics?.endpoint !== undefined\n ) {\n resolved.push(legacyDestination(exporter));\n }\n for (const destination of exporter.destinations ?? []) {\n if (destination.enabled === false) {\n continue;\n }\n const signals: readonly ExportSignal[] = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;\n resolved.push({\n name: destination.name,\n source: \"destinations\",\n protocol: destination.protocol ?? exporter.protocol,\n ...(destination.endpoint === undefined ? {} : { endpoint: destination.endpoint }),\n ...(destination.tracesEndpoint === undefined\n ? {}\n : { tracesEndpoint: destination.tracesEndpoint }),\n ...(destination.logsEndpoint === undefined ? {} : { logsEndpoint: destination.logsEndpoint }),\n ...(destination.metricsEndpoint === undefined\n ? {}\n : { metricsEndpoint: destination.metricsEndpoint }),\n signals: {\n traces: signals.includes(\"traces\"),\n logs: exporter.logs.enabled && signals.includes(\"logs\"),\n metrics: signals.includes(\"metrics\"),\n },\n headers: { ...(destination.headers ?? {}) },\n });\n }\n return resolved;\n};\n\n/** A header value's meaning, without its content. */\nexport type HeaderValueReference =\n | { readonly kind: \"literal\" }\n | { readonly kind: \"env\"; readonly variable: string };\n\nexport const parseHeaderValueReference = (value: string): HeaderValueReference =>\n value.startsWith(HEADER_ENV_REFERENCE_PREFIX)\n ? { kind: \"env\", variable: value.slice(HEADER_ENV_REFERENCE_PREFIX.length) }\n : { kind: \"literal\" };\n\nexport type ResolvedDestinationHeaders = {\n /** Header values ready to send. Never logged, never reported. */\n readonly values: Readonly<Record<string, string>>;\n /** Names of referenced environment variables that are unset or empty. */\n readonly missingVariables: readonly string[];\n};\n\n/**\n * Resolve `env:` references against an explicitly supplied environment.\n *\n * Pure: the process environment is never read implicitly. An unset or empty\n * variable is reported by *name* — the only part of a reference that is safe to\n * say out loud — and its header is left out of `values`.\n */\nexport const resolveDestinationHeaders = (\n headers: Readonly<Record<string, string>>,\n environment: Readonly<Record<string, string | undefined>> | undefined,\n): ResolvedDestinationHeaders => {\n const values: Record<string, string> = {};\n const missing: string[] = [];\n for (const [name, value] of Object.entries(headers)) {\n const reference = parseHeaderValueReference(value);\n if (reference.kind === \"literal\") {\n values[name] = value;\n continue;\n }\n const resolved = environment?.[reference.variable];\n if (resolved === undefined || resolved === \"\") {\n missing.push(reference.variable);\n continue;\n }\n values[name] = resolved;\n }\n return { values, missingVariables: [...new Set(missing)].sort() };\n};\n\n/**\n * Attribute-safe description of one destination: names, origins, and variable\n * names. Never a header value, and never an endpoint beyond its origin.\n */\nexport type DestinationDescription = {\n readonly name: string;\n readonly enabled: boolean;\n readonly protocol: ExporterPolicy[\"protocol\"];\n readonly signals: readonly ExportSignal[];\n readonly tracesEndpointOrigin?: string;\n readonly logsEndpointOrigin?: string;\n readonly metricsEndpointOrigin?: string;\n readonly headerNames: readonly string[];\n /** Environment variables this destination's headers reference. */\n readonly headerVariables: readonly string[];\n};\n\nexport const endpointOrigin = (endpoint: string | undefined): string | undefined => {\n if (endpoint === undefined) {\n return undefined;\n }\n try {\n return new URL(endpoint).origin;\n } catch {\n return \"<unparsable>\";\n }\n};\n\n/** Every configured destination, disabled ones included, for `doctor` and snapshots. */\nexport const describeExportDestinations = (\n exporter: ExporterPolicy,\n): readonly DestinationDescription[] => {\n const describe = (\n destination: ExportDestination,\n enabled: boolean,\n ): DestinationDescription => {\n const tracesOrigin = endpointOrigin(destination.tracesEndpoint ?? destination.endpoint);\n const logsOrigin = endpointOrigin(\n destination.logsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint,\n );\n const metricsOrigin = endpointOrigin(\n destination.metricsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint,\n );\n const variables = Object.values(destination.headers)\n .map(parseHeaderValueReference)\n .flatMap((reference) => (reference.kind === \"env\" ? [reference.variable] : []));\n return {\n name: destination.name,\n enabled,\n protocol: destination.protocol,\n signals: exportSignalSchema.options.filter((signal) => destination.signals[signal]),\n ...(tracesOrigin === undefined || !destination.signals.traces\n ? {}\n : { tracesEndpointOrigin: tracesOrigin }),\n ...(logsOrigin === undefined || !destination.signals.logs\n ? {}\n : { logsEndpointOrigin: logsOrigin }),\n ...(metricsOrigin === undefined || !destination.signals.metrics\n ? {}\n : { metricsEndpointOrigin: metricsOrigin }),\n headerNames:\n destination.source === \"exporter\"\n ? [...exporter.headerNames].sort()\n : Object.keys(destination.headers).sort(),\n headerVariables: [...new Set(variables)].sort(),\n };\n };\n const enabled = resolveExportDestinations(exporter).map((destination) =>\n describe(destination, true),\n );\n const disabled = (exporter.destinations ?? [])\n .filter((destination) => destination.enabled === false)\n .map((destination) =>\n describe(\n {\n name: destination.name,\n source: \"destinations\",\n protocol: destination.protocol ?? exporter.protocol,\n ...(destination.endpoint === undefined ? {} : { endpoint: destination.endpoint }),\n signals: { traces: false, logs: false, metrics: false },\n headers: { ...(destination.headers ?? {}) },\n },\n false,\n ),\n );\n return [...enabled, ...disabled];\n};\n","/**\n * Internal: shared by `OTEL_EXPORTER_OTLP_*HEADERS` parsing and the\n * `exporter.destinations[].headers` schema. Not re-exported from the package.\n */\n\n/**\n * Characters an HTTP field value must not contain once decoded. CR and LF would\n * split the request; the other controls and anything beyond Latin-1 are refused\n * by Node's HTTP client anyway, and refusing them here turns a failed export into\n * a reported, skipped entry.\n */\nexport const isUnsafeHeaderValue = (value: string): boolean =>\n [...value].some((char) => {\n const code = char.codePointAt(0) ?? 0;\n return (code < 0x20 && code !== 0x09) || code === 0x7f || code > 0xff;\n });\n","/**\n * The standard OTLP exporter header variables.\n *\n * `OTEL_EXPORTER_OTLP_HEADERS` applies to every signal;\n * `OTEL_EXPORTER_OTLP_TRACES_HEADERS` and `OTEL_EXPORTER_OTLP_LOGS_HEADERS`\n * apply to one signal each. They exist so a credential (`authorization=Basic …`)\n * can reach the exporter without being written on a command line, where `ps` and\n * `/proc/<pid>/cmdline` would show it to every local user.\n *\n * Header *values* never enter configuration. Parsing returns them to the caller,\n * which hands them straight to the sink at construction; configuration carries\n * header *names* only (`exporter.headerNames`), because a resolved-config\n * snapshot is logged and exported. Every diagnostic here names an entry by its\n * position and the variable by its name — never a key, never a value — because a\n * malformed entry may be the secret itself (`Basic abc` with no `=`).\n */\n\nimport { isUnsafeHeaderValue } from \"./header-value.js\";\n\n/** Upper bound on headers per variable, matching `exporter.headerNames`. */\nexport const MAX_OTLP_HEADERS = 32;\n\nexport const OTLP_HEADER_VARIABLES = Object.freeze({\n generic: \"OTEL_EXPORTER_OTLP_HEADERS\",\n traces: \"OTEL_EXPORTER_OTLP_TRACES_HEADERS\",\n logs: \"OTEL_EXPORTER_OTLP_LOGS_HEADERS\",\n});\n\n/** RFC 9110 `token`: the characters an HTTP field name may contain. */\nconst HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n\nexport type ParsedOtlpHeaders = {\n readonly headers: Readonly<Record<string, string>>;\n /** Position-only explanations; never a key or a value. */\n readonly warnings: readonly string[];\n};\n\nconst decode = (raw: string): string | undefined => {\n try {\n return decodeURIComponent(raw);\n } catch {\n return undefined;\n }\n};\n\n/**\n * Parse one `OTEL_EXPORTER_OTLP_*HEADERS` value.\n *\n * The OpenTelemetry exporter specification defines the format as W3C\n * Baggage-like: comma-separated `key=value` pairs, surrounding whitespace\n * trimmed, keys and values percent-decoded. So `authorization=Basic%20abc` is\n * the header `authorization: Basic abc`, and a `,` inside a value must be\n * written `%2C`. A malformed entry is skipped and reported; the rest of the\n * variable still applies. A repeated key takes its last value.\n */\nexport const parseOtlpHeadersValue = (raw: string): ParsedOtlpHeaders => {\n const headers: Record<string, string> = {};\n const warnings: string[] = [];\n let overflowed = false;\n\n for (const [index, rawEntry] of raw.split(\",\").entries()) {\n const position = String(index + 1);\n const entry = rawEntry.trim();\n if (entry === \"\") {\n continue;\n }\n const equals = entry.indexOf(\"=\");\n if (equals <= 0) {\n warnings.push(`entry ${position} is not a key=value pair; ignored`);\n continue;\n }\n const key = decode(entry.slice(0, equals).trim());\n // Split on the first `=` only: a base64 credential ends in `=` padding.\n const value = decode(entry.slice(equals + 1).trim());\n if (key === undefined || value === undefined) {\n warnings.push(`entry ${position} has malformed percent-encoding; ignored`);\n continue;\n }\n const name = key.trim();\n const trimmedValue = value.trim();\n if (!HEADER_NAME_PATTERN.test(name)) {\n warnings.push(`entry ${position} does not name a valid HTTP header; ignored`);\n continue;\n }\n if (trimmedValue === \"\") {\n warnings.push(`entry ${position} has an empty value; ignored`);\n continue;\n }\n if (isUnsafeHeaderValue(trimmedValue)) {\n warnings.push(`entry ${position} has a character not allowed in an HTTP header value; ignored`);\n continue;\n }\n const existing = findHeaderName(headers, name);\n if (existing === undefined && Object.keys(headers).length >= MAX_OTLP_HEADERS) {\n overflowed = true;\n continue;\n }\n if (existing !== undefined) {\n delete headers[existing];\n }\n headers[name] = trimmedValue;\n }\n\n if (overflowed) {\n warnings.push(`more than ${String(MAX_OTLP_HEADERS)} headers were supplied; the excess was ignored`);\n }\n return { headers, warnings };\n};\n\n/** HTTP field names are case-insensitive: `Authorization` and `authorization` are one header. */\nconst findHeaderName = (headers: Readonly<Record<string, string>>, name: string): string | undefined => {\n const lower = name.toLowerCase();\n return Object.keys(headers).find((candidate) => candidate.toLowerCase() === lower);\n};\n\n/**\n * Overlay header maps, lowest precedence first, per header name.\n *\n * A higher source replaces only the names it sets (case-insensitively), so a\n * signal-specific variable can override `authorization` while a generic tenant\n * header still applies — the same per-key merge the OpenTelemetry SDKs apply.\n */\nexport const mergeOtlpHeaders = (\n ...sources: readonly Readonly<Record<string, string>>[]\n): Readonly<Record<string, string>> => {\n const merged: Record<string, string> = {};\n for (const source of sources) {\n for (const [name, value] of Object.entries(source)) {\n const existing = findHeaderName(merged, name);\n if (existing !== undefined) {\n delete merged[existing];\n }\n merged[name] = value;\n }\n }\n return merged;\n};\n\nexport type ResolvedOtlpHeaders = {\n /** Headers for the traces exporter. */\n readonly traces: Readonly<Record<string, string>>;\n /** Headers for the logs exporter. */\n readonly logs: Readonly<Record<string, string>>;\n /** Variable-qualified, value-free explanations of skipped entries. */\n readonly warnings: readonly { readonly variable: string; readonly detail: string }[];\n};\n\n/**\n * Resolve exporter headers per signal.\n *\n * Precedence, per header name, highest first:\n *\n * ```\n * explicit headers (--header) > OTEL_EXPORTER_OTLP_{TRACES,LOGS}_HEADERS > OTEL_EXPORTER_OTLP_HEADERS\n * ```\n *\n * Pure: the environment is passed in, never read from `process.env`.\n */\nexport const resolveOtlpHeaders = (\n env: Readonly<Record<string, string | undefined>>,\n explicit: Readonly<Record<string, string>> = {},\n): ResolvedOtlpHeaders => {\n const warnings: { variable: string; detail: string }[] = [];\n const read = (variable: string): Readonly<Record<string, string>> => {\n const raw = env[variable];\n if (raw === undefined || raw.trim() === \"\") {\n return {};\n }\n const parsed = parseOtlpHeadersValue(raw);\n for (const detail of parsed.warnings) {\n warnings.push({ variable, detail });\n }\n return parsed.headers;\n };\n const generic = read(OTLP_HEADER_VARIABLES.generic);\n const traces = read(OTLP_HEADER_VARIABLES.traces);\n const logs = read(OTLP_HEADER_VARIABLES.logs);\n return {\n traces: mergeOtlpHeaders(generic, traces, explicit),\n logs: mergeOtlpHeaders(generic, logs, explicit),\n warnings,\n };\n};\n\n/**\n * Header names, deduplicated case-insensitively (first spelling kept), sorted\n * and bounded — the only part of a header that may enter configuration or a\n * diagnostic.\n */\nexport const unionOtlpHeaderNames = (...lists: readonly (readonly string[])[]): readonly string[] => {\n const names: string[] = [];\n const seen = new Set<string>();\n for (const name of lists.flat()) {\n if (!seen.has(name.toLowerCase())) {\n seen.add(name.toLowerCase());\n names.push(name);\n }\n }\n return names.sort().slice(0, MAX_OTLP_HEADERS);\n};\n\n/** {@link unionOtlpHeaderNames} over the names of header maps. */\nexport const describeOtlpHeaderNames = (\n ...sources: readonly Readonly<Record<string, string>>[]\n): readonly string[] => unionOtlpHeaderNames(...sources.map((source) => Object.keys(source)));\n","import { isAbsolute } from \"node:path\";\n\nimport { z } from \"zod\";\n\nimport { detectionConfidenceSchema, nonEmptyStringSchema } from \"../model/primitives.js\";\nimport {\n contentModeSchema,\n DEFAULT_PRIVACY_POLICY,\n privacyPolicySchema,\n} from \"../privacy/policy.js\";\nimport { exportDestinationsSchema, spoolPolicySchema } from \"./destinations.js\";\nimport { EMPTY_RESOURCE_ATTRIBUTES, resourceAttributesSchema } from \"./resource-attributes.js\";\n\n/**\n * Policy for the OTLP logs signal.\n *\n * Two switches rather than one, because they answer different questions and an\n * operator needs to be able to answer them differently:\n *\n * - `enabled` — whether a second signal leaves this host at all. Off by default:\n * an installation that upgrades must not silently start sending a new stream to a\n * collector whose receivers, quotas, and retention were sized for traces.\n * - `includeContent` — whether *disclosed* text may appear in a log body. Also off\n * by default, and deliberately not the same knob as `privacy.contentMode`: spans\n * carry no content in any content mode, so an installation that set\n * `contentMode` to get a hash and a length has never had content on the wire.\n * Reusing that setting to also mean \"publish prompts\" would change what an\n * existing configuration discloses without anybody editing it.\n *\n * `raw` content additionally requires the pre-existing `privacy.allowRawContent`\n * opt-in, which the privacy service enforces before a fact is ever built and the\n * log mapping re-checks at the wire.\n */\nexport const logsPolicySchema = z.strictObject({\n enabled: z.boolean(),\n /**\n * Full URL for the logs signal.\n *\n * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes\n * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.\n */\n endpoint: z.string().url().max(2048).optional(),\n includeContent: z.boolean(),\n maxBatchSize: z.number().int().min(1).max(4096),\n});\nexport type LogsPolicy = z.infer<typeof logsPolicySchema>;\n\nexport const DEFAULT_LOGS_POLICY: LogsPolicy = Object.freeze({\n enabled: false,\n includeContent: false,\n maxBatchSize: 128,\n});\n\n/**\n * Policy for hook-derived metrics (issue #69).\n *\n * Off by default, like logs: an upgrade must not start a new stream to a\n * collector nobody sized for it. `enabled` governs the `default` destination\n * (the single-endpoint settings); an `exporter.destinations[]` entry receives\n * metrics when its `signals` list names `metrics`. Metrics carry no content, so\n * listing the signal is the whole opt-in.\n *\n * - `temporality`: `cumulative` (default) exports running totals per series,\n * kept in the state store across hook processes, so a receiver that merges\n * counters by keeping the largest value stays correct. `delta` exports what one\n * callback observed and keeps no state.\n * - `includeSessionId`: put `session.id` on every data point (default true). Turn\n * it off where per-session series are too many for the backend.\n */\nexport const metricsPolicySchema = z.strictObject({\n enabled: z.boolean(),\n /** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */\n endpoint: z.string().url().max(2048).optional(),\n temporality: z.enum([\"cumulative\", \"delta\"]),\n includeSessionId: z.boolean(),\n});\nexport type MetricsPolicy = z.infer<typeof metricsPolicySchema>;\n\nexport const DEFAULT_METRICS_POLICY: MetricsPolicy = Object.freeze({\n enabled: false,\n temporality: \"cumulative\",\n includeSessionId: true,\n});\n\n/**\n * Runtime exporter policy.\n *\n * This describes *where and how* telemetry goes. It deliberately contains no\n * session, invocation, or workspace field: see ADR 0001. Mixing the two would\n * make identity globally reachable through configuration.\n */\nexport const exporterPolicySchema = z.strictObject({\n enabled: z.boolean(),\n protocol: z.enum([\"http/protobuf\", \"http/json\", \"none\"]),\n endpoint: z.string().url().max(2048).optional(),\n /**\n * Header names only. Values are supplied separately at construction time and\n * are never part of a resolved-config snapshot, which is logged and exported.\n */\n headerNames: z.array(nonEmptyStringSchema).max(32).readonly(),\n timeoutMillis: z.number().int().min(1).max(600_000),\n maxBatchSize: z.number().int().min(1).max(4096),\n maxQueueSize: z.number().int().min(1).max(65_536),\n maxRetryAttempts: z.number().int().min(0).max(10),\n serviceName: nonEmptyStringSchema,\n serviceNamespace: nonEmptyStringSchema.optional(),\n /**\n * Custom attributes merged into the exported OTLP Resource.\n *\n * Bounded and validated, and refusing `service.name`/`service.namespace`,\n * which are the two fields above. Distinct from an invocation's\n * `consumerAttributes`: this describes the emitting deployment, carries no\n * identity, and is the same for every span this process exports.\n */\n resourceAttributes: resourceAttributesSchema,\n /**\n * The logs signal. Nested under the exporter because it shares the endpoint,\n * headers, timeout, protocol, service identity, and resource attributes above —\n * a second top-level section would invite two of each to drift apart.\n */\n logs: logsPolicySchema,\n /**\n * Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before\n * metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.\n */\n metrics: metricsPolicySchema.optional(),\n /**\n * Additional OTLP destinations, each sent every batch in parallel.\n *\n * Absent (the default), the exporter has exactly one destination — the\n * single-endpoint settings above, named `default` — and behaves exactly as it\n * did before this list existed. See `destinations.ts`.\n *\n * Merged as one leaf: a higher layer that sets the list replaces it whole,\n * because \"the union of two partial lists\" has no answer an operator could\n * predict.\n */\n destinations: exportDestinationsSchema.optional(),\n /**\n * Per-destination retry spool bounds, each optional and merged per leaf; any\n * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.\n */\n spool: spoolPolicySchema.partial().optional(),\n});\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\n/**\n * Per-provider behaviour that is not part of an adapter's parse.\n *\n * `claudeCode.readTranscriptUsage` is the one sanctioned exception to \"no\n * transcript reads in the hook\" (docs/claude-code-usage-contract.md, finding 8).\n * When true, the hook runtime — never the adapter — reads the session transcript\n * named by a Claude Code `Stop` / `StopFailure` payload, bounded, and attaches the\n * turn's model and summed token usage before the adapter parses it. Off by\n * default: without it, otel-hook reads no file a hook payload names.\n */\nexport const providersPolicySchema = z.strictObject({\n claudeCode: z\n .strictObject({\n readTranscriptUsage: z.boolean(),\n })\n .optional(),\n});\nexport type ProvidersPolicy = z.infer<typeof providersPolicySchema>;\n\n/**\n * Session context (`docs/session-context.md`): a directory a harness writes one\n * JSON file per agent session into, laid out `<dir>/<agent-tool>/<session-id>.json`.\n * With `dir` set, the hook reads that one file on every event and stamps the\n * attributes of the segment in force on every span, log record and metric point.\n * Absent (the default), nothing is read.\n *\n * Set in the configuration file or with `--session-context-dir`, never through\n * the environment: some agents (Claude Code) strip `OTEL_*` variables from the\n * hook processes they start.\n */\nexport const sessionContextPolicySchema = z.strictObject({\n /** Absolute path of the context directory. */\n dir: z\n .string()\n .min(1)\n .max(4096)\n .refine((value) => isAbsolute(value), { message: \"must be an absolute path\" }),\n});\nexport type SessionContextPolicy = z.infer<typeof sessionContextPolicySchema>;\n\nexport const otelHookConfigSchema = z.strictObject({\n exporter: exporterPolicySchema,\n privacy: privacyPolicySchema,\n detection: detectionPolicySchema,\n diagnostics: diagnosticsPolicySchema,\n /** Optional so a hand-built configuration from before it existed stays valid. */\n providers: providersPolicySchema.optional(),\n /** Optional: absent means no session context is read. */\n sessionContext: sessionContextPolicySchema.optional(),\n});\nexport type OtelHookConfig = z.infer<typeof otelHookConfigSchema>;\n\n/** Partial overlay accepted from a configuration layer. */\nexport const otelHookConfigPatchSchema = z.strictObject({\n // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:\n // merging happens per leaf, so a layer must be able to set `logs.enabled` alone\n // without also restating the endpoint and the batch size.\n exporter: exporterPolicySchema\n .omit({ logs: true, metrics: true, spool: true })\n .partial()\n .extend({\n logs: logsPolicySchema.partial().optional(),\n metrics: metricsPolicySchema.partial().optional(),\n spool: spoolPolicySchema.partial().optional(),\n })\n .optional(),\n privacy: privacyPolicySchema\n .omit({ limits: true })\n .partial()\n .extend({ limits: privacyPolicySchema.shape.limits.partial().optional() })\n .optional(),\n detection: detectionPolicySchema.partial().optional(),\n diagnostics: diagnosticsPolicySchema.partial().optional(),\n providers: z\n .strictObject({\n claudeCode: z.strictObject({ readTranscriptUsage: z.boolean() }).partial().optional(),\n })\n .partial()\n .optional(),\n sessionContext: sessionContextPolicySchema.partial().optional(),\n});\nexport type OtelHookConfigPatch = z.infer<typeof otelHookConfigPatchSchema>;\n\nexport const DEFAULT_EXPORTER_POLICY: ExporterPolicy = Object.freeze({\n enabled: true,\n protocol: \"http/protobuf\",\n headerNames: Object.freeze([]),\n timeoutMillis: 10_000,\n maxBatchSize: 128,\n maxQueueSize: 2048,\n maxRetryAttempts: 2,\n serviceName: \"coding-agent\",\n resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,\n logs: DEFAULT_LOGS_POLICY,\n metrics: DEFAULT_METRICS_POLICY,\n});\n\nexport const DEFAULT_DETECTION_POLICY: DetectionPolicy = Object.freeze({\n minimumConfidence: \"strong\",\n allowAmbiguousFallback: true,\n allowedProviderIds: Object.freeze([]),\n});\n\nexport const DEFAULT_DIAGNOSTICS_POLICY: DiagnosticsPolicy = Object.freeze({\n logLevel: \"warn\",\n emitErrorEvents: true,\n});\n\nexport const DEFAULT_PROVIDERS_POLICY: ProvidersPolicy = Object.freeze({\n claudeCode: Object.freeze({ readTranscriptUsage: false }),\n});\n\nexport const DEFAULT_CONFIG: OtelHookConfig = Object.freeze({\n exporter: DEFAULT_EXPORTER_POLICY,\n privacy: DEFAULT_PRIVACY_POLICY,\n detection: DEFAULT_DETECTION_POLICY,\n diagnostics: DEFAULT_DIAGNOSTICS_POLICY,\n providers: DEFAULT_PROVIDERS_POLICY,\n});\n\n/** Whether the runtime may read Claude Code transcripts at `Stop` (default false). */\nexport const readsClaudeTranscriptUsage = (config: OtelHookConfig): boolean =>\n config.providers?.claudeCode?.readTranscriptUsage === true;\n\n/** The session context directory in force, or `undefined` when none is configured. */\nexport const sessionContextDir = (config: OtelHookConfig): string | undefined => config.sessionContext?.dir;\n\n/** Content mode is re-exported for callers building patches. */\nexport { contentModeSchema };\n\n/** The metrics policy in force, defaults filled in. */\nexport const effectiveMetricsPolicy = (exporter: ExporterPolicy): MetricsPolicy => ({\n ...DEFAULT_METRICS_POLICY,\n ...(exporter.metrics ?? {}),\n});\n","import type { Attributes } from \"@opentelemetry/api\";\nimport type { Resource } from \"@opentelemetry/resources\";\n\nimport type { CanonicalEvent, GenerationEndEvent } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\nimport { resolveExportedSessionId } from \"./export-identity.js\";\n\n/**\n * Metrics derived from hook events (issue #69).\n *\n * otel-hook already normalizes every provider's hook callbacks into canonical\n * events; this module turns one batch of those events into *observations* — a\n * value recorded against an instrument, with attributes. It is pure: it reads no\n * state and sends nothing. Aggregating observations into OTLP data points\n * (cumulative across processes, or delta per batch) and exporting them are the\n * jobs of `lifecycle/metric-series.ts` and `otlp-metric-sink.ts`.\n *\n * ## Why observations come from the runtime's accounting, not from the events alone\n *\n * Token usage is taken from the orchestrator's `UsageObservation` deltas rather than\n * from `generation.end.usage` directly. A provider that reports a session-wide\n * running total (Codex) stamps the *cumulative* figure on every turn; summing those\n * into a histogram would bill a three-turn session several times over. The\n * orchestrator already diffs them against a persisted baseline, exactly once per\n * delivery, so the metric reuses that answer.\n *\n * ## What is never on a metric\n *\n * Session context attributes (`docs/session-context.md`) are on every data point\n * of an event that has them, so a new context starts a new series.\n *\n * No account identity (`user.*`, `enduser.*`, `organization.id`), no content, no\n * paths, and no per-event ids (`otelhook.event.id`, tool-call ids, generation ids):\n * an id per data point is a new series per data point. `session.id` is the one\n * high-cardinality attribute, and it can be switched off.\n */\n\n/** Recommended bucket boundaries from the GenAI semantic conventions. */\nexport const TOKEN_USAGE_BUCKETS: readonly number[] = Object.freeze([\n 1, 4, 16, 64, 256, 1_024, 4_096, 16_384, 65_536, 262_144, 1_048_576, 4_194_304, 16_777_216,\n 67_108_864,\n]);\nexport const OPERATION_DURATION_BUCKETS: readonly number[] = Object.freeze([\n 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24, 20.48, 40.96, 81.92,\n]);\n\nexport const METRIC_TOKEN_USAGE = \"gen_ai.client.token.usage\";\nexport const METRIC_OPERATION_DURATION = \"gen_ai.client.operation.duration\";\nexport const METRIC_SESSIONS = \"otelhook.sessions\";\nexport const METRIC_TOOL_CALLS = \"otelhook.tool.calls\";\nexport const METRIC_COST_USAGE = \"otelhook.cost.usage\";\n\nexport type MetricInstrumentName =\n | typeof METRIC_TOKEN_USAGE\n | typeof METRIC_OPERATION_DURATION\n | typeof METRIC_SESSIONS\n | typeof METRIC_TOOL_CALLS\n | typeof METRIC_COST_USAGE;\n\nexport type MetricInstrument = {\n readonly name: MetricInstrumentName;\n readonly kind: \"histogram\" | \"counter\";\n readonly unit: string;\n readonly description: string;\n /** Integer values (`asInt`) or doubles. Histograms always carry a double sum. */\n readonly valueType: \"int\" | \"double\";\n /** Histograms only. */\n readonly boundaries?: readonly number[];\n};\n\nexport const METRIC_INSTRUMENTS: Readonly<Record<MetricInstrumentName, MetricInstrument>> = Object.freeze({\n [METRIC_TOKEN_USAGE]: {\n name: METRIC_TOKEN_USAGE,\n kind: \"histogram\",\n unit: \"{token}\",\n description: \"Tokens used per generation, by token type (hook-derived)\",\n valueType: \"int\",\n boundaries: TOKEN_USAGE_BUCKETS,\n },\n [METRIC_OPERATION_DURATION]: {\n name: METRIC_OPERATION_DURATION,\n kind: \"histogram\",\n unit: \"s\",\n description: \"Generation duration, from its start hook to its end hook (hook-derived)\",\n valueType: \"double\",\n boundaries: OPERATION_DURATION_BUCKETS,\n },\n [METRIC_SESSIONS]: {\n name: METRIC_SESSIONS,\n kind: \"counter\",\n unit: \"{session}\",\n description: \"Agent sessions started\",\n valueType: \"int\",\n },\n [METRIC_TOOL_CALLS]: {\n name: METRIC_TOOL_CALLS,\n kind: \"counter\",\n unit: \"{call}\",\n description: \"Completed tool calls, by tool name and outcome\",\n valueType: \"int\",\n },\n [METRIC_COST_USAGE]: {\n name: METRIC_COST_USAGE,\n kind: \"counter\",\n unit: \"USD\",\n description: \"Cost reported by the provider; never estimated\",\n valueType: \"double\",\n },\n});\n\nexport const isMetricInstrumentName = (value: unknown): value is MetricInstrumentName =>\n typeof value === \"string\" && Object.hasOwn(METRIC_INSTRUMENTS, value);\n\nexport const ATTR_GEN_AI_TOKEN_TYPE = \"gen_ai.token.type\";\nexport const ATTR_GEN_AI_PROVIDER_NAME = \"gen_ai.provider.name\";\nconst ATTR_GEN_AI_OPERATION_NAME = \"gen_ai.operation.name\";\nconst ATTR_GEN_AI_REQUEST_MODEL = \"gen_ai.request.model\";\nconst ATTR_GEN_AI_RESPONSE_MODEL = \"gen_ai.response.model\";\nconst ATTR_GEN_AI_TOOL_NAME = \"gen_ai.tool.name\";\nconst ATTR_ERROR_TYPE = \"error.type\";\nconst ATTR_SESSION_ID = \"session.id\";\nconst ATTR_OTELHOOK_PROVIDER_ID = \"otelhook.provider.id\";\nconst ATTR_OTELHOOK_OUTCOME = \"otelhook.outcome\";\nconst ATTR_OTELHOOK_SESSION_KIND = \"otelhook.session.kind\";\n\n/**\n * Token types on `gen_ai.client.token.usage`.\n *\n * `input` is inclusive of cache reads, as the GenAI conventions define\n * `gen_ai.usage.input_tokens`. `cache_read` and `cache_creation` are extra series\n * describing parts of the input; summing every token type double-counts.\n */\nexport type TokenType = \"input\" | \"output\" | \"cache_read\" | \"cache_creation\";\n\nexport type MetricsTemporality = \"cumulative\" | \"delta\";\n\n/** One recorded value. */\nexport type MetricObservation = {\n readonly instrument: MetricInstrumentName;\n readonly value: number;\n /** Data-point attributes. Primitives only. */\n readonly attributes: Readonly<Record<string, string | number | boolean>>;\n /** When the observed thing happened, in epoch milliseconds. */\n readonly timeMillis: number;\n /** Provider session the observation belongs to; scopes cumulative state. */\n readonly sessionId: string;\n};\n\n/** A start time recovered for a generation, by generation id. */\nexport type GenerationStart = {\n readonly startMillis: number;\n readonly requestModel?: string;\n};\n\n/** The usage delta the orchestrator derived for one usage-bearing event. */\nexport type MetricUsageInput = {\n readonly eventId: string;\n readonly scope: string;\n readonly delta: CanonicalUsage;\n};\n\nexport type DeriveMetricObservationsInput = {\n readonly events: readonly CanonicalEvent[];\n readonly usage: readonly MetricUsageInput[];\n /** The exported resource; supplies the launcher's `session.id` when it sets one. */\n readonly resource: Resource;\n /** Put `session.id` on every data point. Default true. */\n readonly includeSessionId?: boolean;\n /**\n * Start times for generations whose start edge is not in this batch (it was\n * recorded by an earlier hook process). Looked up by generation id.\n */\n readonly generationStarts?: (generationId: string) => GenerationStart | undefined;\n /**\n * When the session's current turn began: the last `prompt.submitted` recorded,\n * by an earlier callback or this one. The fallback duration source for\n * providers whose generation is a turn (Claude Code, Codex).\n */\n readonly turnStart?: (sessionId: string) => number | undefined;\n};\n\nconst commonAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n includeSessionId: boolean,\n): Record<string, string | number | boolean> => ({\n // Session context first, so the metric's own attributes always win; and never\n // anything account-shaped, whatever the context says.\n ...(event.contextAttributes === undefined\n ? {}\n : (withoutAccountIdentity(event.contextAttributes) as Record<string, string | number | boolean>)),\n [ATTR_OTELHOOK_PROVIDER_ID]: event.provenance.providerId,\n ...(includeSessionId\n ? { [ATTR_SESSION_ID]: resolveExportedSessionId(event.sessionId, resource).sessionId }\n : {}),\n});\n\nconst generationAttributes = (\n end: GenerationEndEvent,\n requestModel: string | undefined,\n): Record<string, string> => ({\n [ATTR_GEN_AI_OPERATION_NAME]: \"chat\",\n ...(end.model.vendor === undefined ? {} : { [ATTR_GEN_AI_PROVIDER_NAME]: end.model.vendor }),\n [ATTR_GEN_AI_REQUEST_MODEL]: requestModel ?? end.model.modelId,\n [ATTR_GEN_AI_RESPONSE_MODEL]: end.model.modelId,\n});\n\nconst TOKEN_FIELDS: readonly (readonly [TokenType, (usage: CanonicalUsage) => number])[] = [\n [\"input\", (usage) => usage.inputTokens],\n [\"output\", (usage) => usage.outputTokens],\n [\"cache_read\", (usage) => usage.cachedInputTokens],\n [\"cache_creation\", (usage) => usage.cacheCreationInputTokens],\n];\n\nconst isFailedOutcome = (outcome: string): boolean =>\n outcome !== \"ok\" && outcome !== \"unknown\" && outcome !== \"cancelled\";\n\n/**\n * Observations for one batch.\n *\n * - `otelhook.sessions`: one per `session.start`.\n * - `otelhook.tool.calls`: one per `tool.end`.\n * - `gen_ai.client.operation.duration`: one per `generation.end` whose duration is\n * known, from the first source that has it:\n * 1. the duration the provider stated (`durationMillis`);\n * 2. a `generation.start` recorded by an *earlier* callback;\n * 3. the turn's start: the last `prompt.submitted` of the session, no later than\n * the end. For Claude Code and Codex a generation is a turn, so this is the\n * turn's wall-clock time, tool calls included. Not for a subagent's\n * generation, which did not start with the parent's prompt.\n * A `generation.start` in the *same* batch as its end is not a start: an\n * adapter that emits both from one callback (Claude Code's `Stop`) synthesized\n * it, and measuring from it would record a zero.\n * - `gen_ai.client.token.usage`: per generation-scoped usage delta, one per token\n * type. A zero `cache_read` / `cache_creation` is not recorded: a provider that\n * never reports cache tokens would otherwise fill the low bucket with zeros.\n * `input` and `output` are always recorded, zero included, so the count of a\n * token histogram is the number of generations with usage.\n * - `otelhook.cost.usage`: per `generation.end` with a provider-reported USD cost.\n */\nexport const deriveMetricObservations = (\n input: DeriveMetricObservationsInput,\n): readonly MetricObservation[] => {\n const includeSessionId = input.includeSessionId ?? true;\n const observations: MetricObservation[] = [];\n const byId = new Map<string, CanonicalEvent>();\n const startsInBatch = new Map<string, GenerationStart>();\n for (const event of input.events) {\n byId.set(event.eventId, event);\n if (event.type === \"generation.start\") {\n startsInBatch.set(event.generationId, {\n startMillis: event.occurredAt,\n requestModel: event.model.modelId,\n });\n }\n }\n // Request model only: a start in this batch says what was asked for, but not when.\n const requestModelOf = (generationId: string): string | undefined =>\n startsInBatch.get(generationId)?.requestModel ?? input.generationStarts?.(generationId)?.requestModel;\n let lastPromptInBatch: Map<string, number> | undefined;\n for (const event of input.events) {\n if (event.type === \"prompt.submitted\") {\n lastPromptInBatch ??= new Map();\n lastPromptInBatch.set(event.sessionId, Math.max(lastPromptInBatch.get(event.sessionId) ?? 0, event.occurredAt));\n }\n }\n const measuredDurationOf = (end: GenerationEndEvent): number | undefined => {\n if (end.durationMillis !== undefined) {\n return end.durationMillis;\n }\n const recovered = startsInBatch.has(end.generationId) ? undefined : input.generationStarts?.(end.generationId);\n if (recovered !== undefined) {\n return end.occurredAt - recovered.startMillis;\n }\n // The turn's prompt is the parent's: a subagent's generation started later,\n // when the subagent did, so measuring from the prompt would overstate it.\n if (end.subagentId !== undefined) {\n return undefined;\n }\n const turn = lastPromptInBatch?.get(end.sessionId) ?? input.turnStart?.(end.sessionId);\n return turn === undefined || turn > end.occurredAt ? undefined : end.occurredAt - turn;\n };\n\n const push = (\n event: CanonicalEvent,\n instrument: MetricInstrumentName,\n value: number,\n attributes: Record<string, string | number | boolean>,\n ): void => {\n if (!Number.isFinite(value) || value < 0) {\n return;\n }\n observations.push({\n instrument,\n value,\n attributes: { ...commonAttributes(event, input.resource, includeSessionId), ...attributes },\n timeMillis: event.occurredAt,\n sessionId: event.sessionId,\n });\n };\n\n for (const event of input.events) {\n switch (event.type) {\n case \"session.start\":\n push(event, METRIC_SESSIONS, 1, { [ATTR_OTELHOOK_SESSION_KIND]: event.sessionKind });\n break;\n case \"tool.end\":\n push(event, METRIC_TOOL_CALLS, 1, {\n [ATTR_GEN_AI_TOOL_NAME]: event.toolName,\n [ATTR_OTELHOOK_OUTCOME]: event.outcome,\n });\n break;\n case \"generation.end\": {\n const attributes = generationAttributes(event, requestModelOf(event.generationId));\n const durationMillis = measuredDurationOf(event);\n if (durationMillis !== undefined && durationMillis >= 0) {\n push(event, METRIC_OPERATION_DURATION, durationMillis / 1000, {\n ...attributes,\n ...(isFailedOutcome(event.outcome) ? { [ATTR_ERROR_TYPE]: event.outcome } : {}),\n });\n }\n if (\n event.cost !== undefined &&\n event.cost.source === \"provider-reported\" &&\n event.cost.currency === \"USD\"\n ) {\n push(event, METRIC_COST_USAGE, event.cost.amount, attributes);\n }\n break;\n }\n default:\n break;\n }\n }\n\n for (const observation of input.usage) {\n if (observation.scope !== \"generation\") {\n // Session totals and subagent rollups restate generation spend; counting them\n // too would double it.\n continue;\n }\n const event = byId.get(observation.eventId);\n if (event?.type !== \"generation.end\") {\n continue;\n }\n const attributes = generationAttributes(event, requestModelOf(event.generationId));\n for (const [tokenType, read] of TOKEN_FIELDS) {\n const value = read(observation.delta);\n if (value === 0 && (tokenType === \"cache_read\" || tokenType === \"cache_creation\")) {\n continue;\n }\n push(event, METRIC_TOKEN_USAGE, value, { ...attributes, [ATTR_GEN_AI_TOKEN_TYPE]: tokenType });\n }\n }\n return observations;\n};\n\n/** Accumulated histogram state for one series. */\nexport type HistogramState = {\n readonly count: number;\n readonly sum: number;\n readonly min: number;\n readonly max: number;\n /** One more entry than the instrument's boundaries. */\n readonly bucketCounts: readonly number[];\n};\n\n/**\n * One OTLP data point, as plain JSON so it can be spooled.\n *\n * A point is self-describing: the instrument, its temporality, and its interval.\n * A cumulative point is a snapshot of a running total, so resending one (from a\n * spool) restates a value rather than adding to it.\n */\nexport type MetricPoint = {\n readonly instrument: MetricInstrumentName;\n readonly temporality: MetricsTemporality;\n readonly attributes: Readonly<Record<string, string | number | boolean>>;\n readonly startTimeMillis: number;\n readonly timeMillis: number;\n /** Counters. */\n readonly value?: number;\n /** Histograms. */\n readonly histogram?: HistogramState;\n};\n\nexport const emptyHistogram = (boundaries: readonly number[]): HistogramState => ({\n count: 0,\n sum: 0,\n min: Number.POSITIVE_INFINITY,\n max: Number.NEGATIVE_INFINITY,\n bucketCounts: new Array<number>(boundaries.length + 1).fill(0),\n});\n\n/** OTLP explicit buckets: bucket `i` holds values in `(boundaries[i-1], boundaries[i]]`. */\nexport const bucketIndex = (boundaries: readonly number[], value: number): number => {\n for (let index = 0; index < boundaries.length; index += 1) {\n const bound = boundaries[index];\n if (bound !== undefined && value <= bound) {\n return index;\n }\n }\n return boundaries.length;\n};\n\nexport const recordIntoHistogram = (\n state: HistogramState,\n boundaries: readonly number[],\n value: number,\n): HistogramState => {\n const bucketCounts = [...state.bucketCounts];\n const index = bucketIndex(boundaries, value);\n bucketCounts[index] = (bucketCounts[index] ?? 0) + 1;\n return {\n count: state.count + 1,\n sum: state.sum + value,\n min: Math.min(state.min, value),\n max: Math.max(state.max, value),\n bucketCounts,\n };\n};\n\n/**\n * Stable identity of a series: instrument plus sorted attributes.\n *\n * Used as a map key and, digested, as a state key. JSON of sorted entries is\n * unambiguous where a joined string would not be.\n */\nexport const seriesIdentity = (\n instrument: MetricInstrumentName,\n attributes: Readonly<Record<string, string | number | boolean>>,\n): string =>\n JSON.stringify([\n instrument,\n Object.entries(attributes).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),\n ]);\n\n/**\n * Delta points for one batch: observations of the same series folded together,\n * over the interval from the earliest observation to `nowMillis`.\n */\nexport const aggregateDeltaPoints = (\n observations: readonly MetricObservation[],\n nowMillis: number,\n): readonly MetricPoint[] => {\n const series = new Map<\n string,\n { observation: MetricObservation; start: number; value: number; histogram?: HistogramState }\n >();\n for (const observation of observations) {\n const instrument = METRIC_INSTRUMENTS[observation.instrument];\n const key = seriesIdentity(observation.instrument, observation.attributes);\n const existing =\n series.get(key) ??\n ({\n observation,\n start: observation.timeMillis,\n value: 0,\n ...(instrument.boundaries === undefined ? {} : { histogram: emptyHistogram(instrument.boundaries) }),\n });\n existing.start = Math.min(existing.start, observation.timeMillis);\n if (existing.histogram !== undefined && instrument.boundaries !== undefined) {\n existing.histogram = recordIntoHistogram(existing.histogram, instrument.boundaries, observation.value);\n } else {\n existing.value += observation.value;\n }\n series.set(key, existing);\n }\n return [...series.values()].map((entry) => ({\n instrument: entry.observation.instrument,\n temporality: \"delta\",\n attributes: entry.observation.attributes,\n startTimeMillis: Math.min(entry.start, nowMillis),\n timeMillis: Math.max(nowMillis, entry.start),\n ...(entry.histogram === undefined ? { value: entry.value } : { histogram: entry.histogram }),\n }));\n};\n\n/** Data-point attribute keys that must never appear on a metric. */\nexport const FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES: readonly string[] = Object.freeze([\n \"user.\",\n \"enduser.\",\n \"organization.\",\n]);\n\n/** Strip anything account-shaped from attributes, as a last line of defence. */\nexport const withoutAccountIdentity = (attributes: Attributes): Attributes =>\n Object.fromEntries(\n Object.entries(attributes).filter(\n ([key]) => !FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES.some((prefix) => key.startsWith(prefix)),\n ),\n );\n","import type { Attributes } from \"@opentelemetry/api\";\n\nimport type { Clock, Logger } from \"../runtime/ports.js\";\nimport type { StoreNamespace } from \"../state/keys.js\";\nimport { isMetricInstrumentName, METRIC_INSTRUMENTS, type MetricPoint } from \"./metric-model.js\";\nimport {\n createSpoolQueue,\n type SpoolDrainResult,\n type SpoolEnqueueResult,\n type SpoolOverflowPolicy,\n type SpoolSendOutcome,\n type SpoolStats,\n type SpoolValidation,\n} from \"./spool-queue.js\";\n\n/**\n * A batch of metric points a destination could not take, kept for the next\n * invocation.\n *\n * Points are plain JSON (`MetricPoint`), so a batch replays without the process\n * that recorded it. A cumulative point is a snapshot of a running total: replaying\n * an old one after a newer one was delivered restates an earlier value with an\n * earlier timestamp, which a receiver orders by time rather than adding.\n */\nexport type MetricSpoolBatch = {\n readonly providerId: string;\n readonly installationId: string;\n readonly resourceAttributes: Attributes;\n readonly instrumentationScope: { readonly name: string; readonly version?: string };\n readonly points: readonly MetricPoint[];\n readonly enqueuedAt: number;\n};\n\nexport const MAX_SPOOLED_METRIC_POINTS_PER_BATCH = 4_096;\nconst MAX_STRING_LENGTH = 8_192;\nconst MAX_ATTRIBUTES_PER_POINT = 64;\nconst MAX_BUCKETS = 64;\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isFiniteNonNegative = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n\nconst isBoundedString = (value: unknown): value is string =>\n typeof value === \"string\" && value.length > 0 && value.length <= MAX_STRING_LENGTH;\n\nconst isPrimitiveAttribute = (value: unknown): boolean =>\n (typeof value === \"string\" && value.length <= MAX_STRING_LENGTH) ||\n (typeof value === \"number\" && Number.isFinite(value)) ||\n typeof value === \"boolean\";\n\n/**\n * Whether one spooled point can be replayed. A spool file is untrusted input, and\n * a malformed point would otherwise fail inside the OTLP encoder, where it reads\n * as an unreachable collector and wedges the queue head.\n */\nconst isReplayablePoint = (value: unknown): value is MetricPoint => {\n if (!isPlainObject(value) || !isMetricInstrumentName(value.instrument)) {\n return false;\n }\n if (value.temporality !== \"cumulative\" && value.temporality !== \"delta\") {\n return false;\n }\n if (!isFiniteNonNegative(value.startTimeMillis) || !isFiniteNonNegative(value.timeMillis)) {\n return false;\n }\n if (!isPlainObject(value.attributes)) {\n return false;\n }\n const entries = Object.entries(value.attributes);\n if (entries.length > MAX_ATTRIBUTES_PER_POINT || !entries.every(([, item]) => isPrimitiveAttribute(item))) {\n return false;\n }\n const instrument = METRIC_INSTRUMENTS[value.instrument];\n if (instrument.kind === \"counter\") {\n return isFiniteNonNegative(value.value) && value.histogram === undefined;\n }\n const histogram = value.histogram;\n if (!isPlainObject(histogram) || value.value !== undefined) {\n return false;\n }\n const buckets = histogram.bucketCounts;\n return (\n isFiniteNonNegative(histogram.count) &&\n Number.isInteger(histogram.count) &&\n isFiniteNonNegative(histogram.sum) &&\n typeof histogram.min === \"number\" &&\n typeof histogram.max === \"number\" &&\n Array.isArray(buckets) &&\n buckets.length <= MAX_BUCKETS &&\n buckets.length === (instrument.boundaries?.length ?? 0) + 1 &&\n buckets.every((count) => isFiniteNonNegative(count) && Number.isInteger(count))\n );\n};\n\nexport const validateMetricSpoolBatch = (\n value: unknown,\n identity: StoreNamespace,\n): SpoolValidation<MetricSpoolBatch> => {\n if (!isPlainObject(value)) {\n return { rejection: \"not-an-object\" };\n }\n if (value.providerId !== identity.providerId || value.installationId !== identity.installationId) {\n return { rejection: \"identity-mismatch\" };\n }\n if (!isPlainObject(value.resourceAttributes)) {\n return { rejection: \"resource-attributes-invalid\" };\n }\n if (!isPlainObject(value.instrumentationScope) || !isBoundedString(value.instrumentationScope.name)) {\n return { rejection: \"instrumentation-scope-invalid\" };\n }\n if (\n value.instrumentationScope.version !== undefined &&\n typeof value.instrumentationScope.version !== \"string\"\n ) {\n return { rejection: \"instrumentation-scope-invalid\" };\n }\n if (\n !Array.isArray(value.points) ||\n value.points.length === 0 ||\n value.points.length > MAX_SPOOLED_METRIC_POINTS_PER_BATCH\n ) {\n return { rejection: \"points-invalid\" };\n }\n if (!value.points.every(isReplayablePoint)) {\n return { rejection: \"point-field-invalid\" };\n }\n if (!isFiniteNonNegative(value.enqueuedAt)) {\n return { rejection: \"not-an-object\" };\n }\n return { batch: value as unknown as MetricSpoolBatch };\n};\n\nexport interface DurableMetricSpool {\n enqueue(batch: MetricSpoolBatch): Promise<SpoolEnqueueResult>;\n drain(\n send: (batch: MetricSpoolBatch) => Promise<SpoolSendOutcome>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\n stats?(): Promise<SpoolStats>;\n}\n\nexport type DurableMetricSpoolOptions = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n readonly maxSpoolFiles?: number;\n /** Queue directory below the identity namespace. Default `spool-metrics`. */\n readonly queueName?: string;\n readonly maxBytes?: number;\n readonly maxAgeMillis?: number;\n readonly overflow?: SpoolOverflowPolicy;\n};\n\nexport const DEFAULT_MAX_METRIC_SPOOL_FILES = 500;\n\n/** Durable queue for metric batches, in its own directory beside the trace and log spools. */\nexport const createFileDurableMetricSpool = (options: DurableMetricSpoolOptions): DurableMetricSpool =>\n createSpoolQueue<MetricSpoolBatch>({\n rootDir: options.rootDir,\n providerId: options.providerId,\n installationId: options.installationId,\n clock: options.clock,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_METRIC_SPOOL_FILES,\n queueName: options.queueName ?? \"spool-metrics\",\n ...(options.maxBytes === undefined ? {} : { maxBytes: options.maxBytes }),\n ...(options.maxAgeMillis === undefined ? {} : { maxAgeMillis: options.maxAgeMillis }),\n ...(options.overflow === undefined ? {} : { overflow: options.overflow }),\n validate: validateMetricSpoolBatch,\n });\n","import { ValueType } from \"@opentelemetry/api\";\nimport { ExportResultCode, millisToHrTime, type ExportResult, type InstrumentationScope } from \"@opentelemetry/core\";\nimport { OTLPMetricExporter } from \"@opentelemetry/exporter-metrics-otlp-proto\";\nimport { resourceFromAttributes, type Resource } from \"@opentelemetry/resources\";\nimport {\n AggregationTemporality,\n DataPointType,\n type MetricData,\n type ResourceMetrics,\n} from \"@opentelemetry/sdk-metrics\";\n\nimport { siblingSignalEndpoint } from \"../config/otlp-endpoint.js\";\nimport type { ExporterPolicy } from \"../config/schema.js\";\nimport { createHealthTracker, type DeliveryHealthSnapshot } from \"../diagnostics/health.js\";\nimport { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { Clock, Logger } from \"../runtime/ports.js\";\nimport type { DurableMetricSpool, MetricSpoolBatch } from \"./durable-metric-spool.js\";\nimport { isPermanentExportFailure } from \"./export-failure.js\";\nimport { replayResource, resourceFromExporterPolicy, resourceWithContext } from \"./exporter-resource.js\";\nimport { METRIC_INSTRUMENTS, withoutAccountIdentity, type MetricPoint } from \"./metric-model.js\";\nimport { DEFAULT_INSTRUMENTATION_SCOPE } from \"./semconv.js\";\nimport type { SpoolSendOutcome } from \"./spool-queue.js\";\n\n/**\n * OTLP HTTP/protobuf sink for hook-derived metrics (issue #69).\n *\n * Unlike the trace and log sinks, it does not take canonical events: the points it\n * sends are already aggregated (see `metric-model.ts` and\n * `lifecycle/metric-series.ts`), because cumulative aggregation needs state the\n * telemetry layer must not own. This module only encodes, sends, spools what a\n * destination could not take, and replays the spool on flush.\n *\n * There is deliberately no `MeterProvider` and no periodic reader. A hook process\n * lives for one callback; a reader that collects on an interval would either never\n * fire or hold the process open. Points are exported once, right after the\n * callback's telemetry, inside the same bounded flush window.\n *\n * Fails open like the other sinks: every failure is a diagnostic, never a throw.\n */\n\nexport type MetricsEndpointResolution =\n | { readonly endpoint: string; readonly derived: boolean }\n | { readonly unresolvable: \"no-endpoint\" };\n\n/**\n * Where metric points are posted: `metrics.endpoint` as stated, else the traces\n * endpoint with `/v1/traces` swapped for `/v1/metrics` (or `/v1/metrics` appended\n * to a base URL).\n */\nexport const resolveMetricsEndpoint = (exporter: ExporterPolicy): MetricsEndpointResolution => {\n const stated = exporter.metrics?.endpoint;\n if (stated !== undefined) {\n return { endpoint: stated, derived: false };\n }\n if (exporter.endpoint === undefined) {\n return { unresolvable: \"no-endpoint\" };\n }\n return { endpoint: siblingSignalEndpoint(exporter.endpoint, \"metrics\"), derived: true };\n};\n\nexport type MetricsDeliverability =\n | { readonly status: \"configured\"; readonly endpoint: string; readonly derivedEndpoint: boolean }\n | {\n readonly status: \"disabled\";\n readonly reason:\n | \"metrics-disabled\"\n | \"exporter-disabled\"\n | \"protocol-none\"\n | \"protocol-unsupported\"\n | \"no-endpoint\";\n };\n\nexport const describeMetricsDeliverability = (exporter: ExporterPolicy): MetricsDeliverability => {\n if (exporter.metrics?.enabled !== true) {\n return { status: \"disabled\", reason: \"metrics-disabled\" };\n }\n if (!exporter.enabled) {\n return { status: \"disabled\", reason: \"exporter-disabled\" };\n }\n if (exporter.protocol === \"none\") {\n return { status: \"disabled\", reason: \"protocol-none\" };\n }\n if (exporter.protocol !== \"http/protobuf\") {\n return { status: \"disabled\", reason: \"protocol-unsupported\" };\n }\n const resolved = resolveMetricsEndpoint(exporter);\n if (\"unresolvable\" in resolved) {\n return { status: \"disabled\", reason: \"no-endpoint\" };\n }\n return { status: \"configured\", endpoint: resolved.endpoint, derivedEndpoint: resolved.derived };\n};\n\nconst DISABLED_DETAIL: Readonly<\n Record<Exclude<Extract<MetricsDeliverability, { status: \"disabled\" }>[\"reason\"], \"metrics-disabled\">, string>\n> = Object.freeze({\n \"exporter-disabled\": \"otlp metric sink disabled: the exporter is disabled\",\n \"protocol-none\": \"otlp metric sink disabled: protocol is none\",\n \"protocol-unsupported\": \"otlp metric sink disabled: protocol not supported by this build\",\n \"no-endpoint\": \"otlp metric sink disabled: no metrics endpoint configured and none could be derived\",\n});\n\nexport type MetricExportResult = {\n /** Points delivered or spooled. */\n readonly accepted: number;\n readonly rejected: number;\n readonly errors: readonly OtelHookErrorInfo[];\n};\n\nexport interface OtlpMetricTelemetrySink {\n /** Whether this sink sends anything. A disabled sink accepts nothing and reports nothing. */\n readonly enabled: boolean;\n /**\n * `context`: the session context the points' events agree on (see\n * `agreedContextAttributes`). It overrides the same keys on the Resource for\n * this export, as the trace and log sinks do; the points carry it already.\n */\n exportPoints(\n points: readonly MetricPoint[],\n context?: Readonly<Record<string, string | number | boolean>>,\n ): Promise<MetricExportResult>;\n /** Replays spooled batches; bounded, best-effort, never throws. */\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n health(): DeliveryHealthSnapshot;\n drainSpool(\n maxBatches?: number,\n ): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }>;\n}\n\nexport type OtlpMetricSinkOptions = {\n readonly exporter: ExporterPolicy;\n readonly headers?: Readonly<Record<string, string>>;\n readonly providerId: string;\n readonly installationId: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n readonly spool?: DurableMetricSpool;\n readonly instrumentationScope?: InstrumentationScope;\n /** Export destination this sink delivers to. */\n readonly destination?: string;\n};\n\nconst createDisabledMetricSink = (destination?: string): OtlpMetricTelemetrySink => {\n const health = createHealthTracker(\n \"telemetry-metric-sink\",\n destination === undefined ? {} : { destination },\n );\n return {\n enabled: false,\n exportPoints: (): Promise<MetricExportResult> => Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),\n flush: (): Promise<void> => Promise.resolve(),\n shutdown: (): Promise<void> => Promise.resolve(),\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool: (): Promise<{\n readonly drained: number;\n readonly remaining: number;\n readonly failed: number;\n }> => Promise.resolve({ drained: 0, remaining: 0, failed: 0 }),\n };\n};\n\n/** A sink for a destination that does not take metrics, or a build with metrics off. */\nexport const createDisabledOtlpMetricSink = createDisabledMetricSink;\n\nconst toMetricData = (points: readonly MetricPoint[]): MetricData[] => {\n const byInstrument = new Map<string, MetricPoint[]>();\n for (const point of points) {\n const key = `${point.instrument}|${point.temporality}`;\n const group = byInstrument.get(key) ?? [];\n group.push(point);\n byInstrument.set(key, group);\n }\n const metrics: MetricData[] = [];\n for (const group of byInstrument.values()) {\n const first = group[0];\n if (first === undefined) {\n continue;\n }\n const instrument = METRIC_INSTRUMENTS[first.instrument];\n const descriptor = {\n name: instrument.name,\n description: instrument.description,\n unit: instrument.unit,\n valueType: instrument.valueType === \"int\" ? ValueType.INT : ValueType.DOUBLE,\n };\n const aggregationTemporality =\n first.temporality === \"cumulative\" ? AggregationTemporality.CUMULATIVE : AggregationTemporality.DELTA;\n const times = (point: MetricPoint): { startTime: [number, number]; endTime: [number, number] } => ({\n startTime: millisToHrTime(point.startTimeMillis),\n endTime: millisToHrTime(point.timeMillis),\n });\n if (instrument.kind === \"counter\") {\n metrics.push({\n descriptor,\n aggregationTemporality,\n dataPointType: DataPointType.SUM,\n isMonotonic: true,\n dataPoints: group.map((point) => ({\n ...times(point),\n attributes: { ...point.attributes },\n value: point.value ?? 0,\n })),\n });\n continue;\n }\n metrics.push({\n descriptor,\n aggregationTemporality,\n dataPointType: DataPointType.HISTOGRAM,\n dataPoints: group.map((point) => {\n const histogram = point.histogram;\n return {\n ...times(point),\n attributes: { ...point.attributes },\n value: {\n buckets: {\n boundaries: [...(instrument.boundaries ?? [])],\n counts: [...(histogram?.bucketCounts ?? [])],\n },\n count: histogram?.count ?? 0,\n sum: histogram?.sum ?? 0,\n ...(histogram === undefined || histogram.count === 0\n ? {}\n : { min: histogram.min, max: histogram.max }),\n },\n };\n }),\n });\n }\n return metrics;\n};\n\nexport const createOtlpMetricSink = (options: OtlpMetricSinkOptions): OtlpMetricTelemetrySink => {\n const destinationFields =\n options.destination === undefined ? {} : { \"export.destination\": options.destination };\n const deliverability = describeMetricsDeliverability(options.exporter);\n if (deliverability.status === \"disabled\") {\n if (deliverability.reason !== \"metrics-disabled\") {\n options.logger?.warn(DISABLED_DETAIL[deliverability.reason], {\n \"exporter.protocol\": options.exporter.protocol,\n ...destinationFields,\n });\n }\n return createDisabledMetricSink(options.destination);\n }\n\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n // No account identity on any metric, even if an operator put it on the resource.\n const resource = resourceFromAttributes(\n withoutAccountIdentity(resourceFromExporterPolicy(options.exporter).attributes),\n );\n const health = createHealthTracker(\n \"telemetry-metric-sink\",\n options.destination === undefined ? {} : { destination: options.destination },\n );\n const exporter = new OTLPMetricExporter({\n url: deliverability.endpoint,\n headers: { ...options.headers },\n timeoutMillis: options.exporter.timeoutMillis,\n });\n let shutdownCompleted = false;\n\n const exportResourceMetrics = (\n points: readonly MetricPoint[],\n batchResource: Resource,\n batchScope: InstrumentationScope,\n ): Promise<ExportResult> =>\n new Promise((resolve) => {\n const payload: ResourceMetrics = {\n resource: batchResource,\n scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }],\n };\n try {\n exporter.export(payload, (result: ExportResult) => resolve(result));\n } catch (thrown) {\n resolve({\n code: ExportResultCode.FAILED,\n error: thrown instanceof Error ? thrown : new Error(\"export threw\"),\n });\n }\n });\n\n const toSpoolBatch = (points: readonly MetricPoint[], batchResource: Resource): MetricSpoolBatch => ({\n providerId: options.providerId,\n installationId: options.installationId,\n resourceAttributes: { ...batchResource.attributes },\n instrumentationScope: {\n name: scope.name,\n ...(scope.version === undefined ? {} : { version: scope.version }),\n },\n points: points.map((point) => ({ ...point })),\n enqueuedAt: options.clock.now(),\n });\n\n const sendSerializedBatch = async (batch: MetricSpoolBatch): Promise<SpoolSendOutcome> => {\n const batchResource = resourceFromAttributes(\n withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes),\n );\n const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);\n if (result.code === ExportResultCode.SUCCESS) {\n return true;\n }\n return isPermanentExportFailure(result) ? \"discard\" : false;\n };\n\n const exportPoints = async (\n points: readonly MetricPoint[],\n context?: Readonly<Record<string, string | number | boolean>>,\n ): Promise<MetricExportResult> => {\n if (points.length === 0) {\n return { accepted: 0, rejected: 0, errors: [] };\n }\n const batchResource = context === undefined ? resource : resourceWithContext(resource, context);\n const result = await exportResourceMetrics(points, batchResource, scope);\n if (result.code === ExportResultCode.SUCCESS) {\n health.recordSuccess(points.length, options.clock.now());\n return { accepted: points.length, rejected: 0, errors: [] };\n }\n health.recordFailure(\"telemetry-export-failure\", points.length, options.clock.now());\n const permanent = isPermanentExportFailure(result);\n if (options.spool !== undefined && !permanent) {\n const spooled = await options.spool.enqueue(toSpoolBatch(points, batchResource)).catch(() => ({\n spooled: false as const,\n reason: \"capacity-exceeded\" as const,\n }));\n if (spooled.spooled) {\n options.logger?.warn(\"metric batch not delivered; spooled for the next invocation\", {\n \"export.batch_size\": points.length,\n ...destinationFields,\n });\n return { accepted: points.length, rejected: 0, errors: [] };\n }\n }\n return {\n accepted: 0,\n rejected: points.length,\n errors: [\n createErrorInfo({\n code: \"telemetry-export-failure\",\n phase: \"export\",\n detail: permanent\n ? \"collector refused a metric batch with a non-retryable status\"\n : \"collector rejected or was unreachable for a metric batch\",\n details: {\n \"export.batch_size\": points.length,\n \"export.signal\": \"metrics\",\n ...destinationFields,\n },\n }),\n ],\n };\n };\n\n const drainSpool = async (\n maxBatches?: number,\n ): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }> => {\n if (options.spool === undefined) {\n return { drained: 0, remaining: 0, failed: 0 };\n }\n const result = await options.spool.drain(sendSerializedBatch, {\n ...(maxBatches === undefined ? {} : { maxBatches }),\n });\n if (result.drained > 0) {\n health.recordSuccess(result.drained, options.clock.now());\n }\n return result;\n };\n\n const flush = async (): Promise<void> => {\n try {\n await exporter.forceFlush();\n } catch {\n // Best-effort; reported through health.\n }\n await drainSpool().catch(() => undefined);\n };\n\n const shutdown = async (): Promise<void> => {\n if (shutdownCompleted) {\n return;\n }\n shutdownCompleted = true;\n await flush();\n try {\n await exporter.shutdown();\n } catch {\n // Idempotent and non-throwing.\n }\n };\n\n return {\n enabled: true,\n exportPoints,\n flush,\n shutdown,\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool,\n };\n};\n","import {\n DEFAULT_DESTINATION_NAME,\n effectiveSpoolPolicy,\n hasConfiguredDestinations,\n resolveDestinationHeaders,\n resolveExportDestinations,\n type ExportDestination,\n} from \"../config/destinations.js\";\nimport { siblingSignalEndpoint } from \"../config/otlp-endpoint.js\";\nimport { effectiveMetricsPolicy, type ExporterPolicy } from \"../config/schema.js\";\nimport type { DeliveryHealthSnapshot } from \"../diagnostics/health.js\";\nimport { createHealthTracker } from \"../diagnostics/health.js\";\nimport { errorInfoFromThrown, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { Clock, Logger, TelemetryEmitResult } from \"../runtime/ports.js\";\nimport { createFileDurableLogSpool, type DurableLogSpool } from \"./durable-log-spool.js\";\nimport { createFileDurableMetricSpool, type DurableMetricSpool } from \"./durable-metric-spool.js\";\nimport { createFileDurableSpool, type DurableSpool } from \"./durable-spool.js\";\nimport type { LogContentPolicy } from \"./log-records.js\";\nimport {\n createOtlpLogSink,\n resolveLogsEndpoint,\n type OtlpLogTelemetrySink,\n} from \"./otlp-log-sink.js\";\nimport {\n createDisabledOtlpMetricSink,\n createOtlpMetricSink,\n type OtlpMetricTelemetrySink,\n} from \"./otlp-metric-sink.js\";\nimport { createOtlpTraceSink, type OtlpTelemetrySink } from \"./otlp-sink.js\";\nimport type { SpanCorrelationResolver } from \"./semconv.js\";\nimport { createSignalFanout, type SignalFanoutSink } from \"./signal-fanout.js\";\n\n/**\n * Spool queue directories for one destination, below the identity namespace.\n *\n * `default` keeps the directories it has always had, so batches an earlier\n * version queued are still drained after an upgrade. Every other destination\n * queues under `destinations/<name>/`, so one destination's outage can never\n * consume another's budget or be drained by another's sender.\n */\nexport const spoolQueueNamesFor = (\n destination: string,\n): { readonly traces: string; readonly logs: string; readonly metrics: string } =>\n destination === DEFAULT_DESTINATION_NAME\n ? { traces: \"spool\", logs: \"spool-logs\", metrics: \"spool-metrics\" }\n : {\n traces: `destinations/${destination}/spool`,\n logs: `destinations/${destination}/spool-logs`,\n metrics: `destinations/${destination}/spool-metrics`,\n };\n\n/**\n * The exporter policy one destination's sinks are built from.\n *\n * Everything but where and how to send — timeout, batch sizes, service identity,\n * resource attributes, log content policy — is shared, so every destination\n * receives the same spans. The `default` destination gets the policy unchanged.\n */\nexport const exporterPolicyForDestination = (\n exporter: ExporterPolicy,\n destination: ExportDestination,\n): ExporterPolicy => {\n if (destination.source === \"exporter\") {\n return exporter;\n }\n const { destinations, endpoint, logs, ...shared } = exporter;\n void destinations;\n void endpoint;\n const tracesEndpoint = destination.tracesEndpoint ?? destination.endpoint;\n // An explicit logs URL wins; otherwise derive from `endpoint` (not from a\n // traces-only override), and failing that let the sink derive from the traces URL.\n const derivedLogs =\n destination.logsEndpoint ??\n (destination.endpoint === undefined\n ? undefined\n : (() => {\n const derived = resolveLogsEndpoint({\n ...exporter,\n endpoint: destination.endpoint,\n logs: { enabled: true, includeContent: false, maxBatchSize: logs.maxBatchSize },\n });\n return \"endpoint\" in derived ? derived.endpoint : undefined;\n })());\n const { metrics: sharedMetrics, ...rest } = shared;\n // Like logs: an explicit metrics URL wins; otherwise derive from `endpoint`, and\n // failing that let the sink derive from the traces URL.\n const derivedMetrics =\n destination.metricsEndpoint ??\n (destination.endpoint === undefined\n ? undefined\n : siblingSignalEndpoint(destination.endpoint, \"metrics\"));\n return {\n ...rest,\n protocol: destination.protocol,\n ...(tracesEndpoint === undefined ? {} : { endpoint: tracesEndpoint }),\n headerNames: Object.keys(destination.headers).sort(),\n logs: {\n ...logs,\n enabled: destination.signals.logs,\n ...(derivedLogs === undefined ? {} : { endpoint: derivedLogs }),\n },\n metrics: {\n ...effectiveMetricsPolicy({ ...exporter, metrics: sharedMetrics }),\n enabled: destination.signals.metrics,\n ...(derivedMetrics === undefined ? {} : { endpoint: derivedMetrics }),\n },\n };\n};\n\n/** The pair of sinks, and their spools, serving one destination. */\nexport type ExportDestinationSinks = {\n readonly name: string;\n readonly traces: OtlpTelemetrySink;\n readonly logs: OtlpLogTelemetrySink;\n readonly spool?: DurableSpool;\n readonly logSpool?: DurableLogSpool;\n /** Hook-derived metrics; a disabled sink unless this destination takes `metrics`. */\n readonly metrics: OtlpMetricTelemetrySink;\n readonly metricSpool?: DurableMetricSpool;\n};\n\n/** A destination left out of this invocation, and why — by name only. */\nexport type SkippedExportDestination = {\n readonly name: string;\n readonly reason: \"header-variable-missing\";\n /** Environment variable *names*; never a value. */\n readonly missingVariables: readonly string[];\n};\n\nexport type ExportDestinationsOptions = {\n readonly exporter: ExporterPolicy;\n /**\n * Header values for the `default` destination's traces: `--header` over\n * `OTEL_EXPORTER_OTLP_TRACES_HEADERS` over `OTEL_EXPORTER_OTLP_HEADERS`, as\n * resolved by `resolveOtlpHeaders`.\n */\n readonly defaultHeaders?: Readonly<Record<string, string>>;\n /**\n * Header values for the `default` destination's logs, when they differ from\n * its traces' (`OTEL_EXPORTER_OTLP_LOGS_HEADERS`). Defaults to {@link defaultHeaders}.\n */\n readonly defaultLogHeaders?: Readonly<Record<string, string>>;\n /**\n * The environment `env:` header references resolve against. Never read\n * implicitly; without it, a destination whose headers reference a variable is\n * skipped and reported.\n */\n readonly headerEnvironment?: Readonly<Record<string, string | undefined>>;\n readonly providerId: string;\n readonly installationId: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Root of the spool trees. Absent, nothing is spooled. */\n readonly spoolRootDir?: string;\n /** Whether the logs signal gets a spool at all; it is only built when logs are on. */\n readonly logContent: LogContentPolicy;\n readonly correlate?: SpanCorrelationResolver;\n};\n\n/**\n * A trace sink for a destination that does not take the traces signal.\n *\n * Contributes zero accepted and zero rejected — unlike a *disabled exporter*,\n * which accepts everything — because the counts decide commit-or-retry and a\n * signal that never tried must not make a real loss elsewhere look delivered.\n */\nconst createOptedOutTraceSink = (destination: string | undefined): OtlpTelemetrySink => {\n const health = createHealthTracker(\n \"telemetry-sink\",\n destination === undefined ? {} : { destination },\n );\n return {\n emit: (): Promise<TelemetryEmitResult> =>\n Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),\n flush: (): Promise<void> => Promise.resolve(),\n shutdown: (): Promise<void> => Promise.resolve(),\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool: (): Promise<{\n readonly drained: number;\n readonly remaining: number;\n readonly failed: number;\n }> => Promise.resolve({ drained: 0, remaining: 0, failed: 0 }),\n };\n};\n\n/**\n * Build one sink pair per enabled destination.\n *\n * With no `exporter.destinations`, this is exactly the single `default`\n * destination the runtime has always built: the same policy, the same header\n * values, the same spool directories.\n */\nexport const createExportDestinationSinks = (\n options: ExportDestinationsOptions,\n): {\n readonly destinations: readonly ExportDestinationSinks[];\n readonly skipped: readonly SkippedExportDestination[];\n} => {\n const labelled = hasConfiguredDestinations(options.exporter);\n const spoolPolicy = effectiveSpoolPolicy(options.exporter);\n const destinations: ExportDestinationSinks[] = [];\n const skipped: SkippedExportDestination[] = [];\n\n for (const destination of resolveExportDestinations(options.exporter)) {\n let headers: Readonly<Record<string, string>> | undefined;\n let logHeaders: Readonly<Record<string, string>> | undefined;\n if (destination.source === \"exporter\") {\n headers = options.defaultHeaders;\n logHeaders = options.defaultLogHeaders ?? options.defaultHeaders;\n } else {\n const resolved = resolveDestinationHeaders(destination.headers, options.headerEnvironment);\n if (resolved.missingVariables.length > 0) {\n // Sending without the header would be refused at best, and at worst\n // accepted into somebody else's unauthenticated tenant. So the destination\n // sits this invocation out, and says which variable it is waiting for.\n options.logger?.warn(\"export destination skipped: a header references an unset environment variable\", {\n \"export.destination\": destination.name,\n \"config.variables\": [...resolved.missingVariables],\n });\n skipped.push({\n name: destination.name,\n reason: \"header-variable-missing\",\n missingVariables: resolved.missingVariables,\n });\n continue;\n }\n headers = resolved.values;\n logHeaders = resolved.values;\n }\n\n const label = labelled ? destination.name : undefined;\n const policy = exporterPolicyForDestination(options.exporter, destination);\n const queues = spoolQueueNamesFor(destination.name);\n const bounds = {\n maxSpoolFiles: spoolPolicy.maxBatches,\n maxBytes: spoolPolicy.maxBytes,\n maxAgeMillis: spoolPolicy.maxAgeMillis,\n overflow: \"drop-oldest\" as const,\n };\n const shared = {\n providerId: options.providerId,\n installationId: options.installationId,\n clock: options.clock,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n };\n const spool =\n options.spoolRootDir === undefined || !destination.signals.traces\n ? undefined\n : createFileDurableSpool({\n rootDir: options.spoolRootDir,\n ...shared,\n ...bounds,\n queueName: queues.traces,\n });\n // Only built when logs are on: a default installation must not create a\n // directory for a signal it never emits.\n const logSpool =\n options.spoolRootDir === undefined || !destination.signals.logs\n ? undefined\n : createFileDurableLogSpool({\n rootDir: options.spoolRootDir,\n ...shared,\n ...bounds,\n queueName: queues.logs,\n });\n\n const metricSpool =\n options.spoolRootDir === undefined || !destination.signals.metrics\n ? undefined\n : createFileDurableMetricSpool({\n rootDir: options.spoolRootDir,\n ...shared,\n ...bounds,\n queueName: queues.metrics,\n });\n\n const sinkShared = {\n exporter: policy,\n ...shared,\n ...(options.correlate === undefined ? {} : { correlate: options.correlate }),\n ...(label === undefined ? {} : { destination: label }),\n };\n const traces = destination.signals.traces\n ? createOtlpTraceSink({\n ...sinkShared,\n ...(headers === undefined || Object.keys(headers).length === 0 ? {} : { headers }),\n ...(spool === undefined ? {} : { spool }),\n })\n : createOptedOutTraceSink(label);\n const logs = createOtlpLogSink({\n ...sinkShared,\n ...(logHeaders === undefined || Object.keys(logHeaders).length === 0\n ? {}\n : { headers: logHeaders }),\n ...(logSpool === undefined ? {} : { spool: logSpool }),\n content: options.logContent,\n });\n const metrics = destination.signals.metrics\n ? createOtlpMetricSink({\n exporter: policy,\n ...shared,\n ...(label === undefined ? {} : { destination: label }),\n ...(headers === undefined || Object.keys(headers).length === 0 ? {} : { headers }),\n ...(metricSpool === undefined ? {} : { spool: metricSpool }),\n })\n : createDisabledOtlpMetricSink(label);\n destinations.push({\n name: destination.name,\n traces,\n logs,\n metrics,\n ...(spool === undefined ? {} : { spool }),\n ...(logSpool === undefined ? {} : { logSpool }),\n ...(metricSpool === undefined ? {} : { metricSpool }),\n });\n }\n return { destinations, skipped };\n};\n\n/**\n * One canonical batch, every destination, in parallel.\n *\n * Each destination is its own {@link createSignalFanout} (traces then logs, which\n * must stay sequential so they share one correlation resolution); destinations run\n * concurrently, each bounded by the exporter's own timeout, so a slow or dead\n * destination costs at most that timeout and never another destination's delivery.\n * A destination that throws is contained to a rejection of its own share.\n *\n * Counts are summed across destinations, which gives the durability decision the\n * right inputs: everything delivered or spooled → `delivered`; nothing → `lost`\n * and safe to retry; some → `partial`, terminal, because retrying would re-export\n * to the destinations that already accepted.\n *\n * With one destination this returns that destination's fanout unchanged.\n */\nexport const createDestinationFanout = (\n destinations: readonly ExportDestinationSinks[],\n): SignalFanoutSink => {\n const fanouts = destinations.map((destination) => ({\n name: destination.name,\n sink: createSignalFanout({ traces: destination.traces, logs: destination.logs }),\n }));\n const only = fanouts.length === 1 ? fanouts[0] : undefined;\n if (only !== undefined) {\n return only.sink;\n }\n\n const emit = async (events: readonly CanonicalEvent[]): Promise<TelemetryEmitResult> => {\n const results = await Promise.all(\n fanouts.map((fanout) =>\n fanout.sink.emit(events).catch(\n (thrown: unknown): TelemetryEmitResult => ({\n accepted: 0,\n rejected: events.length,\n errors: [errorInfoFromThrown(thrown, { code: \"telemetry-export-failure\", phase: \"export\" })],\n }),\n ),\n ),\n );\n const errors: OtelHookErrorInfo[] = results.flatMap((result) => result.errors);\n return {\n accepted: results.reduce((sum, result) => sum + result.accepted, 0),\n rejected: results.reduce((sum, result) => sum + result.rejected, 0),\n errors,\n };\n };\n\n const settleAll = async (run: (sink: SignalFanoutSink) => Promise<void>): Promise<void> => {\n await Promise.all(fanouts.map((fanout) => run(fanout.sink).catch(() => undefined)));\n };\n\n return {\n emit,\n // Each destination drains its own spool in its flush; in parallel, so one\n // unreachable destination's drain cannot use up the others' flush window.\n flush: () => settleAll((sink) => sink.flush()),\n shutdown: () => settleAll((sink) => sink.shutdown()),\n health: (): readonly DeliveryHealthSnapshot[] => fanouts.flatMap((fanout) => fanout.sink.health()),\n };\n};\n"],"mappings":";AAAA,SAAS,kBAAkB;AAE3B,SAAS,UAAU,gBAAgB,kBAAsE;AACzG,SAAS,sBAAsB;AAI/B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACdA,IAAM,UAAU;;;ACJvB,SAAS,uBAAuB;;;ACFhC,SAAS,KAAAA,UAAS;;;ACAlB,SAAS,SAAS;AAMX,IAAM,0BAA0B,EAAE,KAAK;AAAA;AAAA,EAE5C;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA,EACA;AAAA;AAAA,EAEA;AACF,CAAC;AAGM,IAAM,sBAAsB,EAAE,KAAK,CAAC,WAAW,OAAO,CAAC;AAIvD,IAAM,mBAAmB,EAAE,KAAK;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAWM,IAAM,uBAAuB,EAAE,KAAK,CAAC,aAAa,yBAAyB,CAAC;AAY5E,IAAM,iBACX,OAAO,OAAO;AAAA,EACZ,iBAAiB;AAAA,IACf,MAAM;AAAA,IACN,UAAU;AAAA,IACV,SAAS;AAAA,IACT,WAAW;AAAA,IACX,SAAS;AAAA,EACX;AAAA,EACA,4BAA4B;AAAA,IAC1B,MAAM;AAAA,IACN,UAAU;AAAA,I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,SAAS,QAAW;AACtB,WAAO,KAAK;AAAA,EACd;AAEA,QAAM,OAAO,OAAO,WAAoE;AACtF,UAAM,UAAU,MAAM,QAAQ;AAAA,MAC5B,QAAQ;AAAA,QAAI,CAAC,WACX,OAAO,KAAK,KAAK,MAAM,EAAE;AAAA,UACvB,CAAC,YAA0C;AAAA,YACzC,UAAU;AAAA,YACV,UAAU,OAAO;AAAA,YACjB,QAAQ,CAAC,oBAAoB,QAAQ,EAAE,MAAM,4BAA4B,OAAO,SAAS,CAAC,CAAC;AAAA,UAC7F;AAAA,QACF;AAAA,MACF;AAAA,IACF;AACA,UAAM,SAA8B,QAAQ,QAAQ,CAAC,WAAW,OAAO,MAAM;AAC7E,WAAO;AAAA,MACL,UAAU,QAAQ,OAAO,CAAC,KAAK,WAAW,MAAM,OAAO,UAAU,CAAC;AAAA,MAClE,UAAU,QAAQ,OAAO,CAAC,KAAK,WAAW,MAAM,OAAO,UAAU,CAAC;AAAA,MAClE;AAAA,IACF;AAAA,EACF;AAEA,QAAM,YAAY,OAAO,QAAkE;AACzF,UAAM,QAAQ,IAAI,QAAQ,IAAI,CAAC,WAAW,IAAI,OAAO,IAAI,EAAE,MAAM,MAAM,MAAS,CAAC,CAAC;AAAA,EACpF;AAEA,SAAO;AAAA,IACL;AAAA;AAAA;AAAA,IAGA,OAAO,MAAM,UAAU,CAAC,SAAS,KAAK,MAAM,CAAC;AAAA,IAC7C,UAAU,MAAM,UAAU,CAAC,SAAS,KAAK,SAAS,CAAC;AAAA,IACnD,QAAQ,MAAyC,QAAQ,QAAQ,CAAC,WAAW,OAAO,KAAK,OAAO,CAAC;AAAA,EACnG;AACF;","names":["z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","event","event","event","parent","createHash","z","z","z","z","z","event","TraceFlags","millisToHrTime","ATTR_ERROR_TYPE","ATTR_GEN_AI_OPERATION_NAME","ATTR_GEN_AI_REQUEST_MODEL","ATTR_GEN_AI_RESPONSE_MODEL","ATTR_GEN_AI_SYSTEM","ATTR_GEN_AI_TOOL_CALL_ID","ATTR_GEN_AI_TOOL_NAME","ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS","ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS","ATTR_GEN_AI_USAGE_INPUT_TOKENS","ATTR_GEN_AI_USAGE_OUTPUT_TOKENS","ATTR_OTELHOOK_OUTCOME","ATTR_OTELHOOK_TOOL_KIND","ATTR_OTELHOOK_DELEGATION_DEPTH","ATTR_OTELHOOK_AGENT_NAME","ATTR_OTELHOOK_AGENT_VERSION","ATTR_OTELHOOK_GENERATION_ID","ATTR_OTELHOOK_COMPACTION_TRIGGER","event","identityAttributes","ATTR_GEN_AI_REQUEST_MODEL","usageAttributes","ATTR_GEN_AI_OPERATION_NAME","ATTR_GEN_AI_SYSTEM","ATTR_GEN_AI_RESPONSE_MODEL","ATTR_GEN_AI_TOOL_NAME","ATTR_GEN_AI_TOOL_CALL_ID","ATTR_ERROR_TYPE","ATTR_GEN_AI_USAGE_INPUT_TOKENS","ATTR_GEN_AI_USAGE_OUTPUT_TOKENS","ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS","ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS","millisToHrTime","TraceFlags","TRACE_ID_PATTERN","SPAN_ID_PATTERN","isFiniteNonNegative","isBoundedString","isPlainObject","TraceFlags","ExportResultCode","millisToHrTime","TraceFlags","millisToHrTime","chunk","createDisabledSink","ExportResultCode","z","z","z","z","ATTR_GEN_AI_OPERATION_NAME","ATTR_GEN_AI_REQUEST_MODEL","ATTR_GEN_AI_RESPONSE_MODEL","ATTR_GEN_AI_TOOL_NAME","ATTR_ERROR_TYPE","ATTR_SESSION_ID","ATTR_OTELHOOK_PROVIDER_ID","ATTR_OTELHOOK_OUTCOME","ATTR_OTELHOOK_SESSION_KIND","event","isPlainObject","isFiniteNonNegative","isBoundedString","isPrimitiveAttribute","ExportResultCode","millisToHrTime","resourceFromAttributes","DISABLED_DETAIL","millisToHrTime","resourceFromAttributes","ExportResultCode"]}
|