@osfactory/otel-hook 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +28 -2
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +10 -1
- package/dist/index.js.map +1 -1
- package/dist/integration.js +1 -1
- package/dist/integration.js.map +1 -1
- package/dist/lifecycle.js +1 -1
- package/dist/lifecycle.js.map +1 -1
- package/dist/providers.js +9 -0
- package/dist/providers.js.map +1 -1
- package/dist/telemetry.js +1 -1
- package/dist/telemetry.js.map +1 -1
- package/dist/testing.js +9 -0
- package/dist/testing.js.map +1 -1
- package/package.json +1 -1
package/dist/telemetry.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/telemetry/semconv.ts","../node_modules/@opentelemetry/core/src/common/time.ts","../node_modules/@opentelemetry/core/src/ExportResult.ts","../src/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/model/primitives.ts","../src/errors/taxonomy.ts","../src/diagnostics/health.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/telemetry/signal-fanout.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 ATTR_SESSION_ID,\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\";\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_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\";\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\";\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\";\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 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 };\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 case \"tool.start\":\n return { [ATTR_OTELHOOK_TOOL_KIND]: event.toolKind };\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 = (event: CanonicalEvent): Attributes => ({\n [ATTR_SESSION_ID]: event.sessionId,\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});\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 ...(resetDetected ? { [ATTR_OTELHOOK_RESET_DETECTED]: true } : {}),\n };\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),\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 ...attributes,\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 ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...usageAttributes(end?.usage, false),\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 ...attributes,\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 };\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 let attributes: Attributes = { ...identityAttributes(event), [ATTR_OTELHOOK_SPAN_PAIRED]: true };\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 };\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 ...(parent === undefined\n ? {}\n : { parentSpanId: deriveSpanId(providerId, event.sessionId, parent) }),\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};\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 identities.set(event.eventId, {\n traceId: deriveTraceId(providerId, event.sessionId),\n spanId: deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId),\n });\n continue;\n }\n identities.set(event.eventId, { traceId: plan.traceId, spanId: plan.spanId });\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 * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type * as api from '@opentelemetry/api';\nimport { otperformance as performance } from '../platform';\n\nconst NANOSECOND_DIGITS = 9;\nconst NANOSECOND_DIGITS_IN_MILLIS = 6;\nconst MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);\nconst SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);\n\n/**\n * Converts a number of milliseconds from epoch to HrTime([seconds, remainder in nanoseconds]).\n * @param epochMillis\n */\nexport function millisToHrTime(epochMillis: number): api.HrTime {\n const epochSeconds = epochMillis / 1000;\n // Decimals only.\n const seconds = Math.trunc(epochSeconds);\n // Round sub-nanosecond accuracy to nanosecond.\n const nanos = Math.round((epochMillis % 1000) * MILLISECONDS_TO_NANOSECONDS);\n return [seconds, nanos];\n}\n\n/**\n * @deprecated Use `performance.timeOrigin` directly.\n */\nexport function getTimeOrigin(): number {\n return performance.timeOrigin;\n}\n\n/**\n * Returns an hrtime calculated via performance component.\n * @param performanceNow\n */\nexport function hrTime(performanceNow?: number): api.HrTime {\n const timeOrigin = millisToHrTime(performance.timeOrigin);\n const now = millisToHrTime(\n typeof performanceNow === 'number' ? performanceNow : performance.now()\n );\n\n return addHrTimes(timeOrigin, now);\n}\n\n/**\n *\n * Converts a TimeInput to an HrTime, defaults to _hrtime().\n * @param time\n */\nexport function timeInputToHrTime(time: api.TimeInput): api.HrTime {\n // process.hrtime\n if (isTimeInputHrTime(time)) {\n return time as api.HrTime;\n } else if (typeof time === 'number') {\n // Distinguish between a relative performance.now() value and an absolute\n // epoch-millisecond timestamp.\n //\n // performance.timeOrigin uses a monotonic clock that may be slightly ahead\n // of Date.now() due to clock adjustments (see MDN docs). This means a\n // real epoch-ms value (e.g. Date.now()) can land just below\n // performance.timeOrigin, causing it to be misclassified as a relative\n // performance.now() reading and doubled when timeOrigin is added.\n //\n // A genuine performance.now() value represents elapsed time since the\n // document/process started, so it is bounded by system uptime. No real\n // system has been running long enough for performance.now() to reach half\n // the current epoch time (~1994 in ms terms). We therefore treat any value\n // below half of performance.timeOrigin as a relative performance.now()\n // reading, and everything else as an absolute epoch-millisecond timestamp.\n if (time < performance.timeOrigin / 2) {\n return hrTime(time);\n } else {\n // epoch milliseconds or performance.timeOrigin\n return millisToHrTime(time);\n }\n } else if (time instanceof Date) {\n return millisToHrTime(time.getTime());\n } else {\n throw TypeError('Invalid input type');\n }\n}\n\n/**\n * Returns a duration of two hrTime.\n * @param startTime\n * @param endTime\n */\nexport function hrTimeDuration(\n startTime: api.HrTime,\n endTime: api.HrTime\n): api.HrTime {\n let seconds = endTime[0] - startTime[0];\n let nanos = endTime[1] - startTime[1];\n\n // overflow\n if (nanos < 0) {\n seconds -= 1;\n // negate\n nanos += SECOND_TO_NANOSECONDS;\n }\n\n return [seconds, nanos];\n}\n\n/**\n * Convert hrTime to timestamp, for example \"2019-05-14T17:00:00.000123456Z\"\n * @param time\n */\nexport function hrTimeToTimeStamp(time: api.HrTime): string {\n const precision = NANOSECOND_DIGITS;\n const tmp = `${'0'.repeat(precision)}${time[1]}Z`;\n const nanoString = tmp.substring(tmp.length - precision - 1);\n const date = new Date(time[0] * 1000).toISOString();\n return date.replace('000Z', nanoString);\n}\n\n/**\n * Convert hrTime to nanoseconds.\n * @param time\n */\nexport function hrTimeToNanoseconds(time: api.HrTime): number {\n return time[0] * SECOND_TO_NANOSECONDS + time[1];\n}\n\n/**\n * Convert hrTime to microseconds.\n * @param time\n */\nexport function hrTimeToMicroseconds(time: api.HrTime): number {\n return time[0] * 1e6 + time[1] / 1e3;\n}\n\n/**\n * Convert hrTime to milliseconds.\n * @param time\n */\nexport function hrTimeToMilliseconds(time: api.HrTime): number {\n return time[0] * 1e3 + time[1] / 1e6;\n}\n\n/**\n * Convert hrTime to seconds.\n * @param time\n */\nexport function hrTimeToSeconds(time: api.HrTime): number {\n return time[0] + time[1] / SECOND_TO_NANOSECONDS;\n}\n/**\n * check if time is HrTime\n * @param value\n */\nexport function isTimeInputHrTime(value: unknown): value is api.HrTime {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'number' &&\n typeof value[1] === 'number'\n );\n}\n\n/**\n * check if input value is a correct types.TimeInput\n * @param value\n */\nexport function isTimeInput(\n value: unknown\n): value is api.HrTime | number | Date {\n return (\n isTimeInputHrTime(value) ||\n typeof value === 'number' ||\n value instanceof Date\n );\n}\n\n/**\n * Given 2 HrTime formatted times, return their sum as an HrTime.\n */\nexport function addHrTimes(time1: api.HrTime, time2: api.HrTime): api.HrTime {\n const out = [time1[0] + time2[0], time1[1] + time2[1]] as api.HrTime;\n\n // Nanoseconds\n if (out[1] >= SECOND_TO_NANOSECONDS) {\n out[1] -= SECOND_TO_NANOSECONDS;\n out[0] += 1;\n }\n\n return out;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport interface ExportResult {\n code: ExportResultCode;\n error?: Error;\n}\n\nexport enum ExportResultCode {\n SUCCESS,\n FAILED,\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.1.2\";\n","import { randomBytes } from \"node:crypto\";\nimport { mkdir, readFile, readdir, rename, 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/** 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 /** Refuses new entries once this many are queued, rather than growing without bound. */\n readonly maxFiles: 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<boolean>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\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 const enqueue = async (batch: TBatch): Promise<SpoolEnqueueResult> => {\n await ensureDirs();\n const existing = await listSorted();\n if (existing.length >= options.maxFiles) {\n options.logger?.warn(\"durable spool at capacity; batch dropped\", {\n \"spool.max_files\": options.maxFiles,\n \"spool.queue\": options.queueName,\n });\n return { spooled: false, reason: \"capacity-exceeded\" };\n }\n const fileName = `${String(options.clock.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, JSON.stringify(batch), \"utf8\");\n await rename(tmp, target);\n return { spooled: true };\n };\n\n const drain = async (\n send: (batch: TBatch) => Promise<boolean>,\n drainOptions?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult> => {\n await ensureDirs();\n const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;\n const files = await listSorted();\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: boolean;\n try {\n delivered = await send(validation.batch);\n } catch {\n delivered = false;\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 };\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} 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\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<boolean>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\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: \"spool\",\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 { replayResource, resourceFromExporterPolicy } 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\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 = (): OtlpTelemetrySink => {\n const health = createHealthTracker(\"telemetry-sink\");\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 if (!options.exporter.enabled || options.exporter.protocol === \"none\") {\n return createDisabledSink();\n }\n if (options.exporter.endpoint === undefined) {\n options.logger?.warn(\"otlp sink disabled: no endpoint configured\", {});\n return createDisabledSink();\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 });\n return createDisabledSink();\n }\n\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const resource = resourceFromExporterPolicy(options.exporter);\n const health = createHealthTracker(\"telemetry-sink\");\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[]): SpoolBatch => ({\n providerId: options.providerId,\n installationId: options.installationId,\n resourceAttributes: { ...resource.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<boolean> => {\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 return result.code === ExportResultCode.SUCCESS;\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 const spans = canonicalEventsToReadableSpans(events, {\n resource,\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 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 if (options.spool !== undefined) {\n const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({\n spooled: false as const,\n reason: \"capacity-exceeded\" as const,\n }));\n if (spoolResult.spooled) {\n accepted += batch.length;\n continue;\n }\n }\n rejected += batch.length;\n errors.push(\n createErrorInfo({\n code: \"telemetry-export-failure\",\n phase: \"export\",\n detail: \"collector rejected or was unreachable for a span batch\",\n details: { \"export.batch_size\": batch.length },\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 { 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\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 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 | \"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\nexport type HealthTrackerOptions = {\n /** Consecutive failures at or beyond this count flip `healthy` to false. Default 3. */\n readonly unhealthyAfterConsecutiveFailures?: number;\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 }),\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 { 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 { 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","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 { TraceFlags, type SpanContext } from \"@opentelemetry/api\";\nimport { SeverityNumber, type LogAttributes } from \"@opentelemetry/api-logs\";\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_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n ATTR_SESSION_ID,\n} from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport type { ContentFact } from \"../model/content.js\";\nimport type { CanonicalEvent, CanonicalEventType } from \"../model/events.js\";\nimport {\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_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\";\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 = (event: CanonicalEvent): LogAttributes => ({\n [ATTR_SESSION_ID]: event.sessionId,\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});\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): LogAttributes => {\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 };\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 };\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 };\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 };\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 };\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 = (\n usage: { readonly inputTokens: number; readonly outputTokens: number } | undefined,\n): LogAttributes =>\n usage === undefined\n ? {}\n : {\n [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: usage.inputTokens,\n [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: usage.outputTokens,\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\nconst discloseBody = (fact: ContentFact, policy: LogContentPolicy): DisclosedBody => {\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): LogAttributes => ({\n [ATTR_CONTENT_KIND]: fact.kind,\n ...(fact.role === undefined ? {} : { [ATTR_CONTENT_ROLE]: fact.role }),\n [ATTR_CONTENT_DISCLOSURE]: 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 : { [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: LogAttributes;\n readonly body?: string;\n readonly spanContext: SpanContext;\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),\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: shared,\n spanContext,\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 ...(\"withheld\" in body ? {} : { body: body.text }),\n spanContext,\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} 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\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<boolean>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\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: \"spool-logs\",\n validate: validateLogSpoolBatch,\n });\n","import { TraceFlags, type AttributeValue, type Attributes, type SpanContext } from \"@opentelemetry/api\";\nimport type { LogAttributes } from \"@opentelemetry/api-logs\";\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 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 { replayResource, resourceFromExporterPolicy } 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\nconst OTLP_TRACES_PATH = \"/v1/traces\";\nconst OTLP_LOGS_PATH = \"/v1/logs\";\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 */\nconst 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 * 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 * `LogAttributes` admits nested maps and byte strings; 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: LogAttributes): 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};\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 = (): OtlpLogTelemetrySink => {\n const health = createHealthTracker(\"telemetry-log-sink\");\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 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 });\n }\n return createDisabledSink();\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(\"telemetry-log-sink\");\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[]): LogSpoolBatch => ({\n providerId: options.providerId,\n installationId: options.installationId,\n resourceAttributes: { ...resource.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<boolean> => {\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 return result.code === ExportResultCode.SUCCESS;\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 const mapped = canonicalEventsToLogRecords(events, {\n resource,\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 if (options.spool !== undefined) {\n const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({\n spooled: false as const,\n reason: \"capacity-exceeded\" as const,\n }));\n if (spoolResult.spooled) {\n accepted += batch.length;\n continue;\n }\n }\n rejected += batch.length;\n errors.push(\n createErrorInfo({\n code: \"telemetry-export-failure\",\n phase: \"export\",\n detail: \"collector rejected or was unreachable for a log record batch\",\n details: { \"export.batch_size\": batch.length, \"export.signal\": \"logs\" },\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","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"],"mappings":";AAAA,SAAS,kBAAkB;AAE3B,SAAS,UAAU,gBAAgB,kBAAsE;;;ACMzG,IAAM,oBAAoB;AAC1B,IAAM,8BAA8B;AACpC,IAAM,8BAA8B,KAAK,IAAI,IAAI,2BAA2B;AAC5E,IAAM,wBAAwB,KAAK,IAAI,IAAI,iBAAiB;AAMtD,SAAU,eAAe,aAAmB;AAChD,QAAM,eAAe,cAAc;AAEnC,QAAM,UAAU,KAAK,MAAM,YAAY;AAEvC,QAAM,QAAQ,KAAK,MAAO,cAAc,MAAQ,2BAA2B;AAC3E,SAAO,CAAC,SAAS,KAAK;AACxB;;;ACdA,IAAY;CAAZ,SAAYA,mBAAgB;AAC1B,EAAAA,kBAAAA,kBAAA,SAAA,IAAA,CAAA,IAAA;AACA,EAAAA,kBAAAA,kBAAA,QAAA,IAAA,CAAA,IAAA;AACF,GAHY,qBAAA,mBAAg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MAAM,EAAE,MAAM,MAAM,MAAS;AAClD,UAAM,QAAQ,KAAK,MAAM,EAAE,MAAM,MAAM,MAAS;AAAA,EAClD;AAEA,QAAM,WAAW,YAA2B;AAC1C,UAAM,QAAQ,OAAO,SAAS,EAAE,MAAM,MAAM,MAAS;AACrD,UAAM,QAAQ,KAAK,SAAS,EAAE,MAAM,MAAM,MAAS;AAAA,EACrD;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA,QAAQ,MAAyC;AAAA,MAC/C,QAAQ,OAAO,OAAO;AAAA,MACtB,QAAQ,KAAK,OAAO;AAAA,IACtB;AAAA,EACF;AACF;AAeO,IAAM,2BAA2B,CACtC,cAC4B;AAC5B,MAAI;AAMJ,SAAO,CAAC,WAAgD;AACtD,QAAI,SAAS,WAAW,QAAQ;AAC9B,aAAO,QAAQ;AAAA,IACjB;AACA,UAAM,SAAS,UAAU,MAAM;AAC/B,cAAU,EAAE,QAAQ,OAAO;AAC3B,WAAO;AAAA,EACT;AACF;","names":["ExportResultCode","createHash","z","z","z","z","z","z","TraceFlags","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_INPUT_TOKENS","ATTR_GEN_AI_USAGE_OUTPUT_TOKENS","ATTR_SESSION_ID","ATTR_OTELHOOK_INVOCATION_ID","ATTR_OTELHOOK_PROVIDER_ID","ATTR_OTELHOOK_PROVIDER_VERSION","ATTR_OTELHOOK_WORKSPACE_ID","ATTR_OTELHOOK_OUTCOME","ATTR_OTELHOOK_TOOL_KIND","ATTR_OTELHOOK_DELEGATION_DEPTH","ATTR_OTELHOOK_AGENT_NAME","ATTR_OTELHOOK_AGENT_VERSION","ATTR_OTELHOOK_COMPACTION_TRIGGER","identityAttributes","ATTR_SESSION_ID","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","hrTime","TraceFlags","TRACE_ID_PATTERN","SPAN_ID_PATTERN","isFiniteNonNegative","isBoundedString","isPlainObject","TraceFlags","TraceFlags","chunk","createDisabledSink"]}
|
|
1
|
+
{"version":3,"sources":["../src/telemetry/semconv.ts","../node_modules/@opentelemetry/core/src/common/time.ts","../node_modules/@opentelemetry/core/src/ExportResult.ts","../src/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/model/primitives.ts","../src/errors/taxonomy.ts","../src/diagnostics/health.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/telemetry/signal-fanout.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 ATTR_SESSION_ID,\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\";\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_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\";\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\";\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\";\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 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 };\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 case \"tool.start\":\n return { [ATTR_OTELHOOK_TOOL_KIND]: event.toolKind };\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 = (event: CanonicalEvent): Attributes => ({\n [ATTR_SESSION_ID]: event.sessionId,\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});\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 ...(resetDetected ? { [ATTR_OTELHOOK_RESET_DETECTED]: true } : {}),\n };\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),\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 ...attributes,\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 ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...usageAttributes(end?.usage, false),\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 ...attributes,\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 };\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 let attributes: Attributes = { ...identityAttributes(event), [ATTR_OTELHOOK_SPAN_PAIRED]: true };\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 };\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 ...(parent === undefined\n ? {}\n : { parentSpanId: deriveSpanId(providerId, event.sessionId, parent) }),\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};\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 identities.set(event.eventId, {\n traceId: deriveTraceId(providerId, event.sessionId),\n spanId: deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId),\n });\n continue;\n }\n identities.set(event.eventId, { traceId: plan.traceId, spanId: plan.spanId });\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 * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type * as api from '@opentelemetry/api';\nimport { otperformance as performance } from '../platform';\n\nconst NANOSECOND_DIGITS = 9;\nconst NANOSECOND_DIGITS_IN_MILLIS = 6;\nconst MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);\nconst SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);\n\n/**\n * Converts a number of milliseconds from epoch to HrTime([seconds, remainder in nanoseconds]).\n * @param epochMillis\n */\nexport function millisToHrTime(epochMillis: number): api.HrTime {\n const epochSeconds = epochMillis / 1000;\n // Decimals only.\n const seconds = Math.trunc(epochSeconds);\n // Round sub-nanosecond accuracy to nanosecond.\n const nanos = Math.round((epochMillis % 1000) * MILLISECONDS_TO_NANOSECONDS);\n return [seconds, nanos];\n}\n\n/**\n * @deprecated Use `performance.timeOrigin` directly.\n */\nexport function getTimeOrigin(): number {\n return performance.timeOrigin;\n}\n\n/**\n * Returns an hrtime calculated via performance component.\n * @param performanceNow\n */\nexport function hrTime(performanceNow?: number): api.HrTime {\n const timeOrigin = millisToHrTime(performance.timeOrigin);\n const now = millisToHrTime(\n typeof performanceNow === 'number' ? performanceNow : performance.now()\n );\n\n return addHrTimes(timeOrigin, now);\n}\n\n/**\n *\n * Converts a TimeInput to an HrTime, defaults to _hrtime().\n * @param time\n */\nexport function timeInputToHrTime(time: api.TimeInput): api.HrTime {\n // process.hrtime\n if (isTimeInputHrTime(time)) {\n return time as api.HrTime;\n } else if (typeof time === 'number') {\n // Distinguish between a relative performance.now() value and an absolute\n // epoch-millisecond timestamp.\n //\n // performance.timeOrigin uses a monotonic clock that may be slightly ahead\n // of Date.now() due to clock adjustments (see MDN docs). This means a\n // real epoch-ms value (e.g. Date.now()) can land just below\n // performance.timeOrigin, causing it to be misclassified as a relative\n // performance.now() reading and doubled when timeOrigin is added.\n //\n // A genuine performance.now() value represents elapsed time since the\n // document/process started, so it is bounded by system uptime. No real\n // system has been running long enough for performance.now() to reach half\n // the current epoch time (~1994 in ms terms). We therefore treat any value\n // below half of performance.timeOrigin as a relative performance.now()\n // reading, and everything else as an absolute epoch-millisecond timestamp.\n if (time < performance.timeOrigin / 2) {\n return hrTime(time);\n } else {\n // epoch milliseconds or performance.timeOrigin\n return millisToHrTime(time);\n }\n } else if (time instanceof Date) {\n return millisToHrTime(time.getTime());\n } else {\n throw TypeError('Invalid input type');\n }\n}\n\n/**\n * Returns a duration of two hrTime.\n * @param startTime\n * @param endTime\n */\nexport function hrTimeDuration(\n startTime: api.HrTime,\n endTime: api.HrTime\n): api.HrTime {\n let seconds = endTime[0] - startTime[0];\n let nanos = endTime[1] - startTime[1];\n\n // overflow\n if (nanos < 0) {\n seconds -= 1;\n // negate\n nanos += SECOND_TO_NANOSECONDS;\n }\n\n return [seconds, nanos];\n}\n\n/**\n * Convert hrTime to timestamp, for example \"2019-05-14T17:00:00.000123456Z\"\n * @param time\n */\nexport function hrTimeToTimeStamp(time: api.HrTime): string {\n const precision = NANOSECOND_DIGITS;\n const tmp = `${'0'.repeat(precision)}${time[1]}Z`;\n const nanoString = tmp.substring(tmp.length - precision - 1);\n const date = new Date(time[0] * 1000).toISOString();\n return date.replace('000Z', nanoString);\n}\n\n/**\n * Convert hrTime to nanoseconds.\n * @param time\n */\nexport function hrTimeToNanoseconds(time: api.HrTime): number {\n return time[0] * SECOND_TO_NANOSECONDS + time[1];\n}\n\n/**\n * Convert hrTime to microseconds.\n * @param time\n */\nexport function hrTimeToMicroseconds(time: api.HrTime): number {\n return time[0] * 1e6 + time[1] / 1e3;\n}\n\n/**\n * Convert hrTime to milliseconds.\n * @param time\n */\nexport function hrTimeToMilliseconds(time: api.HrTime): number {\n return time[0] * 1e3 + time[1] / 1e6;\n}\n\n/**\n * Convert hrTime to seconds.\n * @param time\n */\nexport function hrTimeToSeconds(time: api.HrTime): number {\n return time[0] + time[1] / SECOND_TO_NANOSECONDS;\n}\n/**\n * check if time is HrTime\n * @param value\n */\nexport function isTimeInputHrTime(value: unknown): value is api.HrTime {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'number' &&\n typeof value[1] === 'number'\n );\n}\n\n/**\n * check if input value is a correct types.TimeInput\n * @param value\n */\nexport function isTimeInput(\n value: unknown\n): value is api.HrTime | number | Date {\n return (\n isTimeInputHrTime(value) ||\n typeof value === 'number' ||\n value instanceof Date\n );\n}\n\n/**\n * Given 2 HrTime formatted times, return their sum as an HrTime.\n */\nexport function addHrTimes(time1: api.HrTime, time2: api.HrTime): api.HrTime {\n const out = [time1[0] + time2[0], time1[1] + time2[1]] as api.HrTime;\n\n // Nanoseconds\n if (out[1] >= SECOND_TO_NANOSECONDS) {\n out[1] -= SECOND_TO_NANOSECONDS;\n out[0] += 1;\n }\n\n return out;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport interface ExportResult {\n code: ExportResultCode;\n error?: Error;\n}\n\nexport enum ExportResultCode {\n SUCCESS,\n FAILED,\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.2.0\";\n","import { randomBytes } from \"node:crypto\";\nimport { mkdir, readFile, readdir, rename, 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/** 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 /** Refuses new entries once this many are queued, rather than growing without bound. */\n readonly maxFiles: 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<boolean>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\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 const enqueue = async (batch: TBatch): Promise<SpoolEnqueueResult> => {\n await ensureDirs();\n const existing = await listSorted();\n if (existing.length >= options.maxFiles) {\n options.logger?.warn(\"durable spool at capacity; batch dropped\", {\n \"spool.max_files\": options.maxFiles,\n \"spool.queue\": options.queueName,\n });\n return { spooled: false, reason: \"capacity-exceeded\" };\n }\n const fileName = `${String(options.clock.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, JSON.stringify(batch), \"utf8\");\n await rename(tmp, target);\n return { spooled: true };\n };\n\n const drain = async (\n send: (batch: TBatch) => Promise<boolean>,\n drainOptions?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult> => {\n await ensureDirs();\n const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;\n const files = await listSorted();\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: boolean;\n try {\n delivered = await send(validation.batch);\n } catch {\n delivered = false;\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 };\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} 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\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<boolean>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\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: \"spool\",\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 { replayResource, resourceFromExporterPolicy } 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\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 = (): OtlpTelemetrySink => {\n const health = createHealthTracker(\"telemetry-sink\");\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 if (!options.exporter.enabled || options.exporter.protocol === \"none\") {\n return createDisabledSink();\n }\n if (options.exporter.endpoint === undefined) {\n options.logger?.warn(\"otlp sink disabled: no endpoint configured\", {});\n return createDisabledSink();\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 });\n return createDisabledSink();\n }\n\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const resource = resourceFromExporterPolicy(options.exporter);\n const health = createHealthTracker(\"telemetry-sink\");\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[]): SpoolBatch => ({\n providerId: options.providerId,\n installationId: options.installationId,\n resourceAttributes: { ...resource.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<boolean> => {\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 return result.code === ExportResultCode.SUCCESS;\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 const spans = canonicalEventsToReadableSpans(events, {\n resource,\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 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 if (options.spool !== undefined) {\n const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({\n spooled: false as const,\n reason: \"capacity-exceeded\" as const,\n }));\n if (spoolResult.spooled) {\n accepted += batch.length;\n continue;\n }\n }\n rejected += batch.length;\n errors.push(\n createErrorInfo({\n code: \"telemetry-export-failure\",\n phase: \"export\",\n detail: \"collector rejected or was unreachable for a span batch\",\n details: { \"export.batch_size\": batch.length },\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 { 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\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 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 | \"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\nexport type HealthTrackerOptions = {\n /** Consecutive failures at or beyond this count flip `healthy` to false. Default 3. */\n readonly unhealthyAfterConsecutiveFailures?: number;\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 }),\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 { 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 { 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","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 { TraceFlags, type SpanContext } from \"@opentelemetry/api\";\nimport { SeverityNumber, type LogAttributes } from \"@opentelemetry/api-logs\";\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_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n ATTR_SESSION_ID,\n} from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport type { ContentFact } from \"../model/content.js\";\nimport type { CanonicalEvent, CanonicalEventType } from \"../model/events.js\";\nimport {\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_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\";\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 = (event: CanonicalEvent): LogAttributes => ({\n [ATTR_SESSION_ID]: event.sessionId,\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});\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): LogAttributes => {\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 };\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 };\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 };\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 };\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 };\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 = (\n usage: { readonly inputTokens: number; readonly outputTokens: number } | undefined,\n): LogAttributes =>\n usage === undefined\n ? {}\n : {\n [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: usage.inputTokens,\n [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: usage.outputTokens,\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\nconst discloseBody = (fact: ContentFact, policy: LogContentPolicy): DisclosedBody => {\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): LogAttributes => ({\n [ATTR_CONTENT_KIND]: fact.kind,\n ...(fact.role === undefined ? {} : { [ATTR_CONTENT_ROLE]: fact.role }),\n [ATTR_CONTENT_DISCLOSURE]: 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 : { [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: LogAttributes;\n readonly body?: string;\n readonly spanContext: SpanContext;\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),\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: shared,\n spanContext,\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 ...(\"withheld\" in body ? {} : { body: body.text }),\n spanContext,\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} 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\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<boolean>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\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: \"spool-logs\",\n validate: validateLogSpoolBatch,\n });\n","import { TraceFlags, type AttributeValue, type Attributes, type SpanContext } from \"@opentelemetry/api\";\nimport type { LogAttributes } from \"@opentelemetry/api-logs\";\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 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 { replayResource, resourceFromExporterPolicy } 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\nconst OTLP_TRACES_PATH = \"/v1/traces\";\nconst OTLP_LOGS_PATH = \"/v1/logs\";\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 */\nconst 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 * 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 * `LogAttributes` admits nested maps and byte strings; 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: LogAttributes): 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};\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 = (): OtlpLogTelemetrySink => {\n const health = createHealthTracker(\"telemetry-log-sink\");\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 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 });\n }\n return createDisabledSink();\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(\"telemetry-log-sink\");\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[]): LogSpoolBatch => ({\n providerId: options.providerId,\n installationId: options.installationId,\n resourceAttributes: { ...resource.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<boolean> => {\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 return result.code === ExportResultCode.SUCCESS;\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 const mapped = canonicalEventsToLogRecords(events, {\n resource,\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 if (options.spool !== undefined) {\n const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({\n spooled: false as const,\n reason: \"capacity-exceeded\" as const,\n }));\n if (spoolResult.spooled) {\n accepted += batch.length;\n continue;\n }\n }\n rejected += batch.length;\n errors.push(\n createErrorInfo({\n code: \"telemetry-export-failure\",\n phase: \"export\",\n detail: \"collector rejected or was unreachable for a log record batch\",\n details: { \"export.batch_size\": batch.length, \"export.signal\": \"logs\" },\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","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"],"mappings":";AAAA,SAAS,kBAAkB;AAE3B,SAAS,UAAU,gBAAgB,kBAAsE;;;ACMzG,IAAM,oBAAoB;AAC1B,IAAM,8BAA8B;AACpC,IAAM,8BAA8B,KAAK,IAAI,IAAI,2BAA2B;AAC5E,IAAM,wBAAwB,KAAK,IAAI,IAAI,iBAAiB;AAMtD,SAAU,eAAe,aAAmB;AAChD,QAAM,eAAe,cAAc;AAEnC,QAAM,UAAU,KAAK,MAAM,YAAY;AAEvC,QAAM,QAAQ,KAAK,MAAO,cAAc,MAAQ,2BAA2B;AAC3E,SAAO,CAAC,SAAS,KAAK;AACxB;;;ACdA,IAAY;CAAZ,SAAYA,mBAAgB;AAC1B,EAAAA,kBAAAA,kBAAA,SAAA,IAAA,CAAA,IAAA;AACA,EAAAA,kBAAAA,kBAAA,QAAA,IAAA,CAAA,IAAA;AACF,GAHY,qBAAA,mBAAgB,CAAA,EAAA;;;AFH5B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA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AAM,WAAW,YAA2B;AAC1C,UAAM,QAAQ,OAAO,SAAS,EAAE,MAAM,MAAM,MAAS;AACrD,UAAM,QAAQ,KAAK,SAAS,EAAE,MAAM,MAAM,MAAS;AAAA,EACrD;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA,QAAQ,MAAyC;AAAA,MAC/C,QAAQ,OAAO,OAAO;AAAA,MACtB,QAAQ,KAAK,OAAO;AAAA,IACtB;AAAA,EACF;AACF;AAeO,IAAM,2BAA2B,CACtC,cAC4B;AAC5B,MAAI;AAMJ,SAAO,CAAC,WAAgD;AACtD,QAAI,SAAS,WAAW,QAAQ;AAC9B,aAAO,QAAQ;AAAA,IACjB;AACA,UAAM,SAAS,UAAU,MAAM;AAC/B,cAAU,EAAE,QAAQ,OAAO;AAC3B,WAAO;AAAA,EACT;AACF;","names":["ExportResultCode","createHash","z","z","z","z","z","z","TraceFlags","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_INPUT_TOKENS","ATTR_GEN_AI_USAGE_OUTPUT_TOKENS","ATTR_SESSION_ID","ATTR_OTELHOOK_INVOCATION_ID","ATTR_OTELHOOK_PROVIDER_ID","ATTR_OTELHOOK_PROVIDER_VERSION","ATTR_OTELHOOK_WORKSPACE_ID","ATTR_OTELHOOK_OUTCOME","ATTR_OTELHOOK_TOOL_KIND","ATTR_OTELHOOK_DELEGATION_DEPTH","ATTR_OTELHOOK_AGENT_NAME","ATTR_OTELHOOK_AGENT_VERSION","ATTR_OTELHOOK_COMPACTION_TRIGGER","identityAttributes","ATTR_SESSION_ID","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","hrTime","TraceFlags","TRACE_ID_PATTERN","SPAN_ID_PATTERN","isFiniteNonNegative","isBoundedString","isPlainObject","TraceFlags","TraceFlags","chunk","createDisabledSink"]}
|