@osfactory/otel-hook 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/{adapter-DXpNtnaf.d.ts → adapter-BgqtlADe.d.ts} +10 -3
  2. package/dist/cli.js +1001 -487
  3. package/dist/cli.js.map +1 -1
  4. package/dist/{events-VxBnDFaO.d.ts → events-C3h3GvHj.d.ts} +58 -0
  5. package/dist/{filesystem-store-J8jjDMTh.d.ts → filesystem-store-BAq3VGVv.d.ts} +1 -1
  6. package/dist/{hook-_mlO3akA.d.ts → hook-CQiNa88Q.d.ts} +12 -4
  7. package/dist/index.d.ts +13 -12
  8. package/dist/index.js +1127 -599
  9. package/dist/index.js.map +1 -1
  10. package/dist/install.d.ts +5 -4
  11. package/dist/install.js +99 -68
  12. package/dist/install.js.map +1 -1
  13. package/dist/integration.d.ts +15 -8
  14. package/dist/integration.js +505 -121
  15. package/dist/integration.js.map +1 -1
  16. package/dist/lifecycle.d.ts +3 -3
  17. package/dist/lifecycle.js +23 -2
  18. package/dist/lifecycle.js.map +1 -1
  19. package/dist/{memory-DXVBc8V9.d.ts → memory-kflYgZbg.d.ts} +2 -2
  20. package/dist/model.d.ts +2 -1
  21. package/dist/model.js +79 -41
  22. package/dist/model.js.map +1 -1
  23. package/dist/{otlp-log-sink-DTSa0KRF.d.ts → otlp-log-sink-BZIgYPKN.d.ts} +3 -3
  24. package/dist/{payload-BWV5-4n3.d.ts → payload-DpyU8F-z.d.ts} +1 -1
  25. package/dist/{ports-Q8x0ODhs.d.ts → ports-B_iwJQPQ.d.ts} +20 -2
  26. package/dist/providers.d.ts +27 -9
  27. package/dist/providers.js +664 -452
  28. package/dist/providers.js.map +1 -1
  29. package/dist/{registry-Dqr3VNmT.d.ts → registry-BSBS8t7S.d.ts} +1 -1
  30. package/dist/runtime.d.ts +87 -11
  31. package/dist/runtime.js +379 -67
  32. package/dist/runtime.js.map +1 -1
  33. package/dist/{semconv-CIU-2kGO.d.ts → semconv-BeUPQ7_q.d.ts} +1 -1
  34. package/dist/state.d.ts +4 -4
  35. package/dist/state.js.map +1 -1
  36. package/dist/target-8RfaVxp8.d.ts +83 -0
  37. package/dist/telemetry.d.ts +6 -6
  38. package/dist/telemetry.js +86 -10
  39. package/dist/telemetry.js.map +1 -1
  40. package/dist/testing.d.ts +14 -7
  41. package/dist/testing.js +814 -492
  42. package/dist/testing.js.map +1 -1
  43. package/package.json +4 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/diagnostics/health.ts","../src/errors/index.ts","../src/model/primitives.ts","../src/errors/taxonomy.ts","../src/lifecycle/dedup.ts","../src/state/async-lock.ts","../src/state/store.ts","../src/lifecycle/keys.ts","../src/lifecycle/janitor.ts","../src/telemetry/semconv.ts","../node_modules/@opentelemetry/core/src/common/time.ts","../node_modules/@opentelemetry/core/src/ExportResult.ts","../src/version.ts","../src/telemetry/export-identity.ts","../src/lifecycle/span-correlator.ts","../src/model/usage.ts","../src/lifecycle/usage-accumulator.ts","../src/privacy/service.ts","../src/model/extensions.ts","../src/privacy/policy.ts","../src/runtime/clock.ts","../src/runtime/hook.ts","../src/config/schema.ts","../src/config/resource-attributes.ts","../src/model/content.ts","../src/model/identity.ts","../src/model/version.ts","../src/providers/adapter.ts","../src/model/events.ts","../src/providers/registry.ts","../src/runtime/delivery.ts","../src/runtime/ids.ts","../src/runtime/ports.ts","../src/runtime/logger.ts","../src/state/filesystem-store.ts","../src/state/keys.ts","../src/telemetry/spool-queue.ts","../src/telemetry/durable-log-spool.ts","../src/telemetry/durable-spool.ts","../src/telemetry/otlp-log-sink.ts","../src/telemetry/exporter-resource.ts","../src/telemetry/log-records.ts","../src/telemetry/otlp-sink.ts","../src/telemetry/signal-fanout.ts","../src/integration/hook-runtime.ts"],"sourcesContent":["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 { 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 { randomBytes } from \"node:crypto\";\n\nimport type { Attributes } from \"../model/primitives.js\";\nimport type { Clock, StateRecord, StateStore } from \"../runtime/ports.js\";\nimport { withOptionalSessionLock } from \"../state/store.js\";\nimport { dedupKey, dedupScanPrefix, dedupScopeOf } from \"./keys.js\";\n\nexport type DedupCheckResult = {\n /** True when `callbackId` was already marked seen for this scope. */\n readonly duplicate: boolean;\n};\n\nexport type DedupCleanupResult = {\n readonly removed: number;\n readonly scanned: number;\n /**\n * Aged-out records the sweep deliberately kept because they are uncommitted\n * claims younger than the stale-claim window — a live process may still be\n * working on them.\n *\n * Reported rather than merely not-removed, because the two are indistinguishable\n * in `removed` and only one of them means \"retention is configured shorter than\n * this installation's own export budget\". Absent when nothing was retained.\n */\n readonly retainedInFlight?: number;\n};\n\n/**\n * What happened when a delivery tried to take ownership of a callback id.\n *\n * - `fresh`: nothing had this id. The caller owns it and must `commit`.\n * - `duplicate`: a previous delivery ran this callback to completion.\n * - `in-flight`: another delivery holds the id right now — a concurrent process,\n * or one that has not committed yet. Treated as a duplicate.\n * - `reclaimed`: a claim was abandoned long enough ago to be assumed dead, and\n * this delivery has taken it over. The caller owns it and must `commit`.\n */\nexport type DeliveryClaimOutcome = \"fresh\" | \"duplicate\" | \"in-flight\" | \"reclaimed\";\n\nexport type DeliveryClaimResult = {\n readonly outcome: DeliveryClaimOutcome;\n /** True for `duplicate` and `in-flight`: the caller must not export or account. */\n readonly duplicate: boolean;\n /** True for `fresh` and `reclaimed`: the caller owns the id and should commit. */\n readonly owned: boolean;\n /** How many deliveries have claimed this id, including this one. */\n readonly attempt: number;\n /** Age of the claim that was taken over. Present only for `reclaimed`. */\n readonly abandonedForMillis?: number;\n /**\n * Opaque proof that *this* delivery owns the claim. Present when `owned`.\n *\n * No floor computation can be proven exact, so the stale window may still be too\n * short for some real installation. Passing this back to {@link\n * CallbackDeduplicator.commit} turns that from a silent double-count into a\n * detected, reported condition: if a peer reclaimed the id in the meantime the\n * record carries a different token, and the commit refuses rather than\n * overwriting the peer's in-flight work.\n */\n readonly owner?: string;\n};\n\n/** Whether a commit actually took effect. */\nexport type DeliveryCommitResult = {\n readonly status: \"committed\" | \"superseded\";\n /** The attempt number recorded, for diagnostics. */\n readonly attempt: number;\n};\n\nexport type DeliveryClaimOptions = {\n /**\n * How long an uncommitted claim is respected before it is assumed to belong to\n * a process that died mid-flight. Default 60,000ms.\n */\n readonly staleClaimMillis?: number;\n};\n\n/**\n * Delivery guard: suppresses a redelivered callback while local state is intact.\n *\n * Deliberately not described as \"exactly-once\". This records intent and completion\n * in a local store; the collector it protects is a separate system with no shared\n * transaction, so a process killed between an accepted export and `commit` leaves a\n * callback that will be exported again. What this guarantees is that a redelivery\n * seen by a *live* store is suppressed, and that a crash is recoverable rather than\n * either silently lost or permanently blocked.\n *\n * Coding-agent hosts redeliver callbacks — a retried hook invocation, a\n * duplicated event, a replayed transcript — and a deterministic identity makes\n * the replay recomputable, but something still has to remember which identities\n * have already been handled. This is that memory: a bounded, TTL-swept set of\n * seen ids per scope, independent of what the id actually names.\n *\n * Ownership is two-phase on purpose. `claim` records an intent before the caller\n * exports anything and `commit` records completion afterwards, so the window\n * where a crash could produce a double export does not exist: a second delivery\n * arriving in that window sees `in-flight` and stands down. The cost of that\n * choice is that a process killed between the two leaves an uncommitted claim,\n * which is why an old one is reclaimable rather than permanent — permanent would\n * turn every crash into silently lost telemetry.\n */\nexport interface CallbackDeduplicator {\n /**\n * Single-phase check: marks the id complete immediately and reports whether it\n * had been seen. Retained for callers that have nothing to protect between the\n * check and the side effect; `claim`/`commit` is the stronger guarantee.\n */\n checkAndMark(scope: string, callbackId: string): Promise<DedupCheckResult>;\n /** Take ownership of a callback id before acting on it. */\n claim(\n scope: string,\n callbackId: string,\n options?: DeliveryClaimOptions,\n ): Promise<DeliveryClaimResult>;\n /**\n * Record that a claimed callback ran to completion.\n *\n * `owner` is the token {@link DeliveryClaimResult.owner} handed out. Supplied and\n * matching, the claim completes. Supplied and *not* matching, the claim has been\n * reclaimed by a peer while this delivery was still working, and the commit is\n * refused — reported as `\"superseded\"` so the caller can say so instead of\n * silently marking a callback handled that somebody else is mid-flight on.\n */\n commit(scope: string, callbackId: string, owner?: string): Promise<DeliveryCommitResult>;\n /**\n * Give up a claim without completing it, so the next delivery of the same\n * callback is treated as fresh instead of waiting out the stale window.\n */\n release(scope: string, callbackId: string): Promise<void>;\n /**\n * Drop dedup records older than `maxAgeMillis`.\n *\n * An uncommitted claim is held back until it is also older than\n * `staleClaimMillis`, whatever the retention says. Retention is an operator's\n * answer to \"how long should a handled callback stay recognizable\"; the stale\n * window is a statement about how long one process's own work can take. Deleting\n * a claim inside that window would hand the callback to a concurrent delivery as\n * *fresh* while the holder is still exporting it — a retention setting silently\n * converting suppression into a double export, which is the opposite of what\n * tightening retention looks like it does.\n */\n cleanup(\n maxAgeMillis: number,\n options?: {\n readonly maxEntries?: number;\n readonly sessionId?: string;\n /** Floor on how long an uncommitted claim survives. Default 60,000ms. */\n readonly staleClaimMillis?: number;\n },\n ): Promise<DedupCleanupResult>;\n}\n\nexport type CallbackDeduplicatorDependencies = {\n readonly stateStore: StateStore;\n readonly clock: Clock;\n};\n\nconst DEFAULT_STALE_CLAIM_MILLIS = 60_000;\n\ntype DedupState = \"claimed\" | \"completed\";\n\n/**\n * Read the recorded state of a dedup record.\n *\n * A record written by an older release carries only `seenAt`, which meant\n * \"handled\". Absent a `state` field it is therefore read as `completed`, so an\n * upgrade never resurrects a callback the previous version had already exported.\n */\nconst stateOf = (record: StateRecord | undefined): DedupState | undefined => {\n if (record?.value.kind !== \"attributes\") {\n return undefined;\n }\n const declared = record.value.attributes.state;\n if (declared === \"claimed\" || declared === \"completed\") {\n return declared;\n }\n return \"completed\";\n};\n\nconst attemptOf = (record: StateRecord | undefined): number => {\n if (record?.value.kind !== \"attributes\") {\n return 0;\n }\n const attempt = record.value.attributes.attempt;\n return typeof attempt === \"number\" && Number.isInteger(attempt) && attempt > 0 ? attempt : 1;\n};\n\nconst ownerOf = (record: StateRecord | undefined): string | undefined => {\n if (record?.value.kind !== \"attributes\") {\n return undefined;\n }\n const owner = record.value.attributes.owner;\n return typeof owner === \"string\" && owner.length > 0 ? owner : undefined;\n};\n\nconst newOwnerToken = (): string => randomBytes(12).toString(\"hex\");\n\nconst claimedAtOf = (record: StateRecord | undefined): number | undefined => {\n if (record?.value.kind !== \"attributes\") {\n return undefined;\n }\n const claimedAt = record.value.attributes.claimedAt;\n return typeof claimedAt === \"number\" ? claimedAt : record.updatedAt;\n};\n\nexport const createCallbackDeduplicator = (\n deps: CallbackDeduplicatorDependencies,\n): CallbackDeduplicator => {\n const { stateStore, clock } = deps;\n\n const write = (key: string, attributes: Attributes): Promise<unknown> =>\n stateStore.write(key, { kind: \"attributes\", attributes });\n\n const checkAndMark = (scope: string, callbackId: string): Promise<DedupCheckResult> =>\n withOptionalSessionLock(stateStore, scope, async (): Promise<DedupCheckResult> => {\n const key = dedupKey(scope, callbackId);\n const existing = await stateStore.read(key);\n if (existing?.value.kind === \"attributes\") {\n return { duplicate: true };\n }\n const now = clock.now();\n await write(key, {\n state: \"completed\",\n attempt: 1,\n claimedAt: now,\n seenAt: now,\n owner: newOwnerToken(),\n });\n return { duplicate: false };\n });\n\n const claim = (\n scope: string,\n callbackId: string,\n options?: DeliveryClaimOptions,\n ): Promise<DeliveryClaimResult> =>\n withOptionalSessionLock(stateStore, scope, async (): Promise<DeliveryClaimResult> => {\n const staleClaimMillis = options?.staleClaimMillis ?? DEFAULT_STALE_CLAIM_MILLIS;\n const key = dedupKey(scope, callbackId);\n const existing = await stateStore.read(key);\n const state = stateOf(existing);\n const now = clock.now();\n\n if (state === \"completed\") {\n return { outcome: \"duplicate\", duplicate: true, owned: false, attempt: attemptOf(existing) };\n }\n\n if (state === \"claimed\") {\n const claimedAt = claimedAtOf(existing) ?? now;\n const age = now - claimedAt;\n if (age <= staleClaimMillis) {\n return {\n outcome: \"in-flight\",\n duplicate: true,\n owned: false,\n attempt: attemptOf(existing),\n };\n }\n const attempt = attemptOf(existing) + 1;\n const owner = newOwnerToken();\n await write(key, { state: \"claimed\", attempt, claimedAt: now, owner });\n return {\n outcome: \"reclaimed\",\n duplicate: false,\n owned: true,\n attempt,\n abandonedForMillis: age,\n owner,\n };\n }\n\n const owner = newOwnerToken();\n await write(key, { state: \"claimed\", attempt: 1, claimedAt: now, owner });\n return { outcome: \"fresh\", duplicate: false, owned: true, attempt: 1, owner };\n });\n\n const commit = (\n scope: string,\n callbackId: string,\n owner?: string,\n ): Promise<DeliveryCommitResult> =>\n withOptionalSessionLock(stateStore, scope, async (): Promise<DeliveryCommitResult> => {\n const key = dedupKey(scope, callbackId);\n const existing = await stateStore.read(key);\n const now = clock.now();\n const attempt = Math.max(attemptOf(existing), 1);\n\n const recordedOwner = ownerOf(existing);\n if (owner !== undefined && recordedOwner !== undefined && recordedOwner !== owner) {\n // A peer reclaimed this id while we were still working, which means the\n // stale window was shorter than this installation's real worst case.\n // Completing it now would tell that peer's delivery to stand down after it\n // has already exported. Refusing is the honest answer, and being able to\n // say so is the point of the token: no floor computation can be proven\n // exact, so the failure has to be detectable rather than merely unlikely.\n return { status: \"superseded\", attempt };\n }\n\n await write(key, {\n state: \"completed\",\n attempt,\n claimedAt: claimedAtOf(existing) ?? now,\n completedAt: now,\n seenAt: now,\n ...(recordedOwner === undefined ? {} : { owner: recordedOwner }),\n });\n return { status: \"committed\", attempt };\n });\n\n const release = (scope: string, callbackId: string): Promise<void> =>\n withOptionalSessionLock(stateStore, scope, async (): Promise<void> => {\n const key = dedupKey(scope, callbackId);\n // Only an uncommitted claim is droppable: releasing a completed record\n // would re-open a callback whose telemetry has already been exported.\n if (stateOf(await stateStore.read(key)) === \"claimed\") {\n await stateStore.delete(key);\n }\n });\n\n const cleanup = async (\n maxAgeMillis: number,\n options?: {\n readonly maxEntries?: number;\n readonly sessionId?: string;\n readonly staleClaimMillis?: number;\n },\n ): Promise<DedupCleanupResult> => {\n const keys = await stateStore.keys(dedupScanPrefix(options?.sessionId));\n const cap = options?.maxEntries ?? 1_000;\n const staleClaimMillis = options?.staleClaimMillis ?? DEFAULT_STALE_CLAIM_MILLIS;\n const now = clock.now();\n let removed = 0;\n let scanned = 0;\n let retainedInFlight = 0;\n\n /** Whether this record may be dropped, counting a live claim as it goes. */\n const isDroppable = (record: StateRecord | undefined, count: boolean): boolean => {\n if (record === undefined || now - record.updatedAt <= maxAgeMillis) {\n return false;\n }\n if (stateOf(record) === \"claimed\") {\n const age = now - (claimedAtOf(record) ?? record.updatedAt);\n if (age <= staleClaimMillis) {\n if (count) {\n retainedInFlight += 1;\n }\n return false;\n }\n }\n return true;\n };\n\n for (const key of keys) {\n if (scanned >= cap) {\n break;\n }\n scanned += 1;\n\n // Unlocked first pass. It decides only whether this key is worth locking for,\n // which is what keeps a sweep of a mostly-live store from paying a lock\n // acquisition per record: the common answer is \"not aged out, leave it\".\n if (!isDroppable(await stateStore.read(key), true)) {\n continue;\n }\n\n const scope = dedupScopeOf(key);\n if (scope === undefined) {\n // A key from a previous layout version: unreachable by any current read, so\n // there is no claim to race and no scope to lock on.\n await stateStore.delete(key);\n removed += 1;\n continue;\n }\n\n // Locked second pass, because a peer's `claim` takes this same lock and may\n // have refreshed the record since the first read. Deciding once, outside the\n // lock, would let a sweep delete a claim written microseconds earlier — and the\n // concurrent redelivery would then read `fresh` and export a second time.\n await withOptionalSessionLock(stateStore, scope, async (): Promise<void> => {\n if (!isDroppable(await stateStore.read(key), false)) {\n return;\n }\n await stateStore.delete(key);\n removed += 1;\n });\n }\n\n return {\n removed,\n scanned,\n ...(retainedInFlight === 0 ? {} : { retainedInFlight }),\n };\n };\n\n return { checkAndMark, claim, commit, release, cleanup };\n};\n","/**\n * Per-key async mutex.\n *\n * Ordinary promises already serialize a single caller's `await`s, but two\n * concurrent callers racing a read-modify-write against the same key (two\n * hook invocations updating the same session, in the same process) are not\n * serialized by anything. This chains each key's operations through a promise\n * tail so they run one at a time, in arrival order, without blocking unrelated\n * keys.\n */\nexport interface AsyncLock {\n /**\n * `timeoutMillis` bounds how long the caller waits to *acquire* the key.\n *\n * Two guarantees, and the boundary between them is the whole contract:\n *\n * - **A timed-out caller's `fn` never runs.** Giving up on the wait cancels the\n * queued operation. It has to: a caller that has been told \"I could not take\n * the lock\" will report contention and move on, and if `fn` then ran anyway it\n * would mutate state after the caller had already declared that nothing\n * happened. That is worse than either outcome on its own — the state changes\n * and nobody is watching.\n * - **Work is never cancelled after acquisition.** Once `fn` has started the\n * timeout is irrelevant; interrupting a read-modify-write partway through is\n * exactly the corruption a mutex exists to prevent. So the timeout bounds\n * *waiting*, never *exclusivity* and never *completion*.\n *\n * Cancellation does not let a waiter skip the queue: the cancelled slot still\n * settles in order, so everyone behind it keeps its place. A cancelled call\n * rejects with {@link LockWaitTimeoutError}, the same error a timed-out wait\n * produces, because from the caller's side they are one condition.\n */\n run<T>(key: string, fn: () => Promise<T>, timeoutMillis?: number): Promise<T>;\n}\n\nexport class LockWaitTimeoutError extends Error {\n public readonly lockKey: string;\n\n public constructor(key: string, timeoutMillis: number) {\n super(`lock wait exceeded ${timeoutMillis}ms`);\n this.name = \"LockWaitTimeoutError\";\n this.lockKey = key;\n }\n}\n\nexport const createAsyncLock = (): AsyncLock => {\n const tail = new Map<string, Promise<void>>();\n\n const run = async <T>(key: string, fn: () => Promise<T>, timeoutMillis?: number): Promise<T> => {\n const previous = tail.get(key) ?? Promise.resolve();\n const queued = previous.then(\n () => undefined,\n () => undefined,\n );\n\n /**\n * `entered` flips synchronously, immediately before `fn` is invoked, and\n * `cancelled` is only ever set from the timer while `entered` is false.\n *\n * That ordering is what makes the two guarantees exclusive rather than racy.\n * Microtasks drain before timers, so if this slot's turn has arrived at all,\n * the callback below has already run and set `entered` before any timer\n * callback can observe it — there is no window in which the timer sees a\n * not-yet-entered slot that is in fact about to run.\n */\n let cancelled = false;\n let entered = false;\n\n const current = queued.then((): T | Promise<T> => {\n if (cancelled) {\n // The waiter gave up before its turn came, so `fn` is skipped entirely.\n // The slot still settles here, in order, so nothing behind it is reordered.\n throw new LockWaitTimeoutError(key, timeoutMillis ?? 0);\n }\n entered = true;\n return fn();\n });\n\n const swallowed = current.then(\n () => undefined,\n () => undefined,\n );\n tail.set(key, swallowed);\n void swallowed.then(() => {\n if (tail.get(key) === swallowed) {\n tail.delete(key);\n }\n });\n\n if (timeoutMillis === undefined) {\n return current;\n }\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n if (!entered) {\n cancelled = true;\n }\n reject(new LockWaitTimeoutError(key, timeoutMillis));\n }, timeoutMillis);\n timer.unref?.();\n });\n try {\n // Raced against the queue gate, not against `current`: once the slot is\n // entered the caller waits for `fn` however long it takes.\n await Promise.race([queued, timeout]);\n } finally {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n }\n return current;\n };\n\n return { run };\n};\n","import type { Clock, StateStore } from \"../runtime/ports.js\";\nimport { LockWaitTimeoutError } from \"./async-lock.js\";\n\n/**\n * A lock could not be acquired within its wait bound because somebody else holds\n * it.\n *\n * Distinct from \"the store is broken\" on purpose, and the distinction is\n * load-bearing for callers that guard a read-modify-write with it. Contention\n * means a peer is plausibly *inside* the critical section right now, so\n * proceeding unlocked would produce exactly the lost update the lock exists to\n * prevent. A store that cannot lock at all — an unwritable directory, a full\n * disk — protects nothing, because the state the lock guards is equally\n * unreachable; there proceeding is the fail-open answer and costs nothing.\n */\nexport class StateLockTimeoutError extends Error {\n public readonly lockKey: string;\n\n public constructor(key: string, timeoutMillis: number) {\n super(`state store lock wait for \"${key}\" exceeded ${String(timeoutMillis)}ms`);\n this.name = \"StateLockTimeoutError\";\n this.lockKey = key;\n }\n}\n\n/**\n * Whether a thrown value means \"somebody else holds the lock\".\n *\n * Also true for {@link LockWaitTimeoutError}, the in-process variant, which\n * carries a second warning for callers: a timed-out wait does not cancel the\n * queued critical section, so it may still run afterwards. A caller that treats\n * contention as \"retry unlocked\" would therefore risk running the section twice.\n */\nexport const isStateLockContention = (thrown: unknown): boolean =>\n thrown instanceof StateLockTimeoutError || thrown instanceof LockWaitTimeoutError;\n\n/**\n * Optional capability beyond the frozen {@link StateStore} contract: a\n * session-scoped lock a caller can use to make a multi-step read-modify-write\n * atomic across an entire session, not just a single key.\n *\n * Deliberately keyed by an explicit `sessionId` the caller already knows,\n * rather than derived by parsing the store's own keys, so a store never has\n * to understand any particular key scheme.\n */\nexport interface LockingStateStore extends StateStore {\n withSessionLock<T>(\n sessionId: string,\n fn: () => Promise<T>,\n options?: { readonly timeoutMillis?: number },\n ): Promise<T>;\n}\n\nexport const isLockingStateStore = (store: StateStore): store is LockingStateStore =>\n typeof (store as Partial<LockingStateStore>).withSessionLock === \"function\";\n\n/** Runs `fn` under the store's session lock when it has one; otherwise runs it directly. */\nexport const withOptionalSessionLock = async <T>(\n store: StateStore,\n sessionId: string,\n fn: () => Promise<T>,\n options?: { readonly timeoutMillis?: number },\n): Promise<T> => {\n if (isLockingStateStore(store)) {\n return store.withSessionLock(sessionId, fn, options);\n }\n return fn();\n};\n\nexport type StateStoreDependencies = {\n readonly clock: Clock;\n};\n","/**\n * State key namespaces for lifecycle bookkeeping.\n *\n * Prefixed with `lifecycle:` so these keys can never collide with the\n * orchestrator's own `sequence:<sessionId>` and `usage:<sessionId>:...` keys\n * in the same {@link StateStore}, even though both share the store.\n *\n * Two properties are load-bearing here, because the store hashes a *whole\n * logical key* into one record: keys must be unambiguous, and a key space whose\n * layout changes must not be readable under its old meaning.\n */\nexport const LIFECYCLE_PREFIX = \"lifecycle\";\n\n/**\n * Layout version of the span key space.\n *\n * Bumped when the *segments* change, not when a record's contents do — that is\n * {@link SPAN_RECORD_VERSION}'s job. Version 2 inserted the provider segment,\n * so a v1 key must never be reachable: reading one would pair a span across\n * providers, which is exactly the attribution guess this library refuses.\n */\nexport const SPAN_KEY_VERSION = 2;\n\n/**\n * Layout version of the dedup key space.\n *\n * Version 2 re-scoped these keys from a session id to a delivery scope. The two\n * spaces are not interchangeable — a v1 key found under a v2 read would suppress\n * an unrelated callback — so the version segment keeps them disjoint.\n */\nexport const DEDUP_KEY_VERSION = 2;\n\n/**\n * Make a variable segment unambiguous within a `:`-delimited key.\n *\n * Without this, `dedupKey(\"a:b\", \"c\")` and `dedupKey(\"a\", \"b:c\")` produce the\n * identical logical key, and the store hashes both to one record — so one\n * delivery silently suppresses an unrelated one. That is reachable input, not a\n * theoretical one: `--callback-scope` is host-supplied, and a provider's session\n * or tool-call id is not required to avoid a colon.\n *\n * `%` is escaped first so the encoding stays injective, which makes this a true\n * bijection on segments rather than a lossy scrub. A segment containing neither\n * character encodes to itself, so keys already on disk keep their identity and\n * no cumulative baseline is reset by adopting this.\n */\nconst encodeSegment = (segment: string): string =>\n segment.replaceAll(\"%\", \"%25\").replaceAll(\":\", \"%3A\");\n\n/**\n * Session first, then provider: the janitor sweeps a whole session by prefix,\n * so the session segment has to lead. The provider segment below it is what\n * makes cross-provider pairing impossible by construction rather than only by\n * the runtime check in the span correlator.\n */\nexport const spanKey = (\n sessionId: string,\n providerId: string,\n scope: string,\n scopeKey: string,\n): string =>\n `${spanScanPrefix(sessionId)}${encodeSegment(providerId)}:${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;\n\n/**\n * The session-scoped prefix names one layout version; the bare prefix names\n * every one of them. That asymmetry is deliberate: a sweep must be able to\n * reclaim records written by a previous version, which a versioned prefix could\n * never match, while a *read* must never reach across a layout change.\n */\nexport const spanScanPrefix = (sessionId?: string): string =>\n sessionId === undefined\n ? `${LIFECYCLE_PREFIX}:span:`\n : `${LIFECYCLE_PREFIX}:span:v${String(SPAN_KEY_VERSION)}:${encodeSegment(sessionId)}:`;\n\n/**\n * Dedup keys are scoped by a *delivery scope*, not by a session id.\n *\n * A host-supplied delivery id carries its own namespace, and a provider-derived\n * one is scoped by a digest of provider, installation, and session — so neither\n * is a session id, and neither can be found by scanning for one.\n */\nexport const dedupKey = (scope: string, callbackId: string): string =>\n `${dedupScanPrefix(scope)}${encodeSegment(callbackId)}`;\n\nexport const dedupScanPrefix = (scope?: string): string =>\n scope === undefined\n ? `${LIFECYCLE_PREFIX}:dedup:`\n : `${LIFECYCLE_PREFIX}:dedup:v${String(DEDUP_KEY_VERSION)}:${encodeSegment(scope)}:`;\n\nconst decodeSegment = (segment: string): string =>\n segment.replaceAll(\"%3A\", \":\").replaceAll(\"%25\", \"%\");\n\n/**\n * Recover the delivery scope a dedup key belongs to.\n *\n * Needed by the sweep and nothing else. A sweep enumerates keys rather than being\n * handed a scope, but deleting a dedup record is a read-modify-write against the\n * same record a concurrent `claim` is deciding on — so the sweep has to take the\n * same per-scope lock, and to take it, it has to know the scope. Recovering it\n * from the key is safe precisely because {@link encodeSegment} is injective.\n *\n * Returns `undefined` for a key from a previous layout version, which no lock\n * protects because no current read can reach it.\n */\nexport const dedupScopeOf = (key: string): string | undefined => {\n const prefix = `${LIFECYCLE_PREFIX}:dedup:v${String(DEDUP_KEY_VERSION)}:`;\n if (!key.startsWith(prefix)) {\n return undefined;\n }\n // Exactly two segments follow the prefix, and neither can contain a raw `:`,\n // so the first `:` after the prefix is unambiguously the boundary.\n const rest = key.slice(prefix.length);\n const boundary = rest.indexOf(\":\");\n return boundary <= 0 ? undefined : decodeSegment(rest.slice(0, boundary));\n};\n\n/**\n * Usage rollup keys are escaped but deliberately *not* versioned: their layout\n * has not changed, and a version segment would orphan every cumulative token\n * baseline on disk — resetting usage accounting to fix a bug that escaping\n * already fixes.\n */\nexport const rollupUsageKey = (sessionId: string, scope: string, scopeKey: string): string =>\n `${rollupScanPrefix(sessionId)}${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;\n\nexport const rollupEpochKey = (sessionId: string, scope: string, scopeKey: string): string =>\n `${rollupEpochScanPrefix(sessionId)}${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;\n\nexport const rollupScanPrefix = (sessionId?: string): string =>\n sessionId === undefined\n ? `${LIFECYCLE_PREFIX}:usage:`\n : `${LIFECYCLE_PREFIX}:usage:${encodeSegment(sessionId)}:`;\n\nexport const rollupEpochScanPrefix = (sessionId?: string): string =>\n sessionId === undefined\n ? `${LIFECYCLE_PREFIX}:epoch:`\n : `${LIFECYCLE_PREFIX}:epoch:${encodeSegment(sessionId)}:`;\n","import type { CallbackDeduplicator } from \"./dedup.js\";\nimport type { SpanCorrelator } from \"./span-correlator.js\";\nimport type { UsageAccumulator } from \"./usage-accumulator.js\";\n\nconst DEFAULT_MAX_AGE_MILLIS = 24 * 60 * 60 * 1000;\nconst DEFAULT_MAX_ENTRIES_PER_COMPONENT = 1_000;\n\nexport type LifecycleJanitorOptions = {\n readonly spanCorrelator?: SpanCorrelator;\n readonly deduplicator?: CallbackDeduplicator;\n readonly usageAccumulator?: UsageAccumulator;\n readonly spanMaxAgeMillis?: number;\n readonly dedupMaxAgeMillis?: number;\n /**\n * Floor on how long an uncommitted delivery claim survives the sweep, whatever\n * `dedupMaxAgeMillis` says.\n *\n * Passed through rather than left to the deduplicator's default so it can be the\n * *effective* window the runtime computed, which is raised from the requested one\n * to cover a process's whole export budget. A sweep using a smaller number than\n * the claim path uses would delete claims the claim path still considers live.\n */\n readonly dedupStaleClaimMillis?: number;\n readonly usageMaxAgeMillis?: number;\n /** Caps how many keys any single component scans per sweep. */\n readonly maxEntriesPerComponent?: number;\n};\n\nexport type LifecycleSweepStats = {\n readonly removed: number;\n readonly scanned: number;\n /**\n * Span records dropped with a start and no end — spans that were never\n * exported. Reported only by the span sweep; see `SpanCleanupResult`.\n */\n readonly expiredOpen?: number;\n /**\n * Aged-out records kept back because they are delivery claims a live process may\n * still hold. Reported only by the dedup sweep; see `DedupCleanupResult`.\n */\n readonly retainedInFlight?: number;\n};\n\nexport type LifecycleCleanupReport = {\n readonly span?: LifecycleSweepStats;\n readonly dedup?: LifecycleSweepStats;\n readonly usage?: LifecycleSweepStats;\n};\n\n/**\n * Fans a single bounded cleanup pass out across whichever lifecycle\n * components are configured.\n *\n * Each component already bounds its own sweep (`maxEntries`); this exists so\n * a caller — a CLI subcommand, a periodic timer, an opportunistic call at the\n * end of `flush()` — can run \"the\" cleanup without wiring each component by\n * hand, and so the bound is enforced uniformly rather than per call site.\n */\nexport interface LifecycleJanitor {\n runOnce(sessionId?: string): Promise<LifecycleCleanupReport>;\n}\n\nexport const createLifecycleJanitor = (options: LifecycleJanitorOptions): LifecycleJanitor => {\n const maxEntries = options.maxEntriesPerComponent ?? DEFAULT_MAX_ENTRIES_PER_COMPONENT;\n const spanMaxAge = options.spanMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;\n const dedupMaxAge = options.dedupMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;\n const usageMaxAge = options.usageMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;\n\n const runOnce = async (sessionId?: string): Promise<LifecycleCleanupReport> => {\n const scope = { maxEntries, ...(sessionId === undefined ? {} : { sessionId }) };\n const [span, dedup, usage] = await Promise.all([\n options.spanCorrelator?.cleanup(spanMaxAge, scope),\n // Deduplication is deliberately swept across every scope rather than the\n // ending session's: a delivery scope is a host-chosen namespace or a\n // digest of provider/installation/session, never a session id, so scoping\n // this sweep by `sessionId` would match nothing and let records accumulate\n // forever. The sweep is TTL-driven and still bounded by `maxEntries`.\n options.deduplicator?.cleanup(dedupMaxAge, {\n maxEntries,\n ...(options.dedupStaleClaimMillis === undefined\n ? {}\n : { staleClaimMillis: options.dedupStaleClaimMillis }),\n }),\n options.usageAccumulator?.cleanup(usageMaxAge, scope),\n ]);\n return {\n ...(span === undefined ? {} : { span }),\n ...(dedup === undefined ? {} : { dedup }),\n ...(usage === undefined ? {} : { usage }),\n };\n };\n\n return { runOnce };\n};\n","import { createHash } from \"node:crypto\";\n\nimport { SpanKind, SpanStatusCode, TraceFlags, type Attributes, type SpanContext, type SpanStatus } from \"@opentelemetry/api\";\nimport { millisToHrTime } from \"@opentelemetry/core\";\nimport type { InstrumentationScope } from \"@opentelemetry/core\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport type { ReadableSpan } from \"@opentelemetry/sdk-trace\";\nimport {\n ATTR_ERROR_TYPE,\n ATTR_GEN_AI_OPERATION_NAME,\n ATTR_GEN_AI_REQUEST_MODEL,\n ATTR_GEN_AI_RESPONSE_MODEL,\n ATTR_GEN_AI_SYSTEM,\n ATTR_GEN_AI_TOOL_CALL_ID,\n ATTR_GEN_AI_TOOL_NAME,\n ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n} from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport type { CanonicalEvent, CanonicalEventType } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\nimport { VERSION } from \"../version.js\";\nimport { exportIdentityAttributes } from \"./export-identity.js\";\n\nconst SCOPE_NAME = \"@osfactory/otel-hook\";\n\nexport const DEFAULT_INSTRUMENTATION_SCOPE: InstrumentationScope = Object.freeze({\n name: SCOPE_NAME,\n version: VERSION,\n});\n\nconst ATTR_OTELHOOK_SPAN_PAIRED = \"otelhook.span.paired\";\nconst ATTR_OTELHOOK_SPAN_PAIRING = \"otelhook.span.pairing\";\nconst ATTR_OTELHOOK_SPAN_ORPHAN = \"otelhook.span.orphan\";\nconst ATTR_OTELHOOK_OUTCOME = \"otelhook.outcome\";\nconst ATTR_OTELHOOK_RESET_DETECTED = \"otelhook.usage.reset_detected\";\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 = (\n event: CanonicalEvent,\n resource: Resource,\n ids: { readonly traceId: string; readonly spanId: string; readonly parentSpanId?: string },\n): Attributes => exportIdentityAttributes(event, resource, ids);\n\nconst usageAttributes = (usage: CanonicalUsage | undefined, resetDetected: boolean): Attributes => {\n if (usage === undefined) {\n return {};\n }\n return {\n [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: usage.inputTokens,\n [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: usage.outputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: usage.cachedInputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: usage.cacheCreationInputTokens,\n [ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]: usage.reasoningOutputTokens,\n ...(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, resource, {\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n }),\n ...resolved.recovered,\n [ATTR_OTELHOOK_SPAN_PAIRED]: resolved.pairing !== \"unpaired\",\n [ATTR_OTELHOOK_SPAN_PAIRING]: resolved.pairing,\n [ATTR_OTELHOOK_SPAN_ORPHAN]: resolved.orphan,\n };\n\n switch (group.ref.family) {\n case \"session\": {\n const end = group.end?.type === \"session.end\" ? group.end : undefined;\n const start = group.start?.type === \"session.start\" ? group.start : undefined;\n name = \"session\";\n kind = SpanKind.INTERNAL;\n attributes = {\n ...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 const parentSpanId =\n parent === undefined ? undefined : deriveSpanId(providerId, event.sessionId, parent);\n let attributes: Attributes = {\n ...identityAttributes(event, resource, {\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n }),\n [ATTR_OTELHOOK_SPAN_PAIRED]: true,\n };\n let status: SpanStatus = { code: SpanStatusCode.UNSET };\n let name: string = event.type;\n\n switch (event.type) {\n case \"prompt.submitted\":\n name = \"prompt\";\n attributes = { ...attributes, \"otelhook.prompt.source\": event.promptSource };\n break;\n case \"compaction.performed\":\n name = \"compaction\";\n attributes = {\n ...attributes,\n [ATTR_OTELHOOK_COMPACTION_TRIGGER]: event.trigger,\n ...usageAttributes(event.usage, false),\n };\n break;\n case \"error.raised\":\n name = \"error\";\n status = { code: SpanStatusCode.ERROR, message: event.errorCode };\n attributes = {\n ...attributes,\n [ATTR_ERROR_TYPE]: event.errorCode,\n \"otelhook.error.phase\": event.phase,\n \"otelhook.error.retryable\": event.retryable,\n };\n break;\n default:\n break;\n }\n\n return toReadableSpan({\n name,\n kind: SpanKind.INTERNAL,\n startMillis: event.occurredAt,\n endMillis: event.occurredAt,\n attributes,\n status,\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n resource,\n instrumentationScope: scope,\n });\n};\n\nexport type SemanticMappingOptions = {\n readonly resource: Resource;\n readonly instrumentationScope?: InstrumentationScope;\n /**\n * Cross-process pairing facts, at most one entry per lifecycle scope in\n * `events`. Omitted entirely, the mapping degrades to in-batch pairing only —\n * the behavior of a host that wired no state store.\n */\n readonly correlations?: readonly SpanCorrelation[];\n /**\n * Whether a correlator was consulted at all, and whether it answered.\n *\n * This is what separates \"the state store is holding this start, so the end edge\n * will publish it\" from \"nothing recorded this start\". Both look like an empty\n * `correlations` list, and only the first is safe to drop — dropping the second\n * would discard an observation that was neither persisted nor exported, while a\n * caller that saw zero rejections went on to mark the callback handled.\n *\n * - `true` — the correlator ran; an absent or non-`defer` entry means emit.\n * - `false` — the correlator failed; every unpaired start is emitted as an\n * explicitly labelled, uniquely identified fallback.\n * - omitted — no correlator is wired, so cross-process pairing was never on\n * offer and an unpaired start is deferred (the documented no-state-root\n * degradation).\n */\n readonly correlationAvailable?: boolean;\n};\n\n/**\n * Fill in a correlation for an unpaired start that nothing recorded.\n *\n * Reached when a correlator was consulted and either failed outright or reported\n * nothing for this scope. The synthesized entry says what is true — the state was\n * not consulted successfully, so this span is unpaired and no end can complete it\n * — and carries a discriminator so the record cannot claim the span id a later end\n * will publish for the same scope.\n */\nconst effectiveCorrelation = (\n group: SpanGroup,\n correlation: SpanCorrelation | undefined,\n): SpanCorrelation | undefined => {\n if (correlation !== undefined || group.end !== undefined || group.start === undefined) {\n return correlation;\n }\n return {\n providerId: group.start.provenance.providerId,\n sessionId: group.start.sessionId,\n ref: group.ref,\n pairing: \"unpaired\",\n orphan: \"state-unavailable\",\n disposition: \"emit\",\n spanIdDiscriminator: group.start.eventId,\n };\n};\n\n/** How one batch's events distribute over the lifecycle scopes they are edges of. */\ntype BatchLayout = {\n readonly groups: ReadonlyMap<string, SpanGroup>;\n readonly standalone: readonly CanonicalEvent[];\n /** Event id of each lifecycle edge, mapped to the group key it belongs to. */\n readonly groupOf: ReadonlyMap<string, string>;\n};\n\nconst layoutBatch = (events: readonly CanonicalEvent[]): BatchLayout => {\n const groups = new Map<string, SpanGroup>();\n const standalone: CanonicalEvent[] = [];\n const groupOf = new Map<string, string>();\n\n for (const event of events) {\n const ref = spanScopeRefOf(event);\n if (ref === undefined) {\n standalone.push(event);\n continue;\n }\n const groupKey = correlationKey(event.provenance.providerId, event.sessionId, ref);\n const group: SpanGroup = groups.get(groupKey) ?? { ref };\n if (event.type.endsWith(\".start\")) {\n group.start = event;\n } else {\n group.end = event;\n }\n groups.set(groupKey, group);\n groupOf.set(event.eventId, groupKey);\n }\n return { groups, standalone, groupOf };\n};\n\nconst indexCorrelations = (\n correlations: readonly SpanCorrelation[] | undefined,\n): ReadonlyMap<string, SpanCorrelation> => {\n const indexed = new Map<string, SpanCorrelation>();\n for (const correlation of correlations ?? []) {\n indexed.set(\n correlationKey(correlation.providerId, correlation.sessionId, correlation.ref),\n correlation,\n );\n }\n return indexed;\n};\n\n/**\n * What this batch does with one lifecycle scope, decided once.\n *\n * Both the span mapping and the log mapping need the *same* answer to \"which\n * span id identifies this scope, and is a record for it going out now?\" — a log\n * record whose `spanContext` names a span id the exporter never published would\n * dangle at the collector. Computing it in one place is what keeps the two\n * signals pointing at the same span rather than at two plausible derivations of\n * it.\n */\ntype GroupPlan = {\n readonly group: SpanGroup;\n /** The event the span's identity and provenance are read from. */\n readonly anchor: CanonicalEvent;\n /**\n * False when the start is deferred: the state store is holding it and the end\n * edge will publish the one complete span, so nothing is exported for it now.\n */\n readonly emits: boolean;\n readonly correlation: SpanCorrelation | undefined;\n readonly traceId: string;\n readonly spanId: string;\n};\n\nconst planGroup = (\n group: SpanGroup,\n correlation: SpanCorrelation | undefined,\n correlationAvailable: boolean | undefined,\n): GroupPlan | undefined => {\n const anchor = group.start ?? group.end;\n if (anchor === undefined) {\n // Unreachable: a group exists only because an event was filed into it.\n return undefined;\n }\n const providerId = anchor.provenance.providerId;\n const sessionId = anchor.sessionId;\n\n // A start with no end in this batch is dropped **only** when something states\n // that it is durably recorded, because its span id is a pure function of the\n // scope: emitting here and again at the end edge would put two records with one\n // id on the wire, and OTLP has no update operation.\n //\n // `defer` is that statement, and it is the correlator's to make — it just wrote\n // the record. Anything else means nothing is holding this start, so dropping it\n // would lose an observation that was neither persisted nor exported, while the\n // caller saw zero rejections and marked the callback handled. Those are exported\n // under a discriminated span id instead.\n const durablyRecorded =\n group.end === undefined &&\n (correlation?.disposition === \"defer\" ||\n // No correlator wired at all: cross-process pairing was never on offer, so\n // this is the documented no-state-root degradation rather than a failure to\n // persist something that should have been persisted.\n (correlation === undefined && correlationAvailable === undefined));\n\n // A deferred start keeps the scope's *plain* span id, because that is the id the\n // end edge will publish. Only a record actually going out now may claim a\n // discriminated one.\n const effective = durablyRecorded ? correlation : effectiveCorrelation(group, correlation);\n const discriminator = durablyRecorded ? undefined : effective?.spanIdDiscriminator;\n\n return {\n group,\n anchor,\n emits: !durablyRecorded,\n correlation: effective,\n traceId: deriveTraceId(providerId, sessionId),\n spanId:\n discriminator === undefined\n ? deriveSpanId(providerId, sessionId, group.ref)\n : digestHex(\n [\n \"otelhook/span\",\n providerId,\n sessionId,\n group.ref.family,\n group.ref.scopeKey,\n discriminator,\n ],\n 16,\n ),\n };\n};\n\n/** Trace and span a record derived from one canonical event belongs to. */\nexport type EventTraceIdentity = {\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n};\n\n/**\n * Resolve the trace and span identity of every event in one batch.\n *\n * Exposed for signals other than traces — a log record correlates by carrying\n * the *same* derived ids the span mapping would compute, including the deferred\n * and discriminated cases. Whole batch at once because a start's identity\n * depends on whether its end is in the same batch.\n *\n * Both ids come from the event's own `(providerId, sessionId)`, never from a\n * batch-level or module-level value, which is what makes cross-session\n * contamination structurally impossible: two sessions in one batch derive two\n * different trace ids.\n */\nexport const canonicalEventTraceIdentities = (\n events: readonly CanonicalEvent[],\n options: {\n readonly correlations?: readonly SpanCorrelation[];\n readonly correlationAvailable?: boolean;\n } = {},\n): ReadonlyMap<string, EventTraceIdentity> => {\n const layout = layoutBatch(events);\n const correlations = indexCorrelations(options.correlations);\n const plans = new Map<string, GroupPlan>();\n for (const [groupKey, group] of layout.groups) {\n const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);\n if (plan !== undefined) {\n plans.set(groupKey, plan);\n }\n }\n\n const identities = new Map<string, EventTraceIdentity>();\n for (const event of events) {\n const providerId = event.provenance.providerId;\n const groupKey = layout.groupOf.get(event.eventId);\n const plan = groupKey === undefined ? undefined : plans.get(groupKey);\n if (plan === undefined) {\n const parent = parentScopeRefOf(event);\n identities.set(event.eventId, {\n traceId: deriveTraceId(providerId, event.sessionId),\n spanId: deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId),\n ...(parent === undefined\n ? {}\n : { parentSpanId: deriveSpanId(providerId, event.sessionId, parent) }),\n });\n continue;\n }\n const parent = plan.correlation?.parent ?? parentScopeRefOf(event);\n identities.set(event.eventId, {\n traceId: plan.traceId,\n spanId: plan.spanId,\n ...(parent === undefined\n ? {}\n : { parentSpanId: deriveSpanId(providerId, event.sessionId, parent) }),\n });\n }\n return identities;\n};\n\n/** Maps one invocation's canonical event batch into OTLP-ready spans. */\nexport const canonicalEventsToReadableSpans = (\n events: readonly CanonicalEvent[],\n options: SemanticMappingOptions,\n): readonly ReadableSpan[] => {\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const layout = layoutBatch(events);\n const correlations = indexCorrelations(options.correlations);\n\n const spans: ReadableSpan[] = [];\n for (const [groupKey, group] of layout.groups) {\n const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);\n if (plan === undefined || !plan.emits) {\n continue;\n }\n spans.push(buildLifecycleSpan(plan, options.resource, scope));\n }\n for (const event of layout.standalone) {\n spans.push(buildStandaloneSpan(event, options.resource, scope));\n }\n return spans;\n};\n","/*\n * 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.3.0\";\n","import type { Attributes } from \"@opentelemetry/api\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport { ATTR_SESSION_ID } from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport type { CanonicalEvent } from \"../model/events.js\";\n\n/**\n * W3C hex identity attributes on every log and span.\n *\n * Mission Control (and any consumer that decodes OTLP protobuf with a JSON\n * `toObject` that stringifies bytes as UTF-8) cannot recover a usable id from\n * the protobuf `trace_id` / `span_id` fields. These attributes are already hex\n * in the OpenTelemetry JS API; they are copied onto the attribute map so a\n * consumer never has to stringify binary ids.\n */\nexport const ATTR_TRACE_ID = \"trace_id\";\nexport const ATTR_SPAN_ID = \"span_id\";\nexport const ATTR_PARENT_SPAN_ID = \"parent_span_id\";\n\n/** Provider session id, kept when `session.id` is an externally supplied key. */\nexport const ATTR_OTELHOOK_SESSION_ID = \"otelhook.session.id\";\n/** Same provider session id under the gen_ai conversation attribute. */\nexport const ATTR_GEN_AI_CONVERSATION_ID = \"gen_ai.conversation.id\";\n\nexport const TRACE_ID_HEX_PATTERN = /^[0-9a-f]{32}$/;\nexport const SPAN_ID_HEX_PATTERN = /^[0-9a-f]{16}$/;\n\nconst ATTR_OTELHOOK_INVOCATION_ID = \"otelhook.invocation.id\";\nconst ATTR_OTELHOOK_PROVIDER_ID = \"otelhook.provider.id\";\nconst ATTR_OTELHOOK_PROVIDER_VERSION = \"otelhook.provider.version\";\nconst ATTR_OTELHOOK_WORKSPACE_ID = \"otelhook.workspace.id\";\n\nconst HAR_SESSION_KEY = \"har.session_key\";\n\nconst isPrimitiveAttribute = (value: unknown): value is string | number | boolean =>\n typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\";\n\n/**\n * Resource attributes a HAR (or similar) launcher put on the process.\n *\n * Copied onto every log and span so a consumer that reads record attributes\n * rather than the resource still sees them. Only `har.*` primitives are\n * forwarded; nothing is invented when they are absent.\n */\nexport const passthroughHarAttributes = (resource: Resource): Attributes => {\n const attributes: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(resource.attributes)) {\n if (key.startsWith(\"har.\") && isPrimitiveAttribute(value)) {\n attributes[key] = value;\n }\n }\n return attributes;\n};\n\n/**\n * Session id to put on `session.id`, preferring a HAR-supplied key.\n *\n * The provider's own session id is never discarded: it is returned separately\n * so callers can emit it as `otelhook.session.id` / `gen_ai.conversation.id`.\n */\nexport const resolveExportedSessionId = (\n eventSessionId: string,\n resource: Resource,\n): { readonly sessionId: string; readonly providerSessionId: string } => {\n const har = resource.attributes[HAR_SESSION_KEY];\n if (typeof har === \"string\") {\n const trimmed = har.trim();\n if (trimmed.length > 0) {\n return { sessionId: trimmed, providerSessionId: eventSessionId };\n }\n }\n return { sessionId: eventSessionId, providerSessionId: eventSessionId };\n};\n\nexport type ExportedTraceIds = {\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n};\n\n/**\n * Hex-only trace/span attributes. A value that is not W3C hex is omitted\n * rather than stringified — binary blobs must never appear in id fields.\n */\nexport const hexTraceAttributes = (ids: ExportedTraceIds): Attributes => ({\n ...(TRACE_ID_HEX_PATTERN.test(ids.traceId) ? { [ATTR_TRACE_ID]: ids.traceId } : {}),\n ...(SPAN_ID_HEX_PATTERN.test(ids.spanId) ? { [ATTR_SPAN_ID]: ids.spanId } : {}),\n ...(ids.parentSpanId !== undefined && SPAN_ID_HEX_PATTERN.test(ids.parentSpanId)\n ? { [ATTR_PARENT_SPAN_ID]: ids.parentSpanId }\n : {}),\n});\n\n/**\n * Identity attributes shared by the log and span mappings.\n *\n * `session.id` is the HAR session key when the resource carries one, otherwise\n * the provider session id. The provider id is always also emitted under\n * `otelhook.session.id` and `gen_ai.conversation.id`.\n */\nexport const exportIdentityAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n ids: ExportedTraceIds,\n): Attributes => {\n const { sessionId, providerSessionId } = resolveExportedSessionId(event.sessionId, resource);\n return {\n [ATTR_SESSION_ID]: sessionId,\n [ATTR_OTELHOOK_SESSION_ID]: providerSessionId,\n [ATTR_GEN_AI_CONVERSATION_ID]: providerSessionId,\n [ATTR_OTELHOOK_INVOCATION_ID]: event.invocationId,\n [ATTR_OTELHOOK_PROVIDER_ID]: event.provenance.providerId,\n ...(event.provenance.providerVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event.provenance.providerVersion }),\n [ATTR_OTELHOOK_WORKSPACE_ID]: event.workspace.workspaceId,\n ...passthroughHarAttributes(resource),\n ...hexTraceAttributes(ids),\n };\n};\n","import type { Attributes as SpanAttributes } from \"@opentelemetry/api\";\n\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport {\n MAX_ATTRIBUTE_STRING_LENGTH,\n MAX_IDENTIFIER_LENGTH,\n type Attributes,\n} from \"../model/primitives.js\";\nimport type { Clock, StateStore, StateValue } from \"../runtime/ports.js\";\nimport { withOptionalSessionLock } from \"../state/store.js\";\nimport {\n MAX_RECOVERED_START_ATTRIBUTES,\n parentScopeRefOf,\n spanScopeRefOf,\n startOnlySpanAttributes,\n type SpanCorrelation,\n type SpanFamily,\n type SpanOrphanClassification,\n type SpanScopeRef,\n} from \"../telemetry/semconv.js\";\nimport { spanKey, spanScanPrefix } from \"./keys.js\";\n\n/** Correlation scopes that pair a `*.start` event with a later `*.end` event. */\nexport type LifecycleScope = SpanFamily;\n\n/**\n * Shape version of a persisted span record.\n *\n * A record written under a different version is discarded on read rather than\n * interpreted: guessing at an older layout is exactly the kind of silent\n * mis-attribution this library refuses to do. See `docs/state-retention.md`.\n */\nexport const SPAN_RECORD_VERSION = 2;\n\n/** Facts about a span recovered from, or written to, persisted state. */\nexport type SpanCorrelationFacts = {\n readonly startedAt?: number;\n readonly endedAt?: number;\n readonly parent?: SpanScopeRef;\n readonly attributes?: SpanAttributes;\n};\n\nexport type SpanStartInput = {\n readonly sessionId: string;\n /** Attribution boundary: a scope recorded by one provider never pairs with another's. */\n readonly providerId: string;\n readonly scope: LifecycleScope;\n readonly scopeKey: string;\n /** The canonical event id of the start event; used to detect redelivery. */\n readonly eventId: string;\n readonly occurredAt: number;\n /** Where this span hangs, so an end-only process reparents it identically. */\n readonly parent?: SpanScopeRef;\n /** Attributes only the start edge knows; carried forward to the end-side span. */\n readonly attributes?: SpanAttributes;\n};\n\nexport type SpanEndInput = {\n readonly sessionId: string;\n readonly providerId: string;\n readonly scope: LifecycleScope;\n readonly scopeKey: string;\n readonly eventId: string;\n readonly occurredAt: number;\n};\n\nexport type SpanStartResult =\n | { readonly status: \"recorded\"; readonly facts: SpanCorrelationFacts }\n /** The same start (by event id) was already recorded; state is unchanged. */\n | { readonly status: \"duplicate\"; readonly facts: SpanCorrelationFacts }\n /**\n * The record was completed, but an OTLP record for this scope has already been\n * published under its span id — so this edge must not export one.\n */\n | { readonly status: \"published\"; readonly facts: SpanCorrelationFacts }\n /** A different provider owns this scope key in this session; nothing was written. */\n | { readonly status: \"conflict\"; readonly reason: \"provider-mismatch\" };\n\n/** Why an end could not be paired with a recorded start. */\nexport type SpanEndOrphanReason =\n | \"no-start-recorded\"\n | \"start-expired\"\n | \"already-closed\"\n | \"provider-mismatch\"\n | \"state-incompatible\"\n | \"state-corrupt\";\n\nexport type SpanEndResult =\n | {\n readonly status: \"matched\";\n readonly startedAt: number;\n readonly durationMillis: number;\n readonly facts: SpanCorrelationFacts;\n }\n /** This exact end (by event id) was already applied; the same facts are replayed. */\n | { readonly status: \"duplicate\"; readonly facts: SpanCorrelationFacts }\n | {\n readonly status: \"orphaned\";\n readonly reason: SpanEndOrphanReason;\n readonly facts: SpanCorrelationFacts;\n };\n\nexport type SpanCleanupResult = {\n readonly removed: number;\n readonly scanned: number;\n /**\n * Records dropped that held a start and never received an end.\n *\n * These are the spans that will never be exported at all: the end edge is what\n * emits a lifecycle span, so a scope whose end never arrives — a session the\n * host killed, a tool call that outlived the retention window — produces no\n * OTLP record. That is the standard OpenTelemetry outcome for a span that never\n * ends, and it is deliberately not papered over with a synthetic end time,\n * because a fabricated duration is a wrong measurement rather than a missing\n * one. Counting them keeps the cost visible: a non-zero number here means real\n * activity went unreported, which is a signal about the host or the retention\n * window rather than noise. See `docs/state-retention.md`.\n */\n readonly expiredOpen: number;\n};\n\n/**\n * Cross-invocation start/end correlation for session, generation, tool, and\n * subagent scopes.\n *\n * A coding-agent hook fires once per lifecycle edge, usually as a separate\n * short-lived process for the start and for the end. This records an open span\n * in the shared state store so the end side can report a real start time,\n * duration, parent, and start-only attributes even though its process has no\n * memory of the start — and so a redelivered start or end (an at-least-once\n * host retry) re-exports an identical span instead of being double-counted.\n *\n * ## What it refuses to do\n *\n * - **Pair across sessions.** The state key is session-scoped, so two sessions\n * cannot see each other's open spans.\n * - **Pair across providers.** The key is provider-scoped *and* the record\n * carries the provider that wrote it, so a mismatch is reported rather than\n * guessed at — the same defense in depth the durable spool uses.\n * - **Trust a stale start.** A start older than `maxStartAgeMillis` when its end\n * arrives is dropped and classified `start-expired`, rather than reporting a\n * duration that really measures a machine suspend or a reused id.\n * - **Interpret a record it does not understand.** A corrupt or wrong-version\n * record is deleted and classified, never partially read.\n */\nexport interface SpanCorrelator {\n recordStart(input: SpanStartInput): Promise<SpanStartResult>;\n recordEnd(input: SpanEndInput): Promise<SpanEndResult>;\n /**\n * Records every lifecycle edge in a batch and reports what the exported spans\n * should say. Never rejects: a state failure degrades one scope to\n * `state-unavailable` rather than losing the batch (fail-open telemetry).\n */\n correlateBatch(events: readonly CanonicalEvent[]): Promise<readonly SpanCorrelation[]>;\n /** Bounded sweep: drops spans untouched for longer than `maxAgeMillis`. */\n cleanup(\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<SpanCleanupResult>;\n}\n\nexport type SpanCorrelatorDependencies = {\n readonly stateStore: StateStore;\n readonly clock: Clock;\n /**\n * A recorded start older than this when its end arrives is not trusted.\n * Default 24 hours, matching the janitor's retention window.\n */\n readonly maxStartAgeMillis?: number;\n};\n\nconst DEFAULT_MAX_START_AGE_MILLIS = 24 * 60 * 60 * 1000;\nconst ATTRIBUTE_PREFIX = \"a:\";\n\ntype SpanRecord = {\n readonly providerId: string;\n readonly startEventId?: string;\n readonly startedAt?: number;\n readonly endEventId?: string;\n readonly endedAt?: number;\n readonly parent?: SpanScopeRef;\n readonly attributes?: SpanAttributes;\n /**\n * True once an OTLP record has been produced for this scope under its derived\n * span id.\n *\n * Needed for the ordering nobody controls: the end edge can be mapped before\n * the start edge, and then the end has already exported an orphan carrying the\n * scope's canonical span id. Without this flag the late start would look like\n * the benign \"end raced ahead\" case and export a *second* record with that same\n * id — the duplicate the whole defer strategy exists to avoid. So the flag turns\n * \"was this scope already published?\" into a fact on disk rather than an\n * assumption about arrival order.\n */\n readonly exported?: boolean;\n};\n\ntype DecodedRecord =\n | { readonly kind: \"absent\" }\n | { readonly kind: \"incompatible\" }\n | { readonly kind: \"corrupt\" }\n | { readonly kind: \"present\"; readonly record: SpanRecord };\n\nconst SPAN_FAMILIES: readonly SpanFamily[] = [\"session\", \"generation\", \"tool\", \"subagent\"];\n\nconst isSpanFamily = (value: unknown): value is SpanFamily =>\n typeof value === \"string\" && (SPAN_FAMILIES as readonly string[]).includes(value);\n\nconst optionalNumber = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n\nconst optionalString = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 ? value : undefined;\n\n/**\n * Persisted attributes are flattened under a prefix rather than nested: the\n * state schema admits only flat primitives, which is what keeps a provider\n * payload from ever being smuggled through the state store.\n */\nconst encodeAttributes = (attributes: SpanAttributes | undefined): Attributes => {\n const encoded: Record<string, string | number | boolean> = {};\n let count = 0;\n for (const [key, value] of Object.entries(attributes ?? {})) {\n if (count >= MAX_RECOVERED_START_ATTRIBUTES) {\n break;\n }\n const encodedKey = `${ATTRIBUTE_PREFIX}${key}`;\n if (encodedKey.length > MAX_IDENTIFIER_LENGTH) {\n continue;\n }\n if (typeof value === \"string\") {\n encoded[encodedKey] = value.slice(0, MAX_ATTRIBUTE_STRING_LENGTH);\n } else if (typeof value === \"number\" && Number.isFinite(value)) {\n encoded[encodedKey] = value;\n } else if (typeof value === \"boolean\") {\n encoded[encodedKey] = value;\n } else {\n continue;\n }\n count += 1;\n }\n return encoded;\n};\n\nconst decodeAttributes = (attributes: Attributes): SpanAttributes | undefined => {\n const decoded: Record<string, string | number | boolean> = {};\n let count = 0;\n for (const [key, value] of Object.entries(attributes)) {\n if (!key.startsWith(ATTRIBUTE_PREFIX) || count >= MAX_RECOVERED_START_ATTRIBUTES) {\n continue;\n }\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n decoded[key.slice(ATTRIBUTE_PREFIX.length)] = value;\n count += 1;\n }\n }\n return count === 0 ? undefined : decoded;\n};\n\nconst encodeRecord = (record: SpanRecord): StateValue => ({\n kind: \"attributes\",\n attributes: {\n v: SPAN_RECORD_VERSION,\n providerId: record.providerId,\n ...(record.startEventId === undefined ? {} : { startEventId: record.startEventId }),\n ...(record.startedAt === undefined ? {} : { startedAt: record.startedAt }),\n ...(record.endEventId === undefined ? {} : { endEventId: record.endEventId }),\n ...(record.endedAt === undefined ? {} : { endedAt: record.endedAt }),\n ...(record.exported === true ? { exported: true } : {}),\n ...(record.parent === undefined\n ? {}\n : { parentFamily: record.parent.family, parentScopeKey: record.parent.scopeKey }),\n ...encodeAttributes(record.attributes),\n },\n});\n\nconst decodeRecord = (attributes: Attributes): DecodedRecord => {\n if (attributes[\"v\"] !== SPAN_RECORD_VERSION) {\n return { kind: \"incompatible\" };\n }\n const providerId = optionalString(attributes[\"providerId\"]);\n if (providerId === undefined) {\n return { kind: \"corrupt\" };\n }\n // A half-written edge (a timestamp with no event id, or the reverse) is not\n // an edge we can reason about; the record is refused rather than completed\n // with an invented half.\n const startedAt = optionalNumber(attributes[\"startedAt\"]);\n const startEventId = optionalString(attributes[\"startEventId\"]);\n if ((startedAt === undefined) !== (startEventId === undefined)) {\n return { kind: \"corrupt\" };\n }\n const endedAt = optionalNumber(attributes[\"endedAt\"]);\n const endEventId = optionalString(attributes[\"endEventId\"]);\n if ((endedAt === undefined) !== (endEventId === undefined)) {\n return { kind: \"corrupt\" };\n }\n const exported = attributes[\"exported\"] === true;\n const parentFamily = attributes[\"parentFamily\"];\n const parentScopeKey = optionalString(attributes[\"parentScopeKey\"]);\n const parent =\n isSpanFamily(parentFamily) && parentScopeKey !== undefined\n ? { family: parentFamily, scopeKey: parentScopeKey }\n : undefined;\n const decodedAttributes = decodeAttributes(attributes);\n return {\n kind: \"present\",\n record: {\n providerId,\n ...(startEventId === undefined ? {} : { startEventId }),\n ...(startedAt === undefined ? {} : { startedAt }),\n ...(endEventId === undefined ? {} : { endEventId }),\n ...(endedAt === undefined ? {} : { endedAt }),\n ...(parent === undefined ? {} : { parent }),\n ...(exported ? { exported: true } : {}),\n ...(decodedAttributes === undefined ? {} : { attributes: decodedAttributes }),\n },\n };\n};\n\nconst factsOf = (record: SpanRecord): SpanCorrelationFacts => ({\n ...(record.startedAt === undefined ? {} : { startedAt: record.startedAt }),\n ...(record.endedAt === undefined ? {} : { endedAt: record.endedAt }),\n ...(record.parent === undefined ? {} : { parent: record.parent }),\n ...(record.attributes === undefined ? {} : { attributes: record.attributes }),\n});\n\n/**\n * Persisted facts speak in event time (`startedAt`); a span speaks in the\n * milliseconds it is stamped with. Translated in one place so the two\n * vocabularies cannot silently drift apart.\n */\nconst correlationTimesOf = (\n facts: SpanCorrelationFacts,\n options: { readonly withStart: boolean } = { withStart: true },\n): Pick<SpanCorrelation, \"startMillis\" | \"endMillis\" | \"parent\" | \"attributes\"> => ({\n ...(facts.startedAt === undefined || !options.withStart ? {} : { startMillis: facts.startedAt }),\n ...(facts.endedAt === undefined ? {} : { endMillis: facts.endedAt }),\n ...(facts.parent === undefined ? {} : { parent: facts.parent }),\n ...(facts.attributes === undefined ? {} : { attributes: facts.attributes }),\n});\n\nconst orphanClassificationOf = (reason: SpanEndOrphanReason): SpanOrphanClassification => {\n switch (reason) {\n case \"no-start-recorded\":\n return \"missing-start\";\n case \"start-expired\":\n return \"expired-start\";\n case \"already-closed\":\n return \"already-closed\";\n case \"provider-mismatch\":\n return \"provider-mismatch\";\n case \"state-incompatible\":\n return \"state-incompatible\";\n case \"state-corrupt\":\n return \"state-corrupt\";\n }\n};\n\ntype BatchGroup = {\n readonly providerId: string;\n readonly sessionId: string;\n readonly ref: SpanScopeRef;\n start?: CanonicalEvent;\n end?: CanonicalEvent;\n};\n\nexport const createSpanCorrelator = (deps: SpanCorrelatorDependencies): SpanCorrelator => {\n const { stateStore, clock } = deps;\n const maxStartAgeMillis = deps.maxStartAgeMillis ?? DEFAULT_MAX_START_AGE_MILLIS;\n\n const keyFor = (input: {\n readonly sessionId: string;\n readonly providerId: string;\n readonly scope: LifecycleScope;\n readonly scopeKey: string;\n }): string => spanKey(input.sessionId, input.providerId, input.scope, input.scopeKey);\n\n /**\n * Reads and validates one record, deleting anything it refuses to interpret.\n * Self-healing on purpose: a single unreadable record must not make the same\n * scope unreadable forever.\n */\n const readRecord = async (key: string): Promise<DecodedRecord> => {\n const existing = await stateStore.read(key);\n if (existing === undefined) {\n return { kind: \"absent\" };\n }\n if (existing.value.kind !== \"attributes\") {\n await stateStore.delete(key);\n return { kind: \"corrupt\" };\n }\n const decoded = decodeRecord(existing.value.attributes);\n if (decoded.kind === \"corrupt\" || decoded.kind === \"incompatible\") {\n await stateStore.delete(key);\n }\n return decoded;\n };\n\n const recordStart = (input: SpanStartInput): Promise<SpanStartResult> =>\n withOptionalSessionLock(stateStore, input.sessionId, async (): Promise<SpanStartResult> => {\n const key = keyFor(input);\n const decoded = await readRecord(key);\n\n if (decoded.kind === \"present\") {\n const existing = decoded.record;\n if (existing.providerId !== input.providerId) {\n return { status: \"conflict\", reason: \"provider-mismatch\" };\n }\n if (existing.startEventId === input.eventId) {\n return { status: \"duplicate\", facts: factsOf(existing) };\n }\n if (existing.startEventId === undefined && existing.endEventId !== undefined) {\n // The end raced ahead of the start (two hook processes, no ordering\n // guarantee between them). Complete the record rather than treating\n // the late start as the beginning of a second span.\n //\n // If that end was already exported, the scope's canonical span id is\n // already on the wire and this start must stay silent: re-exporting a\n // now-complete span under the same id would be a duplicate, not a\n // correction, because OTLP has no update. The enrichment is lost and the\n // published record remains the orphan the end could honestly produce.\n const completed: SpanRecord = {\n ...existing,\n startEventId: input.eventId,\n startedAt: input.occurredAt,\n ...(input.parent === undefined ? {} : { parent: input.parent }),\n ...(input.attributes === undefined ? {} : { attributes: input.attributes }),\n };\n await stateStore.write(key, encodeRecord(completed));\n return existing.exported === true\n ? { status: \"published\", facts: factsOf(completed) }\n : { status: \"recorded\", facts: factsOf(completed) };\n }\n }\n\n // Either nothing was recorded, or a *different* start claims this scope\n // key: the previous span is superseded rather than merged into.\n const fresh: SpanRecord = {\n providerId: input.providerId,\n startEventId: input.eventId,\n startedAt: input.occurredAt,\n ...(input.parent === undefined ? {} : { parent: input.parent }),\n ...(input.attributes === undefined ? {} : { attributes: input.attributes }),\n };\n await stateStore.write(key, encodeRecord(fresh));\n return { status: \"recorded\", facts: factsOf(fresh) };\n });\n\n const recordEnd = (input: SpanEndInput): Promise<SpanEndResult> =>\n withOptionalSessionLock(stateStore, input.sessionId, async (): Promise<SpanEndResult> => {\n const key = keyFor(input);\n const decoded = await readRecord(key);\n\n if (decoded.kind === \"incompatible\" || decoded.kind === \"corrupt\") {\n const reason = decoded.kind === \"incompatible\" ? \"state-incompatible\" : \"state-corrupt\";\n return { status: \"orphaned\", reason, facts: { endedAt: input.occurredAt } };\n }\n if (decoded.kind === \"absent\") {\n // Remember the end anyway: a start that arrives late still deserves to\n // be paired rather than exported as a second orphan.\n const endOnly: SpanRecord = {\n providerId: input.providerId,\n endEventId: input.eventId,\n endedAt: input.occurredAt,\n // This end is about to be exported as an orphan under the scope's\n // canonical span id, so a start arriving later must not reuse it.\n exported: true,\n };\n await stateStore.write(key, encodeRecord(endOnly));\n return { status: \"orphaned\", reason: \"no-start-recorded\", facts: factsOf(endOnly) };\n }\n\n const existing = decoded.record;\n if (existing.providerId !== input.providerId) {\n return {\n status: \"orphaned\",\n reason: \"provider-mismatch\",\n facts: { endedAt: input.occurredAt },\n };\n }\n if (existing.endEventId === input.eventId) {\n // Idempotent replay: answer with the facts already on disk so the\n // re-exported span is byte-identical to the first one.\n return { status: \"duplicate\", facts: factsOf(existing) };\n }\n if (existing.endEventId !== undefined) {\n return {\n status: \"orphaned\",\n reason: \"already-closed\",\n facts: { endedAt: input.occurredAt },\n };\n }\n if (existing.startedAt === undefined) {\n const replaced: SpanRecord = {\n ...existing,\n endEventId: input.eventId,\n endedAt: input.occurredAt,\n exported: true,\n };\n await stateStore.write(key, encodeRecord(replaced));\n return { status: \"orphaned\", reason: \"no-start-recorded\", facts: factsOf(replaced) };\n }\n if (input.occurredAt - existing.startedAt > maxStartAgeMillis) {\n await stateStore.delete(key);\n return { status: \"orphaned\", reason: \"start-expired\", facts: { endedAt: input.occurredAt } };\n }\n\n const closed: SpanRecord = {\n ...existing,\n endEventId: input.eventId,\n endedAt: input.occurredAt,\n exported: true,\n };\n await stateStore.write(key, encodeRecord(closed));\n return {\n status: \"matched\",\n startedAt: existing.startedAt,\n durationMillis: Math.max(0, input.occurredAt - existing.startedAt),\n facts: factsOf(closed),\n };\n });\n\n const correlateGroup = async (group: BatchGroup): Promise<SpanCorrelation> => {\n const base = {\n providerId: group.providerId,\n sessionId: group.sessionId,\n ref: group.ref,\n } as const;\n const unpaired = (\n orphan: SpanOrphanClassification,\n facts: SpanCorrelationFacts,\n ): SpanCorrelation => ({\n ...base,\n pairing: \"unpaired\",\n orphan,\n // An unpaired span has no trustworthy start, so a start time is the one\n // fact it must not carry; everything else recovered is still true.\n ...correlationTimesOf(facts, { withStart: false }),\n });\n\n let startFacts: SpanCorrelationFacts | undefined;\n if (group.start !== undefined) {\n const parent = parentScopeRefOf(group.start);\n const result = await recordStart({\n sessionId: group.sessionId,\n providerId: group.providerId,\n scope: group.ref.family,\n scopeKey: group.ref.scopeKey,\n eventId: group.start.eventId,\n occurredAt: group.start.occurredAt,\n ...(parent === undefined ? {} : { parent }),\n attributes: startOnlySpanAttributes(group.start),\n });\n if (result.status === \"conflict\") {\n return unpaired(\"provider-mismatch\", {});\n }\n if (result.status === \"published\" && group.end === undefined) {\n // The end already exported this scope's span. Completing the record was\n // still worth doing (a redelivered end replays identical facts), but\n // emitting here would duplicate a span id already on the wire.\n return { ...unpaired(\"already-closed\", result.facts), disposition: \"defer\" };\n }\n startFacts = result.facts;\n }\n\n if (group.end === undefined) {\n const facts = startFacts ?? {};\n // A start whose end already landed (the racing-process case) closes a\n // complete span, even though only the start is in this batch.\n if (facts.endedAt !== undefined) {\n return {\n ...base,\n pairing: \"cross-process\",\n orphan: \"none\",\n disposition: \"emit\",\n ...correlationTimesOf(facts),\n };\n }\n // The end has not arrived. The start is durable now, so the end edge will\n // export one complete span under this scope's derived id; exporting a\n // zero-duration record here as well would put two records with that same id\n // on the wire, and OTLP cannot revise a span.\n return { ...unpaired(\"missing-end\", facts), disposition: \"defer\" };\n }\n\n const result = await recordEnd({\n sessionId: group.sessionId,\n providerId: group.providerId,\n scope: group.ref.family,\n scopeKey: group.ref.scopeKey,\n eventId: group.end.eventId,\n occurredAt: group.end.occurredAt,\n });\n\n if (result.status === \"orphaned\") {\n const orphan = orphanClassificationOf(result.reason);\n // `already-closed` means a *second, distinct* end for a scope whose first\n // end has already been exported under this scope's derived span id. Both\n // ends are real observations, so neither is dropped — but the second must\n // not reuse that id. Keying the discriminator on the end event id keeps a\n // redelivery of this same second end idempotent, since it recomputes the\n // same id rather than inventing a third.\n return orphan === \"already-closed\"\n ? {\n ...unpaired(orphan, result.facts),\n disposition: \"emit\",\n spanIdDiscriminator: group.end.eventId,\n }\n : { ...unpaired(orphan, result.facts), disposition: \"emit\" };\n }\n if (result.status === \"duplicate\" && result.facts.startedAt === undefined) {\n // A replayed end that never had a start is still an orphan.\n return { ...unpaired(\"missing-start\", result.facts), disposition: \"emit\" };\n }\n return {\n ...base,\n pairing: group.start === undefined ? \"cross-process\" : \"in-batch\",\n orphan: \"none\",\n disposition: \"emit\",\n ...correlationTimesOf(result.facts),\n };\n };\n\n const correlateBatch = async (\n events: readonly CanonicalEvent[],\n ): Promise<readonly SpanCorrelation[]> => {\n const groups = new Map<string, BatchGroup>();\n for (const event of events) {\n const ref = spanScopeRefOf(event);\n if (ref === undefined) {\n continue;\n }\n const providerId = event.provenance.providerId;\n const groupKey = [providerId, event.sessionId, ref.family, ref.scopeKey].join(\"\\u0000\");\n const group: BatchGroup = groups.get(groupKey) ?? {\n providerId,\n sessionId: event.sessionId,\n ref,\n };\n if (event.type.endsWith(\".start\")) {\n group.start = event;\n } else {\n group.end = event;\n }\n groups.set(groupKey, group);\n }\n\n const correlations: SpanCorrelation[] = [];\n for (const group of groups.values()) {\n try {\n correlations.push(await correlateGroup(group));\n } catch {\n // Fail open: an unreachable, locked, or unwritable state store costs a\n // span its pairing, never the whole export.\n //\n // A start whose record could not be written is the case that needs care.\n // It is *not* deferrable — deferring means \"the state store is holding\n // this, the end edge will publish it\", and here the state store is exactly\n // what failed. So it must be exported, and it must not use the scope's\n // canonical span id: nothing recorded this start, so a later end will\n // publish that id itself as an orphan, and reusing it would put two\n // records with one identity on the wire. Discriminating by the start's own\n // event id makes this record honest and collision-free.\n const unrecordedStart = group.start !== undefined && group.end === undefined;\n correlations.push({\n providerId: group.providerId,\n sessionId: group.sessionId,\n ref: group.ref,\n pairing: \"unpaired\",\n orphan: \"state-unavailable\",\n disposition: \"emit\",\n ...(unrecordedStart && group.start !== undefined\n ? { spanIdDiscriminator: group.start.eventId }\n : {}),\n });\n }\n }\n return correlations;\n };\n\n const cleanup = async (\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<SpanCleanupResult> => {\n const keys = await stateStore.keys(spanScanPrefix(options?.sessionId));\n const cap = options?.maxEntries ?? 1_000;\n const now = clock.now();\n let removed = 0;\n let scanned = 0;\n let expiredOpen = 0;\n for (const key of keys) {\n if (scanned >= cap) {\n break;\n }\n scanned += 1;\n const record = await stateStore.read(key);\n if (record !== undefined && now - record.updatedAt > maxAgeMillis) {\n // Classified before deletion: a record with a start and no end is a span\n // that will never be exported, which is worth counting rather than\n // discarding silently.\n if (record.value.kind === \"attributes\") {\n const decoded = decodeRecord(record.value.attributes);\n if (\n decoded.kind === \"present\" &&\n decoded.record.startedAt !== undefined &&\n decoded.record.endedAt === undefined\n ) {\n expiredOpen += 1;\n }\n }\n await stateStore.delete(key);\n removed += 1;\n }\n }\n return { removed, scanned, expiredOpen };\n };\n\n return { recordStart, recordEnd, correlateBatch, cleanup };\n};\n","import { z } from \"zod\";\n\nimport { tokenCountSchema } from \"./primitives.js\";\n\n/**\n * Whether an observation reports the change since the previous observation\n * (`delta`) or the running total for the session/generation (`cumulative`).\n *\n * The canonical model keeps temporality explicit rather than assuming one:\n * summing cumulative observations double-counts, and diffing delta observations\n * silently loses tokens.\n */\nexport const usageTemporalitySchema = z.enum([\"delta\", \"cumulative\"]);\nexport type UsageTemporality = z.infer<typeof usageTemporalitySchema>;\n\n/**\n * Whether the provider counts cache-creation tokens inside its input total or\n * reports them as a disjoint bucket.\n *\n * - `included-in-input`: `cacheCreationInputTokens` is a subset of `inputTokens`.\n * - `disjoint-from-input`: cache-creation tokens are billed in addition to\n * `inputTokens` and must be added when computing a total.\n * - `not-reported`: the provider exposes no cache-creation counter; the field is\n * pinned to zero.\n */\nexport const cacheCreationAccountingSchema = z.enum([\n \"included-in-input\",\n \"disjoint-from-input\",\n \"not-reported\",\n]);\nexport type CacheCreationAccounting = z.infer<typeof cacheCreationAccountingSchema>;\n\n/** Whether a provider-reported total agrees with the canonical computation. */\nexport const providerTotalAgreementSchema = z.enum([\"unreported\", \"agrees\", \"disagrees\"]);\nexport type ProviderTotalAgreement = z.infer<typeof providerTotalAgreementSchema>;\n\n/**\n * What an adapter reports, before normalization.\n *\n * `inputTokens` is *inclusive*: it counts every input token the provider\n * attributes to the call, including cache reads (and cache creation when the\n * provider folds it in). `outputTokens` is likewise inclusive of reasoning\n * output. Subset fields describe portions of those totals, never additions.\n */\nexport const usageReportSchema = z.strictObject({\n temporality: usageTemporalitySchema,\n /** Inclusive input tokens. */\n inputTokens: tokenCountSchema.optional(),\n /** Subset of `inputTokens` served from a prompt cache. */\n cachedInputTokens: tokenCountSchema.optional(),\n /** Tokens written to a prompt cache. */\n cacheCreationInputTokens: tokenCountSchema.optional(),\n /** Required when `cacheCreationInputTokens` is present and non-zero. */\n cacheCreationAccounting: cacheCreationAccountingSchema.optional(),\n /** Inclusive output tokens. */\n outputTokens: tokenCountSchema.optional(),\n /** Subset of `outputTokens` spent on reasoning. */\n reasoningOutputTokens: tokenCountSchema.optional(),\n /** Total exactly as the provider reported it, if it reported one. */\n providerTotalTokens: tokenCountSchema.optional(),\n});\nexport type UsageReport = z.infer<typeof usageReportSchema>;\n\n/**\n * Fully normalized usage.\n *\n * Derived fields (`uncachedInputTokens`, `totalTokens`,\n * `providerTotalAgreement`) are part of the schema and are re-checked on parse,\n * so an inconsistent object cannot exist. Construct values with\n * {@link normalizeUsage} rather than by hand.\n */\nexport const canonicalUsageSchema = z\n .strictObject({\n temporality: usageTemporalitySchema,\n inputTokens: tokenCountSchema,\n cachedInputTokens: tokenCountSchema,\n cacheCreationInputTokens: tokenCountSchema,\n cacheCreationAccounting: cacheCreationAccountingSchema,\n outputTokens: tokenCountSchema,\n reasoningOutputTokens: tokenCountSchema,\n /** Derived: input tokens that were neither cache reads nor cache writes. */\n uncachedInputTokens: tokenCountSchema,\n /** Derived: canonical billable total. */\n totalTokens: tokenCountSchema,\n providerTotalTokens: tokenCountSchema.optional(),\n providerTotalAgreement: providerTotalAgreementSchema,\n })\n .check((ctx) => {\n const usage = ctx.value;\n const push = (message: string): void => {\n ctx.issues.push({ code: \"custom\", input: usage, message });\n };\n\n if (usage.cachedInputTokens > usage.inputTokens) {\n push(\"cachedInputTokens must not exceed inputTokens (it is a subset)\");\n }\n if (usage.reasoningOutputTokens > usage.outputTokens) {\n push(\"reasoningOutputTokens must not exceed outputTokens (it is a subset)\");\n }\n if (usage.cacheCreationAccounting === \"not-reported\" && usage.cacheCreationInputTokens !== 0) {\n push(\"cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported\");\n }\n const creationInsideInput =\n usage.cacheCreationAccounting === \"included-in-input\" ? usage.cacheCreationInputTokens : 0;\n if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {\n push(\n \"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input\",\n );\n }\n const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;\n if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {\n push(`uncachedInputTokens must equal ${expectedUncached}`);\n }\n const creationOutsideInput =\n usage.cacheCreationAccounting === \"disjoint-from-input\" ? usage.cacheCreationInputTokens : 0;\n const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;\n if (usage.totalTokens !== expectedTotal) {\n push(`totalTokens must equal ${expectedTotal}`);\n }\n const expectedAgreement: ProviderTotalAgreement =\n usage.providerTotalTokens === undefined\n ? \"unreported\"\n : usage.providerTotalTokens === expectedTotal\n ? \"agrees\"\n : \"disagrees\";\n if (usage.providerTotalAgreement !== expectedAgreement) {\n push(`providerTotalAgreement must be ${expectedAgreement}`);\n }\n });\nexport type CanonicalUsage = z.infer<typeof canonicalUsageSchema>;\n\nexport type UsageNormalizationIssue = {\n readonly code:\n | \"invalid-report\"\n | \"cached-exceeds-input\"\n | \"reasoning-exceeds-output\"\n | \"cache-creation-exceeds-input\"\n | \"cache-creation-accounting-missing\";\n readonly message: string;\n};\n\nexport type UsageNormalizationResult =\n | { readonly status: \"ok\"; readonly usage: CanonicalUsage; readonly notes: readonly string[] }\n | { readonly status: \"invalid\"; readonly issues: readonly UsageNormalizationIssue[] };\n\n/**\n * Normalize a provider usage report into canonical usage.\n *\n * Deterministic rules:\n * 1. Absent counters default to `0`; `providerTotalTokens` stays absent.\n * 2. Non-integer, negative, or non-finite counters are rejected.\n * 3. A subset exceeding its total is rejected — never clamped — because\n * clamping would silently invent a billing story.\n * 4. `cacheCreationAccounting` defaults to `not-reported` when no cache-creation\n * tokens are reported, and is *required* when they are: guessing whether the\n * bucket is disjoint would mis-total every downstream cost calculation.\n * 5. A provider total that disagrees with the canonical total is preserved as\n * reported and flagged `disagrees`. Both numbers survive; neither is edited.\n */\nexport const normalizeUsage = (report: unknown): UsageNormalizationResult => {\n const parsed = usageReportSchema.safeParse(report);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map((issue) => ({\n code: \"invalid-report\" as const,\n message: `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n })),\n };\n }\n\n const input = parsed.data;\n const issues: UsageNormalizationIssue[] = [];\n const notes: string[] = [];\n\n const inputTokens = input.inputTokens ?? 0;\n const cachedInputTokens = input.cachedInputTokens ?? 0;\n const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;\n const outputTokens = input.outputTokens ?? 0;\n const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;\n\n let accounting: CacheCreationAccounting;\n if (cacheCreationInputTokens === 0) {\n accounting = input.cacheCreationAccounting ?? \"not-reported\";\n if (accounting !== \"not-reported\") {\n notes.push(\n `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`,\n );\n }\n } else if (input.cacheCreationAccounting === undefined) {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message:\n \"cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred\",\n });\n accounting = \"not-reported\";\n } else if (input.cacheCreationAccounting === \"not-reported\") {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message: \"cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens\",\n });\n accounting = \"not-reported\";\n } else {\n accounting = input.cacheCreationAccounting;\n }\n\n if (cachedInputTokens > inputTokens) {\n issues.push({\n code: \"cached-exceeds-input\",\n message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n if (reasoningOutputTokens > outputTokens) {\n issues.push({\n code: \"reasoning-exceeds-output\",\n message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`,\n });\n }\n\n const creationInsideInput = accounting === \"included-in-input\" ? cacheCreationInputTokens : 0;\n if (cachedInputTokens + creationInsideInput > inputTokens) {\n issues.push({\n code: \"cache-creation-exceeds-input\",\n message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const creationOutsideInput = accounting === \"disjoint-from-input\" ? cacheCreationInputTokens : 0;\n const totalTokens = inputTokens + creationOutsideInput + outputTokens;\n const providerTotalAgreement: ProviderTotalAgreement =\n input.providerTotalTokens === undefined\n ? \"unreported\"\n : input.providerTotalTokens === totalTokens\n ? \"agrees\"\n : \"disagrees\";\n\n if (providerTotalAgreement === \"disagrees\") {\n notes.push(\n `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`,\n );\n }\n\n const usage: CanonicalUsage = {\n temporality: input.temporality,\n inputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens,\n reasoningOutputTokens,\n uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,\n totalTokens,\n ...(input.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: input.providerTotalTokens }),\n providerTotalAgreement,\n };\n\n return { status: \"ok\", usage, notes };\n};\n\nexport class UsageNormalizationError extends Error {\n public readonly issues: readonly UsageNormalizationIssue[];\n\n public constructor(issues: readonly UsageNormalizationIssue[]) {\n super(`invalid usage report: ${issues.map((issue) => issue.message).join(\"; \")}`);\n this.name = \"UsageNormalizationError\";\n this.issues = issues;\n }\n}\n\n/** Convenience wrapper for call sites that treat invalid usage as a bug. */\nexport const normalizeUsageOrThrow = (report: unknown): CanonicalUsage => {\n const result = normalizeUsage(report);\n if (result.status === \"invalid\") {\n throw new UsageNormalizationError(result.issues);\n }\n return result.usage;\n};\n\nexport const EMPTY_DELTA_USAGE: CanonicalUsage = Object.freeze(\n normalizeUsageOrThrow({ temporality: \"delta\" }),\n);\n\nexport type UsageDeltaResult = {\n readonly usage: CanonicalUsage;\n /**\n * True when the current snapshot is smaller than the previous one on any\n * counter. That means the cumulative series restarted (new session, replayed\n * transcript, provider reset), so the current snapshot is emitted as the delta\n * instead of a negative difference.\n */\n readonly resetDetected: boolean;\n};\n\nconst requireCumulative = (usage: CanonicalUsage, label: string): void => {\n if (usage.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: `${label} must have cumulative temporality` },\n ]);\n }\n};\n\n/**\n * Convert two cumulative snapshots into a delta observation.\n *\n * Replay safety: re-processing the same snapshot yields an all-zero delta, and a\n * decreasing series is reported as a reset rather than a negative delta.\n * Accounting mode must match; mixing modes would make the subtraction meaningless.\n */\nexport const cumulativeToDelta = (\n previous: CanonicalUsage,\n current: CanonicalUsage,\n): UsageDeltaResult => {\n requireCumulative(previous, \"previous usage\");\n requireCumulative(current, \"current usage\");\n\n if (\n previous.cacheCreationAccounting !== current.cacheCreationAccounting &&\n previous.cacheCreationInputTokens !== 0 &&\n current.cacheCreationInputTokens !== 0\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot diff cumulative usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const resetDetected =\n current.inputTokens < previous.inputTokens ||\n current.cachedInputTokens < previous.cachedInputTokens ||\n current.cacheCreationInputTokens < previous.cacheCreationInputTokens ||\n current.outputTokens < previous.outputTokens ||\n current.reasoningOutputTokens < previous.reasoningOutputTokens;\n\n if (resetDetected) {\n return {\n usage: normalizeUsageOrThrow({ ...toReport(current), temporality: \"delta\" }),\n resetDetected: true,\n };\n }\n\n const usage = normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: current.inputTokens - previous.inputTokens,\n cachedInputTokens: current.cachedInputTokens - previous.cachedInputTokens,\n cacheCreationInputTokens:\n current.cacheCreationInputTokens - previous.cacheCreationInputTokens,\n cacheCreationAccounting: current.cacheCreationAccounting,\n outputTokens: current.outputTokens - previous.outputTokens,\n reasoningOutputTokens: current.reasoningOutputTokens - previous.reasoningOutputTokens,\n });\n\n return { usage, resetDetected: false };\n};\n\n/** Project canonical usage back onto the reported shape. */\nexport const toReport = (usage: CanonicalUsage): UsageReport => ({\n temporality: usage.temporality,\n inputTokens: usage.inputTokens,\n cachedInputTokens: usage.cachedInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n cacheCreationAccounting: usage.cacheCreationAccounting,\n outputTokens: usage.outputTokens,\n reasoningOutputTokens: usage.reasoningOutputTokens,\n ...(usage.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: usage.providerTotalTokens }),\n});\n\n/**\n * Add two delta observations. Cumulative usage is never summed, because two\n * running totals do not compose.\n */\nexport const addUsage = (a: CanonicalUsage, b: CanonicalUsage): CanonicalUsage => {\n if (a.temporality !== \"delta\" || b.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"only delta usage may be summed\" },\n ]);\n }\n const accounting =\n a.cacheCreationInputTokens === 0 && a.cacheCreationAccounting === \"not-reported\"\n ? b.cacheCreationAccounting\n : b.cacheCreationInputTokens === 0 && b.cacheCreationAccounting === \"not-reported\"\n ? a.cacheCreationAccounting\n : a.cacheCreationAccounting;\n\n if (\n a.cacheCreationInputTokens !== 0 &&\n b.cacheCreationInputTokens !== 0 &&\n a.cacheCreationAccounting !== b.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot sum usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n a.providerTotalTokens === undefined && b.providerTotalTokens === undefined\n ? undefined\n : (a.providerTotalTokens ?? 0) + (b.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: a.inputTokens + b.inputTokens,\n cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,\n cacheCreationInputTokens: a.cacheCreationInputTokens + b.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: a.outputTokens + b.outputTokens,\n reasoningOutputTokens: a.reasoningOutputTokens + b.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n","import {\n UsageNormalizationError,\n normalizeUsageOrThrow,\n type CanonicalUsage,\n} from \"../model/usage.js\";\nimport type { Attributes } from \"../model/primitives.js\";\nimport type { Clock, StateStore } from \"../runtime/ports.js\";\nimport { withOptionalSessionLock } from \"../state/store.js\";\nimport { rollupEpochKey, rollupEpochScanPrefix, rollupScanPrefix, rollupUsageKey } from \"./keys.js\";\n\nexport type UsageAccumulatorKey = {\n readonly sessionId: string;\n readonly scope: string;\n readonly scopeKey: string;\n};\n\nexport type UsageAccumulatorSnapshot = {\n readonly total: CanonicalUsage;\n /** Increments every time {@link UsageAccumulator.recordReset} is called for this key. */\n readonly epoch: number;\n};\n\nexport type RollupCleanupResult = { readonly removed: number; readonly scanned: number };\n\n/**\n * Which delivery an accumulation belongs to, and which of its observations this is.\n *\n * Supplying it makes the accumulation idempotent for *that delivery*: a second\n * application of the same `(callbackId, ordinal)` is a no-op that returns the\n * current total. Omitting it keeps the old unconditional behaviour, which is right\n * for a caller that has no delivery identity to key on — there is nothing to\n * recognize a repeat by, and refusing to accumulate would lose a real observation.\n *\n * `callbackId` must be an opaque digest, not a raw host or provider id: it is\n * written into a state record.\n */\nexport type DeliveryStamp = {\n readonly callbackId: string;\n /** Zero-based index of this observation within the delivery, per rollup key. */\n readonly ordinal: number;\n};\n\nexport type AccumulateOptions = { readonly delivery?: DeliveryStamp };\n\n/**\n * Rolls a stream of `delta` usage observations up into a running `cumulative`\n * total per scope, independent of the orchestrator's own per-scope\n * cumulative-to-delta baseline (`docs/usage-semantics.md`) — that baseline\n * answers \"what changed since last time\"; this answers \"what is the running\n * total\", which a diagnostics view or a parent scope (tool -> generation ->\n * session) needs and the core does not compute.\n *\n * A provider counter can restart mid-session (a process restart, a replayed\n * transcript). Rather than let a smaller cumulative total silently deflate the\n * running rollup, {@link UsageAccumulator.recordReset} starts a new epoch: the\n * total resets to zero and the epoch number increments, so a downstream\n * consumer can tell \"the counter restarted\" from \"usage actually decreased\"\n * and never sums across the boundary as if it were one continuous series.\n */\nexport interface UsageAccumulator {\n /**\n * Fold `delta` into the running total for `key`.\n *\n * With `options.delivery`, folding is idempotent for that delivery: a redelivered\n * callback whose claim was reclaimed or superseded re-derives the same delta and\n * would otherwise count it twice. The marker lives in the same record as the total\n * it describes, so the check and the write are one atomic operation — which is the\n * only reason this is expressible without a multi-key transaction. What it does\n * *not* cover is a delivery whose marker a later, different delivery has since\n * overwritten: only the most recent delivery per rollup key is recognizable, which\n * is exactly the retry window and nothing beyond it.\n */\n accumulateDelta(\n key: UsageAccumulatorKey,\n delta: CanonicalUsage,\n options?: AccumulateOptions,\n ): Promise<UsageAccumulatorSnapshot>;\n /** Start a new epoch. Idempotent per delivery when `options.delivery` is given. */\n recordReset(key: UsageAccumulatorKey, options?: AccumulateOptions): Promise<{ readonly epoch: number }>;\n read(key: UsageAccumulatorKey): Promise<UsageAccumulatorSnapshot | undefined>;\n cleanup(\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<RollupCleanupResult>;\n}\n\nexport type UsageAccumulatorDependencies = {\n readonly stateStore: StateStore;\n readonly clock: Clock;\n};\n\nconst EMPTY_CUMULATIVE_USAGE: CanonicalUsage = normalizeUsageOrThrow({ temporality: \"cumulative\" });\n\nconst combineCumulativeWithDelta = (total: CanonicalUsage, delta: CanonicalUsage): CanonicalUsage => {\n if (total.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"usage rollup total must have cumulative temporality\" },\n ]);\n }\n if (delta.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"usage accumulator only accepts delta observations\" },\n ]);\n }\n\n const accounting =\n total.cacheCreationInputTokens === 0 && total.cacheCreationAccounting === \"not-reported\"\n ? delta.cacheCreationAccounting\n : delta.cacheCreationInputTokens === 0 && delta.cacheCreationAccounting === \"not-reported\"\n ? total.cacheCreationAccounting\n : total.cacheCreationAccounting;\n\n if (\n total.cacheCreationInputTokens !== 0 &&\n delta.cacheCreationInputTokens !== 0 &&\n total.cacheCreationAccounting !== delta.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot roll up usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n total.providerTotalTokens === undefined && delta.providerTotalTokens === undefined\n ? undefined\n : (total.providerTotalTokens ?? 0) + (delta.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"cumulative\",\n inputTokens: total.inputTokens + delta.inputTokens,\n cachedInputTokens: total.cachedInputTokens + delta.cachedInputTokens,\n cacheCreationInputTokens: total.cacheCreationInputTokens + delta.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: total.outputTokens + delta.outputTokens,\n reasoningOutputTokens: total.reasoningOutputTokens + delta.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n\nexport const createUsageAccumulator = (deps: UsageAccumulatorDependencies): UsageAccumulator => {\n const { stateStore, clock } = deps;\n\n /**\n * The epoch record's own delivery marker.\n *\n * Kept in the epoch record for the same reason the total's marker is kept in the\n * total: one write, so the counter and the statement about who moved it cannot\n * disagree. The epoch record is an `attributes` value, so the two fields are\n * flat rather than nested.\n */\n const readEpochMarker = (\n attributes: Attributes,\n ): { readonly callbackId: string; readonly applications: number } | undefined => {\n const callbackId = attributes.resetDelivery;\n const applications = attributes.resetApplications;\n if (\n typeof callbackId !== \"string\" ||\n callbackId.length === 0 ||\n typeof applications !== \"number\" ||\n !Number.isInteger(applications) ||\n applications < 1\n ) {\n return undefined;\n }\n return { callbackId, applications };\n };\n\n const readEpoch = async (key: UsageAccumulatorKey): Promise<number> => {\n const record = await stateStore.read(rollupEpochKey(key.sessionId, key.scope, key.scopeKey));\n if (record?.value.kind === \"attributes\" && typeof record.value.attributes.epoch === \"number\") {\n return record.value.attributes.epoch;\n }\n return 0;\n };\n\n /**\n * Whether this delivery's observation number `ordinal` is already folded in.\n *\n * The comparison is `<` rather than `===` because observations are applied in\n * order: `applications` is the count folded in so far, so any ordinal below it has\n * been seen. A marker naming a *different* delivery means this rollup has moved on\n * and nothing can be recognized.\n */\n const alreadyApplied = (\n marker: { readonly callbackId: string; readonly applications: number } | undefined,\n delivery: DeliveryStamp | undefined,\n ): boolean =>\n delivery !== undefined &&\n marker !== undefined &&\n marker.callbackId === delivery.callbackId &&\n delivery.ordinal < marker.applications;\n\n const markerFor = (\n delivery: DeliveryStamp | undefined,\n ): { readonly appliedDelivery?: { readonly callbackId: string; readonly applications: number } } =>\n delivery === undefined\n ? {}\n : {\n appliedDelivery: { callbackId: delivery.callbackId, applications: delivery.ordinal + 1 },\n };\n\n const accumulateDelta = (\n key: UsageAccumulatorKey,\n delta: CanonicalUsage,\n options?: AccumulateOptions,\n ): Promise<UsageAccumulatorSnapshot> =>\n withOptionalSessionLock(stateStore, key.sessionId, async (): Promise<UsageAccumulatorSnapshot> => {\n const usageKey = rollupUsageKey(key.sessionId, key.scope, key.scopeKey);\n const existing = await stateStore.read(usageKey);\n const previousTotal =\n existing?.value.kind === \"usage-cumulative\" ? existing.value.usage : EMPTY_CUMULATIVE_USAGE;\n\n if (\n existing?.value.kind === \"usage-cumulative\" &&\n alreadyApplied(existing.value.appliedDelivery, options?.delivery)\n ) {\n // This exact observation of this exact delivery is already in the total.\n // Reporting the total unchanged is the honest answer: the caller asked for\n // the running figure after its delta, and that is what this is.\n return { total: previousTotal, epoch: await readEpoch(key) };\n }\n\n const total = combineCumulativeWithDelta(previousTotal, delta);\n await stateStore.write(usageKey, {\n kind: \"usage-cumulative\",\n usage: total,\n ...markerFor(options?.delivery),\n });\n return { total, epoch: await readEpoch(key) };\n });\n\n const recordReset = (\n key: UsageAccumulatorKey,\n options?: AccumulateOptions,\n ): Promise<{ readonly epoch: number }> =>\n withOptionalSessionLock(stateStore, key.sessionId, async (): Promise<{ readonly epoch: number }> => {\n const epochKey = rollupEpochKey(key.sessionId, key.scope, key.scopeKey);\n const existingEpoch = await stateStore.read(epochKey);\n const marker =\n existingEpoch?.value.kind === \"attributes\"\n ? readEpochMarker(existingEpoch.value.attributes)\n : undefined;\n\n if (alreadyApplied(marker, options?.delivery)) {\n // A replayed reset must not open a second epoch: the epoch number is what a\n // consumer uses to refuse summing across a counter restart, and inflating it\n // twice for one restart makes a real series look like two.\n return { epoch: await readEpoch(key) };\n }\n\n const epoch = (await readEpoch(key)) + 1;\n const applied = markerFor(options?.delivery).appliedDelivery;\n await stateStore.write(epochKey, {\n kind: \"attributes\",\n attributes: {\n epoch,\n ...(applied === undefined\n ? {}\n : { resetDelivery: applied.callbackId, resetApplications: applied.applications }),\n },\n });\n await stateStore.delete(rollupUsageKey(key.sessionId, key.scope, key.scopeKey));\n return { epoch };\n });\n\n const read = async (key: UsageAccumulatorKey): Promise<UsageAccumulatorSnapshot | undefined> => {\n const record = await stateStore.read(rollupUsageKey(key.sessionId, key.scope, key.scopeKey));\n if (record?.value.kind !== \"usage-cumulative\") {\n return undefined;\n }\n return { total: record.value.usage, epoch: await readEpoch(key) };\n };\n\n const cleanup = async (\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<RollupCleanupResult> => {\n const cap = options?.maxEntries ?? 1_000;\n const now = clock.now();\n let removed = 0;\n let scanned = 0;\n\n const sweep = async (keys: readonly string[]): Promise<void> => {\n for (const key of keys) {\n if (scanned >= cap) {\n return;\n }\n scanned += 1;\n const record = await stateStore.read(key);\n if (record !== undefined && now - record.updatedAt > maxAgeMillis) {\n await stateStore.delete(key);\n removed += 1;\n }\n }\n };\n\n await sweep(await stateStore.keys(rollupScanPrefix(options?.sessionId)));\n await sweep(await stateStore.keys(rollupEpochScanPrefix(options?.sessionId)));\n return { removed, scanned };\n };\n\n return { accumulateDelta, recordReset, read, cleanup };\n};\n","import { createHash } from \"node:crypto\";\n\nimport type { ContentFact, ContentKind, ContentRole } from \"../model/content.js\";\nimport { isValidExtensionKey } from \"../model/extensions.js\";\nimport {\n attributeValueSchema,\n MAX_ATTRIBUTE_ARRAY_LENGTH,\n MAX_ATTRIBUTE_STRING_LENGTH,\n type AttributePrimitive,\n type Attributes,\n type AttributeValue,\n} from \"../model/primitives.js\";\nimport {\n CONTENT_MODE_DISCLOSURE,\n resolvePrivacyPolicy,\n type PrivacyLimits,\n type PrivacyPolicy,\n} from \"./policy.js\";\n\nexport type SanitizedValue =\n | string\n | number\n | boolean\n | null\n | readonly SanitizedValue[]\n | { readonly [key: string]: SanitizedValue };\n\nexport type SanitizeStats = {\n readonly truncatedStrings: number;\n readonly truncatedArrays: number;\n readonly truncatedObjects: number;\n readonly redactedKeys: number;\n readonly depthExceeded: number;\n readonly droppedValues: number;\n readonly circularReferences: number;\n};\n\nexport type SanitizeResult = {\n readonly value: SanitizedValue;\n readonly stats: SanitizeStats;\n};\n\nexport type DescribeContentInput = {\n readonly kind: ContentKind;\n readonly text: string;\n readonly role?: ContentRole;\n readonly label?: string;\n};\n\nexport type DescribeStructuredInput = {\n readonly kind: ContentKind;\n readonly value: unknown;\n readonly role?: ContentRole;\n readonly label?: string;\n};\n\nexport type SanitizeExtensionsResult = {\n readonly extensions: Record<string, AttributeValue>;\n readonly droppedKeys: readonly string[];\n};\n\n/**\n * Single point through which every piece of potentially sensitive data passes.\n *\n * Provider adapters receive this service and are expected to describe content\n * with it rather than copying text into events themselves. That keeps the\n * disclosure decision in one auditable place.\n */\nexport interface PrivacyService {\n readonly policy: PrivacyPolicy;\n /** Notes about deterministic policy downgrades applied at construction. */\n readonly policyNotes: readonly string[];\n /** Stable salted digest, formatted `sha256:<hex>`. */\n hash(value: string): string;\n /** Opaque namespaced handle suitable for a workspace or resource id. */\n deriveOpaqueId(namespace: string, value: string): string;\n describeContent(input: DescribeContentInput): ContentFact;\n /**\n * A content fact for a kind the event can carry when the provider sent no\n * text. Distinct from describing an empty string: there is nothing to\n * disclose under any content mode, so the fact is always omitted.\n */\n describeUnavailableContent(input: Omit<DescribeContentInput, \"text\">): ContentFact;\n describeStructured(input: DescribeStructuredInput): ContentFact;\n isSecretKey(key: string): boolean;\n sanitizeStructured(value: unknown): SanitizeResult;\n /** Attribute-safe projection of a sanitized value, with dotted paths. */\n flattenToAttributes(value: SanitizedValue, prefix: string): Attributes;\n sanitizeAttributes(value: Readonly<Record<string, unknown>>): Attributes;\n sanitizeExtensions(value: Readonly<Record<string, unknown>>): SanitizeExtensionsResult;\n /** Bound a string to the policy limit, reporting whether it was cut. */\n boundString(value: string): { readonly text: string; readonly truncated: boolean };\n}\n\nconst compilePatterns = (sources: readonly string[], flags: string): readonly RegExp[] => {\n const compiled: RegExp[] = [];\n for (const source of sources) {\n try {\n compiled.push(new RegExp(source, flags));\n } catch {\n // An unusable pattern must not disable the whole privacy service; the\n // remaining patterns still apply. Skipping is the conservative choice for\n // key patterns only because a bad pattern would otherwise match nothing\n // anyway.\n continue;\n }\n }\n return compiled;\n};\n\nconst codePointLength = (value: string): number => [...value].length;\n\nconst isSanitizedArray = (value: SanitizedValue): value is readonly SanitizedValue[] =>\n Array.isArray(value);\n\nconst sliceCodePoints = (value: string, max: number): string => {\n if (max <= 0) {\n return \"\";\n }\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\nconst stableStringify = (value: unknown): string => {\n const seen = new WeakSet<object>();\n const walk = (input: unknown): string => {\n if (input === null) {\n return \"null\";\n }\n if (typeof input === \"string\") {\n return JSON.stringify(input);\n }\n if (typeof input === \"number\") {\n return Number.isFinite(input) ? JSON.stringify(input) : \"null\";\n }\n if (typeof input === \"boolean\") {\n return input ? \"true\" : \"false\";\n }\n if (typeof input === \"bigint\") {\n return JSON.stringify(input.toString());\n }\n if (typeof input !== \"object\") {\n return \"null\";\n }\n if (seen.has(input)) {\n return '\"<circular>\"';\n }\n seen.add(input);\n if (Array.isArray(input)) {\n return `[${input.map((entry) => walk(entry)).join(\",\")}]`;\n }\n const record = input as Record<string, unknown>;\n const keys = Object.keys(record).sort();\n return `{${keys\n .map((key) => `${JSON.stringify(key)}:${walk(record[key])}`)\n .join(\",\")}}`;\n };\n return walk(value);\n};\n\ntype MutableStats = {\n truncatedStrings: number;\n truncatedArrays: number;\n truncatedObjects: number;\n redactedKeys: number;\n depthExceeded: number;\n droppedValues: number;\n circularReferences: number;\n};\n\nconst emptyStats = (): MutableStats => ({\n truncatedStrings: 0,\n truncatedArrays: 0,\n truncatedObjects: 0,\n redactedKeys: 0,\n depthExceeded: 0,\n droppedValues: 0,\n circularReferences: 0,\n});\n\nexport const createPrivacyService = (policyInput: PrivacyPolicy): PrivacyService => {\n const { policy, notes } = resolvePrivacyPolicy(policyInput);\n const limits: PrivacyLimits = policy.limits;\n const secretKeyPatterns = compilePatterns(policy.secretKeyPatterns, \"i\");\n const secretValuePatterns = compilePatterns(policy.secretValuePatterns, \"g\");\n\n const hash = (value: string): string =>\n `sha256:${createHash(\"sha256\").update(policy.hashSalt).update(\"\\0\").update(value, \"utf8\").digest(\"hex\")}`;\n\n const isSecretKey = (key: string): boolean =>\n secretKeyPatterns.some((pattern) => pattern.test(key));\n\n const boundString = (value: string): { text: string; truncated: boolean } => {\n const length = codePointLength(value);\n if (length <= limits.maxStringLength) {\n return { text: value, truncated: false };\n }\n return { text: sliceCodePoints(value, limits.maxStringLength), truncated: true };\n };\n\n const redactSecretSpans = (value: string): { text: string; count: number } => {\n let count = 0;\n let text = value;\n for (const pattern of secretValuePatterns) {\n text = text.replace(new RegExp(pattern.source, pattern.flags), () => {\n count += 1;\n return policy.redactionPlaceholder;\n });\n }\n return { text, count };\n };\n\n const maskText = (value: string): string =>\n Array.from(value, (char) => (/\\s/.test(char) ? char : policy.maskCharacter)).join(\"\");\n\n const disclose = (\n original: string,\n ): { text: string | undefined; truncated: boolean; secretsRedacted: number } => {\n switch (policy.contentMode) {\n case \"omit\":\n return { text: undefined, truncated: false, secretsRedacted: 0 };\n case \"mask\": {\n const bounded = boundString(original);\n return { text: maskText(bounded.text), truncated: bounded.truncated, secretsRedacted: 0 };\n }\n case \"redact\": {\n const redacted = redactSecretSpans(original);\n const bounded = boundString(redacted.text);\n return {\n text: bounded.text,\n truncated: bounded.truncated,\n secretsRedacted: redacted.count,\n };\n }\n case \"raw\": {\n const bounded = boundString(original);\n return { text: bounded.text, truncated: bounded.truncated, secretsRedacted: 0 };\n }\n }\n };\n\n const describeText = (input: DescribeContentInput): ContentFact => {\n const disclosed = disclose(input.text);\n return {\n kind: input.kind,\n ...(input.role === undefined ? {} : { role: input.role }),\n characterLength: codePointLength(input.text),\n byteLength: Buffer.byteLength(input.text, \"utf8\"),\n contentHash: hash(input.text),\n disclosure: CONTENT_MODE_DISCLOSURE[policy.contentMode],\n ...(disclosed.text === undefined ? {} : { text: disclosed.text }),\n truncated: disclosed.truncated,\n secretsRedacted: disclosed.secretsRedacted,\n ...(input.label === undefined ? {} : { label: input.label }),\n };\n };\n\n const sanitizeValue = (value: unknown, depth: number, stats: MutableStats, seen: WeakSet<object>): SanitizedValue => {\n if (value === null) {\n return null;\n }\n switch (typeof value) {\n case \"string\": {\n const bounded = boundString(value);\n if (bounded.truncated) {\n stats.truncatedStrings += 1;\n }\n return bounded.text;\n }\n case \"number\":\n if (!Number.isFinite(value)) {\n stats.droppedValues += 1;\n return null;\n }\n return value;\n case \"boolean\":\n return value;\n case \"bigint\":\n return value.toString();\n case \"undefined\":\n case \"function\":\n case \"symbol\":\n stats.droppedValues += 1;\n return null;\n default:\n break;\n }\n\n if (depth >= limits.maxDepth) {\n stats.depthExceeded += 1;\n return \"<depth-exceeded>\";\n }\n if (seen.has(value)) {\n stats.circularReferences += 1;\n return \"<circular>\";\n }\n seen.add(value);\n\n if (Array.isArray(value)) {\n const entries = value.slice(0, limits.maxArrayLength);\n if (value.length > limits.maxArrayLength) {\n stats.truncatedArrays += 1;\n }\n return entries.map((entry) => sanitizeValue(entry, depth + 1, stats, seen));\n }\n\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const retained = keys.slice(0, limits.maxObjectKeys);\n if (keys.length > limits.maxObjectKeys) {\n stats.truncatedObjects += 1;\n }\n const result: Record<string, SanitizedValue> = {};\n for (const key of retained) {\n if (isSecretKey(key)) {\n stats.redactedKeys += 1;\n result[key] = policy.redactionPlaceholder;\n continue;\n }\n result[key] = sanitizeValue(record[key], depth + 1, stats, seen);\n }\n return result;\n };\n\n const sanitizeStructured = (value: unknown): SanitizeResult => {\n const stats = emptyStats();\n const sanitized = sanitizeValue(value, 0, stats, new WeakSet<object>());\n return { value: sanitized, stats };\n };\n\n const toAttributePrimitive = (value: SanitizedValue): AttributePrimitive | undefined => {\n if (typeof value === \"string\") {\n return value.slice(0, MAX_ATTRIBUTE_STRING_LENGTH);\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n return undefined;\n };\n\n const flattenToAttributes = (value: SanitizedValue, prefix: string): Attributes => {\n const attributes: Record<string, AttributeValue> = {};\n const walk = (current: SanitizedValue, path: string): void => {\n if (\n typeof current === \"string\" ||\n typeof current === \"number\" ||\n typeof current === \"boolean\"\n ) {\n const primitive = toAttributePrimitive(current);\n if (primitive !== undefined) {\n attributes[path] = primitive;\n }\n return;\n }\n if (current === null) {\n return;\n }\n if (isSanitizedArray(current)) {\n const primitives: AttributePrimitive[] = [];\n let uniform = true;\n for (const entry of current) {\n const entryPrimitive = toAttributePrimitive(entry);\n if (entryPrimitive === undefined) {\n uniform = false;\n break;\n }\n primitives.push(entryPrimitive);\n }\n if (uniform) {\n attributes[path] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);\n return;\n }\n for (const [index, entry] of current.entries()) {\n walk(entry, `${path}.${index}`);\n }\n return;\n }\n for (const [key, entry] of Object.entries(current)) {\n walk(entry, path === \"\" ? key : `${path}.${key}`);\n }\n };\n walk(value, prefix);\n return attributes;\n };\n\n const sanitizeAttributes = (value: Readonly<Record<string, unknown>>): Attributes => {\n const attributes: Record<string, AttributeValue> = {};\n for (const [key, entry] of Object.entries(value)) {\n if (isSecretKey(key)) {\n attributes[key] = policy.redactionPlaceholder;\n continue;\n }\n const sanitized = sanitizeStructured(entry).value;\n const primitive = toAttributePrimitive(sanitized);\n if (primitive !== undefined) {\n attributes[key] = primitive;\n continue;\n }\n const flattened = flattenToAttributes(sanitized, key);\n Object.assign(attributes, flattened);\n }\n return attributes;\n };\n\n const sanitizeExtensions = (\n value: Readonly<Record<string, unknown>>,\n ): SanitizeExtensionsResult => {\n const extensions: Record<string, AttributeValue> = {};\n const droppedKeys: string[] = [];\n for (const [key, entry] of Object.entries(value)) {\n if (!isValidExtensionKey(key)) {\n droppedKeys.push(key);\n continue;\n }\n if (isSecretKey(key)) {\n extensions[key] = policy.redactionPlaceholder;\n continue;\n }\n const sanitized = sanitizeStructured(entry).value;\n const candidate = attributeValueSchema.safeParse(sanitized);\n if (candidate.success) {\n extensions[key] = candidate.data;\n } else {\n droppedKeys.push(key);\n }\n }\n return { extensions, droppedKeys };\n };\n\n return {\n policy,\n policyNotes: notes,\n hash,\n deriveOpaqueId: (namespace: string, value: string): string =>\n hash(`${namespace}\\0${value}`),\n describeContent: describeText,\n describeUnavailableContent: (input: Omit<DescribeContentInput, \"text\">): ContentFact => ({\n kind: input.kind,\n ...(input.role === undefined ? {} : { role: input.role }),\n characterLength: 0,\n byteLength: 0,\n contentHash: hash(\"\"),\n disclosure: \"omitted\",\n truncated: false,\n secretsRedacted: 0,\n ...(input.label === undefined ? {} : { label: input.label }),\n }),\n describeStructured: (input: DescribeStructuredInput): ContentFact => {\n const serialized = stableStringify(input.value);\n const sanitized = sanitizeStructured(input.value);\n const base = describeText({\n kind: input.kind,\n text: serialized,\n ...(input.role === undefined ? {} : { role: input.role }),\n ...(input.label === undefined ? {} : { label: input.label }),\n });\n if (base.text === undefined) {\n return base;\n }\n // Disclose the sanitized projection rather than the raw serialization, so\n // secret-keyed values never appear even in `raw` mode.\n const disclosed = disclose(stableStringify(sanitized.value));\n return {\n ...base,\n ...(disclosed.text === undefined ? {} : { text: disclosed.text }),\n truncated: base.truncated || disclosed.truncated,\n secretsRedacted: disclosed.secretsRedacted + sanitized.stats.redactedKeys,\n };\n },\n isSecretKey,\n sanitizeStructured,\n flattenToAttributes,\n sanitizeAttributes,\n sanitizeExtensions,\n boundString,\n };\n};\n","import { z } from \"zod\";\n\nimport { attributeValueSchema, type AttributeValue } from \"./primitives.js\";\n\n/**\n * Extension keys must be namespaced: at least one dot-separated segment before\n * the leaf, e.g. `acme.deployment-tier`. Namespacing keeps provider- and\n * consumer-specific fields from colliding with core fields or each other.\n */\nexport const EXTENSION_KEY_PATTERN =\n /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;\n\n/** Namespaces owned by the core model; extensions may not use them. */\nexport const RESERVED_EXTENSION_NAMESPACES: readonly string[] = Object.freeze([\n \"otelhook\",\n \"otel\",\n \"telemetry\",\n]);\n\nexport const MAX_EXTENSION_ENTRIES = 64;\n\nexport const extensionKeyNamespace = (key: string): string => key.slice(0, key.indexOf(\".\"));\n\nexport const isReservedExtensionNamespace = (key: string): boolean =>\n RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));\n\nexport const isValidExtensionKey = (key: string): boolean =>\n EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);\n\n/**\n * Namespaced extension bag.\n *\n * Values are restricted to attribute primitives, so extensions cannot carry\n * nested provider payloads.\n */\nexport const extensionsSchema = z\n .record(z.string(), attributeValueSchema)\n .check((ctx) => {\n const keys = Object.keys(ctx.value);\n if (keys.length > MAX_EXTENSION_ENTRIES) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`,\n });\n }\n for (const key of keys) {\n if (!EXTENSION_KEY_PATTERN.test(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. \"acme.tier\"`,\n });\n continue;\n }\n if (isReservedExtensionNamespace(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`,\n });\n }\n }\n });\n\nexport type Extensions = Record<string, AttributeValue>;\n\nexport const EMPTY_EXTENSIONS: Extensions = Object.freeze({});\n\nexport const emptyExtensions = (): Extensions => ({});\n","import { z } from \"zod\";\n\nimport 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 { epochMillisSchema, type EpochMillis } from \"../model/primitives.js\";\nimport type { Clock } from \"./ports.js\";\n\n/** Clock backed by the host process. */\nexport const createSystemClock = (): Clock => ({\n now: (): EpochMillis => epochMillisSchema.parse(Date.now()),\n monotonicMillis: (): number => Number(process.hrtime.bigint() / 1_000_000n),\n});\n\nexport type FixedClockOptions = {\n readonly startMillis?: number;\n /** Milliseconds added to the wall clock on each `now()` call. */\n readonly tickMillis?: number;\n};\n\n/**\n * Deterministic clock for tests.\n *\n * `advance` moves both readings together so duration arithmetic stays coherent.\n */\nexport interface FixedClock extends Clock {\n advance(millis: number): void;\n set(millis: number): void;\n}\n\nexport const createFixedClock = (options: FixedClockOptions = {}): FixedClock => {\n let wall = options.startMillis ?? 1_700_000_000_000;\n let monotonic = 0;\n const tick = options.tickMillis ?? 0;\n\n return {\n now: (): EpochMillis => {\n const current = wall;\n wall += tick;\n monotonic += tick;\n return epochMillisSchema.parse(current);\n },\n monotonicMillis: (): number => monotonic,\n advance: (millis: number): void => {\n wall += millis;\n monotonic += millis;\n },\n set: (millis: number): void => {\n wall = millis;\n },\n };\n};\n","import { z } from \"zod\";\n\nimport { DEFAULT_CONFIG, type OtelHookConfig } from \"../config/schema.js\";\nimport {\n createErrorInfo,\n errorInfoFromThrown,\n type AttributionOutcome,\n type AttributionReason,\n type OtelHookErrorInfo,\n} from \"../errors/index.js\";\nimport {\n isContentFactConsistent,\n isUnavailableContentFact,\n type ContentFact,\n} from \"../model/content.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport {\n resolveInvocationIdentity,\n sourceProvenanceSchema,\n unknownWorkspaceIdentity,\n type IdentityClaim,\n type InvocationIdentity,\n type WorkspaceIdentity,\n} from \"../model/identity.js\";\nimport {\n type DetectionConfidence,\n type EventId,\n type ResolvedProviderId,\n type SourceTransport,\n} from \"../model/primitives.js\";\nimport {\n cumulativeToDelta,\n normalizeUsage,\n toReport,\n type CanonicalUsage,\n type UsageTemporality,\n} from \"../model/usage.js\";\nimport { CANONICAL_SCHEMA_VERSION } from \"../model/version.js\";\nimport { CONTENT_MODE_DISCLOSURE } from \"../privacy/policy.js\";\nimport { createPrivacyService, type PrivacyService } from \"../privacy/service.js\";\nimport {\n readDeliveryClaim,\n readDeliveryGap,\n SILENT_HOOK_RESPONSE,\n type ProviderAdapter,\n type ProviderContext,\n type ProviderDetection,\n type ProviderHookResponse,\n} from \"../providers/adapter.js\";\nimport { createProviderRegistry, BUILT_IN_PROVIDERS, type ProviderRegistry } from \"../providers/registry.js\";\nimport { createSystemClock } from \"./clock.js\";\nimport { resolveDeliveryIdentity, type DeliveryResolution } from \"./delivery.js\";\nimport { createDeterministicIdGenerator } from \"./ids.js\";\nimport { createNullLogger } from \"./logger.js\";\nimport type { Clock, IdGenerator, Logger, StateStore, TelemetrySink } from \"./ports.js\";\nimport { isStateLockContention, withOptionalSessionLock } from \"../state/store.js\";\n\nexport const usageScopeSchema = z.enum([\"session\", \"generation\", \"subagent\"]);\nexport type UsageScope = z.infer<typeof usageScopeSchema>;\n\n/**\n * Which series a provider's cumulative counters accumulate over. Mirrors\n * `ProviderCapabilities.cumulativeUsageSeries`, defaulting to `event-scope`\n * for the adapters that do not declare one.\n */\nexport type CumulativeUsageSeries = \"event-scope\" | \"session-lifetime\";\n\n/**\n * Delta usage derived for one event.\n *\n * Events keep whatever the provider reported. Deltas are produced alongside them\n * rather than rewritten into them, so a cumulative report and its derived delta\n * are both auditable.\n */\nexport type UsageObservation = {\n readonly eventId: EventId;\n readonly sequence: number;\n readonly scope: UsageScope;\n readonly scopeKey: string;\n readonly reportedTemporality: UsageTemporality;\n readonly delta: CanonicalUsage;\n /** True when the cumulative series restarted; see `cumulativeToDelta`. */\n readonly resetDetected: boolean;\n};\n\nexport type HookIngestInput = {\n /** Decoded provider payload. Only the selected adapter interprets it. */\n readonly payload: unknown;\n readonly transport: SourceTransport;\n readonly environment?: Readonly<Record<string, string | undefined>>;\n readonly providerHint?: string;\n /** Caller-supplied identity claims, arbitrated with the adapter's claims. */\n readonly identityClaims?: readonly IdentityClaim[];\n /** Opaque consumer metadata; sanitized, then carried through unchanged. */\n readonly consumerAttributes?: Readonly<Record<string, unknown>>;\n readonly workspace?: WorkspaceIdentity;\n};\n\n/**\n * The terminal fate of one callback's telemetry, and the only thing a caller\n * should base a commit-or-retry decision on.\n *\n * The distinction that matters is **any** versus **all**, not success versus\n * failure. A batch is chunked before export, so it can be part accepted and part\n * refused — and once a single span has reached a collector or the spool, retrying\n * the callback would re-export that span. So a partial result is *terminal*: the\n * callback is committed, the loss is reported, and nothing is retried. Only a\n * result where nothing at all survived is safe to retry, precisely because there\n * is nothing to duplicate.\n */\nexport type DeliveryDurability =\n /** Suppressed, or no events to export. There is nothing to lose or retry. */\n | \"nothing-to-deliver\"\n /** Every span reached the collector or the spool. */\n | \"delivered\"\n /**\n * Some spans survived and some did not. Terminal: committing loses the refused\n * spans, retrying duplicates the accepted ones, and duplicating an accepted\n * span silently corrupts a total while a reported loss can be acted on.\n */\n | \"partial\"\n /** Nothing survived, so a retry cannot duplicate anything. */\n | \"lost\";\n\nexport const classifyDurability = (input: {\n readonly attempted: boolean;\n readonly accepted: number;\n readonly rejected: number;\n}): DeliveryDurability => {\n if (!input.attempted) {\n return \"nothing-to-deliver\";\n }\n if (input.rejected === 0) {\n return input.accepted === 0 ? \"nothing-to-deliver\" : \"delivered\";\n }\n return input.accepted === 0 ? \"lost\" : \"partial\";\n};\n\n/** Whether this fate permits committing the callback and its accounting. */\nexport const isCommittable = (durability: DeliveryDurability): boolean =>\n durability !== \"lost\";\n\nexport type HookIngestOutcome = {\n /**\n * Always `true`. The hook cannot fail the host agent; look at `attribution`\n * and `diagnostics` to see what actually happened (ADR 0004).\n */\n readonly ok: true;\n readonly attribution: AttributionOutcome;\n readonly attributionReason?: AttributionReason;\n readonly providerId: ResolvedProviderId;\n readonly detectionConfidence: DetectionConfidence;\n readonly identity?: InvocationIdentity;\n readonly events: readonly CanonicalEvent[];\n readonly usageObservations: readonly UsageObservation[];\n /**\n * OTLP records the sink accepted, summed over every wired signal.\n *\n * A count of *records*, never of canonical events: two edges of one lifecycle\n * scope produce one span, and one event carrying three content facts produces\n * three log records. With the logs signal enabled a batch therefore reports both\n * signals' records here — which is what makes {@link durability} correct across\n * them, and why nothing should read this as \"how many events were observed\".\n */\n readonly emitted: number;\n /**\n * Records the sink could neither export nor durably spool.\n *\n * The distinction `emitted` cannot make: a successful spool enqueue counts as\n * emitted, because the batch is safe on disk and a later invocation will retry\n * it. A non-zero value here means those observations are **gone** unless the\n * callback is delivered again — which is what lets a caller decide whether a\n * delivery claim may be committed or has to be released for retry.\n */\n readonly exportRejected: number;\n /**\n * The terminal fate of this callback's telemetry.\n *\n * The field a caller should branch on. `emitted` and `exportRejected` are the\n * raw counts behind it; this is the decision they add up to, computed in one\n * place so a caller cannot get the any-versus-all boundary wrong.\n */\n readonly durability: DeliveryDurability;\n readonly dropped: number;\n readonly hookResponse: ProviderHookResponse;\n readonly diagnostics: readonly OtelHookErrorInfo[];\n};\n\nexport type HookIngestOptions = {\n /**\n * Parse and answer the provider, but export nothing and mutate no canonical\n * state.\n *\n * For a callback that deduplication has already identified as a redelivery.\n * The adapter still runs, so the provider's protocol response comes from a real\n * parse of the real payload rather than a guess — but the session sequence\n * counter is not advanced and no cumulative usage baseline is rewritten,\n * because both are *canonical state* and a redelivery is by definition not a\n * new observation. Advancing the sequence would renumber every later event in\n * the session and change its derived event id, which is exactly the\n * replay-stability the dedup guard exists to protect.\n */\n readonly suppress?: boolean;\n};\n\n/** Public runtime surface. */\nexport interface OtelHook {\n /**\n * Report the replay-stable delivery identity of an input without ingesting it.\n *\n * Synchronous, side-effect free, and never throws. It exists as a separate\n * step because deduplication has to decide *before* anything is exported or\n * accounted, and `ingest` exports as part of its own work — a caller that\n * learned the identity afterwards could only ever suppress a duplicate it had\n * already sent. Only `detect` and `deliveryIdentity` run here; the payload is\n * never parsed.\n */\n resolveDelivery(input: HookIngestInput): DeliveryResolution;\n /** Process one provider observation. Never throws, never rejects. */\n ingest(input: HookIngestInput, options?: HookIngestOptions): Promise<HookIngestOutcome>;\n /** Best-effort delivery of buffered telemetry. Never throws. */\n flush(): Promise<void>;\n /** Flush, then release resources. Never throws; idempotent. */\n shutdown(): Promise<void>;\n /** Resolved configuration in force. Read-only. */\n readonly config: OtelHookConfig;\n}\n\nexport type OtelHookDependencies = {\n readonly sink: TelemetrySink;\n readonly stateStore: StateStore;\n readonly config?: OtelHookConfig;\n readonly registry?: ProviderRegistry;\n readonly clock?: Clock;\n readonly ids?: IdGenerator;\n /** Overrides `config.privacy` when supplied; must already be configured. */\n readonly privacy?: PrivacyService;\n readonly logger?: Logger;\n /**\n * Namespace separating one deployment's derived delivery identities from\n * another's. Not identity: it never reaches an event, and no session or\n * workspace is derived from it. Defaults to `\"default\"`.\n */\n readonly installationId?: string;\n};\n\nconst MAX_ERROR_EVENTS = 8;\n\nconst collectContentFacts = (event: CanonicalEvent): readonly ContentFact[] => {\n const facts: ContentFact[] = [];\n const push = (fact: ContentFact | undefined): void => {\n if (fact !== undefined) {\n facts.push(fact);\n }\n };\n switch (event.type) {\n case \"prompt.submitted\":\n push(event.content);\n break;\n case \"generation.start\":\n facts.push(...(event.inputContent ?? []));\n break;\n case \"generation.end\":\n facts.push(...(event.outputContent ?? []));\n break;\n case \"tool.start\":\n push(event.input);\n break;\n case \"tool.end\":\n push(event.output);\n break;\n case \"error.raised\":\n push(event.message);\n break;\n default:\n break;\n }\n return facts;\n};\n\nconst usageScopeOf = (\n event: CanonicalEvent,\n): { readonly scope: UsageScope; readonly scopeKey: string; readonly usage: CanonicalUsage } | undefined => {\n switch (event.type) {\n case \"session.end\":\n return event.usage === undefined\n ? undefined\n : { scope: \"session\", scopeKey: event.sessionId, usage: event.usage };\n case \"compaction.performed\":\n return event.usage === undefined\n ? undefined\n : { scope: \"session\", scopeKey: event.sessionId, usage: event.usage };\n case \"generation.end\":\n return event.usage === undefined\n ? undefined\n : { scope: \"generation\", scopeKey: event.generationId, usage: event.usage };\n case \"subagent.end\":\n return event.usage === undefined\n ? undefined\n : { scope: \"subagent\", scopeKey: event.subagentInvocationId, usage: event.usage };\n default:\n return undefined;\n }\n};\n\nconst sequenceKey = (sessionId: string): string => `sequence:${sessionId}`;\nconst usageKey = (sessionId: string, scope: UsageScope, scopeKey: string): string =>\n `usage:${sessionId}:${scope}:${scopeKey}`;\n\n/**\n * Where the cumulative baseline for an observation is stored.\n *\n * This is deliberately *not* the same thing as the observation's own scope. The\n * derived delta belongs to the event that reported it — a turn's token spend is\n * attributed to that turn — but the snapshot it must be diffed against belongs\n * to whichever series the provider is actually accumulating.\n *\n * For a `session-lifetime` provider (Codex: every hook carries the session-wide\n * `total_token_usage`), keying the baseline by `generationId` would mean every\n * turn's snapshot found no predecessor and was emitted whole, billing the entire\n * session again on each turn. Redirecting `generation` to the session series\n * makes successive turns diff against each other.\n */\nconst baselineScopeOf = (\n scope: UsageScope,\n scopeKey: string,\n sessionId: string,\n series: CumulativeUsageSeries,\n): { readonly scope: UsageScope; readonly scopeKey: string } =>\n series === \"session-lifetime\" && scope === \"generation\"\n ? { scope: \"session\", scopeKey: sessionId }\n : { scope, scopeKey };\n\n/**\n * Minimal orchestrator wiring detection, identity, parsing, privacy checks,\n * usage derivation, and export.\n *\n * Every step is contained: a throwing adapter, an unavailable state store, or a\n * rejecting sink degrades the telemetry, never the host agent.\n */\nexport const createOtelHook = (deps: OtelHookDependencies): OtelHook => {\n const config = deps.config ?? DEFAULT_CONFIG;\n const registry = deps.registry ?? createProviderRegistry(BUILT_IN_PROVIDERS);\n const clock = deps.clock ?? createSystemClock();\n const ids = deps.ids ?? createDeterministicIdGenerator();\n const privacy = deps.privacy ?? createPrivacyService(config.privacy);\n const logger = deps.logger ?? createNullLogger();\n const installationId = deps.installationId ?? \"default\";\n const limits = privacy.policy.limits;\n const expectedDisclosure = CONTENT_MODE_DISCLOSURE[privacy.policy.contentMode];\n\n const providerContext: ProviderContext = { privacy, clock, ids, logger, limits };\n let shutdownCompleted = false;\n\n const hookResponseFor = (\n adapter: ProviderAdapter | undefined,\n detection: ProviderDetection | undefined,\n attribution: AttributionOutcome,\n attributionReason: AttributionReason | undefined,\n emittedEvents: number,\n errors: readonly OtelHookErrorInfo[],\n ): ProviderHookResponse => {\n if (adapter === undefined) {\n return SILENT_HOOK_RESPONSE;\n }\n try {\n return adapter.hookResponse(\n {\n attribution,\n ...(attributionReason === undefined ? {} : { attributionReason }),\n ...(detection === undefined ? {} : { detection }),\n emittedEvents,\n errors,\n },\n providerContext,\n );\n } catch {\n // A provider that cannot describe its own response gets the silent one.\n return SILENT_HOOK_RESPONSE;\n }\n };\n\n const readSequenceBase = async (\n sessionId: string,\n diagnostics: OtelHookErrorInfo[],\n ): Promise<number> => {\n try {\n const record = await deps.stateStore.read(sequenceKey(sessionId));\n if (record?.value.kind === \"sequence\") {\n return record.value.next;\n }\n return 0;\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, { code: \"state-store-failure\", phase: \"state\", occurredAt: clock.now() }),\n );\n return 0;\n }\n };\n\n /**\n * Derive per-event deltas, advancing the stored cumulative baseline.\n *\n * `suppress` makes this read-only: a redelivered callback must still be able to\n * report what it *would* have counted, but rewriting the baseline would make\n * the next genuine observation diff against the wrong snapshot and report a\n * zero — or negative — delta. Callers run this inside the session lock.\n */\n const deriveUsage = async (\n events: readonly CanonicalEvent[],\n diagnostics: OtelHookErrorInfo[],\n suppress: boolean,\n series: CumulativeUsageSeries,\n ): Promise<readonly UsageObservation[]> => {\n const observations: UsageObservation[] = [];\n for (const event of events) {\n const scoped = usageScopeOf(event);\n if (scoped === undefined) {\n continue;\n }\n if (scoped.usage.temporality === \"delta\") {\n observations.push({\n eventId: event.eventId,\n sequence: event.sequence,\n scope: scoped.scope,\n scopeKey: scoped.scopeKey,\n reportedTemporality: \"delta\",\n delta: scoped.usage,\n resetDetected: false,\n });\n continue;\n }\n\n const baselineScope = baselineScopeOf(scoped.scope, scoped.scopeKey, event.sessionId, series);\n const key = usageKey(event.sessionId, baselineScope.scope, baselineScope.scopeKey);\n let baseline: CanonicalUsage | undefined;\n try {\n const record = await deps.stateStore.read(key);\n if (record?.value.kind === \"usage-cumulative\") {\n baseline = record.value.usage;\n }\n } catch (thrown) {\n // Without a baseline the difference is unknowable. Emitting the raw\n // snapshot as a delta would double-count, so the observation is dropped.\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"state-store-failure\",\n phase: \"state\",\n occurredAt: clock.now(),\n }),\n );\n continue;\n }\n\n let delta: CanonicalUsage;\n let resetDetected = false;\n if (baseline === undefined) {\n const normalized = normalizeUsage({ ...toReport(scoped.usage), temporality: \"delta\" });\n if (normalized.status === \"invalid\") {\n diagnostics.push(\n createErrorInfo({\n code: \"usage-invalid\",\n phase: \"normalization\",\n detail: normalized.issues.map((issue) => issue.message).join(\"; \").slice(0, 400),\n details: { \"event.id\": event.eventId, \"usage.scope\": scoped.scope },\n occurredAt: clock.now(),\n }),\n );\n continue;\n }\n delta = normalized.usage;\n } else {\n try {\n const diffed = cumulativeToDelta(baseline, scoped.usage);\n delta = diffed.usage;\n resetDetected = diffed.resetDetected;\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"usage-invalid\",\n phase: \"normalization\",\n occurredAt: clock.now(),\n }),\n );\n continue;\n }\n }\n\n try {\n if (!suppress) {\n await deps.stateStore.write(key, { kind: \"usage-cumulative\", usage: scoped.usage });\n }\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"state-store-failure\",\n phase: \"state\",\n occurredAt: clock.now(),\n }),\n );\n }\n\n observations.push({\n eventId: event.eventId,\n sequence: event.sequence,\n scope: scoped.scope,\n scopeKey: scoped.scopeKey,\n reportedTemporality: \"cumulative\",\n delta,\n resetDetected,\n });\n }\n return observations;\n };\n\n const screenEvents = (\n events: readonly CanonicalEvent[],\n identity: InvocationIdentity,\n sequenceBase: number,\n diagnostics: OtelHookErrorInfo[],\n ): { readonly kept: readonly CanonicalEvent[]; readonly dropped: number } => {\n const kept: CanonicalEvent[] = [];\n let dropped = 0;\n let expectedSequence = sequenceBase;\n\n for (const event of events) {\n const reject = (code: \"schema-validation-failed\" | \"privacy-policy-violation\" | \"limit-exceeded\", detail: string): void => {\n dropped += 1;\n diagnostics.push(\n createErrorInfo({\n code,\n phase: code === \"privacy-policy-violation\" ? \"privacy\" : \"parsing\",\n detail,\n details: { \"event.type\": event.type, \"event.sequence\": event.sequence },\n occurredAt: clock.now(),\n }),\n );\n };\n\n if (kept.length >= limits.maxEventsPerInvocation) {\n reject(\"limit-exceeded\", `event dropped: maxEventsPerInvocation=${limits.maxEventsPerInvocation}`);\n continue;\n }\n if (event.schemaVersion !== CANONICAL_SCHEMA_VERSION) {\n reject(\"schema-validation-failed\", \"event carries an unexpected schema version\");\n continue;\n }\n if (event.invocationId !== identity.invocationId || event.sessionId !== identity.sessionId) {\n // Fail closed: an adapter may only describe the invocation it was given.\n reject(\"schema-validation-failed\", \"event identity does not match the resolved invocation\");\n continue;\n }\n if (event.provenance.providerId !== identity.provenance.providerId) {\n reject(\"schema-validation-failed\", \"event provenance does not match the detected provider\");\n continue;\n }\n if (event.sequence !== expectedSequence) {\n reject(\n \"schema-validation-failed\",\n `event sequence ${event.sequence} is not consecutive from ${expectedSequence}`,\n );\n continue;\n }\n\n const facts = collectContentFacts(event);\n const offending = facts.find(\n (fact) =>\n !isUnavailableContentFact(fact) &&\n (fact.disclosure !== expectedDisclosure || !isContentFactConsistent(fact)),\n );\n if (offending !== undefined) {\n reject(\n \"privacy-policy-violation\",\n `content fact disclosure ${offending.disclosure} violates policy ${expectedDisclosure}`,\n );\n continue;\n }\n\n expectedSequence += 1;\n kept.push(event);\n }\n return { kept, dropped };\n };\n\n const detectionInputFor = (input: HookIngestInput): {\n readonly payload: unknown;\n readonly transport: SourceTransport;\n readonly environment: Readonly<Record<string, string | undefined>>;\n readonly providerHint?: string;\n } => ({\n payload: input.payload,\n transport: input.transport,\n environment: input.environment ?? {},\n ...(input.providerHint === undefined ? {} : { providerHint: input.providerHint }),\n });\n\n const resolveDelivery = (input: HookIngestInput): DeliveryResolution => {\n let detected;\n try {\n detected = registry.detect(detectionInputFor(input), providerContext, config.detection);\n } catch {\n return { status: \"unavailable\", reason: \"provider-unattributed\" };\n }\n if (detected.status !== \"selected\") {\n return { status: \"unavailable\", reason: \"provider-unattributed\" };\n }\n\n const { adapter, detection } = detected;\n const capability = adapter.capabilities.deliveryIdentifier;\n // Named once, then reused: an unavailable resolution says *which* callback it\n // is talking about, because \"not identifiable\" without a callback name leaves\n // an operator auditing coverage nowhere to go.\n const named = {\n providerId: detection.providerId,\n capability,\n ...(detection.sourceEventName === undefined\n ? {}\n : { sourceEventName: detection.sourceEventName }),\n };\n const gap = readDeliveryGap(adapter, detection.sourceEventName);\n\n if (capability === \"none\") {\n return {\n status: \"unavailable\",\n reason: \"provider-declares-none\",\n ...named,\n ...(gap === undefined ? {} : { detail: gap }),\n };\n }\n\n const read = readDeliveryClaim(adapter, { ...detectionInputFor(input), detection }, providerContext);\n if (read.rejection !== undefined) {\n return {\n status: \"unavailable\",\n reason: \"claim-rejected\",\n ...named,\n detail: read.rejection,\n };\n }\n if (read.claim === undefined) {\n return {\n status: \"unavailable\",\n reason: \"callback-not-identifiable\",\n ...named,\n ...(gap === undefined ? {} : { detail: gap }),\n };\n }\n return {\n status: \"resolved\",\n identity: resolveDeliveryIdentity({\n ids,\n providerId: detection.providerId,\n installationId,\n claim: read.claim,\n }),\n };\n };\n\n const ingest = async (\n input: HookIngestInput,\n ingestOptions?: HookIngestOptions,\n ): Promise<HookIngestOutcome> => {\n const suppress = ingestOptions?.suppress === true;\n const diagnostics: OtelHookErrorInfo[] = [];\n const environment = input.environment ?? {};\n const detectionInput = {\n payload: input.payload,\n transport: input.transport,\n environment,\n ...(input.providerHint === undefined ? {} : { providerHint: input.providerHint }),\n };\n\n try {\n const detected = registry.detect(detectionInput, providerContext, config.detection);\n diagnostics.push(...detected.errors);\n\n if (detected.status !== \"selected\") {\n const reason: AttributionReason =\n detected.status === \"ambiguous\" ? \"provider-detection-ambiguous\" : \"provider-unknown\";\n diagnostics.push(\n createErrorInfo({\n code: detected.status === \"ambiguous\" ? \"provider-detection-ambiguous\" : \"provider-unknown\",\n phase: \"detection\",\n detail: detected.detection.reasons.join(\"; \").slice(0, 400),\n details: { \"detection.candidates\": detected.candidates.length },\n occurredAt: clock.now(),\n }),\n );\n logger.warn(\"provider not attributed\", {\n \"detection.status\": detected.status,\n \"detection.candidates\": detected.candidates.length,\n });\n return {\n ok: true,\n attribution: \"declined\",\n attributionReason: reason,\n providerId: \"unknown\",\n detectionConfidence: detected.detection.confidence,\n events: [],\n usageObservations: [],\n emitted: 0,\n exportRejected: 0,\n durability: \"nothing-to-deliver\" as const,\n dropped: 0,\n hookResponse: SILENT_HOOK_RESPONSE,\n diagnostics,\n };\n }\n\n const { adapter, detection } = detected;\n const provenance = sourceProvenanceSchema.parse({\n providerId: detection.providerId,\n ...(detection.providerVersion === undefined\n ? {}\n : { providerVersion: detection.providerVersion }),\n adapterId: adapter.id,\n adapterVersion: adapter.version,\n detectionConfidence: detection.confidence,\n ...(detection.sourceEventName === undefined\n ? {}\n : { sourceEventName: detection.sourceEventName }),\n transport: input.transport,\n });\n\n let adapterClaims: readonly IdentityClaim[] = [];\n try {\n adapterClaims = adapter.identify({ ...detectionInput, detection }, providerContext);\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"provider-adapter-failure\",\n phase: \"identity\",\n occurredAt: clock.now(),\n }),\n );\n }\n\n const resolution = resolveInvocationIdentity({\n claims: [...adapterClaims, ...(input.identityClaims ?? [])],\n provenance,\n fallback: {\n startedAt: clock.now(),\n workspace: input.workspace ?? unknownWorkspaceIdentity(),\n },\n consumerAttributes: privacy.sanitizeAttributes(input.consumerAttributes ?? {}),\n });\n\n if (resolution.status !== \"resolved\") {\n const reason: AttributionReason =\n resolution.status === \"conflict\" ? \"identity-conflict\" : \"identity-incomplete\";\n const detail =\n resolution.status === \"conflict\"\n ? `conflicting fields: ${resolution.conflicts.map((conflict) => conflict.field).join(\", \")}`\n : resolution.status === \"incomplete\"\n ? `missing fields: ${resolution.missing.join(\", \")}`\n : `invalid claims: ${resolution.issues.join(\"; \")}`;\n diagnostics.push(\n createErrorInfo({\n code: resolution.status === \"conflict\" ? \"identity-conflict\" : \"identity-incomplete\",\n phase: \"identity\",\n detail: detail.slice(0, 400),\n details: { \"provider.id\": detection.providerId },\n occurredAt: clock.now(),\n }),\n );\n logger.warn(\"attribution declined\", {\n \"identity.status\": resolution.status,\n \"provider.id\": detection.providerId,\n });\n return {\n ok: true,\n attribution: \"declined\",\n attributionReason: reason,\n providerId: detection.providerId,\n detectionConfidence: detection.confidence,\n events: [],\n usageObservations: [],\n emitted: 0,\n exportRejected: 0,\n durability: \"nothing-to-deliver\" as const,\n dropped: 0,\n hookResponse: hookResponseFor(adapter, detection, \"declined\", reason, 0, diagnostics),\n diagnostics,\n };\n }\n\n const identity = resolution.identity;\n\n /**\n * Result of the session-state critical section: either a finished outcome\n * (the adapter declined to produce events) or a batch ready to export.\n */\n type Prepared =\n | { readonly kind: \"early\"; readonly outcome: HookIngestOutcome }\n | {\n readonly kind: \"ready\";\n readonly batch: readonly CanonicalEvent[];\n readonly dropped: number;\n };\n\n /**\n * Read this session's sequence, stamp a batch from it, derive usage against\n * the stored baselines, and commit the new sequence — as one unit.\n *\n * These are read-modify-write cycles on state shared by every process\n * handling the same session, and hook processes genuinely run concurrently\n * (a tool callback and a generation callback firing together). Unserialized,\n * two processes both read sequence *n*, both stamp events from *n*, and both\n * write *n + k*: the second batch reuses the first's sequence numbers, so\n * both derive the *same* event ids and a collector sees one event twice\n * while another is never numbered at all. The cumulative usage baseline\n * races the same way, and there the lost update is a wrong token delta\n * rather than a duplicate id.\n *\n * Export deliberately happens *after* this returns, outside the lock. Two\n * reasons, one correctness and one liveness: the span correlator takes this\n * same session lock from inside the sink, so exporting in here would be a\n * non-reentrant self-deadlock; and an unreachable collector must not hold a\n * session's state lock for the length of its timeout. Committing the\n * sequence before exporting means a failed export leaves a gap in the\n * numbering rather than a reused number — a gap is invisible to a\n * collector, a reused id is a corrupted trace.\n */\n const prepare = async (): Promise<Prepared> => {\n const sequenceBase = await readSequenceBase(identity.sessionId, diagnostics);\n\n let parsed;\n try {\n parsed = adapter.parse(\n { ...detectionInput, detection, identity, sequenceBase },\n providerContext,\n );\n } catch (thrown) {\n const info = errorInfoFromThrown(thrown, {\n code: \"provider-adapter-failure\",\n phase: \"parsing\",\n occurredAt: clock.now(),\n });\n diagnostics.push(info);\n return {\n kind: \"early\",\n outcome: {\n ok: true,\n attribution: \"failed\",\n attributionReason: \"adapter-failure\",\n providerId: detection.providerId,\n detectionConfidence: detection.confidence,\n identity,\n events: [],\n usageObservations: [],\n emitted: 0,\n exportRejected: 0,\n durability: \"nothing-to-deliver\" as const,\n dropped: 0,\n hookResponse: hookResponseFor(adapter, detection, \"failed\", \"adapter-failure\", 0, diagnostics),\n diagnostics,\n },\n };\n }\n\n if (parsed.status === \"ignored\") {\n logger.debug(\"adapter ignored input\", {\n \"provider.id\": detection.providerId,\n \"adapter.reason\": parsed.reason.slice(0, 160),\n });\n return {\n kind: \"early\",\n outcome: {\n ok: true,\n attribution: \"not-applicable\",\n attributionReason: \"adapter-ignored-input\",\n providerId: detection.providerId,\n detectionConfidence: detection.confidence,\n identity,\n events: [],\n usageObservations: [],\n emitted: 0,\n exportRejected: 0,\n durability: \"nothing-to-deliver\" as const,\n dropped: 0,\n hookResponse: hookResponseFor(\n adapter,\n detection,\n \"not-applicable\",\n \"adapter-ignored-input\",\n 0,\n diagnostics,\n ),\n diagnostics,\n },\n };\n }\n\n if (parsed.status === \"failed\") {\n diagnostics.push(parsed.error);\n return {\n kind: \"early\",\n outcome: {\n ok: true,\n attribution: \"failed\",\n attributionReason: \"adapter-failure\",\n providerId: detection.providerId,\n detectionConfidence: detection.confidence,\n identity,\n events: [],\n usageObservations: [],\n emitted: 0,\n exportRejected: 0,\n durability: \"nothing-to-deliver\" as const,\n dropped: 0,\n hookResponse: hookResponseFor(adapter, detection, \"failed\", \"adapter-failure\", 0, diagnostics),\n diagnostics,\n },\n };\n }\n\n if (parsed.warnings !== undefined && parsed.warnings.length > 0) {\n // An adapter reports a warning when it understood the payload but had to\n // decline part of it — a counter outside its declared capabilities, a\n // breakdown that disagrees with the total it itemizes. Not a diagnostic:\n // the observation is intact and nothing failed, so raising an error-severity\n // code would misreport a healthy invocation. But not nothing either, which\n // is what these were before: a harness whose attached field is being ignored\n // has no other way to find out.\n logger.warn(\"adapter declined part of the payload it understood\", {\n \"provider.id\": detection.providerId,\n \"adapter.warnings\": parsed.warnings.slice(0, 8).map((warning) => warning.slice(0, 200)),\n });\n }\n\n const screened = screenEvents(parsed.events, identity, sequenceBase, diagnostics);\n\n let batch: readonly CanonicalEvent[] = screened.kept;\n if (config.diagnostics.emitErrorEvents && diagnostics.length > 0) {\n batch = [...batch, ...buildErrorEvents(diagnostics, identity, sequenceBase + batch.length, ids, privacy)];\n }\n\n if (!suppress) {\n try {\n await deps.stateStore.write(sequenceKey(identity.sessionId), {\n kind: \"sequence\",\n next: sequenceBase + batch.length,\n });\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"state-store-failure\",\n phase: \"state\",\n occurredAt: clock.now(),\n }),\n );\n }\n }\n\n return { kind: \"ready\", batch, dropped: screened.dropped };\n };\n\n let prepared: Prepared;\n try {\n prepared = await withOptionalSessionLock(deps.stateStore, identity.sessionId, prepare);\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"state-store-failure\",\n phase: \"state\",\n occurredAt: clock.now(),\n }),\n );\n\n if (!isStateLockContention(thrown)) {\n // The store cannot lock because it cannot be used at all — an unwritable\n // directory, a full disk. There is no peer inside the critical section\n // and no state to lose an update to, so the lock protects nothing here\n // and fail-open wins: process unlocked and export. Each individual read\n // and write inside still degrades to its own diagnostic.\n logger.warn(\"state store unusable; processing without session serialization\", {\n \"provider.id\": detection.providerId,\n });\n prepared = await prepare();\n } else {\n // Genuine contention. Proceeding unlocked would reintroduce exactly the\n // interleaving the lock exists to prevent, so the observation is declined\n // and said out loud — the provider still gets its protocol response, and a\n // caller holding a delivery claim releases it, turning a lock collision\n // into a retry rather than a corrupted sequence.\n //\n // A contended acquisition *cancels* its queued critical section\n // (`AsyncLock.run`), so this is now a provable statement rather than a\n // hopeful one: nothing was read, reserved, or written, which is what makes\n // the retry safe rather than a second half-application.\n logger.warn(\"session state lock contended; observation declined for retry\", {\n \"provider.id\": detection.providerId,\n });\n return {\n ok: true,\n attribution: \"failed\",\n attributionReason: \"internal-error\",\n providerId: detection.providerId,\n detectionConfidence: detection.confidence,\n identity,\n events: [],\n usageObservations: [],\n emitted: 0,\n // Nothing was exported, nothing was reserved, and nothing is on disk,\n // so the caller must see this as a total loss and retry it.\n exportRejected: 1,\n durability: \"lost\",\n dropped: 0,\n hookResponse: hookResponseFor(adapter, detection, \"failed\", \"internal-error\", 0, diagnostics),\n diagnostics,\n };\n }\n }\n\n if (prepared.kind === \"early\") {\n return prepared.outcome;\n }\n const { batch, dropped } = prepared;\n\n let emitted = 0;\n let exportRejected = 0;\n if (!suppress && batch.length > 0) {\n try {\n const result = await deps.sink.emit(batch);\n emitted = result.accepted;\n exportRejected = result.rejected;\n diagnostics.push(...result.errors);\n } catch (thrown) {\n // A throwing sink delivered nothing and spooled nothing.\n exportRejected = batch.length;\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"telemetry-export-failure\",\n phase: \"export\",\n occurredAt: clock.now(),\n }),\n );\n }\n }\n\n const durability = classifyDurability({\n attempted: !suppress && batch.length > 0,\n accepted: emitted,\n rejected: exportRejected,\n });\n\n /**\n * Usage accounting is the *commit* half of the transaction, so it runs here\n * and not in `prepare`.\n *\n * Deriving a delta advances the stored cumulative baseline, which is a\n * one-way move: once it points at this snapshot, the difference this callback\n * represented is no longer recoverable from state. Doing that before knowing\n * whether the telemetry survived means a fully rejected callback releases its\n * claim having *already* consumed its own usage — so the retry diffs against\n * the advanced baseline, reports roughly zero, and the tokens are gone. Delta\n * usage has the mirror-image failure: it needs no baseline, so a retry\n * accumulates the same delta a second time.\n *\n * Nothing exported depends on these numbers — a span carries the usage the\n * provider *reported*, never the derived delta — so deferring costs nothing\n * and buys exactly-once accounting. The read of the baseline, the diff, and\n * the write back all stay inside one critical section, so two concurrent\n * processes cannot both diff against the same snapshot.\n *\n * A suppressed redelivery and a fully rejected attempt both skip this\n * entirely, which is what leaves the baseline where the next real attempt\n * needs it.\n */\n let usageObservations: readonly UsageObservation[] = [];\n if (durability !== \"lost\" && !suppress && batch.length > 0) {\n try {\n usageObservations = await withOptionalSessionLock(\n deps.stateStore,\n identity.sessionId,\n () =>\n deriveUsage(\n batch,\n diagnostics,\n false,\n adapter.capabilities.cumulativeUsageSeries ?? \"event-scope\",\n ),\n );\n } catch (thrown) {\n // The accounting could not be committed. The telemetry is already out, so\n // this is a reporting gap rather than a lost observation: it is said out\n // loud and the callback stays committed, because retrying it would\n // re-export spans a collector has already accepted.\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"state-store-failure\",\n phase: \"state\",\n occurredAt: clock.now(),\n }),\n );\n logger.warn(\"usage accounting could not be committed for a delivered callback\", {\n \"provider.id\": detection.providerId,\n });\n }\n }\n\n return {\n ok: true,\n attribution: \"attributed\",\n providerId: detection.providerId,\n detectionConfidence: detection.confidence,\n identity,\n events: batch,\n usageObservations,\n emitted,\n exportRejected,\n durability,\n dropped,\n hookResponse: hookResponseFor(adapter, detection, \"attributed\", undefined, emitted, diagnostics),\n diagnostics,\n };\n } catch (thrown) {\n // Last line of defence: anything unanticipated becomes a diagnostic.\n const info = errorInfoFromThrown(thrown, { code: \"internal-error\", phase: \"parsing\" });\n diagnostics.push(info);\n logger.error(\"ingest contained an unexpected failure\", {\n \"error.code\": info.code,\n ...(info.details ?? {}),\n });\n return {\n ok: true,\n attribution: \"failed\",\n attributionReason: \"internal-error\",\n providerId: \"unknown\",\n detectionConfidence: \"none\",\n events: [],\n usageObservations: [],\n emitted: 0,\n exportRejected: 0,\n durability: \"nothing-to-deliver\" as const,\n dropped: 0,\n hookResponse: SILENT_HOOK_RESPONSE,\n diagnostics,\n };\n }\n };\n\n const flush = async (): Promise<void> => {\n try {\n await deps.sink.flush();\n } catch (thrown) {\n const info = errorInfoFromThrown(thrown, { code: \"telemetry-export-failure\", phase: \"export\" });\n logger.warn(\"flush failed\", { \"error.code\": info.code });\n }\n };\n\n const shutdown = async (): Promise<void> => {\n if (shutdownCompleted) {\n return;\n }\n shutdownCompleted = true;\n await flush();\n try {\n await deps.sink.shutdown();\n } catch (thrown) {\n const info = errorInfoFromThrown(thrown, {\n code: \"telemetry-export-failure\",\n phase: \"shutdown\",\n });\n logger.warn(\"shutdown failed\", { \"error.code\": info.code });\n }\n };\n\n return { resolveDelivery, ingest, flush, shutdown, config };\n};\n\nconst buildErrorEvents = (\n diagnostics: readonly OtelHookErrorInfo[],\n identity: InvocationIdentity,\n sequenceBase: number,\n ids: IdGenerator,\n privacy: PrivacyService,\n): readonly CanonicalEvent[] => {\n const events: CanonicalEvent[] = [];\n for (const [index, info] of diagnostics.slice(0, MAX_ERROR_EVENTS).entries()) {\n const sequence = sequenceBase + index;\n events.push({\n schemaVersion: CANONICAL_SCHEMA_VERSION,\n eventId: ids.newEventId({\n invocationId: identity.invocationId,\n sequence,\n eventType: \"error.raised\",\n discriminator: info.code,\n }),\n invocationId: identity.invocationId,\n sessionId: identity.sessionId,\n sequence,\n occurredAt: info.occurredAt ?? identity.startedAt,\n provenance: identity.provenance,\n workspace: identity.workspace,\n extensions: {},\n type: \"error.raised\",\n errorCode: info.code,\n severity: info.severity,\n phase: info.phase,\n retryable: info.retryable,\n // The message is already a fixed-vocabulary summary, but it still passes\n // through the privacy service so one policy governs every disclosure.\n message: privacy.describeContent({ kind: \"error-message\", text: info.message }),\n detail: info.code,\n });\n }\n return events;\n};\n","import { z } from \"zod\";\n\nimport { detectionConfidenceSchema, nonEmptyStringSchema } from \"../model/primitives.js\";\nimport {\n contentModeSchema,\n DEFAULT_PRIVACY_POLICY,\n privacyPolicySchema,\n} from \"../privacy/policy.js\";\nimport { EMPTY_RESOURCE_ATTRIBUTES, resourceAttributesSchema } from \"./resource-attributes.js\";\n\n/**\n * Policy for the OTLP logs signal.\n *\n * Two switches rather than one, because they answer different questions and an\n * operator needs to be able to answer them differently:\n *\n * - `enabled` — whether a second signal leaves this host at all. Off by default:\n * an installation that upgrades must not silently start sending a new stream to a\n * collector whose receivers, quotas, and retention were sized for traces.\n * - `includeContent` — whether *disclosed* text may appear in a log body. Also off\n * by default, and deliberately not the same knob as `privacy.contentMode`: spans\n * carry no content in any content mode, so an installation that set\n * `contentMode` to get a hash and a length has never had content on the wire.\n * Reusing that setting to also mean \"publish prompts\" would change what an\n * existing configuration discloses without anybody editing it.\n *\n * `raw` content additionally requires the pre-existing `privacy.allowRawContent`\n * opt-in, which the privacy service enforces before a fact is ever built and the\n * log mapping re-checks at the wire.\n */\nexport const logsPolicySchema = z.strictObject({\n enabled: z.boolean(),\n /**\n * Full URL for the logs signal.\n *\n * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes\n * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.\n */\n endpoint: z.string().url().max(2048).optional(),\n includeContent: z.boolean(),\n maxBatchSize: z.number().int().min(1).max(4096),\n});\nexport type LogsPolicy = z.infer<typeof logsPolicySchema>;\n\nexport const DEFAULT_LOGS_POLICY: LogsPolicy = Object.freeze({\n enabled: false,\n includeContent: false,\n maxBatchSize: 128,\n});\n\n/**\n * Runtime exporter policy.\n *\n * This describes *where and how* telemetry goes. It deliberately contains no\n * session, invocation, or workspace field: see ADR 0001. Mixing the two would\n * make identity globally reachable through configuration.\n */\nexport const exporterPolicySchema = z.strictObject({\n enabled: z.boolean(),\n protocol: z.enum([\"http/protobuf\", \"http/json\", \"none\"]),\n endpoint: z.string().url().max(2048).optional(),\n /**\n * Header names only. Values are supplied separately at construction time and\n * are never part of a resolved-config snapshot, which is logged and exported.\n */\n headerNames: z.array(nonEmptyStringSchema).max(32).readonly(),\n timeoutMillis: z.number().int().min(1).max(600_000),\n maxBatchSize: z.number().int().min(1).max(4096),\n maxQueueSize: z.number().int().min(1).max(65_536),\n maxRetryAttempts: z.number().int().min(0).max(10),\n serviceName: nonEmptyStringSchema,\n serviceNamespace: nonEmptyStringSchema.optional(),\n /**\n * Custom attributes merged into the exported OTLP Resource.\n *\n * Bounded and validated, and refusing `service.name`/`service.namespace`,\n * which are the two fields above. Distinct from an invocation's\n * `consumerAttributes`: this describes the emitting deployment, carries no\n * identity, and is the same for every span this process exports.\n */\n resourceAttributes: resourceAttributesSchema,\n /**\n * The logs signal. Nested under the exporter because it shares the endpoint,\n * headers, timeout, protocol, service identity, and resource attributes above —\n * a second top-level section would invite two of each to drift apart.\n */\n logs: logsPolicySchema,\n});\nexport type ExporterPolicy = z.infer<typeof exporterPolicySchema>;\n\nexport const detectionPolicySchema = z.strictObject({\n /** Detections below this confidence resolve to the unknown provider. */\n minimumConfidence: detectionConfidenceSchema,\n /** When false, an ambiguous detection is an error rather than unknown. */\n allowAmbiguousFallback: z.boolean(),\n /** Optional allow-list of provider ids; empty means \"any registered\". */\n allowedProviderIds: z.array(nonEmptyStringSchema).max(32).readonly(),\n});\nexport type DetectionPolicy = z.infer<typeof detectionPolicySchema>;\n\nexport const diagnosticsPolicySchema = z.strictObject({\n logLevel: z.enum([\"silent\", \"error\", \"warn\", \"info\", \"debug\"]),\n /** Emit `error.raised` events for contained failures. */\n emitErrorEvents: z.boolean(),\n});\nexport type DiagnosticsPolicy = z.infer<typeof diagnosticsPolicySchema>;\n\nexport const otelHookConfigSchema = z.strictObject({\n exporter: exporterPolicySchema,\n privacy: privacyPolicySchema,\n detection: detectionPolicySchema,\n diagnostics: diagnosticsPolicySchema,\n});\nexport type OtelHookConfig = z.infer<typeof otelHookConfigSchema>;\n\n/** Partial overlay accepted from a configuration layer. */\nexport const otelHookConfigPatchSchema = z.strictObject({\n // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:\n // merging happens per leaf, so a layer must be able to set `logs.enabled` alone\n // without also restating the endpoint and the batch size.\n exporter: exporterPolicySchema\n .omit({ logs: true })\n .partial()\n .extend({ logs: logsPolicySchema.partial().optional() })\n .optional(),\n privacy: privacyPolicySchema\n .omit({ limits: true })\n .partial()\n .extend({ limits: privacyPolicySchema.shape.limits.partial().optional() })\n .optional(),\n detection: detectionPolicySchema.partial().optional(),\n diagnostics: diagnosticsPolicySchema.partial().optional(),\n});\nexport type OtelHookConfigPatch = z.infer<typeof otelHookConfigPatchSchema>;\n\nexport const DEFAULT_EXPORTER_POLICY: ExporterPolicy = Object.freeze({\n enabled: true,\n protocol: \"http/protobuf\",\n headerNames: Object.freeze([]),\n timeoutMillis: 10_000,\n maxBatchSize: 128,\n maxQueueSize: 2048,\n maxRetryAttempts: 2,\n serviceName: \"coding-agent\",\n resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,\n logs: DEFAULT_LOGS_POLICY,\n});\n\nexport const DEFAULT_DETECTION_POLICY: DetectionPolicy = Object.freeze({\n minimumConfidence: \"strong\",\n allowAmbiguousFallback: true,\n allowedProviderIds: Object.freeze([]),\n});\n\nexport const DEFAULT_DIAGNOSTICS_POLICY: DiagnosticsPolicy = Object.freeze({\n logLevel: \"warn\",\n emitErrorEvents: true,\n});\n\nexport const DEFAULT_CONFIG: OtelHookConfig = Object.freeze({\n exporter: DEFAULT_EXPORTER_POLICY,\n privacy: DEFAULT_PRIVACY_POLICY,\n detection: DEFAULT_DETECTION_POLICY,\n diagnostics: DEFAULT_DIAGNOSTICS_POLICY,\n});\n\n/** Content mode is re-exported for callers building patches. */\nexport { contentModeSchema };\n","import { z } from \"zod\";\n\nimport { 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 { nonEmptyStringSchema } from \"./primitives.js\";\n\n/** What kind of conversational or tool content a fact describes. */\nexport const contentKindSchema = z.enum([\n \"prompt\",\n \"response\",\n \"reasoning\",\n \"tool-input\",\n \"tool-output\",\n \"error-message\",\n \"system-instruction\",\n \"attachment\",\n]);\nexport type ContentKind = z.infer<typeof contentKindSchema>;\n\nexport const contentRoleSchema = z.enum([\"user\", \"assistant\", \"system\", \"tool\", \"unknown\"]);\nexport type ContentRole = z.infer<typeof contentRoleSchema>;\n\n/**\n * How much of the original content this fact discloses.\n *\n * - `omitted`: no text at all (the default posture).\n * - `masked`: a shape-preserving mask; non-whitespace characters replaced.\n * - `redacted`: text with secret-looking spans replaced by a placeholder.\n * - `raw`: verbatim text. Only reachable through explicit opt-in.\n */\nexport const contentDisclosureSchema = z.enum([\"omitted\", \"masked\", \"redacted\", \"raw\"]);\nexport type ContentDisclosure = z.infer<typeof contentDisclosureSchema>;\n\nexport const CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;\n\n/**\n * A privacy-safe description of content.\n *\n * Lengths and a stable hash are always present so consumers can measure and\n * correlate volume without receiving the content itself. `text` is present only\n * when the resolved privacy policy allows disclosure, and is produced solely by\n * the central privacy service.\n */\nexport const contentFactSchema = z.strictObject({\n kind: contentKindSchema,\n role: contentRoleSchema.optional(),\n /** Unicode code point count of the original content. */\n characterLength: z.number().int().min(0),\n /** UTF-8 byte length of the original content. */\n byteLength: z.number().int().min(0),\n /** Stable salted digest of the original content. */\n contentHash: z.string().regex(CONTENT_HASH_PATTERN),\n disclosure: contentDisclosureSchema,\n /** Disclosed text, bounded by the privacy policy. Absent when omitted. */\n text: z.string().optional(),\n /** True when `text` was cut short by the configured string bound. */\n truncated: z.boolean(),\n /** Number of secret-looking spans replaced while producing `text`. */\n secretsRedacted: z.number().int().min(0),\n /** Optional non-sensitive label, e.g. a MIME type or tool name. */\n label: nonEmptyStringSchema.optional(),\n});\nexport type ContentFact = z.infer<typeof contentFactSchema>;\n\nexport const contentFactsSchema = z.array(contentFactSchema).max(64);\n\n/**\n * Guard used in tests and at the sink boundary: an omitted fact must not carry\n * text, and a disclosing fact must carry it.\n */\nexport const isContentFactConsistent = (fact: ContentFact): boolean =>\n fact.disclosure === \"omitted\" ? fact.text === undefined : fact.text !== undefined;\n\n/**\n * A fact for a content kind the event can carry when the provider sent no text.\n *\n * Always `omitted` with zero length, regardless of the installation's content\n * mode: there is nothing to mask, redact, or export.\n */\nexport const isUnavailableContentFact = (fact: ContentFact): boolean =>\n fact.disclosure === \"omitted\" &&\n fact.text === undefined &&\n fact.characterLength === 0 &&\n fact.byteLength === 0;\n","import { z } from \"zod\";\n\nimport {\n attributesSchema,\n detectionConfidenceSchema,\n DETECTION_CONFIDENCE_RANK,\n epochMillisSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n resolvedProviderIdSchema,\n sessionIdSchema,\n sourceTransportSchema,\n workspaceIdSchema,\n type DetectionConfidence,\n type InvocationId,\n type SessionId,\n type WorkspaceId,\n} from \"./primitives.js\";\n\n/**\n * Where a workspace identifier came from.\n *\n * Ordered from most to least stable. The source is recorded so consumers can\n * tell a repository-scoped identity from a directory-scoped one instead of\n * assuming they are comparable.\n */\nexport const workspaceKeySourceSchema = z.enum([\n \"git-remote\",\n \"git-root\",\n \"working-directory\",\n \"explicit\",\n \"unknown\",\n]);\nexport type WorkspaceKeySource = z.infer<typeof workspaceKeySourceSchema>;\n\n/**\n * Privacy-safe workspace identity.\n *\n * Only opaque handles and explicitly allowed labels are modelled. There is no\n * field for a filesystem path, so paths cannot be exported through this type.\n */\nexport const workspaceIdentitySchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n keySource: workspaceKeySourceSchema,\n /** Repository name only; never an owner path or URL with credentials. */\n repositoryName: nonEmptyStringSchema.optional(),\n vcsBranchName: nonEmptyStringSchema.optional(),\n /** Opaque handle for the checked-out revision. */\n vcsRevisionId: nonEmptyStringSchema.optional(),\n })\n .readonly();\nexport type WorkspaceIdentity = z.infer<typeof workspaceIdentitySchema>;\n\nexport const UNKNOWN_WORKSPACE_ID = \"unknown:0000000000000000\" as WorkspaceId;\n\nexport const unknownWorkspaceIdentity = (): WorkspaceIdentity =>\n workspaceIdentitySchema.parse({\n workspaceId: UNKNOWN_WORKSPACE_ID,\n keySource: \"unknown\",\n });\n\n/**\n * Provenance of an observation: which provider produced it and which adapter\n * interpreted it, with the confidence of that attribution.\n */\nexport const sourceProvenanceSchema = z\n .strictObject({\n providerId: resolvedProviderIdSchema,\n providerVersion: nonEmptyStringSchema.optional(),\n adapterId: nonEmptyStringSchema,\n adapterVersion: nonEmptyStringSchema,\n detectionConfidence: detectionConfidenceSchema,\n /** The provider's own name for the source event, e.g. a hook event name. */\n sourceEventName: nonEmptyStringSchema.optional(),\n transport: sourceTransportSchema,\n })\n .readonly();\nexport type SourceProvenance = z.infer<typeof sourceProvenanceSchema>;\n\n/**\n * Opaque, immutable metadata supplied by the embedding consumer.\n *\n * The library never interprets these values; it only carries and exports them.\n */\nexport const consumerAttributesSchema = attributesSchema.readonly();\nexport type ConsumerAttributes = z.infer<typeof consumerAttributesSchema>;\n\n/**\n * Immutable identity of a single hook invocation.\n *\n * Frozen on parse. There is deliberately no setter, no builder that mutates in\n * place, and no module-level instance: identity is passed explicitly so two\n * concurrent invocations can never observe each other's fields.\n */\nexport const invocationIdentitySchema = z\n .strictObject({\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Set when this invocation runs beneath another agent invocation. */\n parentInvocationId: invocationIdSchema.optional(),\n /** Root of the session tree when the provider exposes one. */\n rootSessionId: sessionIdSchema.optional(),\n /** Stable handle for the agent process/instance, when available. */\n agentInstanceId: nonEmptyStringSchema.optional(),\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n startedAt: epochMillisSchema,\n consumerAttributes: consumerAttributesSchema,\n })\n .readonly();\nexport type InvocationIdentity = z.infer<typeof invocationIdentitySchema>;\n\n/** Fields an identity claim may contribute. */\nexport const identityClaimFieldsSchema = z.strictObject({\n invocationId: invocationIdSchema.optional(),\n sessionId: sessionIdSchema.optional(),\n parentInvocationId: invocationIdSchema.optional(),\n rootSessionId: sessionIdSchema.optional(),\n agentInstanceId: nonEmptyStringSchema.optional(),\n workspace: workspaceIdentitySchema.optional(),\n startedAt: epochMillisSchema.optional(),\n});\nexport type IdentityClaimFields = z.infer<typeof identityClaimFieldsSchema>;\n\n/**\n * A claim about invocation identity from one source.\n *\n * Claims are evidence, not truth. Resolution keeps the highest-confidence claim\n * per field and refuses to merge disagreeing peers.\n */\nexport const identityClaimSchema = z.strictObject({\n /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */\n source: nonEmptyStringSchema,\n confidence: detectionConfidenceSchema,\n fields: identityClaimFieldsSchema,\n});\nexport type IdentityClaim = z.infer<typeof identityClaimSchema>;\n\nexport type IdentityConflict = {\n readonly field: keyof IdentityClaimFields;\n readonly confidence: DetectionConfidence;\n /** Rendered, non-sensitive representations of the disagreeing values. */\n readonly values: readonly string[];\n readonly sources: readonly string[];\n};\n\nexport type IdentityResolution =\n | { readonly status: \"resolved\"; readonly identity: InvocationIdentity }\n | {\n readonly status: \"conflict\";\n readonly conflicts: readonly IdentityConflict[];\n }\n | {\n readonly status: \"incomplete\";\n readonly missing: readonly (keyof IdentityClaimFields)[];\n }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nconst CLAIM_FIELDS = [\n \"invocationId\",\n \"sessionId\",\n \"parentInvocationId\",\n \"rootSessionId\",\n \"agentInstanceId\",\n \"workspace\",\n \"startedAt\",\n] as const satisfies readonly (keyof IdentityClaimFields)[];\n\nconst renderClaimValue = (value: unknown): string => {\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (value !== null && typeof value === \"object\" && \"workspaceId\" in value) {\n const { workspaceId } = value;\n return typeof workspaceId === \"string\" ? workspaceId : \"<workspace>\";\n }\n return \"<opaque>\";\n};\n\nexport type ResolveIdentityInput = {\n readonly claims: readonly IdentityClaim[];\n readonly provenance: SourceProvenance;\n /** Used only for fields no claim provides and that have a safe default. */\n readonly fallback?: {\n readonly startedAt?: number;\n readonly workspace?: WorkspaceIdentity;\n };\n readonly consumerAttributes?: Readonly<Record<string, unknown>>;\n};\n\n/**\n * Resolve identity from claims, failing closed.\n *\n * Rules:\n * 1. For each field, only claims at the highest confidence that provided it are\n * considered. Lower-confidence claims never fill in or override.\n * 2. Two distinct values at that highest confidence produce a `conflict`. The\n * invocation is then not attributed at all — a mislabelled session is worse\n * than a missing one.\n * 3. `invocationId` and `sessionId` are mandatory. Missing either yields\n * `incomplete`; neither is invented here.\n * 4. `startedAt` and `workspace` may come from an explicit fallback, because a\n * clock reading and an `unknown` workspace handle assert nothing false.\n */\nexport const resolveInvocationIdentity = (input: ResolveIdentityInput): IdentityResolution => {\n const parsedClaims: IdentityClaim[] = [];\n const issues: string[] = [];\n for (const [index, claim] of input.claims.entries()) {\n const parsed = identityClaimSchema.safeParse(claim);\n if (parsed.success) {\n parsedClaims.push(parsed.data);\n } else {\n issues.push(\n `claim[${index}]: ${parsed.error.issues.map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`).join(\", \")}`,\n );\n }\n }\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const conflicts: IdentityConflict[] = [];\n const selected: Record<string, unknown> = {};\n\n for (const field of CLAIM_FIELDS) {\n const contributors = parsedClaims.filter((claim) => claim.fields[field] !== undefined);\n if (contributors.length === 0) {\n continue;\n }\n const bestRank = Math.max(\n ...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence]),\n );\n const best = contributors.filter(\n (claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank,\n );\n const rendered = new Map<string, string[]>();\n for (const claim of best) {\n const key = JSON.stringify(claim.fields[field]);\n const sources = rendered.get(key) ?? [];\n sources.push(claim.source);\n rendered.set(key, sources);\n }\n if (rendered.size > 1) {\n const [firstBest] = best;\n conflicts.push({\n field,\n confidence: firstBest?.confidence ?? \"none\",\n values: best.map((claim) => renderClaimValue(claim.fields[field])),\n sources: best.map((claim) => claim.source),\n });\n continue;\n }\n const [winner] = best;\n if (winner !== undefined) {\n selected[field] = winner.fields[field];\n }\n }\n\n if (conflicts.length > 0) {\n return { status: \"conflict\", conflicts };\n }\n\n const missing: (keyof IdentityClaimFields)[] = [];\n if (selected.invocationId === undefined) {\n missing.push(\"invocationId\");\n }\n if (selected.sessionId === undefined) {\n missing.push(\"sessionId\");\n }\n if (missing.length > 0) {\n return { status: \"incomplete\", missing };\n }\n\n const startedAt = (selected.startedAt as number | undefined) ?? input.fallback?.startedAt;\n if (startedAt === undefined) {\n return { status: \"incomplete\", missing: [\"startedAt\"] };\n }\n const workspace =\n (selected.workspace as WorkspaceIdentity | undefined) ??\n input.fallback?.workspace ??\n unknownWorkspaceIdentity();\n\n const candidate = {\n invocationId: selected.invocationId as InvocationId,\n sessionId: selected.sessionId as SessionId,\n ...(selected.parentInvocationId === undefined\n ? {}\n : { parentInvocationId: selected.parentInvocationId as InvocationId }),\n ...(selected.rootSessionId === undefined\n ? {}\n : { rootSessionId: selected.rootSessionId as SessionId }),\n ...(selected.agentInstanceId === undefined\n ? {}\n : { agentInstanceId: selected.agentInstanceId as string }),\n provenance: input.provenance,\n workspace,\n startedAt,\n consumerAttributes: input.consumerAttributes ?? {},\n };\n\n const parsed = invocationIdentitySchema.safeParse(candidate);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n }\n return { status: \"resolved\", identity: parsed.data };\n};\n","import { z } from \"zod\";\n\n/**\n * Version of the canonical event model.\n *\n * Every emitted event carries this value. Consumers must treat an unknown\n * version as unreadable rather than guessing field semantics.\n *\n * Compatibility rules:\n * - Additive optional fields do not change the version.\n * - Renaming, removing, or re-interpreting a field increments the version.\n */\nexport const CANONICAL_SCHEMA_VERSION = 1 as const;\n\nexport type CanonicalSchemaVersion = typeof CANONICAL_SCHEMA_VERSION;\n\nexport const canonicalSchemaVersionSchema = z.literal(CANONICAL_SCHEMA_VERSION);\n","import { z } from \"zod\";\n\nimport type { AttributionOutcome, AttributionReason, OtelHookErrorInfo } from \"../errors/index.js\";\nimport { canonicalEventTypeSchema, type CanonicalEvent, type CanonicalEventType } from \"../model/events.js\";\nimport type { IdentityClaim, InvocationIdentity } from \"../model/identity.js\";\nimport {\n detectionConfidenceSchema,\n nonEmptyStringSchema,\n providerIdSchema,\n resolvedProviderIdSchema,\n type ProviderId,\n type ResolvedProviderId,\n type SourceTransport,\n} from \"../model/primitives.js\";\nimport { cacheCreationAccountingSchema, usageTemporalitySchema, type UsageTemporality } from \"../model/usage.js\";\nimport type { PrivacyLimits } from \"../privacy/policy.js\";\nimport type { PrivacyService } from \"../privacy/service.js\";\nimport type { Clock, IdGenerator, Logger } from \"../runtime/ports.js\";\n\n/** Raw input offered to adapters. `payload` is `unknown` on purpose. */\nexport type ProviderDetectionInput = {\n /** Decoded but uninterpreted provider payload. Must not escape the adapter. */\n readonly payload: unknown;\n readonly transport: SourceTransport;\n readonly environment: Readonly<Record<string, string | undefined>>;\n /** Caller's assertion of the provider, e.g. from a CLI flag. */\n readonly providerHint?: string;\n};\n\nexport const providerDetectionSchema = z.strictObject({\n providerId: resolvedProviderIdSchema,\n confidence: detectionConfidenceSchema,\n /**\n * Short, non-sensitive justifications, e.g. `\"payload.hook_event_name present\"`.\n * Reasons are exported in diagnostics, so they must not quote payload values.\n */\n reasons: z.array(z.string().min(1).max(160)).max(8),\n providerVersion: nonEmptyStringSchema.optional(),\n /** The provider's own name for this event, when the payload states one. */\n sourceEventName: nonEmptyStringSchema.optional(),\n});\nexport type ProviderDetection = z.infer<typeof providerDetectionSchema>;\n\n/**\n * How much of a provider's hook traffic carries an identifier that survives a\n * redelivery.\n *\n * - `none`: no callback carries one. Redelivery is undetectable from the\n * payload, and deduplication needs a host-supplied delivery id.\n * - `partial`: some callbacks do and some do not — typically per-tool-call and\n * per-turn events do, while session and compaction edges do not.\n * - `all`: every callback the adapter recognizes carries one.\n *\n * Declared rather than probed for the same reason as the usage capabilities\n * below: \"this callback has no stable id\" and \"this adapter never looked\" are\n * indistinguishable downstream, and only the first is safe to build on.\n */\nexport const deliveryIdentifierSupportSchema = z.enum([\"none\", \"partial\", \"all\"]);\nexport type DeliveryIdentifierSupport = z.infer<typeof deliveryIdentifierSupportSchema>;\n\n/**\n * Shape a delivery-identity component must have.\n *\n * Deliberately narrow. Provider identifiers, integer counters, hook event\n * names, and ISO-8601 timestamps all satisfy it; prose and filesystem paths do\n * not, because neither spaces nor `/` are allowed. So an adapter that\n * accidentally seeds a delivery identity with a prompt, a tool response, or a\n * home directory produces a *rejected claim* rather than a privacy incident —\n * the guard is structural, not a review convention.\n */\nexport const DELIVERY_COMPONENT_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;\n\nexport const deliveryComponentSchema = z\n .string()\n .regex(\n DELIVERY_COMPONENT_PATTERN,\n \"delivery component must be identifier-shaped: no whitespace, no path separators\",\n );\n\n/** Most identifier-shaped fields one callback identity may be built from. */\nexport const MAX_DELIVERY_COMPONENTS = 8;\n\n/**\n * An adapter's assertion that this callback has a replay-stable identity.\n *\n * The adapter reports *components* rather than a finished id: it knows which\n * payload fields are trustworthy, and the runtime owns how they are combined,\n * scoped, and digested. That split is what keeps a raw provider identifier from\n * becoming an on-disk key or a diagnostic attribute (see\n * `resolveDeliveryIdentity`).\n *\n * Returning nothing is always safe. Claiming an identity that is not actually\n * stable is not: it makes the runtime suppress a *genuine* second callback as if\n * it were a redelivery, which silently loses telemetry.\n */\nexport const providerDeliveryClaimSchema = z.strictObject({\n /**\n * The provider's own session/conversation id. Scopes the callback identity, so\n * two sessions reusing one tool-call id never collide.\n */\n sessionId: nonEmptyStringSchema,\n /** The provider's own name for this callback, e.g. `PostToolUse`. */\n sourceEventName: deliveryComponentSchema,\n /**\n * Identifier-shaped payload fields that, together with `sourceEventName`,\n * name this callback within the session exactly once.\n */\n components: z.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),\n /**\n * Short, non-sensitive justifications, e.g. `\"payload.tool_use_id names one\n * tool call\"`. Evidence reaches diagnostics, so it must name fields, never\n * quote their values.\n */\n evidence: z.array(z.string().min(1).max(160)).min(1).max(4).readonly(),\n});\nexport type ProviderDeliveryClaim = z.infer<typeof providerDeliveryClaimSchema>;\n\n/**\n * Shape a per-callback delivery *gap* explanation must have.\n *\n * These strings reach a diagnostic, so the same reasoning that constrains\n * {@link deliveryComponentSchema} applies for the opposite purpose: a component\n * must be identifier-shaped, a gap reason must be prose that cannot smuggle a\n * filesystem path or a newline-delimited payload dump into stderr. Spaces are\n * allowed — it is a sentence — and `/`, `\\`, and control characters are not,\n * which is what keeps a home directory out of a message an adapter author writes\n * by hand.\n */\nexport const DELIVERY_GAP_REASON_PATTERN = /^[^\\n\\r\\t\\\\/]{1,240}$/;\n\nexport const deliveryGapReasonSchema = z\n .string()\n .regex(\n DELIVERY_GAP_REASON_PATTERN,\n \"delivery gap reason must be one line of prose: no path separators, no control characters\",\n );\n\n/** Most callbacks one adapter may document a delivery gap for. */\nexport const MAX_DELIVERY_GAPS = 48;\n\n/**\n * Why each of an adapter's callbacks carries no replay-stable identity.\n *\n * Keyed by the provider's *own* event name — the same value `detect` reports as\n * `sourceEventName` — so the runtime can look up the reason for the callback in\n * front of it without parsing the payload a second time.\n *\n * This exists because `callback-not-identifiable` on its own is a true statement\n * that helps nobody: an operator auditing coverage with `--require-callback-id`\n * needs to know *which* callback and *what field would have to exist*, and only\n * the adapter knows that. Keeping it declarative rather than computed means the\n * answer is reviewable next to the protocol it describes, and an exhaustiveness\n * test can insist that adding a hook event without deciding its delivery status\n * reads as an omission.\n */\nexport const providerDeliveryGapsSchema = z\n .record(deliveryComponentSchema, deliveryGapReasonSchema)\n .refine((gaps) => Object.keys(gaps).length <= MAX_DELIVERY_GAPS, {\n message: `at most ${String(MAX_DELIVERY_GAPS)} delivery gaps may be declared`,\n });\nexport type ProviderDeliveryGaps = z.infer<typeof providerDeliveryGapsSchema>;\n\n/**\n * What an adapter can actually observe.\n *\n * Capabilities are declared rather than probed so consumers can distinguish\n * \"this provider reports no cached tokens\" from \"this session used no cache\" —\n * the two look identical in the data.\n */\nexport const providerCapabilitiesSchema = z.strictObject({\n /** Event types the adapter can produce. */\n lifecycleEvents: z.array(canonicalEventTypeSchema).max(32).readonly(),\n usageTemporality: usageTemporalitySchema,\n /**\n * Which accumulator series a `cumulative` report continues — that is, which\n * previous snapshot the next one should be diffed against.\n *\n * Only meaningful when `usageTemporality` is `cumulative`; omit otherwise.\n *\n * - `event-scope` (the default when omitted) — each event scope keeps its own\n * running total, so a `generation.end` snapshot is diffed against the\n * previous snapshot *for that same generation*.\n * - `session-lifetime` — the provider maintains **one** running total for the\n * whole session and stamps it onto whichever callback happens to report it.\n * Diffing such a snapshot per event scope would restart the baseline on\n * every new generation id and re-count the entire session total each turn,\n * so session-level and generation-level snapshots share one baseline.\n * Subagent snapshots keep their own series regardless: a delegated agent's\n * counter is not a point on the parent session's curve.\n */\n cumulativeUsageSeries: z.enum([\"event-scope\", \"session-lifetime\"]).optional(),\n reportsCachedInput: z.boolean(),\n reportsCacheCreation: z.boolean(),\n cacheCreationAccounting: cacheCreationAccountingSchema,\n reportsReasoningOutput: z.boolean(),\n reportsProviderTotal: z.boolean(),\n reportsCost: z.boolean(),\n emitsSubagentEvents: z.boolean(),\n emitsCompactionEvents: z.boolean(),\n /** True when the provider reads a structured response from stdout. */\n requiresHookResponse: z.boolean(),\n /** How much of this provider's hook traffic is replay-identifiable. */\n deliveryIdentifier: deliveryIdentifierSupportSchema,\n});\nexport type ProviderCapabilities = z.infer<typeof providerCapabilitiesSchema>;\n\n/** Services an adapter is given. Note the absence of a filesystem or network. */\nexport type ProviderContext = {\n readonly privacy: PrivacyService;\n readonly clock: Clock;\n readonly ids: IdGenerator;\n readonly logger: Logger;\n readonly limits: PrivacyLimits;\n};\n\nexport type ProviderIdentityInput = ProviderDetectionInput & {\n readonly detection: ProviderDetection;\n};\n\nexport type ProviderParseInput = ProviderDetectionInput & {\n readonly detection: ProviderDetection;\n /** Resolved by the core; adapters never resolve identity themselves. */\n readonly identity: InvocationIdentity;\n /**\n * First sequence number the adapter may use. Sequences must be assigned\n * consecutively from here so event ids stay stable across replays.\n */\n readonly sequenceBase: number;\n};\n\nexport type ProviderParseResult =\n | {\n readonly status: \"parsed\";\n readonly events: readonly CanonicalEvent[];\n readonly warnings?: readonly string[];\n }\n /** The input was recognized but carries no telemetry. Not an error. */\n | { readonly status: \"ignored\"; readonly reason: string }\n | { readonly status: \"failed\"; readonly error: OtelHookErrorInfo };\n\nexport const providerHookResponseSchema = z.strictObject({\n /**\n * Always 0. A telemetry hook that can fail the host agent is a liability, so\n * the type forbids expressing anything else (ADR 0004).\n */\n exitCode: z.literal(0),\n /** Protocol response text. Omit to write nothing at all. */\n stdout: z.string().max(8192).optional(),\n /** Non-sensitive diagnostic text for stderr. */\n stderr: z.string().max(8192).optional(),\n /** Declares which of the two stdout contracts this response follows. */\n contract: z.enum([\"silent\", \"provider-protocol\"]),\n});\nexport type ProviderHookResponse = z.infer<typeof providerHookResponseSchema>;\n\n/** The silent response: nothing on stdout, success to the host. */\nexport const SILENT_HOOK_RESPONSE: ProviderHookResponse = Object.freeze({\n exitCode: 0 as const,\n contract: \"silent\" as const,\n});\n\nexport type ProviderHookResponseInput = {\n readonly attribution: AttributionOutcome;\n readonly attributionReason?: AttributionReason;\n readonly detection?: ProviderDetection;\n readonly emittedEvents: number;\n readonly errors: readonly OtelHookErrorInfo[];\n};\n\n/**\n * Contract every provider adapter implements.\n *\n * The four methods are deliberately separate: detection must be cheap and\n * side-effect free, identity must be expressible as claims the core can\n * arbitrate, parsing must be the only place that reads the payload, and the hook\n * response must be derivable from the outcome alone.\n */\nexport interface ProviderAdapter {\n readonly id: ProviderId;\n readonly version: string;\n readonly capabilities: ProviderCapabilities;\n /**\n * Report whether this adapter recognizes the input. Must not throw; must not\n * read files or the network. Return `none` rather than guessing.\n */\n detect(input: ProviderDetectionInput, context: ProviderContext): ProviderDetection;\n /**\n * Contribute identity claims. Returning fewer claims is always safe;\n * fabricating a session id is not.\n */\n identify(input: ProviderIdentityInput, context: ProviderContext): readonly IdentityClaim[];\n /**\n * Report this callback's replay-stable identity, when the payload carries one.\n *\n * Called before `parse`, must be cheap and side-effect free, and must not\n * throw. Return `undefined` whenever the payload's identifying fields are\n * absent or would not survive a redelivery — under-reporting costs\n * deduplication, over-reporting loses real telemetry.\n */\n deliveryIdentity?(\n input: ProviderIdentityInput,\n context: ProviderContext,\n ): ProviderDeliveryClaim | undefined;\n /**\n * Why each callback that {@link ProviderAdapter.deliveryIdentity} declines\n * carries no replay-stable identity, keyed by the provider's own event name.\n *\n * Static data, not control flow: it never decides whether a callback is\n * deduplicated, only what the runtime can *say* when it is not. An adapter that\n * declares `deliveryIdentifier: \"none\"` should still populate this — the gap is\n * then the whole story, and \"the protocol has no request id\" is a far more\n * actionable diagnostic than \"not identifiable\".\n */\n readonly deliveryGaps?: ProviderDeliveryGaps;\n /** Interpret the payload into canonical events. */\n parse(input: ProviderParseInput, context: ProviderContext): ProviderParseResult;\n /** Provider-specific hook response for the given outcome. */\n hookResponse(input: ProviderHookResponseInput, context: ProviderContext): ProviderHookResponse;\n}\n\nexport const adapterSupports = (\n adapter: ProviderAdapter,\n eventType: CanonicalEventType,\n): boolean => adapter.capabilities.lifecycleEvents.includes(eventType);\n\nexport type AdapterDescription = {\n readonly id: ResolvedProviderId;\n readonly version: string;\n readonly lifecycleEvents: readonly string[];\n readonly usageTemporality: UsageTemporality;\n readonly deliveryIdentifier: DeliveryIdentifierSupport;\n};\n\nexport const describeAdapter = (adapter: ProviderAdapter): AdapterDescription => ({\n id: adapter.id,\n version: adapter.version,\n lifecycleEvents: [...adapter.capabilities.lifecycleEvents],\n usageTemporality: adapter.capabilities.usageTemporality,\n deliveryIdentifier: adapter.capabilities.deliveryIdentifier,\n});\n\n/**\n * Ask an adapter for a delivery claim, containing anything it does wrong.\n *\n * A `deliveryIdentity` that throws, or that returns a claim the schema rejects\n * (a component carrying prose, more components than the cap), degrades to \"no\n * stable identity available\" rather than failing the invocation: deduplication\n * is an optimization, and the host's telemetry is not.\n */\nexport const readDeliveryClaim = (\n adapter: ProviderAdapter,\n input: ProviderIdentityInput,\n context: ProviderContext,\n): { readonly claim?: ProviderDeliveryClaim; readonly rejection?: string } => {\n if (adapter.deliveryIdentity === undefined) {\n return {};\n }\n let candidate: ProviderDeliveryClaim | undefined;\n try {\n candidate = adapter.deliveryIdentity(input, context);\n } catch {\n return { rejection: `adapter ${adapter.id} threw while reporting a delivery identity` };\n }\n if (candidate === undefined) {\n return {};\n }\n const parsed = providerDeliveryClaimSchema.safeParse(candidate);\n if (!parsed.success) {\n return {\n rejection: `adapter ${adapter.id} reported a malformed delivery identity: ${parsed.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`)\n .join(\"; \")}`.slice(0, 240),\n };\n }\n return { claim: parsed.data };\n};\n\n/**\n * Look up why this callback has no replay-stable identity, containing anything\n * the adapter got wrong.\n *\n * Validated on the way out rather than trusted, for the same reason a claim is:\n * the string ends up in a diagnostic an operator reads, and an adapter that pasted\n * a path or a payload excerpt into its own gap table must produce *no detail*\n * rather than a disclosure. Returning `undefined` costs a sentence of explanation\n * and nothing else — the reason code is reported either way.\n */\nexport const readDeliveryGap = (\n adapter: ProviderAdapter,\n sourceEventName: string | undefined,\n): string | undefined => {\n if (sourceEventName === undefined || adapter.deliveryGaps === undefined) {\n return undefined;\n }\n // A prototype-polluting event name must not reach a bare property read: the\n // event name comes from a payload, and `__proto__` is a string like any other.\n if (!Object.prototype.hasOwnProperty.call(adapter.deliveryGaps, sourceEventName)) {\n return undefined;\n }\n const parsed = deliveryGapReasonSchema.safeParse(adapter.deliveryGaps[sourceEventName]);\n return parsed.success ? parsed.data : undefined;\n};\n\nexport const asProviderId = (value: string): ProviderId => providerIdSchema.parse(value);\n\nexport const unknownDetection = (\n reasons: readonly string[] = [\"no adapter recognized the input\"],\n): ProviderDetection =>\n providerDetectionSchema.parse({\n providerId: \"unknown\",\n confidence: \"none\",\n reasons: reasons.slice(0, 8),\n });\n","import { z } from \"zod\";\n\nimport {\n errorPhaseSchema,\n errorSeveritySchema,\n otelHookErrorCodeSchema,\n} from \"../errors/taxonomy.js\";\nimport { contentFactSchema, contentFactsSchema } from \"./content.js\";\nimport { extensionsSchema, emptyExtensions } from \"./extensions.js\";\nimport { sourceProvenanceSchema, workspaceIdentitySchema } from \"./identity.js\";\nimport {\n durationMillisSchema,\n epochMillisSchema,\n eventIdSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n sequenceNumberSchema,\n sessionIdSchema,\n tokenCountSchema,\n} from \"./primitives.js\";\nimport { canonicalUsageSchema, type CanonicalUsage } from \"./usage.js\";\nimport { canonicalSchemaVersionSchema } from \"./version.js\";\n\n/** Model being invoked. Model identifiers are not treated as sensitive. */\nexport const modelDescriptorSchema = z.strictObject({\n modelId: nonEmptyStringSchema,\n /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */\n vendor: nonEmptyStringSchema.optional(),\n family: nonEmptyStringSchema.optional(),\n});\nexport type ModelDescriptor = z.infer<typeof modelDescriptorSchema>;\n\nexport const costFactsSchema = z.strictObject({\n /** ISO 4217 code. */\n currency: z.string().length(3),\n amount: z.number().min(0).finite(),\n source: z.enum([\"provider-reported\", \"computed\"]),\n});\nexport type CostFacts = z.infer<typeof costFactsSchema>;\n\nexport const canonicalEventTypeSchema = z.enum([\n \"session.start\",\n \"session.end\",\n \"prompt.submitted\",\n \"generation.start\",\n \"generation.end\",\n \"tool.start\",\n \"tool.end\",\n \"subagent.start\",\n \"subagent.end\",\n \"compaction.performed\",\n \"error.raised\",\n]);\nexport type CanonicalEventType = z.infer<typeof canonicalEventTypeSchema>;\n\nexport const CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;\n\nconst outcomeSchema = z.enum([\"ok\", \"error\", \"cancelled\", \"timeout\", \"denied\", \"unknown\"]);\nexport type EventOutcome = z.infer<typeof outcomeSchema>;\n\n/**\n * Fields present on every canonical event.\n *\n * Identity fields are duplicated onto each event rather than referenced through\n * shared state, so an event is self-describing once it leaves the process.\n */\nconst baseEventFields = {\n schemaVersion: canonicalSchemaVersionSchema,\n eventId: eventIdSchema,\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Per-invocation ordering key. Stable across replays of the same input. */\n sequence: sequenceNumberSchema,\n occurredAt: epochMillisSchema,\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n extensions: extensionsSchema.default(emptyExtensions),\n} as const;\n\nconst event = <TShape extends z.ZodRawShape>(shape: TShape) =>\n z.strictObject({ ...baseEventFields, ...shape });\n\nexport const sessionStartEventSchema = event({\n type: z.literal(\"session.start\"),\n sessionKind: z.enum([\"interactive\", \"non-interactive\", \"unknown\"]),\n agentName: nonEmptyStringSchema.optional(),\n agentVersion: nonEmptyStringSchema.optional(),\n model: modelDescriptorSchema.optional(),\n});\n\nexport const sessionEndEventSchema = event({\n type: z.literal(\"session.end\"),\n reason: z.enum([\"completed\", \"aborted\", \"error\", \"timeout\", \"unknown\"]),\n durationMillis: durationMillisSchema.optional(),\n /** Session totals, typically cumulative. */\n usage: canonicalUsageSchema.optional(),\n cost: costFactsSchema.optional(),\n});\n\nexport const promptSubmittedEventSchema = event({\n type: z.literal(\"prompt.submitted\"),\n promptSource: z.enum([\"user\", \"automation\", \"resumed\", \"unknown\"]),\n content: contentFactSchema.optional(),\n turnIndex: z.number().int().min(0).optional(),\n});\n\nexport const generationStartEventSchema = event({\n type: z.literal(\"generation.start\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n requestedMaxOutputTokens: tokenCountSchema.optional(),\n inputContent: contentFactsSchema.optional(),\n});\n\nexport const generationEndEventSchema = event({\n type: z.literal(\"generation.end\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n outcome: outcomeSchema,\n stopReason: nonEmptyStringSchema.optional(),\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n cost: costFactsSchema.optional(),\n outputContent: contentFactsSchema.optional(),\n});\n\nexport const toolKindSchema = z.enum([\n \"read\",\n \"write\",\n \"execute\",\n \"search\",\n \"network\",\n \"delegate\",\n \"other\",\n \"unknown\",\n]);\nexport type ToolKind = z.infer<typeof toolKindSchema>;\n\nexport const toolStartEventSchema = event({\n type: z.literal(\"tool.start\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n toolKind: toolKindSchema,\n generationId: nonEmptyStringSchema.optional(),\n input: contentFactSchema.optional(),\n});\n\nexport const toolEndEventSchema = event({\n type: z.literal(\"tool.end\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n /** Present when the host asked for or recorded a permission decision. */\n permissionDecision: z.enum([\"allowed\", \"denied\", \"deferred\", \"not-required\"]).optional(),\n output: contentFactSchema.optional(),\n});\n\nexport const subagentStartEventSchema = event({\n type: z.literal(\"subagent.start\"),\n subagentInvocationId: invocationIdSchema,\n subagentType: nonEmptyStringSchema.optional(),\n /** 0 for the top-level agent; 1 for its direct children. */\n delegationDepth: z.number().int().min(0).max(64),\n model: modelDescriptorSchema.optional(),\n});\n\nexport const subagentEndEventSchema = event({\n type: z.literal(\"subagent.end\"),\n subagentInvocationId: invocationIdSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const compactionPerformedEventSchema = event({\n type: z.literal(\"compaction.performed\"),\n trigger: z.enum([\"automatic\", \"manual\", \"unknown\"]),\n /** Provider-reported context size before and after compaction, if known. */\n contextTokensBefore: tokenCountSchema.optional(),\n contextTokensAfter: tokenCountSchema.optional(),\n droppedMessageCount: z.number().int().min(0).optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const errorRaisedEventSchema = event({\n type: z.literal(\"error.raised\"),\n errorCode: otelHookErrorCodeSchema,\n severity: errorSeveritySchema,\n phase: errorPhaseSchema,\n retryable: z.boolean(),\n /** Error text is content: it is described, never embedded verbatim by default. */\n message: contentFactSchema.optional(),\n /** Non-sensitive, provider-agnostic short label. */\n detail: nonEmptyStringSchema.optional(),\n});\n\nexport const canonicalEventSchema = z.discriminatedUnion(\"type\", [\n sessionStartEventSchema,\n sessionEndEventSchema,\n promptSubmittedEventSchema,\n generationStartEventSchema,\n generationEndEventSchema,\n toolStartEventSchema,\n toolEndEventSchema,\n subagentStartEventSchema,\n subagentEndEventSchema,\n compactionPerformedEventSchema,\n errorRaisedEventSchema,\n]);\n\nexport type CanonicalEvent = z.infer<typeof canonicalEventSchema>;\nexport type CanonicalEventInput = z.input<typeof canonicalEventSchema>;\n\nexport type SessionStartEvent = z.infer<typeof sessionStartEventSchema>;\nexport type SessionEndEvent = z.infer<typeof sessionEndEventSchema>;\nexport type PromptSubmittedEvent = z.infer<typeof promptSubmittedEventSchema>;\nexport type GenerationStartEvent = z.infer<typeof generationStartEventSchema>;\nexport type GenerationEndEvent = z.infer<typeof generationEndEventSchema>;\nexport type ToolStartEvent = z.infer<typeof toolStartEventSchema>;\nexport type ToolEndEvent = z.infer<typeof toolEndEventSchema>;\nexport type SubagentStartEvent = z.infer<typeof subagentStartEventSchema>;\nexport type SubagentEndEvent = z.infer<typeof subagentEndEventSchema>;\nexport type CompactionPerformedEvent = z.infer<typeof compactionPerformedEventSchema>;\nexport type ErrorRaisedEvent = z.infer<typeof errorRaisedEventSchema>;\n\nexport type CanonicalEventOfType<TType extends CanonicalEventType> = Extract<\n CanonicalEvent,\n { type: TType }\n>;\n\nexport type EventValidationResult =\n | { readonly status: \"ok\"; readonly event: CanonicalEvent }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nexport const validateCanonicalEvent = (value: unknown): EventValidationResult => {\n const parsed = canonicalEventSchema.safeParse(value);\n if (parsed.success) {\n return { status: \"ok\", event: parsed.data };\n }\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n};\n\n/** Parse or throw. Intended for fixtures and tests, not the hook path. */\nexport const parseCanonicalEvent = (value: unknown): CanonicalEvent =>\n canonicalEventSchema.parse(value);\n\n/** Usage carried by an event, if the event type can carry any. */\nexport const eventUsage = (event: CanonicalEvent): CanonicalUsage | undefined =>\n \"usage\" in event ? event.usage : undefined;\n\n/** Stable ordering: by sequence, then by timestamp, then by event id. */\nexport const compareEvents = (a: CanonicalEvent, b: CanonicalEvent): number =>\n a.sequence - b.sequence || a.occurredAt - b.occurredAt || a.eventId.localeCompare(b.eventId);\n","import type { DetectionPolicy } from \"../config/schema.js\";\nimport { createErrorInfo, errorInfoFromThrown, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport {\n DETECTION_CONFIDENCE_RANK,\n type ProviderId,\n} from \"../model/primitives.js\";\nimport {\n providerDetectionSchema,\n unknownDetection,\n type ProviderAdapter,\n type ProviderContext,\n type ProviderDetection,\n type ProviderDetectionInput,\n} from \"./adapter.js\";\n\nexport type DetectionCandidate = {\n readonly adapter: ProviderAdapter;\n readonly detection: ProviderDetection;\n};\n\nexport type RegistryDetectionResult =\n | {\n readonly status: \"selected\";\n readonly adapter: ProviderAdapter;\n readonly detection: ProviderDetection;\n readonly candidates: readonly DetectionCandidate[];\n readonly errors: readonly OtelHookErrorInfo[];\n }\n | {\n readonly status: \"unknown\";\n readonly reason:\n | \"no-adapters-registered\"\n | \"no-candidates\"\n | \"below-minimum-confidence\"\n | \"provider-not-allowed\";\n readonly detection: ProviderDetection;\n readonly candidates: readonly DetectionCandidate[];\n readonly errors: readonly OtelHookErrorInfo[];\n }\n | {\n readonly status: \"ambiguous\";\n readonly detection: ProviderDetection;\n readonly candidates: readonly DetectionCandidate[];\n readonly errors: readonly OtelHookErrorInfo[];\n };\n\n/**\n * Immutable set of adapters.\n *\n * A registry is a value passed to the runtime, not a mutable module-level\n * singleton: two hooks in one process may legitimately be configured with\n * different adapter sets, and a global would let one silently reconfigure the\n * other.\n */\nexport interface ProviderRegistry {\n readonly adapters: readonly ProviderAdapter[];\n get(id: string): ProviderAdapter | undefined;\n detect(\n input: ProviderDetectionInput,\n context: ProviderContext,\n policy: DetectionPolicy,\n ): RegistryDetectionResult;\n}\n\nexport const createProviderRegistry = (\n adapters: readonly ProviderAdapter[],\n): ProviderRegistry => {\n const byId = new Map<string, ProviderAdapter>();\n for (const adapter of adapters) {\n if (byId.has(adapter.id)) {\n throw createDuplicateAdapterError(adapter.id);\n }\n byId.set(adapter.id, adapter);\n }\n const frozen = Object.freeze([...adapters]);\n\n return {\n adapters: frozen,\n get: (id: string): ProviderAdapter | undefined => byId.get(id),\n detect: (\n input: ProviderDetectionInput,\n context: ProviderContext,\n policy: DetectionPolicy,\n ): RegistryDetectionResult => {\n const errors: OtelHookErrorInfo[] = [];\n const candidates: DetectionCandidate[] = [];\n\n if (frozen.length === 0) {\n return {\n status: \"unknown\",\n reason: \"no-adapters-registered\",\n detection: unknownDetection([\"no adapters registered\"]),\n candidates,\n errors,\n };\n }\n\n // Reasons from adapters that recognized the callback well enough to\n // explain why they declined it — as opposed to one that never looked at\n // this payload shape at all. Kept only for the \"no-candidates\" outcome\n // below: a payload every adapter genuinely ignores should still read as\n // the generic message, but a payload one adapter recognized and rejected\n // (e.g. Cursor's own envelope contract) must not be flattened into that\n // same generic message — that is the difference between \"provider\n // unknown\" and \"provider known, payload rejected for a stated reason\",\n // and only the raw per-adapter `detect()` result carries the latter.\n const nearMisses: string[] = [];\n\n for (const adapter of frozen) {\n let detection: ProviderDetection;\n try {\n detection = providerDetectionSchema.parse(adapter.detect(input, context));\n } catch (thrown) {\n // A misbehaving adapter must not suppress its peers.\n errors.push(errorInfoFromThrown(thrown, { code: \"provider-adapter-failure\", phase: \"detection\" }));\n continue;\n }\n if (detection.confidence === \"none\") {\n for (const reason of detection.reasons) {\n const prefixed = `${adapter.id}: ${reason}`;\n nearMisses.push(prefixed.length <= 160 ? prefixed : `${prefixed.slice(0, 159)}…`);\n }\n continue;\n }\n if (detection.providerId !== adapter.id) {\n errors.push(\n createErrorInfo({\n code: \"provider-adapter-failure\",\n phase: \"detection\",\n detail: `adapter ${adapter.id} claimed provider id ${detection.providerId}`,\n details: { \"adapter.id\": adapter.id, \"detection.provider_id\": detection.providerId },\n }),\n );\n continue;\n }\n candidates.push({ adapter, detection });\n }\n\n if (candidates.length === 0) {\n return {\n status: \"unknown\",\n reason: \"no-candidates\",\n detection: unknownDetection(nearMisses.length === 0 ? undefined : nearMisses.slice(0, 8)),\n candidates,\n errors,\n };\n }\n\n const bestRank = Math.max(\n ...candidates.map((candidate) => DETECTION_CONFIDENCE_RANK[candidate.detection.confidence]),\n );\n const best = candidates.filter(\n (candidate) => DETECTION_CONFIDENCE_RANK[candidate.detection.confidence] === bestRank,\n );\n\n if (best.length > 1) {\n return {\n status: \"ambiguous\",\n detection: unknownDetection([\n `${best.length} adapters matched at equal confidence`,\n ...best.map((candidate) => `candidate ${candidate.adapter.id}`),\n ]),\n candidates,\n errors,\n };\n }\n\n const [winner] = best;\n if (winner === undefined) {\n return {\n status: \"unknown\",\n reason: \"no-candidates\",\n detection: unknownDetection(),\n candidates,\n errors,\n };\n }\n\n if (bestRank < DETECTION_CONFIDENCE_RANK[policy.minimumConfidence]) {\n return {\n status: \"unknown\",\n reason: \"below-minimum-confidence\",\n detection: unknownDetection([\n `best confidence ${winner.detection.confidence} is below required ${policy.minimumConfidence}`,\n ]),\n candidates,\n errors,\n };\n }\n\n if (\n policy.allowedProviderIds.length > 0 &&\n !policy.allowedProviderIds.includes(winner.adapter.id)\n ) {\n return {\n status: \"unknown\",\n reason: \"provider-not-allowed\",\n detection: unknownDetection([`provider ${winner.adapter.id} is not in the allow-list`]),\n candidates,\n errors,\n };\n }\n\n return {\n status: \"selected\",\n adapter: winner.adapter,\n detection: winner.detection,\n candidates,\n errors,\n };\n },\n };\n};\n\nconst createDuplicateAdapterError = (id: ProviderId): Error =>\n new Error(`duplicate provider adapter id: ${id}`);\n\n/**\n * Built-in adapters.\n *\n * Empty by design in the core package: provider support is added by dedicated\n * adapter modules, and the core must remain testable without any of them.\n */\nexport const BUILT_IN_PROVIDERS: readonly ProviderAdapter[] = Object.freeze([]);\n","import type { DeliveryIdentifierSupport, ProviderDeliveryClaim } from \"../providers/adapter.js\";\nimport type { IdGenerator } from \"./ports.js\";\n\n/**\n * Where a delivery identity came from.\n *\n * `host` is an id the embedding host passed in; `provider` is one normalized\n * from payload fields the selected adapter vouched for. The two are kept\n * distinguishable because they carry different guarantees: a host id is unique\n * by construction, a provider-derived one is only as good as the adapter's\n * evidence.\n */\nexport type DeliveryOrigin = \"host\" | \"provider\";\n\n/**\n * A delivery identity reduced to the two opaque strings deduplication needs.\n *\n * Both are digests, never raw payload values. That matters because the pair\n * becomes a state-store key and a diagnostic attribute: a provider's session id,\n * tool-call id, or turn id would otherwise be written to disk and logged as a\n * side effect of deduplication, which is not a disclosure anybody asked for.\n */\nexport type ResolvedDeliveryIdentity = {\n /** Namespace the callback id is unique within. */\n readonly scope: string;\n /** Opaque identity of this callback within that scope. */\n readonly callbackId: string;\n readonly origin: DeliveryOrigin;\n /** Non-sensitive justifications, for diagnostics. Empty for a host id. */\n readonly evidence: readonly string[];\n};\n\n/** Why no replay-stable delivery identity could be established. */\nexport type DeliveryUnavailableReason =\n /** No adapter was selected, so nothing could vouch for an identifier. */\n | \"provider-unattributed\"\n /** The adapter declares that no callback of this provider carries one. */\n | \"provider-declares-none\"\n /** The adapter supports some callbacks, but not this one. */\n | \"callback-not-identifiable\"\n /** The adapter offered an identity that failed the contract's own guards. */\n | \"claim-rejected\"\n /**\n * An identity was established but the state store could not be read or written,\n * so nothing could be claimed against it.\n */\n | \"state-unavailable\";\n\nexport type DeliveryResolution =\n | { readonly status: \"resolved\"; readonly identity: ResolvedDeliveryIdentity }\n | {\n readonly status: \"unavailable\";\n readonly reason: DeliveryUnavailableReason;\n /** Present once a provider has been selected. */\n readonly providerId?: string;\n /** The adapter's declared coverage, when there is an adapter. */\n readonly capability?: DeliveryIdentifierSupport;\n /**\n * The provider's own name for the callback that could not be identified.\n *\n * Taken from the detection, which already carries it into span attributes\n * and provenance, so it discloses nothing new — and it is the difference\n * between a diagnostic an operator can act on and one that only restates\n * that something is missing.\n */\n readonly sourceEventName?: string;\n /**\n * Why, in the adapter's own words: a rejected claim's failure, or the\n * per-callback gap the adapter documents. Never contains payload values.\n */\n readonly detail?: string;\n };\n\n/**\n * Scope prefix for provider-derived identities.\n *\n * Kept distinct from a host-chosen scope so the two id spaces cannot be\n * confused, and so a host that starts supplying `--callback-id` does not inherit\n * whatever the adapter had already recorded for the same callbacks.\n */\nconst PROVIDER_SCOPE_PREFIX = \"provider-session\";\n\n/**\n * Namespace a host-supplied delivery id.\n *\n * Deliberately *not* scoped by session or installation: the host documented its\n * id as unique between distinct callbacks, so narrowing the scope here would\n * make a host id that repeats across two sessions stop being recognized as the\n * redelivery the host said it was.\n */\nexport const hostDeliveryIdentity = (\n callbackId: string,\n scope?: string,\n): ResolvedDeliveryIdentity => ({\n scope: scope ?? \"delivery\",\n callbackId,\n origin: \"host\",\n evidence: [],\n});\n\n/**\n * Reduce an adapter's delivery claim to an opaque, replay-stable identity.\n *\n * Scoping runs provider id, installation, and the provider's own session id\n * through the digest, so the same tool-call id observed by two installations, two\n * providers, or two sessions is three different callbacks. The callback digest\n * covers the event name and the adapter's components, so a `PreToolUse` and a\n * `PostToolUse` sharing one `tool_use_id` stay distinct.\n *\n * The digest comes from the injected {@link IdGenerator}, which is\n * content-addressed by default — that is precisely what makes the identity\n * survive a process restart: a later process with the same namespace recomputes\n * the identical pair without reading any state.\n */\nexport const resolveDeliveryIdentity = (input: {\n readonly ids: IdGenerator;\n readonly providerId: string;\n readonly installationId: string;\n readonly claim: ProviderDeliveryClaim;\n}): ResolvedDeliveryIdentity => {\n const { ids, providerId, installationId, claim } = input;\n return {\n scope: `${PROVIDER_SCOPE_PREFIX}:${ids.newOpaqueId([\n \"delivery-scope\",\n providerId,\n installationId,\n claim.sessionId,\n ])}`,\n callbackId: ids.newOpaqueId([\n \"delivery-callback\",\n providerId,\n claim.sessionId,\n claim.sourceEventName,\n ...claim.components,\n ]),\n origin: \"provider\",\n evidence: [...claim.evidence],\n };\n};\n","import { createHash, randomUUID } from \"node:crypto\";\n\nimport {\n eventIdSchema,\n invocationIdSchema,\n type EventId,\n type InvocationId,\n} from \"../model/primitives.js\";\nimport type { EventIdSeed, IdGenerator, InvocationIdSeed } from \"./ports.js\";\n\nconst digest = (namespace: string, parts: readonly (string | number | undefined)[]): string => {\n const hash = createHash(\"sha256\");\n hash.update(namespace);\n for (const part of parts) {\n hash.update(\"\\0\");\n hash.update(part === undefined ? \"\" : String(part));\n }\n return hash.digest(\"hex\");\n};\n\nexport type DeterministicIdOptions = {\n /**\n * Namespace mixed into every id. Two deployments using different namespaces\n * produce different ids for identical input, which prevents cross-tenant id\n * collisions in a shared collector.\n */\n readonly namespace?: string;\n /** Hex characters retained. 32 gives a 128-bit id. */\n readonly length?: number;\n};\n\n/**\n * Content-addressed id generator.\n *\n * Ids are a pure function of their seed, so re-running a hook on the same input\n * — a retry, a replayed transcript, a duplicated delivery — yields identical\n * ids. That makes the pipeline idempotent at the collector instead of relying on\n * exactly-once delivery, which hooks cannot provide.\n */\nexport const createDeterministicIdGenerator = (\n options: DeterministicIdOptions = {},\n): IdGenerator => {\n const namespace = options.namespace ?? \"otel-hook\";\n const length = Math.min(Math.max(options.length ?? 32, 16), 64);\n const truncate = (hex: string): string => hex.slice(0, length);\n\n return {\n newInvocationId: (seed: InvocationIdSeed): InvocationId =>\n invocationIdSchema.parse(\n `inv_${truncate(\n digest(`${namespace}/invocation`, [\n seed.providerId,\n seed.sessionId,\n seed.sourceEventName,\n seed.occurredAt,\n seed.discriminator,\n ]),\n )}`,\n ),\n newEventId: (seed: EventIdSeed): EventId =>\n eventIdSchema.parse(\n `evt_${truncate(\n digest(`${namespace}/event`, [\n seed.invocationId,\n seed.sequence,\n seed.eventType,\n seed.discriminator,\n ]),\n )}`,\n ),\n newOpaqueId: (parts: readonly string[]): string =>\n truncate(digest(`${namespace}/opaque`, parts)),\n };\n};\n\n/**\n * Random id generator.\n *\n * Use only when no stable seed exists; it is not replay-safe, so duplicate\n * deliveries become duplicate events.\n */\nexport const createRandomIdGenerator = (): IdGenerator => ({\n newInvocationId: (): InvocationId => invocationIdSchema.parse(`inv_${randomUUID()}`),\n newEventId: (): EventId => eventIdSchema.parse(`evt_${randomUUID()}`),\n newOpaqueId: (): string => randomUUID().replace(/-/g, \"\"),\n});\n","import { z } from \"zod\";\n\nimport type { OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport {\n attributesSchema,\n epochMillisSchema,\n sequenceNumberSchema,\n type Attributes,\n type EpochMillis,\n type EventId,\n type InvocationId,\n} from \"../model/primitives.js\";\nimport { canonicalUsageSchema } from \"../model/usage.js\";\n\n/**\n * Time source.\n *\n * Injected rather than read from `Date.now()` so tests are deterministic and so\n * a host with its own time authority can supply it.\n */\nexport interface Clock {\n /** Wall-clock time in whole milliseconds since the Unix epoch. */\n now(): EpochMillis;\n /** Monotonic reading for durations; unrelated to wall clock. */\n monotonicMillis(): number;\n}\n\n/** Stable inputs from which an invocation id is derived. */\nexport type InvocationIdSeed = {\n readonly providerId: string;\n readonly sessionId: string;\n readonly sourceEventName?: string;\n readonly occurredAt: number;\n /** Provider-supplied uniqueness, e.g. a request id. */\n readonly discriminator?: string;\n};\n\n/** Stable inputs from which an event id is derived. */\nexport type EventIdSeed = {\n readonly invocationId: string;\n readonly sequence: number;\n readonly eventType: string;\n readonly discriminator?: string;\n};\n\n/**\n * Identifier factory.\n *\n * Seeds are structured rather than free-form so the default implementation can\n * be a pure function of its inputs: replaying the same source data produces the\n * same ids, which lets a collector dedupe instead of double-counting.\n */\nexport interface IdGenerator {\n newInvocationId(seed: InvocationIdSeed): InvocationId;\n newEventId(seed: EventIdSeed): EventId;\n /** Short opaque id for spans and generations, derived from its parts. */\n newOpaqueId(parts: readonly string[]): string;\n}\n\n/**\n * Which delivery's observations are already folded into a stored total.\n *\n * The reason this rides *inside* the total's own record rather than beside it: the\n * store has no multi-key transaction, so a marker in a second key could be written\n * without the total or the other way round, and a marker that can disagree with\n * what it describes is worse than none. In one record the two move together under a\n * single write, which is what makes re-applying a redelivered callback's usage a\n * no-op instead of a double count.\n *\n * `callbackId` is an opaque digest supplied by the caller, never a host's raw\n * delivery id: a state record is somewhere a raw provider or host identifier must\n * not appear as a side effect of deduplicating on it.\n */\nexport const appliedDeliverySchema = z.strictObject({\n callbackId: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/),\n /** How many of that delivery's observations are folded in, counted from one. */\n applications: z.number().int().min(1).max(4_096),\n});\nexport type AppliedDelivery = z.infer<typeof appliedDeliverySchema>;\n\n/** Values the state store may hold. Restricted so state stays inspectable. */\nexport const stateValueSchema = z.discriminatedUnion(\"kind\", [\n z.strictObject({\n kind: z.literal(\"usage-cumulative\"),\n usage: canonicalUsageSchema,\n /**\n * Optional: absent on every record written before this field existed, which\n * reads as \"unknown provenance\" and simply forgoes the idempotency check\n * rather than resetting a baseline to gain it.\n */\n appliedDelivery: appliedDeliverySchema.optional(),\n }),\n z.strictObject({\n kind: z.literal(\"sequence\"),\n next: sequenceNumberSchema,\n }),\n z.strictObject({\n kind: z.literal(\"attributes\"),\n attributes: attributesSchema,\n }),\n]);\nexport type StateValue = z.infer<typeof stateValueSchema>;\n\nexport const stateRecordSchema = z.strictObject({\n /** Incremented on each write; lets callers detect lost updates. */\n revision: z.number().int().min(0),\n updatedAt: epochMillisSchema,\n value: stateValueSchema,\n});\nexport type StateRecord = z.infer<typeof stateRecordSchema>;\n\n/**\n * Durable-ish key/value state.\n *\n * Needed because a hook process is short-lived but usage accounting spans an\n * entire session. The interface is intentionally minimal: no transactions, no\n * queries, nothing a file or a KV row cannot provide.\n */\nexport interface StateStore {\n read(key: string): Promise<StateRecord | undefined>;\n /** Writes unconditionally, returning the stored record. */\n write(key: string, value: StateValue): Promise<StateRecord>;\n delete(key: string): Promise<void>;\n keys(prefix: string): Promise<readonly string[]>;\n}\n\nexport type TelemetryEmitResult = {\n readonly accepted: number;\n readonly rejected: number;\n readonly errors: readonly OtelHookErrorInfo[];\n};\n\n/**\n * Destination for canonical events.\n *\n * The sink receives canonical events only — never provider payloads — so an\n * exporter cannot become a second, unaudited disclosure path.\n */\nexport interface TelemetrySink {\n emit(events: readonly CanonicalEvent[]): Promise<TelemetryEmitResult>;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nexport const logLevelSchema = z.enum([\"silent\", \"error\", \"warn\", \"info\", \"debug\"]);\nexport type LogLevel = z.infer<typeof logLevelSchema>;\n\nexport const LOG_LEVEL_RANK: Readonly<Record<LogLevel, number>> = Object.freeze({\n silent: 0,\n error: 1,\n warn: 2,\n info: 3,\n debug: 4,\n});\n\n/**\n * Diagnostic logger.\n *\n * Fields are attribute values, not arbitrary objects, so a log line cannot\n * become a way to print a provider payload. Implementations must never write to\n * stdout (ADR 0004).\n */\nexport interface Logger {\n error(message: string, fields?: Attributes): void;\n warn(message: string, fields?: Attributes): void;\n info(message: string, fields?: Attributes): void;\n debug(message: string, fields?: Attributes): void;\n}\n","import type { Attributes } from \"../model/primitives.js\";\nimport { LOG_LEVEL_RANK, type Logger, type LogLevel } from \"./ports.js\";\n\nexport const createNullLogger = (): Logger => ({\n error: (): void => undefined,\n warn: (): void => undefined,\n info: (): void => undefined,\n debug: (): void => undefined,\n});\n\nexport type StderrLoggerOptions = {\n readonly level?: LogLevel;\n /** Injected for tests; defaults to `process.stderr.write`. */\n readonly write?: (line: string) => void;\n};\n\n/**\n * Diagnostic logger that writes to stderr only.\n *\n * stdout belongs to the host agent's hook protocol: anything written there can\n * be parsed as a hook response and change the agent's behaviour (ADR 0004).\n */\nexport const createStderrLogger = (options: StderrLoggerOptions = {}): Logger => {\n const level = options.level ?? \"warn\";\n const write =\n options.write ??\n ((line: string): void => {\n process.stderr.write(line);\n });\n const threshold = LOG_LEVEL_RANK[level];\n\n const log = (entryLevel: LogLevel, message: string, fields?: Attributes): void => {\n if (LOG_LEVEL_RANK[entryLevel] > threshold || threshold === 0) {\n return;\n }\n const payload =\n fields === undefined || Object.keys(fields).length === 0\n ? { level: entryLevel, message }\n : { level: entryLevel, message, fields };\n write(`${JSON.stringify(payload)}\\n`);\n };\n\n return {\n error: (message: string, fields?: Attributes): void => {\n log(\"error\", message, fields);\n },\n warn: (message: string, fields?: Attributes): void => {\n log(\"warn\", message, fields);\n },\n info: (message: string, fields?: Attributes): void => {\n log(\"info\", message, fields);\n },\n debug: (message: string, fields?: Attributes): void => {\n log(\"debug\", message, fields);\n },\n };\n};\n","import { randomBytes } from \"node:crypto\";\nimport { mkdir, open, readFile, readdir, rename, unlink, writeFile } from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport type { Clock, Logger, StateRecord, StateValue } from \"../runtime/ports.js\";\nimport { stateRecordSchema } from \"../runtime/ports.js\";\nimport { createAsyncLock } from \"./async-lock.js\";\nimport { keyDigest, namespaceSegments, sanitizeSegment, type StoreNamespace } from \"./keys.js\";\nimport { StateLockTimeoutError, type LockingStateStore } from \"./store.js\";\n\nexport type FilesystemStateStoreOptions = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Bounds how long a write, read, or session lock waits. Default 5,000ms. */\n readonly lockTimeoutMillis?: number;\n /** A lock file older than this is assumed to belong to a crashed process and is reclaimed. Default 30,000ms. */\n readonly lockStaleMillis?: number;\n /** Delay between lock acquisition attempts. Default 25ms. */\n readonly lockPollIntervalMillis?: number;\n};\n\nexport interface FilesystemStateStore extends LockingStateStore {\n readonly recordsDir: string;\n readonly quarantineDir: string;\n /** Bounded sweep: removes records untouched for longer than `maxAgeMillis`. */\n pruneStale(\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number },\n ): Promise<{ readonly removed: number; readonly scanned: number }>;\n}\n\ntype Envelope = { readonly key: string; readonly record: StateRecord };\n\nconst isErrnoException = (thrown: unknown, code: string): boolean =>\n thrown instanceof Error && (thrown as NodeJS.ErrnoException).code === code;\n\nconst sleep = (millis: number): Promise<void> =>\n new Promise((resolve) => {\n const timer = setTimeout(resolve, millis);\n timer.unref?.();\n });\n\nconst wrapFsError = (thrown: unknown, operation: string): Error => {\n if (thrown instanceof Error) {\n return new Error(`filesystem state store ${operation} failed: ${thrown.name}`, { cause: thrown });\n }\n return new Error(`filesystem state store ${operation} failed`);\n};\n\n/**\n * Crash-safe filesystem {@link StateStore}.\n *\n * Every write lands via a temp file plus `rename`, which POSIX guarantees is\n * atomic within one directory: a reader never observes a half-written record,\n * and a process killed mid-write leaves only an orphaned temp file, never a\n * corrupt one. A record that still fails to parse (disk corruption, a manual\n * edit, a future incompatible version) is quarantined rather than thrown from\n * `read`, so a single bad file degrades one key instead of the whole store.\n *\n * Locking is layered: an in-process {@link createAsyncLock} orders same-process\n * callers, and a lock file with a staleness timeout orders across processes\n * and recovers automatically if the holder crashed while holding it.\n */\nexport const createFilesystemStateStore = (\n options: FilesystemStateStoreOptions,\n): FilesystemStateStore => {\n const [providerSegment, installationSegment] = namespaceSegments(options);\n const baseDir = path.join(options.rootDir, providerSegment, installationSegment);\n const recordsDir = path.join(baseDir, \"records\");\n const quarantineDir = path.join(baseDir, \"quarantine\");\n const locksDir = path.join(baseDir, \"locks\");\n\n const lockTimeoutMillis = options.lockTimeoutMillis ?? 5_000;\n const lockStaleMillis = options.lockStaleMillis ?? 30_000;\n const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;\n\n const keyLock = createAsyncLock();\n const sessionLock = createAsyncLock();\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(recordsDir, { recursive: true });\n await mkdir(quarantineDir, { recursive: true });\n await mkdir(locksDir, { recursive: true });\n })();\n dirsReady = promise;\n try {\n await promise;\n } catch (thrown) {\n dirsReady = undefined;\n throw wrapFsError(thrown, \"ensure-dirs\");\n }\n };\n\n const recordPath = (key: string): string => path.join(recordsDir, `${keyDigest(key)}.json`);\n const tempPath = (key: string): string =>\n path.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes(6).toString(\"hex\")}.json`);\n const lockPath = (sessionId: string): string =>\n path.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);\n\n const quarantine = async (filePath: string, key: string, reason: string): Promise<void> => {\n const dest = path.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);\n try {\n await rename(filePath, dest);\n } catch {\n await unlink(filePath).catch(() => undefined);\n }\n options.logger?.warn(\"filesystem state record quarantined\", { \"state.reason\": reason });\n };\n\n const readUnlocked = async (key: string): Promise<StateRecord | undefined> => {\n await ensureDirs();\n const filePath = recordPath(key);\n let raw: string;\n try {\n raw = await readFile(filePath, \"utf8\");\n } catch (thrown) {\n if (isErrnoException(thrown, \"ENOENT\")) {\n return undefined;\n }\n throw wrapFsError(thrown, \"read\");\n }\n\n let parsedJson: unknown;\n try {\n parsedJson = JSON.parse(raw);\n } catch {\n await quarantine(filePath, key, \"invalid-json\");\n return undefined;\n }\n\n const envelope = parsedJson as Partial<Envelope>;\n if (envelope.key !== key) {\n await quarantine(filePath, key, \"key-mismatch\");\n return undefined;\n }\n const parsed = stateRecordSchema.safeParse(envelope.record);\n if (!parsed.success) {\n await quarantine(filePath, key, \"schema-invalid\");\n return undefined;\n }\n return parsed.data;\n };\n\n const writeUnlocked = async (key: string, value: StateValue): Promise<StateRecord> => {\n await ensureDirs();\n const previous = await readUnlocked(key);\n const record = stateRecordSchema.parse({\n revision: (previous?.revision ?? 0) + 1,\n updatedAt: options.clock.now(),\n value,\n });\n const envelope: Envelope = { key, record };\n const tmp = tempPath(key);\n try {\n await writeFile(tmp, JSON.stringify(envelope), \"utf8\");\n await rename(tmp, recordPath(key));\n } catch (thrown) {\n await unlink(tmp).catch(() => undefined);\n throw wrapFsError(thrown, \"write\");\n }\n return record;\n };\n\n const acquireFileLock = async (\n sessionId: string,\n timeoutMillis: number,\n ): Promise<() => Promise<void>> => {\n await ensureDirs();\n const filePath = lockPath(sessionId);\n const startedAt = options.clock.monotonicMillis();\n\n for (;;) {\n try {\n const handle = await open(filePath, \"wx\");\n try {\n await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));\n } finally {\n await handle.close();\n }\n return async (): Promise<void> => {\n await unlink(filePath).catch(() => undefined);\n };\n } catch (thrown) {\n if (!isErrnoException(thrown, \"EEXIST\")) {\n throw wrapFsError(thrown, \"lock\");\n }\n }\n\n const stale = await (async (): Promise<boolean> => {\n try {\n const raw = await readFile(filePath, \"utf8\");\n const parsed = JSON.parse(raw) as { acquiredAt?: unknown };\n return (\n typeof parsed.acquiredAt !== \"number\" ||\n options.clock.now() - parsed.acquiredAt > lockStaleMillis\n );\n } catch {\n return true;\n }\n })();\n if (stale) {\n await unlink(filePath).catch(() => undefined);\n continue;\n }\n\n if (options.clock.monotonicMillis() - startedAt >= timeoutMillis) {\n // A typed error, so a caller can tell \"a peer holds this\" apart from \"the\n // store is unusable\" — the two demand opposite responses.\n throw new StateLockTimeoutError(sessionId, timeoutMillis);\n }\n await sleep(lockPollIntervalMillis);\n }\n };\n\n return {\n recordsDir,\n quarantineDir,\n read: (key: string): Promise<StateRecord | undefined> =>\n keyLock.run(key, () => readUnlocked(key), lockTimeoutMillis),\n write: (key: string, value: StateValue): Promise<StateRecord> =>\n keyLock.run(key, () => writeUnlocked(key, value), lockTimeoutMillis),\n delete: (key: string): Promise<void> =>\n keyLock.run(\n key,\n async (): Promise<void> => {\n await ensureDirs();\n await unlink(recordPath(key)).catch((thrown: unknown) => {\n if (!isErrnoException(thrown, \"ENOENT\")) {\n throw wrapFsError(thrown, \"delete\");\n }\n });\n },\n lockTimeoutMillis,\n ),\n keys: async (prefix: string): Promise<readonly string[]> => {\n await ensureDirs();\n let entries: string[];\n try {\n entries = await readdir(recordsDir);\n } catch (thrown) {\n if (isErrnoException(thrown, \"ENOENT\")) {\n return [];\n }\n throw wrapFsError(thrown, \"keys\");\n }\n const found: string[] = [];\n for (const entry of entries) {\n if (!entry.endsWith(\".json\") || entry.startsWith(\".tmp-\")) {\n continue;\n }\n let raw: string;\n try {\n raw = await readFile(path.join(recordsDir, entry), \"utf8\");\n } catch {\n continue;\n }\n try {\n const envelope = JSON.parse(raw) as Partial<Envelope>;\n if (typeof envelope.key === \"string\" && envelope.key.startsWith(prefix)) {\n found.push(envelope.key);\n }\n } catch {\n continue;\n }\n }\n return found.sort();\n },\n withSessionLock: async <T>(\n sessionId: string,\n fn: () => Promise<T>,\n lockOptions?: { readonly timeoutMillis?: number },\n ): Promise<T> => {\n const timeoutMillis = lockOptions?.timeoutMillis ?? lockTimeoutMillis;\n return sessionLock.run(\n sessionId,\n async (): Promise<T> => {\n const release = await acquireFileLock(sessionId, timeoutMillis);\n try {\n return await fn();\n } finally {\n await release();\n }\n },\n timeoutMillis,\n );\n },\n pruneStale: async (\n maxAgeMillis: number,\n pruneOptions?: { readonly maxEntries?: number },\n ): Promise<{ readonly removed: number; readonly scanned: number }> => {\n await ensureDirs();\n const cap = pruneOptions?.maxEntries ?? 5_000;\n const now = options.clock.now();\n let removed = 0;\n let scanned = 0;\n\n let entries: string[];\n try {\n entries = await readdir(recordsDir);\n } catch (thrown) {\n if (!isErrnoException(thrown, \"ENOENT\")) {\n throw wrapFsError(thrown, \"prune\");\n }\n entries = [];\n }\n for (const entry of entries) {\n if (scanned >= cap) {\n break;\n }\n if (!entry.endsWith(\".json\") || entry.startsWith(\".tmp-\")) {\n continue;\n }\n scanned += 1;\n const filePath = path.join(recordsDir, entry);\n try {\n // Ages are measured against the record's own `updatedAt`, taken from\n // the injected clock at write time, never the OS mtime: a test (or a\n // host) using a clock other than the wall clock would otherwise be\n // compared against a completely unrelated time source.\n const raw = await readFile(filePath, \"utf8\");\n const envelope = JSON.parse(raw) as Partial<Envelope>;\n const updatedAt = envelope.record?.updatedAt;\n if (typeof updatedAt === \"number\" && now - updatedAt > maxAgeMillis) {\n await unlink(filePath).catch(() => undefined);\n removed += 1;\n }\n } catch {\n continue;\n }\n }\n\n let lockEntries: string[];\n try {\n lockEntries = await readdir(locksDir);\n } catch {\n lockEntries = [];\n }\n for (const entry of lockEntries) {\n const filePath = path.join(locksDir, entry);\n try {\n const raw = await readFile(filePath, \"utf8\");\n const parsed = JSON.parse(raw) as { acquiredAt?: unknown };\n if (typeof parsed.acquiredAt === \"number\" && now - parsed.acquiredAt > lockStaleMillis) {\n await unlink(filePath).catch(() => undefined);\n }\n } catch {\n continue;\n }\n }\n\n return { removed, scanned };\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 { 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 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 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 { 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 { 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 { 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_CACHE_CREATION_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n} from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport type { ContentFact } from \"../model/content.js\";\nimport type { CanonicalEvent, CanonicalEventType } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\nimport { exportIdentityAttributes } from \"./export-identity.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_EVENT_TYPE = \"otelhook.event.type\";\nconst ATTR_OTELHOOK_EVENT_ID = \"otelhook.event.id\";\nconst ATTR_OTELHOOK_EVENT_SEQUENCE = \"otelhook.event.sequence\";\nconst ATTR_OTELHOOK_LOG_SIGNAL = \"otelhook.log.signal\";\nconst ATTR_OTELHOOK_LOG_MAPPING_VERSION = \"otelhook.log.mapping_version\";\nconst ATTR_OTELHOOK_OUTCOME = \"otelhook.outcome\";\nconst ATTR_OTELHOOK_TOOL_KIND = \"otelhook.tool.kind\";\nconst ATTR_OTELHOOK_TOOL_PERMISSION = \"otelhook.tool.permission_decision\";\nconst ATTR_OTELHOOK_DELEGATION_DEPTH = \"otelhook.delegation_depth\";\nconst ATTR_OTELHOOK_SUBAGENT_TYPE = \"otelhook.subagent.type\";\nconst ATTR_OTELHOOK_AGENT_NAME = \"otelhook.agent.name\";\nconst ATTR_OTELHOOK_AGENT_VERSION = \"otelhook.agent.version\";\nconst ATTR_OTELHOOK_SESSION_KIND = \"otelhook.session.kind\";\nconst ATTR_OTELHOOK_PROMPT_SOURCE = \"otelhook.prompt.source\";\nconst ATTR_OTELHOOK_PROMPT_TURN_INDEX = \"otelhook.prompt.turn_index\";\nconst ATTR_OTELHOOK_GENERATION_ID = \"otelhook.generation.id\";\nconst ATTR_OTELHOOK_STOP_REASON = \"otelhook.generation.stop_reason\";\nconst ATTR_OTELHOOK_COMPACTION_TRIGGER = \"otelhook.compaction.trigger\";\nconst ATTR_OTELHOOK_CONTEXT_TOKENS_BEFORE = \"otelhook.compaction.context_tokens_before\";\nconst ATTR_OTELHOOK_CONTEXT_TOKENS_AFTER = \"otelhook.compaction.context_tokens_after\";\nconst ATTR_OTELHOOK_DROPPED_MESSAGES = \"otelhook.compaction.dropped_message_count\";\nconst ATTR_OTELHOOK_ERROR_PHASE = \"otelhook.error.phase\";\nconst ATTR_OTELHOOK_ERROR_RETRYABLE = \"otelhook.error.retryable\";\nconst ATTR_OTELHOOK_ERROR_SEVERITY = \"otelhook.error.severity\";\n\nconst ATTR_CONTENT_KIND = \"otelhook.content.kind\";\nconst ATTR_CONTENT_ROLE = \"otelhook.content.role\";\nconst ATTR_CONTENT_DISCLOSURE = \"otelhook.content.disclosure\";\nconst ATTR_CONTENT_CHARACTER_LENGTH = \"otelhook.content.character_length\";\nconst ATTR_CONTENT_BYTE_LENGTH = \"otelhook.content.byte_length\";\nconst ATTR_CONTENT_HASH = \"otelhook.content.hash\";\nconst ATTR_CONTENT_TRUNCATED = \"otelhook.content.truncated\";\nconst ATTR_CONTENT_SECRETS_REDACTED = \"otelhook.content.secrets_redacted\";\nconst ATTR_CONTENT_LABEL = \"otelhook.content.label\";\nconst ATTR_CONTENT_WITHHELD = \"otelhook.content.withheld\";\nconst ATTR_CONTENT_BODY_TRUNCATED = \"otelhook.content.body_truncated\";\n\n/**\n * Why a content fact reached the wire without its text.\n *\n * Stated rather than left as an absence, because \"this prompt was empty\", \"this\n * deployment omits content\", and \"this deployment discloses content but not to\n * the logs pipeline\" are three different operational facts that all look like a\n * missing body.\n */\nexport type ContentWithholdingReason =\n /** The privacy policy produced no text at all — the default `omit` posture. */\n | \"privacy-policy\"\n /** Content is disclosed elsewhere, but the logs pipeline is not permitted it. */\n | \"logs-content-disabled\"\n /** The fact carries verbatim text and `allowRawContent` is not set. */\n | \"raw-not-permitted\";\n\n/**\n * Whether disclosed content text may reach a log body.\n *\n * Two gates rather than one, and both must open. `includeContent` is the logs\n * pipeline's own switch, and it exists because spans carry no content in *any*\n * content mode: without it, turning on `privacy.contentMode` to get a hash and a\n * length — which is all it ever bought before — would start putting prompts on\n * the wire. `allowRawContent` is the pre-existing verbatim-content opt-in,\n * re-checked here because the sink is the last boundary before the wire and a\n * hand-built fact could otherwise carry `disclosure: \"raw\"` past a policy that\n * never permitted it.\n */\nexport type LogContentPolicy = {\n readonly includeContent: boolean;\n readonly allowRawContent: boolean;\n};\n\n/** Content disabled, which is what an unconfigured installation gets. */\nexport const NO_LOG_CONTENT: LogContentPolicy = Object.freeze({\n includeContent: false,\n allowRawContent: false,\n});\n\nconst codePointLength = (value: string): number => [...value].length;\n\nconst sliceCodePoints = (value: string, max: number): string => {\n let result = \"\";\n let count = 0;\n for (const char of value) {\n if (count >= max) {\n break;\n }\n result += char;\n count += 1;\n }\n return result;\n};\n\n/**\n * Which pipeline an event's records belong to.\n *\n * `factKind` refines the answer where one event type carries more than one kind\n * of content: a `generation.end` holds the response *and*, on providers that\n * report it, the reasoning that produced it, and collapsing those into one signal\n * would make \"drop reasoning, keep responses\" unexpressible.\n */\nexport const logSignalOf = (event: CanonicalEvent, factKind?: ContentFact[\"kind\"]): LogSignal => {\n switch (event.type) {\n case \"session.start\":\n case \"session.end\":\n return \"session\";\n case \"prompt.submitted\":\n return \"prompt\";\n case \"generation.start\":\n return factKind === \"reasoning\" ? \"reasoning\" : \"prompt\";\n case \"generation.end\":\n return factKind === \"reasoning\" ? \"reasoning\" : \"response\";\n case \"subagent.start\":\n case \"subagent.end\":\n return \"delegation\";\n case \"compaction.performed\":\n return \"compaction\";\n case \"error.raised\":\n return \"error\";\n case \"tool.start\":\n return toolSignal(event.toolName, event.toolKind);\n case \"tool.end\":\n // A `tool.end` carries no `toolKind`: only the start edge does. Classifying\n // from the name alone is what the canonical model permits here, so a shell\n // or file operation whose name does not say so lands on `tool` — and the\n // span for the same scope, which *did* recover the kind from state, is where\n // that detail is authoritative.\n return toolSignal(event.toolName, undefined);\n }\n};\n\nconst toolSignal = (\n toolName: string,\n toolKind: Extract<CanonicalEvent, { type: \"tool.start\" }>[\"toolKind\"] | undefined,\n): LogSignal => {\n if (MCP_TOOL_NAME_PATTERN.test(toolName)) {\n return \"mcp\";\n }\n switch (toolKind) {\n case \"execute\":\n return \"shell\";\n case \"read\":\n case \"write\":\n return \"file-operation\";\n case \"delegate\":\n return \"delegation\";\n default:\n return \"tool\";\n }\n};\n\n/**\n * Log signals an adapter declaring these lifecycle events can produce.\n *\n * Derived from the adapter's existing `lifecycleEvents` declaration rather than\n * declared separately, which is the whole point: a hand-maintained second list\n * can disagree with the first, and a capability declaration that has gone stale is\n * worse than none — a consumer cannot tell \"this provider reports no tool output\"\n * from \"this declaration was never updated\".\n *\n * The tool refinements (`shell`, `file-operation`, `mcp`) are reported whenever\n * the adapter emits tool events at all, because which of them a given callback\n * produces depends on the payload, not on the adapter. So this is a statement\n * about what *may* appear, not what always will.\n */\nexport const logSignalsForLifecycleEvents = (\n lifecycleEvents: readonly CanonicalEventType[],\n): readonly LogSignal[] => {\n const signals = new Set<LogSignal>();\n const add = (...values: readonly LogSignal[]): void => {\n for (const value of values) {\n signals.add(value);\n }\n };\n for (const type of lifecycleEvents) {\n switch (type) {\n case \"session.start\":\n case \"session.end\":\n add(\"session\");\n break;\n case \"prompt.submitted\":\n add(\"prompt\");\n break;\n case \"generation.start\":\n add(\"prompt\");\n break;\n case \"generation.end\":\n add(\"response\", \"reasoning\");\n break;\n case \"tool.start\":\n case \"tool.end\":\n add(\"tool\", \"shell\", \"file-operation\", \"mcp\", \"delegation\");\n break;\n case \"subagent.start\":\n case \"subagent.end\":\n add(\"delegation\");\n break;\n case \"compaction.performed\":\n add(\"compaction\");\n break;\n case \"error.raised\":\n add(\"error\");\n break;\n }\n }\n return LOG_SIGNALS.filter((signal) => signals.has(signal));\n};\n\nconst severityFor = (event: CanonicalEvent): SeverityNumber => {\n switch (event.type) {\n case \"error.raised\":\n return event.severity === \"error\" ? SeverityNumber.ERROR : SeverityNumber.WARN;\n case \"session.end\":\n return event.reason === \"error\" || event.reason === \"timeout\"\n ? SeverityNumber.ERROR\n : event.reason === \"aborted\"\n ? SeverityNumber.WARN\n : SeverityNumber.INFO;\n case \"generation.end\":\n case \"tool.end\":\n case \"subagent.end\":\n return event.outcome === \"error\" || event.outcome === \"timeout\"\n ? SeverityNumber.ERROR\n : event.outcome === \"denied\" || event.outcome === \"cancelled\"\n ? SeverityNumber.WARN\n : SeverityNumber.INFO;\n default:\n return SeverityNumber.INFO;\n }\n};\n\nconst SEVERITY_TEXT: Readonly<Record<number, string>> = Object.freeze({\n [SeverityNumber.INFO]: \"INFO\",\n [SeverityNumber.WARN]: \"WARN\",\n [SeverityNumber.ERROR]: \"ERROR\",\n});\n\nconst identityAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n ids: { readonly traceId: string; readonly spanId: string; readonly parentSpanId?: string },\n): LogAttributes => exportIdentityAttributes(event, resource, ids);\n\n/**\n * Attributes describing the event itself, independent of any content it carries.\n *\n * Every attribute here is a closed vocabulary, an identifier this library\n * derived, a count, or a boolean — the same restriction the privacy service\n * applies everywhere else, so an attribute can never become a second disclosure\n * path alongside the body.\n */\nconst eventAttributes = (event: CanonicalEvent): 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 = (usage: CanonicalUsage | undefined): 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 [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: usage.cachedInputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: usage.cacheCreationInputTokens,\n };\n\n/** Content facts an event carries, paired with the field they came from. */\nconst contentFactsOf = (event: CanonicalEvent): readonly ContentFact[] => {\n switch (event.type) {\n case \"prompt.submitted\":\n return event.content === undefined ? [] : [event.content];\n case \"generation.start\":\n return event.inputContent ?? [];\n case \"generation.end\":\n return event.outputContent ?? [];\n case \"tool.start\":\n return event.input === undefined ? [] : [event.input];\n case \"tool.end\":\n return event.output === undefined ? [] : [event.output];\n case \"error.raised\":\n return event.message === undefined ? [] : [event.message];\n default:\n return [];\n }\n};\n\ntype DisclosedBody =\n | { readonly text: string; readonly truncated: boolean }\n | { readonly withheld: ContentWithholdingReason }\n | { readonly metadataOnly: true };\n\nconst discloseBody = (fact: ContentFact, policy: LogContentPolicy): DisclosedBody => {\n if (fact.text === undefined && fact.characterLength === 0) {\n // The provider sent no text. Distinct from a privacy omit of real content:\n // there is nothing to withhold, and the record must say metadata_only.\n return { metadataOnly: true };\n }\n if (fact.text === undefined) {\n return { withheld: \"privacy-policy\" };\n }\n if (!policy.includeContent) {\n return { withheld: \"logs-content-disabled\" };\n }\n if (fact.disclosure === \"raw\" && !policy.allowRawContent) {\n // Belt to the privacy service's braces: `resolvePrivacyPolicy` already\n // downgrades `raw` without the opt-in, so reaching here means a fact was built\n // outside that path. Refusing rather than trusting it keeps the opt-in a\n // property of the wire, not of one code path.\n return { withheld: \"raw-not-permitted\" };\n }\n const length = codePointLength(fact.text);\n return length <= MAX_LOG_BODY_CHARACTERS\n ? { text: fact.text, truncated: false }\n : { text: sliceCodePoints(fact.text, MAX_LOG_BODY_CHARACTERS), truncated: true };\n};\n\nconst contentAttributes = (fact: ContentFact, body: DisclosedBody): LogAttributes => ({\n [ATTR_CONTENT_KIND]: fact.kind,\n ...(fact.role === undefined ? {} : { [ATTR_CONTENT_ROLE]: fact.role }),\n [ATTR_CONTENT_DISCLOSURE]: \"metadataOnly\" in body ? \"metadata_only\" : fact.disclosure,\n [ATTR_CONTENT_CHARACTER_LENGTH]: fact.characterLength,\n [ATTR_CONTENT_BYTE_LENGTH]: fact.byteLength,\n [ATTR_CONTENT_HASH]: fact.contentHash,\n [ATTR_CONTENT_TRUNCATED]: fact.truncated,\n [ATTR_CONTENT_SECRETS_REDACTED]: fact.secretsRedacted,\n ...(fact.label === undefined ? {} : { [ATTR_CONTENT_LABEL]: fact.label }),\n ...(\"withheld\" in body\n ? { [ATTR_CONTENT_WITHHELD]: body.withheld }\n : \"metadataOnly\" in body\n ? {}\n : { [ATTR_CONTENT_BODY_TRUNCATED]: body.truncated }),\n});\n\nexport type LogMappingOptions = {\n readonly resource: Resource;\n readonly instrumentationScope?: InstrumentationScope;\n /** Whether disclosed text may reach a body. Defaults to {@link NO_LOG_CONTENT}. */\n readonly content?: LogContentPolicy;\n /**\n * The same cross-process pairing facts the span mapping is given, so a record's\n * `spanContext` names the span id that batch actually exported.\n */\n readonly correlations?: readonly SpanCorrelation[];\n /** See `SemanticMappingOptions.correlationAvailable`. */\n readonly correlationAvailable?: boolean;\n};\n\nexport type LogMappingResult = {\n readonly records: readonly ReadableLogRecord[];\n /**\n * Content facts no record was produced for, because a bound was reached.\n *\n * Reported rather than truncated silently: a caller that logged \"N records\n * exported\" and nothing else would read a clipped batch as a complete one.\n */\n readonly droppedFacts: number;\n};\n\nconst buildRecord = (input: {\n readonly event: CanonicalEvent;\n readonly signal: LogSignal;\n readonly attributes: LogAttributes;\n readonly body?: string;\n readonly spanContext: SpanContext;\n readonly parentSpanId?: string;\n readonly resource: Resource;\n readonly scope: InstrumentationScope;\n}): ReadableLogRecord => {\n const severityNumber = severityFor(input.event);\n const hrTime = millisToHrTime(input.event.occurredAt);\n return {\n hrTime,\n // A hook observes an event that already happened, and this mapping is pure —\n // there is no clock here to read a real observation time from. Reporting the\n // occurrence time for both is the honest answer: it says \"this is when it\n // happened\" twice rather than inventing a second, wrong timestamp.\n hrTimeObserved: hrTime,\n spanContext: input.spanContext,\n severityNumber,\n severityText: SEVERITY_TEXT[severityNumber] ?? \"INFO\",\n ...(input.body === undefined ? {} : { body: input.body }),\n eventName: `otelhook.${input.event.type}`,\n resource: input.resource,\n instrumentationScope: input.scope,\n attributes: {\n ...identityAttributes(input.event, input.resource, {\n traceId: input.spanContext.traceId,\n spanId: input.spanContext.spanId,\n ...(input.parentSpanId === undefined ? {} : { parentSpanId: input.parentSpanId }),\n }),\n [ATTR_OTELHOOK_EVENT_TYPE]: input.event.type,\n [ATTR_OTELHOOK_EVENT_ID]: input.event.eventId,\n [ATTR_OTELHOOK_EVENT_SEQUENCE]: input.event.sequence,\n [ATTR_OTELHOOK_LOG_SIGNAL]: input.signal,\n [ATTR_OTELHOOK_LOG_MAPPING_VERSION]: LOG_MAPPING_VERSION,\n ...input.attributes,\n },\n droppedAttributesCount: 0,\n };\n};\n\n/**\n * Map one invocation's canonical event batch into OTLP-ready log records.\n *\n * One record per content fact, and one record per event that carries none, so an\n * event is never silently absent from the stream just because the provider\n * reported no text for it.\n */\nexport const canonicalEventsToLogRecords = (\n events: readonly CanonicalEvent[],\n options: LogMappingOptions,\n): LogMappingResult => {\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const content = options.content ?? NO_LOG_CONTENT;\n const identities = canonicalEventTraceIdentities(events, {\n ...(options.correlations === undefined ? {} : { correlations: options.correlations }),\n ...(options.correlationAvailable === undefined\n ? {}\n : { correlationAvailable: options.correlationAvailable }),\n });\n\n const records: ReadableLogRecord[] = [];\n let droppedFacts = 0;\n\n for (const event of events) {\n const identity = identities.get(event.eventId);\n if (identity === undefined) {\n // Unreachable: every event in the batch is given an identity above.\n continue;\n }\n const spanContext: SpanContext = {\n traceId: identity.traceId,\n spanId: identity.spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n };\n const shared = eventAttributes(event);\n const facts = contentFactsOf(event);\n\n if (facts.length === 0) {\n if (records.length >= MAX_LOG_RECORDS_PER_BATCH) {\n droppedFacts += 1;\n continue;\n }\n records.push(\n buildRecord({\n event,\n signal: logSignalOf(event),\n attributes:\n event.type === \"generation.end\"\n ? { ...shared, [ATTR_CONTENT_KIND]: \"response\", [ATTR_CONTENT_DISCLOSURE]: \"metadata_only\" }\n : shared,\n spanContext,\n ...(identity.parentSpanId === undefined ? {} : { parentSpanId: identity.parentSpanId }),\n resource: options.resource,\n scope,\n }),\n );\n continue;\n }\n\n let perEvent = 0;\n for (const fact of facts) {\n if (perEvent >= MAX_LOG_RECORDS_PER_EVENT || records.length >= MAX_LOG_RECORDS_PER_BATCH) {\n droppedFacts += 1;\n continue;\n }\n perEvent += 1;\n const body = discloseBody(fact, content);\n records.push(\n buildRecord({\n event,\n signal: logSignalOf(event, fact.kind),\n attributes: { ...shared, ...contentAttributes(fact, body) },\n ...(\"text\" in body ? { body: body.text } : {}),\n spanContext,\n ...(identity.parentSpanId === undefined ? {} : { parentSpanId: identity.parentSpanId }),\n resource: options.resource,\n scope,\n }),\n );\n }\n }\n\n return { records, droppedFacts };\n};\n","import { 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 type { DeliveryHealthSnapshot } from \"../diagnostics/health.js\";\nimport type { OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { TelemetryEmitResult, TelemetrySink } from \"../runtime/ports.js\";\nimport type { OtlpLogTelemetrySink } from \"./otlp-log-sink.js\";\nimport type { OtlpTelemetrySink } from \"./otlp-sink.js\";\nimport type { SpanCorrelation, SpanCorrelationResolver } from \"./semconv.js\";\n\n/**\n * One canonical batch, two OTLP signals.\n *\n * A hook has a single {@link TelemetrySink} seam, and both signals map the *same*\n * canonical events — so this fans one batch out rather than making the orchestrator\n * aware that there is more than one destination.\n *\n * ## Durability adds up across signals\n *\n * The counts are summed rather than taken from the primary signal, because the\n * caller's question is \"may I commit this callback?\" and the answer turns on whether\n * *anything* reached a collector or a spool. Summing gives `classifyDurability`\n * exactly the right inputs:\n *\n * - both signals delivered → `delivered`\n * - neither delivered → `lost`, and the callback is safe to retry precisely because\n * there is nothing to duplicate\n * - one delivered and one did not → `partial`, which is terminal: retrying would\n * re-export what the healthy signal already delivered, and a duplicate silently\n * corrupts a total whereas a reported loss is a number somebody can act on\n *\n * A disabled sink accepts everything, so an installation with logs off behaves\n * exactly as it did before logs existed.\n *\n * ## Correlation must be resolved once per batch\n *\n * Both sinks want the same pairing facts, and `SpanCorrelator.correlateBatch` is not\n * a read — it records a start edge, marks a scope published, and takes the session\n * lock to do it. Wrap the correlator in {@link shareCorrelationPerBatch} and give\n * *the same wrapped function* to both sinks; `emit` here is sequential so the first\n * sink resolves it and the second is served the memoized answer.\n */\n\nexport type SignalFanoutOptions = {\n readonly traces: OtlpTelemetrySink;\n readonly logs: OtlpLogTelemetrySink;\n};\n\nexport interface SignalFanoutSink extends TelemetrySink {\n /** One snapshot per wired signal, in a stable order: traces, then logs. */\n health(): readonly DeliveryHealthSnapshot[];\n}\n\nexport const createSignalFanout = (options: SignalFanoutOptions): SignalFanoutSink => {\n const emit = async (events: readonly CanonicalEvent[]): Promise<TelemetryEmitResult> => {\n // Sequential, not concurrent: the first sink to ask resolves correlation, and\n // the second must be served that answer rather than race to start a second\n // resolution against the same state.\n const traces = await options.traces.emit(events);\n const logs = await options.logs.emit(events);\n const errors: readonly OtelHookErrorInfo[] = [...traces.errors, ...logs.errors];\n return {\n accepted: traces.accepted + logs.accepted,\n rejected: traces.rejected + logs.rejected,\n errors,\n };\n };\n\n const flush = async (): Promise<void> => {\n // Each signal's flush is already best-effort and non-throwing; awaiting both\n // unconditionally means a stuck logs endpoint cannot skip the trace flush.\n await options.traces.flush().catch(() => undefined);\n await options.logs.flush().catch(() => undefined);\n };\n\n const shutdown = async (): Promise<void> => {\n await options.traces.shutdown().catch(() => undefined);\n await options.logs.shutdown().catch(() => undefined);\n };\n\n return {\n emit,\n flush,\n shutdown,\n health: (): readonly DeliveryHealthSnapshot[] => [\n options.traces.health(),\n options.logs.health(),\n ],\n };\n};\n\n/**\n * Wrap a correlation resolver so one batch resolves at most once.\n *\n * Memoized on the identity of the `events` array, which is what makes it correct\n * without a reset: every batch is a distinct array, so a new batch cannot be served\n * a previous one's answer, and a retry of the *same* array deliberately is. The\n * promise is cached rather than its value, so two callers arriving before the first\n * resolution completes still share it.\n *\n * Exported because the one-call-per-batch property is a requirement of the\n * correlator, not a convenience of the fanout: a host wiring its own pair of sinks\n * needs to be able to express it too.\n */\nexport const shareCorrelationPerBatch = (\n correlate: SpanCorrelationResolver,\n): SpanCorrelationResolver => {\n let pending:\n | {\n readonly events: readonly CanonicalEvent[];\n readonly result: Promise<readonly SpanCorrelation[]>;\n }\n | undefined;\n return (events): Promise<readonly SpanCorrelation[]> => {\n if (pending?.events === events) {\n return pending.result;\n }\n const result = correlate(events);\n pending = { events, result };\n return result;\n };\n};\n","import type { OtelHookConfig } from \"../config/schema.js\";\nimport { summarizeHealth, type DeliveryHealthSnapshot, type OverallHealth } from \"../diagnostics/health.js\";\nimport { createErrorInfo, errorInfoFromThrown, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport {\n createCallbackDeduplicator,\n type CallbackDeduplicator,\n type DeliveryClaimOutcome,\n} from \"../lifecycle/dedup.js\";\nimport { createLifecycleJanitor, type LifecycleCleanupReport, type LifecycleJanitor } from \"../lifecycle/janitor.js\";\nimport { createSpanCorrelator, type SpanCorrelator } from \"../lifecycle/span-correlator.js\";\nimport {\n createUsageAccumulator,\n type UsageAccumulator,\n type UsageAccumulatorSnapshot,\n} from \"../lifecycle/usage-accumulator.js\";\nimport { createPrivacyService, type PrivacyService } from \"../privacy/service.js\";\nimport type { ProviderRegistry } from \"../providers/registry.js\";\nimport { createSystemClock } from \"../runtime/clock.js\";\nimport {\n createOtelHook,\n isCommittable,\n type HookIngestInput,\n type HookIngestOutcome,\n type OtelHook,\n type UsageObservation,\n} from \"../runtime/hook.js\";\nimport {\n hostDeliveryIdentity,\n type DeliveryOrigin,\n type DeliveryResolution,\n type DeliveryUnavailableReason,\n type ResolvedDeliveryIdentity,\n} from \"../runtime/delivery.js\";\nimport { createDeterministicIdGenerator } from \"../runtime/ids.js\";\nimport { createNullLogger } from \"../runtime/logger.js\";\nimport type { Clock, IdGenerator, Logger } from \"../runtime/ports.js\";\nimport { createAsyncLock } from \"../state/async-lock.js\";\nimport { createFilesystemStateStore, type FilesystemStateStore } from \"../state/filesystem-store.js\";\nimport {\n createFileDurableLogSpool,\n type DurableLogSpool,\n} from \"../telemetry/durable-log-spool.js\";\nimport { createFileDurableSpool, type DurableSpool } from \"../telemetry/durable-spool.js\";\nimport { createOtlpLogSink, type OtlpLogTelemetrySink } from \"../telemetry/otlp-log-sink.js\";\nimport { createOtlpTraceSink, type OtlpTelemetrySink } from \"../telemetry/otlp-sink.js\";\nimport {\n createSignalFanout,\n shareCorrelationPerBatch,\n} from \"../telemetry/signal-fanout.js\";\n\n/**\n * A hook process lives for milliseconds and then exits, but the facts it needs\n * — the previous cumulative token baseline, the next sequence number, a running\n * per-scope rollup, which deliveries have already been handled — span a whole\n * session. This module is the wiring that makes those two facts coexist without\n * a daemon: filesystem-backed state, a filesystem spool for batches an\n * unreachable collector refused, and a *bounded* flush so a hanging collector\n * costs the host a known number of milliseconds rather than a stalled agent.\n *\n * ## Delivery deduplication\n *\n * A redelivered callback must not be exported or accounted twice, and it must\n * stay suppressed across a process restart — which rules out anything held in\n * memory. Two identities can carry that:\n *\n * 1. An explicit, host-supplied delivery id ({@link HookProcessInput.delivery}),\n * unique by construction because only the host knows it.\n * 2. One normalized from payload fields the selected adapter vouches for — a\n * `tool_use_id`, an `agent_id`, a `prompt_id`. Adapters declare coverage as\n * `deliveryIdentifier` and report components per callback, and the runtime\n * digests them into an opaque, installation-and-session-scoped pair.\n *\n * Neither `invocationId` nor `eventId` can serve: some adapters seed the former\n * with a clock reading (Claude Code documents each hook firing as a distinct\n * invocation), and the latter is seeded with a session sequence number that has\n * already advanced by the time a redelivery arrives.\n *\n * Ownership is taken *before* `ingest` and committed only once the batch is\n * somewhere durable: a delivery arriving inside the window sees the claim and\n * stands down, and a batch that reached neither the collector nor the spool\n * releases its claim for retry instead of committing a loss.\n *\n * **This is at-least-once export, not exactly-once.** The collector is a separate\n * system and there is no transaction spanning an OTLP acceptance and a local state\n * write, so a process killed after the collector took a batch and before the claim\n * commits will re-export on redelivery. That ordering is deliberate: a duplicate\n * carries the same derived trace and span id and can be dropped at the collector,\n * whereas committing first would turn the same window into silent loss. Local\n * accounting *is* at-most-once, because it commits under the claim's own lock.\n *\n * ## Ordering and locks\n *\n * Two locks, always acquired in one order — delivery-scope lock, then state lock —\n * and never nested one state lock inside another:\n *\n * - An in-process lock on the delivery scope serializes same-scope deliveries in\n * arrival order, so deduplication never reorders what it lets through.\n * - `ingest` holds the store's *cross-process* session lock across the session\n * state critical section, which is what stops two hook processes from stamping\n * two batches with one sequence range. Export happens after that lock is\n * released: the span correlator takes the same session lock from inside the sink,\n * and it is not reentrant.\n *\n * ## Deliberate limitations\n *\n * 1. **Deduplication coverage is per provider, and partial for every adapter.** An\n * adapter that declares `deliveryIdentifier: \"partial\"` identifies only the\n * callbacks carrying a field that separates a genuine second firing from a\n * redelivery — for most that means per-tool-call and per-subagent edges, and for\n * the Gemini CLI, whose protocol has no such field at all, only the\n * once-per-session edges. The rest are exported without the at-most-once\n * guarantee unless the host supplies a delivery id; with `requireCallbackId` the\n * runtime says so per callback instead of leaving it to be inferred.\n * 2. **Cross-process span pairing needs a durable state root.** The\n * {@link SpanCorrelator} is wired into the sink, so a `*.end` emitted by a\n * later process carries its start time, duration, parent, and start-only\n * attributes. That correlation lives entirely in the state store: point two\n * invocations at different `stateRootDir`s and each exports a lone,\n * explicitly classified orphan instead. A disabled exporter records nothing,\n * since there is no span to pair.\n */\n\nexport type HookRuntimeDelivery = {\n /**\n * Host-supplied identifier for *this* delivery of a hook callback. Stable\n * across a redelivery of the same callback, unique between distinct\n * callbacks. Nothing derives it: only the host knows it.\n */\n readonly callbackId: string;\n /** Namespace the id is unique within. Defaults to `\"delivery\"`. */\n readonly scope?: string;\n};\n\nexport type HookProcessInput = HookIngestInput & {\n readonly delivery?: HookRuntimeDelivery;\n};\n\n/**\n * What deduplication did with this callback.\n *\n * Reported rather than inferred: \"exported once because it was fresh\" and\n * \"exported once because nothing could tell it apart from a redelivery\" produce\n * identical telemetry, and only the first is a guarantee.\n */\nexport type DeliveryReport = {\n /**\n * True when a replay-stable identity was established and a claim enforced.\n *\n * Not a promise of exactly-once export: see this module's note on crash\n * semantics. It means a redelivery arriving *while local state is intact* is\n * suppressed.\n */\n readonly deduplicated: boolean;\n /** Where the identity came from. Absent when none was established. */\n readonly origin?: DeliveryOrigin;\n /** How the claim resolved. Absent when no identity was established. */\n readonly outcome?: DeliveryClaimOutcome;\n /** Why no identity was established. Absent when one was. */\n readonly reason?: DeliveryUnavailableReason;\n /** The adapter's declared coverage, when a provider was selected. */\n readonly capability?: string;\n /**\n * The provider's own name for the callback that could not be identified.\n *\n * Present only alongside `reason`. Coverage is per callback, so a host auditing\n * its own gaps needs the callback name to act on the report at all — the\n * provider id and the capability are the same for every one of them.\n */\n readonly sourceEventName?: string;\n /**\n * The adapter's own account of why this callback has no identity, and what field\n * would close the gap. Absent when the adapter documents none.\n */\n readonly detail?: string;\n /** Adapter-supplied justifications for a provider-derived identity. */\n readonly evidence?: readonly string[];\n /**\n * True when a claim was released because the batch reached neither the\n * collector nor the spool, so redelivering this callback is expected to\n * re-export it rather than be suppressed.\n */\n readonly retryable?: boolean;\n /**\n * Spans permanently lost on a callback that is nonetheless **committed**.\n *\n * Present only for a partial batch: some spans reached the collector or the\n * spool and some did not. The callback is not retried, because retrying would\n * re-export the accepted spans, so these observations are gone. Reported as a\n * number rather than folded into `retryable` because the two demand opposite\n * responses — a retryable callback needs redelivering, a partial loss needs\n * investigating.\n */\n readonly partialLoss?: number;\n /**\n * True when another process reclaimed this callback's claim before this one\n * committed.\n *\n * Deduplication did not hold for this callback: both deliveries may have\n * exported it. Reported rather than hidden, because the cause is a\n * configured stale window that is too short for this installation and only an\n * operator can fix that.\n */\n readonly superseded?: boolean;\n};\n\nexport type HookProcessOutcome = {\n readonly ingest: HookIngestOutcome;\n /**\n * True when a matching delivery id had already been handled, so this\n * invocation's events were deliberately not exported. `ingest.emitted` is 0 in\n * that case; the provider's hook response is still produced normally, because\n * a redelivered callback still expects its protocol response.\n */\n readonly duplicateDelivery: boolean;\n /** Why this callback was, or was not, deduplicated. */\n readonly delivery: DeliveryReport;\n /** Running per-scope totals after applying this invocation's deltas. */\n readonly usageRollups: readonly UsageRollup[];\n /** Cleanup performed opportunistically; absent when no sweep ran. */\n readonly cleanup?: LifecycleCleanupReport;\n /** Diagnostics raised by this module, in addition to `ingest.diagnostics`. */\n readonly diagnostics: readonly OtelHookErrorInfo[];\n};\n\nexport type UsageRollup = {\n readonly scope: UsageObservation[\"scope\"];\n readonly scopeKey: string;\n readonly snapshot: UsageAccumulatorSnapshot;\n};\n\nexport type HookShutdownReport = {\n /** False when the bounded flush window elapsed before delivery finished. */\n readonly flushCompleted: boolean;\n readonly flushTimeoutMillis: number;\n readonly health: OverallHealth;\n};\n\nexport interface HookRuntime {\n readonly hook: OtelHook;\n readonly config: OtelHookConfig;\n readonly stateStore: FilesystemStateStore;\n /** The traces signal. Named `sink` because it is the one every installation has. */\n readonly sink: OtlpTelemetrySink;\n /** The logs signal. A no-op sink unless `exporter.logs.enabled` is set. */\n readonly logSink: OtlpLogTelemetrySink;\n readonly spool?: DurableSpool;\n /** Retry queue for the logs signal. Absent when spooling or logs are disabled. */\n readonly logSpool?: DurableLogSpool;\n readonly privacy: PrivacyService;\n readonly deduplicator: CallbackDeduplicator;\n readonly usageAccumulator: UsageAccumulator;\n /** Backs the cross-process pairing the sink applies to every exported span. */\n readonly spanCorrelator: SpanCorrelator;\n readonly janitor: LifecycleJanitor;\n /** Ingest one observation, then apply lifecycle accumulation. Never throws. */\n process(input: HookProcessInput): Promise<HookProcessOutcome>;\n /** Bounded flush + shutdown. Never throws; idempotent. */\n shutdown(): Promise<HookShutdownReport>;\n health(): OverallHealth;\n}\n\nexport type HookRuntimeOptions = {\n readonly config: OtelHookConfig;\n readonly registry: ProviderRegistry;\n /** Root of the state and spool trees. One directory per provider/installation below it. */\n readonly stateRootDir: string;\n /**\n * Namespace separating one deployment's state from another's. Not identity: it\n * never reaches an event, and no session or workspace is derived from it.\n */\n readonly installationId: string;\n /** State/spool namespace segment; the selected provider id, or a placeholder. */\n readonly providerNamespace: string;\n /** Exporter header *values*, deliberately absent from the config snapshot. */\n readonly headers?: Readonly<Record<string, string>>;\n readonly clock?: Clock;\n readonly ids?: IdGenerator;\n readonly logger?: Logger;\n readonly privacy?: PrivacyService;\n /** Upper bound on flush + shutdown. Default 2,000ms. */\n readonly flushTimeoutMillis?: number;\n /** Persist batches an unreachable collector refused. Default true. */\n readonly enableSpool?: boolean;\n /** Bounded lock waits keep a stuck peer from stalling the host. Default 1,000ms. */\n readonly stateLockTimeoutMillis?: number;\n /** Sweep expired lifecycle state when a session ends. Default true. */\n readonly sweepOnSessionEnd?: boolean;\n readonly lifecycleMaxAgeMillis?: number;\n /**\n * Normalize a delivery identity from the adapter when the host supplies none.\n * Default true. Set false to keep deduplication strictly opt-in per callback.\n */\n readonly deriveDeliveryIdentity?: boolean;\n /**\n * Raise `delivery-identifier-unavailable` for every callback that could not be\n * deduplicated, naming the provider and the capability that is missing. Default\n * false: without it, an unidentifiable callback is a silent absence of a\n * guarantee, which is exactly what a host auditing its own coverage cannot see.\n */\n readonly requireCallbackId?: boolean;\n /**\n * How long an uncommitted claim is respected before a later delivery may\n * assume the process that took it died. Default 60,000ms.\n */\n readonly staleClaimMillis?: number;\n /** TTL for dedup records specifically. Defaults to `lifecycleMaxAgeMillis`. */\n readonly deliveryRetentionMillis?: number;\n};\n\nconst DEFAULT_FLUSH_TIMEOUT_MILLIS = 2_000;\nconst DEFAULT_STATE_LOCK_TIMEOUT_MILLIS = 1_000;\nconst DEFAULT_LIFECYCLE_MAX_AGE_MILLIS = 24 * 60 * 60 * 1000;\nconst DEFAULT_STALE_CLAIM_MILLIS = 60_000;\n\nconst delay = (millis: number): Promise<\"timeout\"> =>\n new Promise((resolve) => {\n const timer = setTimeout(() => resolve(\"timeout\"), millis);\n timer.unref?.();\n });\n\nconst containsSessionEnd = (events: readonly CanonicalEvent[]): boolean =>\n events.some((event) => event.type === \"session.end\");\n\n/** Delivery is this module's own concern; `ingest` never sees it. */\nconst withoutDelivery = (input: HookProcessInput): HookIngestInput => {\n const { delivery, ...ingestInput } = input;\n void delivery;\n return ingestInput;\n};\n\n/**\n * Smallest stale-claim window that cannot expire while a live process is still\n * working on the callback it claimed.\n *\n * A claim is taken before `ingest` and committed after export, so the window has\n * to cover the whole of that: waiting for the session state lock, the adapter's\n * work, then every export attempt the exporter policy permits, then the bounded\n * flush. If `staleClaimMillis` is shorter than that, a second delivery arriving\n * mid-flight declares the first one abandoned and *reclaims* it — and then both\n * processes export the same callback. That is not a smaller guarantee, it is the\n * opposite of the one being advertised, produced by a configuration value that\n * looks like a harmless tuning knob.\n *\n * So the floor is derived from the same policy the work is bounded by, rather\n * than being a constant that a later timeout change could silently outgrow. The\n * multiplier on the export timeout counts the first attempt plus each retry.\n */\n/**\n * Bounded lock acquisitions between `claim` and `commit`, counted rather than\n * guessed.\n *\n * Each one can cost a full `stateLockTimeoutMillis` under contention, so the floor\n * has to include all of them. Enumerated so that adding a locked step without\n * revisiting this number is visibly an omission:\n *\n * 1. `ingest` phase 1 — the session-state critical section (read sequence, parse,\n * reserve).\n * 2. `ingest` phase 3 — the usage-accounting critical section.\n * 3. the span correlator, called from inside the sink during export.\n * 4. `deduplicator.commit` itself.\n */\nconst POST_CLAIM_LOCK_ACQUISITIONS = 4;\n\n/**\n * Locked operations the *accounting* phase performs, per usage observation.\n *\n * `recordReset` then `accumulateDelta`, each taking the session lock on its own.\n * Multiplied by the observation cap below rather than by the raw event limit: usage\n * lands on end-edge events only, so the cap is generous rather than exact.\n */\nconst ACCOUNTING_LOCKS_PER_OBSERVATION = 2;\n\n/**\n * How many usage observations the floor budgets for.\n *\n * Deliberately not `limits.maxEventsPerInvocation` (512 by default): summing 1,024\n * lock timeouts would put the floor in the tens of minutes, and a floor that large\n * is its own problem — it delays recovery of genuinely crashed claims by that long.\n * A real hook callback carries a handful of usage-bearing events, so this is the\n * conservative-but-useful bound, and the ownership check below is what covers the\n * case where reality exceeds it: a claim reclaimed under a live holder is *detected*\n * at commit rather than silently double-counted.\n */\nconst BUDGETED_USAGE_OBSERVATIONS = 8;\n\n/**\n * Smallest stale-claim window that cannot expire while a live process is still\n * working on the callback it claimed.\n *\n * A claim is taken before `ingest` and committed after accounting, so the window has\n * to cover the whole of that: every bounded lock acquisition on the way, every\n * export attempt the exporter policy permits, the spool write that follows a refused\n * export, and the bounded flush. If `staleClaimMillis` is shorter, a second delivery\n * arriving mid-flight declares the first one abandoned and *reclaims* it — and then\n * both processes export the same callback. That is not a smaller guarantee, it is\n * the opposite of the one being advertised, produced by a value that looks like a\n * harmless tuning knob.\n *\n * Derived from the same policy the work is bounded by, rather than a constant a\n * later timeout change could silently outgrow. It is a *floor*, not a prediction:\n * being generous costs only recovery latency after a crash, while being short costs\n * correctness.\n */\nexport const minimumStaleClaimMillis = (input: {\n readonly exportTimeoutMillis: number;\n readonly maxRetryAttempts: number;\n readonly flushTimeoutMillis: number;\n readonly stateLockTimeoutMillis: number;\n}): number => {\n const exportBudget = input.exportTimeoutMillis * (input.maxRetryAttempts + 1);\n const lockBudget =\n input.stateLockTimeoutMillis *\n (POST_CLAIM_LOCK_ACQUISITIONS +\n ACCOUNTING_LOCKS_PER_OBSERVATION * BUDGETED_USAGE_OBSERVATIONS);\n // A refused export writes the batch to the spool before returning, and the\n // janitor may sweep on a session-end callback. Both are bounded but neither has\n // its own configured timeout, so they share one allowance.\n const spoolAndSweepAllowance = 2 * input.stateLockTimeoutMillis;\n // A margin so a value derived from the same numbers is not exactly on the\n // boundary; process scheduling alone can cost tens of milliseconds.\n const margin = 1_000;\n return lockBudget + exportBudget + input.flushTimeoutMillis + spoolAndSweepAllowance + margin;\n};\n\nconst DELIVERY_UNAVAILABLE_DETAIL: Readonly<Record<DeliveryUnavailableReason, string>> =\n Object.freeze({\n \"provider-unattributed\":\n \"no provider was attributed, so no adapter could vouch for a replay-stable identifier\",\n \"provider-declares-none\":\n \"the selected adapter declares deliveryIdentifier=none: no callback of this provider carries a replay-stable identifier, so only --callback-id can deduplicate it\",\n \"callback-not-identifiable\":\n \"the selected adapter identifies some callbacks but not this one; it carries no field that separates a redelivery from a genuine second firing\",\n \"claim-rejected\":\n \"the selected adapter offered a delivery identity that failed the contract's own guards\",\n \"state-unavailable\":\n \"a delivery identity was established but the state store could not record a claim against it\",\n });\n\nexport const createHookRuntime = (options: HookRuntimeOptions): HookRuntime => {\n const clock = options.clock ?? createSystemClock();\n const ids = options.ids ?? createDeterministicIdGenerator();\n const logger = options.logger ?? createNullLogger();\n const privacy = options.privacy ?? createPrivacyService(options.config.privacy);\n const flushTimeoutMillis = options.flushTimeoutMillis ?? DEFAULT_FLUSH_TIMEOUT_MILLIS;\n const lifecycleMaxAge = options.lifecycleMaxAgeMillis ?? DEFAULT_LIFECYCLE_MAX_AGE_MILLIS;\n const stateLockTimeoutMillis = options.stateLockTimeoutMillis ?? DEFAULT_STATE_LOCK_TIMEOUT_MILLIS;\n\n // Raised, never lowered, and reported when raised: silently honouring a window\n // shorter than one process's own work would turn suppression into a double\n // export. See `minimumStaleClaimMillis`.\n const staleClaimFloor = minimumStaleClaimMillis({\n exportTimeoutMillis: options.config.exporter.timeoutMillis,\n maxRetryAttempts: options.config.exporter.maxRetryAttempts,\n flushTimeoutMillis,\n stateLockTimeoutMillis,\n });\n const requestedStaleClaim = options.staleClaimMillis ?? DEFAULT_STALE_CLAIM_MILLIS;\n const staleClaimMillis = Math.max(requestedStaleClaim, staleClaimFloor);\n if (staleClaimMillis > requestedStaleClaim) {\n logger.warn(\"staleClaimMillis raised to cover this installation's own export budget\", {\n \"delivery.stale_claim_requested_millis\": requestedStaleClaim,\n \"delivery.stale_claim_effective_millis\": staleClaimMillis,\n });\n }\n\n const stateStore = createFilesystemStateStore({\n rootDir: options.stateRootDir,\n providerId: options.providerNamespace,\n installationId: options.installationId,\n clock,\n logger,\n lockTimeoutMillis: stateLockTimeoutMillis,\n });\n\n const spool =\n options.enableSpool === false\n ? undefined\n : createFileDurableSpool({\n rootDir: options.stateRootDir,\n providerId: options.providerNamespace,\n installationId: options.installationId,\n clock,\n logger,\n });\n\n // A separate queue from the trace spool, so a logs outage cannot consume the\n // capacity the primary signal's retries need. Only built when logs are on: a\n // default installation must not create a directory for a signal it never emits.\n const logSpool =\n options.enableSpool === false || !options.config.exporter.logs.enabled\n ? undefined\n : createFileDurableLogSpool({\n rootDir: options.stateRootDir,\n providerId: options.providerNamespace,\n installationId: options.installationId,\n clock,\n logger,\n });\n\n const spanCorrelator = createSpanCorrelator({\n stateStore,\n clock,\n maxStartAgeMillis: lifecycleMaxAge,\n });\n\n /**\n * One correlation resolution per batch, shared by both signals.\n *\n * `correlateBatch` records the start edge and marks a scope published, so two\n * calls for one batch would have the second see the first's writes and report a\n * start it just recorded as a duplicate — leaving the two signals pointing at\n * different span ids for the same scope.\n */\n const correlate = shareCorrelationPerBatch((events) => spanCorrelator.correlateBatch(events));\n\n const traceSink = createOtlpTraceSink({\n exporter: options.config.exporter,\n ...(options.headers === undefined ? {} : { headers: options.headers }),\n providerId: options.providerNamespace,\n installationId: options.installationId,\n clock,\n logger,\n ...(spool === undefined ? {} : { spool }),\n correlate,\n });\n\n const logSink = createOtlpLogSink({\n exporter: options.config.exporter,\n ...(options.headers === undefined ? {} : { headers: options.headers }),\n providerId: options.providerNamespace,\n installationId: options.installationId,\n clock,\n logger,\n ...(logSpool === undefined ? {} : { spool: logSpool }),\n content: {\n includeContent: options.config.exporter.logs.includeContent,\n // The pre-existing verbatim-content opt-in, passed through rather than\n // re-derived: `raw` disclosure in a log body is governed by the same flag it\n // has always been governed by.\n allowRawContent: privacy.policy.allowRawContent,\n },\n correlate,\n });\n\n const sink = createSignalFanout({ traces: traceSink, logs: logSink });\n\n const hookDeps = {\n stateStore,\n config: options.config,\n registry: options.registry,\n clock,\n ids,\n privacy,\n logger,\n installationId: options.installationId,\n };\n const hook = createOtelHook({ ...hookDeps, sink });\n\n const deduplicator = createCallbackDeduplicator({ stateStore, clock });\n const usageAccumulator = createUsageAccumulator({ stateStore, clock });\n const deliveryRetentionMillis = options.deliveryRetentionMillis ?? lifecycleMaxAge;\n if (deliveryRetentionMillis < staleClaimMillis) {\n // Not raised, only reported: an operator who wants dedup records gone in a\n // minute is entitled to that, and the sweep already refuses to drop a claim\n // inside the stale window. What they are not entitled to is a *silent* gap —\n // a completed record that expires before a redelivery could plausibly arrive\n // stops suppressing it, and this is the number that explains why.\n logger.warn(\"delivery retention is shorter than the stale-claim window\", {\n \"delivery.retention_millis\": deliveryRetentionMillis,\n \"delivery.stale_claim_effective_millis\": staleClaimMillis,\n });\n }\n const janitor = createLifecycleJanitor({\n spanCorrelator,\n deduplicator,\n usageAccumulator,\n spanMaxAgeMillis: lifecycleMaxAge,\n dedupMaxAgeMillis: deliveryRetentionMillis,\n // The *effective* window, not the requested one: a sweep that considered a\n // claim dead earlier than the claim path does would hand a live callback to a\n // peer as fresh.\n dedupStaleClaimMillis: staleClaimMillis,\n usageMaxAgeMillis: lifecycleMaxAge,\n });\n\n const deliveryLock = createAsyncLock();\n\n const stateDiagnostic = (thrown: unknown): OtelHookErrorInfo =>\n errorInfoFromThrown(thrown, { code: \"state-store-failure\", phase: \"state\", occurredAt: clock.now() });\n\n /**\n * Opaque, replay-stable token for a delivery, safe to write into a state record.\n *\n * Digested rather than used directly, because a *host-supplied* callback id is a\n * raw external identifier and a rollup record's contents are not a place one may\n * appear as a side effect of deduplicating on it. The digest is content-addressed,\n * so a later process recomputes the same token — which is the whole point: the\n * retry has to recognize its own earlier application.\n */\n const rollupDeliveryToken = (identity: ResolvedDeliveryIdentity): string | undefined => {\n // Clamped to the shape the state schema admits, because `ids` is injected: the\n // default generator returns a hex digest, but a host's own could return anything.\n // An unusable token must cost the *idempotency check* and nothing else — writing\n // it would fail validation and take the whole rollup down with it, which trades a\n // possible double count for a certain lost one.\n const token = ids\n .newOpaqueId([\"usage-delivery\", identity.scope, identity.callbackId])\n .replace(/[^A-Za-z0-9_-]/g, \"\")\n .slice(0, 128);\n return token.length === 0 ? undefined : token;\n };\n\n const applyRollups = async (\n sessionId: string,\n observations: readonly UsageObservation[],\n diagnostics: OtelHookErrorInfo[],\n deliveryToken?: string,\n ): Promise<readonly UsageRollup[]> => {\n const rollups: UsageRollup[] = [];\n // Per rollup key, because idempotency is per record: two observations landing on\n // one key are the first and second application *to that key*, whatever their\n // position in the batch.\n const ordinals = new Map<string, number>();\n for (const observation of observations) {\n const key = { sessionId, scope: observation.scope, scopeKey: observation.scopeKey };\n const rollupId = `${observation.scope}\u0000${observation.scopeKey}`;\n const ordinal = ordinals.get(rollupId) ?? 0;\n ordinals.set(rollupId, ordinal + 1);\n // Absent when no delivery identity was established: there is then nothing to\n // recognize a repeat by, and declining to accumulate would lose a real\n // observation rather than avoid a duplicate one.\n const options =\n deliveryToken === undefined\n ? undefined\n : { delivery: { callbackId: deliveryToken, ordinal } };\n try {\n if (observation.resetDetected) {\n // A restarted provider counter starts a new epoch rather than\n // deflating the running total (see createUsageAccumulator).\n await usageAccumulator.recordReset(key, options);\n }\n const snapshot = await usageAccumulator.accumulateDelta(key, observation.delta, options);\n rollups.push({ scope: observation.scope, scopeKey: observation.scopeKey, snapshot });\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"usage-invalid\",\n phase: \"normalization\",\n occurredAt: clock.now(),\n }),\n );\n }\n }\n return rollups;\n };\n\n /**\n * Establish this callback's delivery identity.\n *\n * A host-supplied id always wins: the host knows things about its own\n * redelivery that no payload states. Only when there is none does the adapter\n * get asked, and only if derivation is enabled.\n */\n const identifyDelivery = (\n input: HookProcessInput,\n ): { readonly identity?: ResolvedDeliveryIdentity; readonly unavailable?: DeliveryResolution } => {\n if (input.delivery !== undefined) {\n return {\n identity: hostDeliveryIdentity(input.delivery.callbackId, input.delivery.scope),\n };\n }\n if (options.deriveDeliveryIdentity === false) {\n return {};\n }\n const resolution = hook.resolveDelivery(withoutDelivery(input));\n return resolution.status === \"resolved\"\n ? { identity: resolution.identity }\n : { unavailable: resolution };\n };\n\n const reportUnavailable = (\n resolution: DeliveryResolution | undefined,\n diagnostics: OtelHookErrorInfo[],\n ): DeliveryReport => {\n if (resolution === undefined || resolution.status === \"resolved\") {\n // Either an identity was established, or none was even attempted because the\n // host supplied its own id or switched derivation off. Neither is a provider\n // gap, so `requireCallbackId` has nothing to report.\n return { deduplicated: false };\n }\n if (options.requireCallbackId === true) {\n // The generic sentence explains the *reason code*; the adapter's own gap\n // explains the *callback*. Both are useful and they answer different\n // questions, so the detail carries the general statement and then the\n // specific one rather than replacing either.\n const generic = DELIVERY_UNAVAILABLE_DETAIL[resolution.reason];\n const detail =\n resolution.detail === undefined ? generic : `${generic}; ${resolution.detail}`;\n diagnostics.push(\n createErrorInfo({\n code: \"delivery-identifier-unavailable\",\n phase: \"identity\",\n detail: detail.slice(0, 400),\n details: {\n \"delivery.reason\": resolution.reason,\n ...(resolution.providerId === undefined ? {} : { \"provider.id\": resolution.providerId }),\n ...(resolution.capability === undefined\n ? {}\n : { \"provider.delivery_identifier\": resolution.capability }),\n ...(resolution.sourceEventName === undefined\n ? {}\n : { \"delivery.source_event_name\": resolution.sourceEventName }),\n \"delivery.remedy\": \"pass an explicit host delivery id (--callback-id)\",\n },\n occurredAt: clock.now(),\n }),\n );\n }\n return {\n deduplicated: false,\n reason: resolution.reason,\n ...(resolution.capability === undefined ? {} : { capability: resolution.capability }),\n ...(resolution.sourceEventName === undefined\n ? {}\n : { sourceEventName: resolution.sourceEventName }),\n ...(resolution.detail === undefined ? {} : { detail: resolution.detail }),\n };\n };\n\n const runProcess = async (\n input: HookProcessInput,\n identity: ResolvedDeliveryIdentity | undefined,\n report: DeliveryReport,\n diagnostics: OtelHookErrorInfo[],\n ): Promise<HookProcessOutcome> => {\n let delivery = report;\n let owned = false;\n let claimOwner: string | undefined;\n\n if (identity !== undefined) {\n try {\n const claimed = await deduplicator.claim(identity.scope, identity.callbackId, {\n staleClaimMillis,\n });\n owned = claimed.owned;\n claimOwner = claimed.owner;\n delivery = {\n deduplicated: true,\n origin: identity.origin,\n outcome: claimed.outcome,\n ...(identity.evidence.length === 0 ? {} : { evidence: identity.evidence }),\n };\n if (claimed.outcome === \"reclaimed\") {\n logger.warn(\"took over a delivery claim no process ever completed\", {\n \"delivery.origin\": identity.origin,\n \"delivery.attempt\": claimed.attempt,\n \"delivery.abandoned_for_millis\": claimed.abandonedForMillis ?? 0,\n });\n }\n if (claimed.duplicate) {\n logger.info(\"delivery already handled; telemetry suppressed\", {\n \"delivery.origin\": identity.origin,\n \"delivery.outcome\": claimed.outcome,\n });\n }\n } catch (thrown) {\n // An unreadable dedup record must not drop telemetry: exporting a\n // possible duplicate is recoverable at the collector, losing a real\n // observation is not. Deduplication is what lapses here, so\n // the report says so rather than claiming a guarantee that did not hold.\n diagnostics.push(stateDiagnostic(thrown));\n delivery = { deduplicated: false, origin: identity.origin, reason: \"state-unavailable\" };\n }\n }\n\n const duplicateDelivery = delivery.outcome === \"duplicate\" || delivery.outcome === \"in-flight\";\n // A redelivery is parsed but changes nothing: no export, no sequence advance,\n // no cumulative-usage rewrite. Suppressing inside `ingest` rather than at the\n // sink is what makes that true — a discarding sink still let the orchestrator\n // renumber the session and move the usage baseline, so a redelivered callback\n // silently shifted every later event's derived id.\n const ingest = await hook.ingest(withoutDelivery(input), { suppress: duplicateDelivery });\n\n let usageRollups: readonly UsageRollup[] = [];\n if (!duplicateDelivery && ingest.identity !== undefined && ingest.usageObservations.length > 0) {\n // The rollup is the one piece of accounting that sits *outside* `ingest`'s\n // own transaction, in a second critical section — the accumulator takes the\n // same non-reentrant session lock. That leaves this the only place a retried\n // or reclaimed delivery could apply its numbers twice, so it is the one place\n // that gets stamped with the delivery it belongs to.\n usageRollups = await applyRollups(\n ingest.identity.sessionId,\n ingest.usageObservations,\n diagnostics,\n identity === undefined ? undefined : rollupDeliveryToken(identity),\n );\n }\n\n if (owned && identity !== undefined) {\n // Committing means \"this callback is accounted for; never process it again\",\n // so the decision turns on whether *anything* survived rather than whether\n // everything did — see `DeliveryDurability`.\n //\n // A partially delivered batch is terminal, and that is the uncomfortable but\n // correct answer. Releasing it would retry the whole callback and re-export\n // every span a collector already accepted, turning a reported loss into a\n // silent double-count; a duplicated span corrupts a total that nobody can\n // reconstruct, whereas a reported loss is a number somebody can act on. So\n // the callback commits and the loss is stated.\n try {\n if (isCommittable(ingest.durability)) {\n const committed = await deduplicator.commit(\n identity.scope,\n identity.callbackId,\n claimOwner,\n );\n if (committed.status === \"superseded\") {\n // The stale window was shorter than this installation's real worst\n // case, so a peer took the claim over mid-flight and both of us may have\n // exported. No floor computation can rule this out, so it is reported\n // rather than assumed away.\n delivery = { ...delivery, deduplicated: false, superseded: true };\n diagnostics.push(\n createErrorInfo({\n code: \"delivery-claim-superseded\",\n phase: \"state\",\n detail:\n \"another process reclaimed this delivery claim before it was committed; raise staleClaimMillis\",\n details: {\n \"delivery.origin\": identity.origin,\n \"delivery.attempt\": committed.attempt,\n },\n occurredAt: clock.now(),\n }),\n );\n logger.warn(\"delivery claim superseded before commit; deduplication did not hold\", {\n \"delivery.origin\": identity.origin,\n \"delivery.attempt\": committed.attempt,\n });\n }\n if (ingest.durability === \"partial\") {\n delivery = { ...delivery, partialLoss: ingest.exportRejected };\n logger.warn(\"delivery partially lost; committed to avoid re-exporting accepted spans\", {\n \"delivery.origin\": identity.origin,\n \"export.accepted\": ingest.emitted,\n \"export.rejected\": ingest.exportRejected,\n });\n }\n } else {\n // Nothing survived, so a retry cannot duplicate anything. Released rather\n // than left to age out, so the next delivery is treated as fresh\n // immediately instead of standing down for the whole stale window against\n // a process that is no longer running.\n await deduplicator.release(identity.scope, identity.callbackId);\n delivery = { ...delivery, deduplicated: false, retryable: true };\n logger.warn(\"delivery not durably recorded; claim released for retry\", {\n \"delivery.origin\": identity.origin,\n \"export.rejected\": ingest.exportRejected,\n });\n }\n } catch (thrown) {\n diagnostics.push(stateDiagnostic(thrown));\n }\n }\n\n let cleanup: LifecycleCleanupReport | undefined;\n if (\n (options.sweepOnSessionEnd ?? true) &&\n ingest.identity !== undefined &&\n containsSessionEnd(ingest.events)\n ) {\n try {\n cleanup = await janitor.runOnce(ingest.identity.sessionId);\n const neverExported = cleanup.span?.expiredOpen ?? 0;\n if (neverExported > 0) {\n // A start that aged out without its end never produced a span at all.\n // Said out loud, because the alternative reading of the same silence is\n // \"nothing happened\".\n logger.warn(\"expired lifecycle spans were never completed, so never exported\", {\n \"lifecycle.expired_open_spans\": neverExported,\n });\n }\n } catch (thrown) {\n diagnostics.push(stateDiagnostic(thrown));\n }\n }\n\n return {\n ingest,\n duplicateDelivery,\n delivery,\n usageRollups,\n ...(cleanup === undefined ? {} : { cleanup }),\n diagnostics,\n };\n };\n\n const process_ = async (input: HookProcessInput): Promise<HookProcessOutcome> => {\n const diagnostics: OtelHookErrorInfo[] = [];\n const identified = identifyDelivery(input);\n const report = reportUnavailable(identified.unavailable, diagnostics);\n\n if (identified.identity === undefined) {\n return runProcess(input, undefined, report, diagnostics);\n }\n\n // Deliveries sharing a scope run one at a time, in arrival order: a claim\n // that is only decided after a peer has already exported is not a claim.\n // Unrelated scopes stay concurrent, and this is an in-process lock layered\n // over the store's cross-process one, so it never contends with itself.\n return deliveryLock.run(identified.identity.scope, () =>\n runProcess(input, identified.identity, report, diagnostics),\n );\n };\n\n const snapshots = (): readonly DeliveryHealthSnapshot[] => sink.health();\n\n let shutdownReport: Promise<HookShutdownReport> | undefined;\n const shutdown = (): Promise<HookShutdownReport> => {\n shutdownReport ??= (async (): Promise<HookShutdownReport> => {\n const raced = await Promise.race([\n hook.shutdown().then(() => \"completed\" as const),\n delay(flushTimeoutMillis),\n ]);\n if (raced === \"timeout\") {\n // Not an error the host should ever feel: the batch is either spooled\n // for a later invocation or reported unhealthy, and either way the hook\n // returns within a bounded time.\n logger.warn(\"bounded flush window elapsed before delivery completed\", {\n \"shutdown.flush_timeout_millis\": flushTimeoutMillis,\n });\n }\n return {\n flushCompleted: raced === \"completed\",\n flushTimeoutMillis,\n health: summarizeHealth(snapshots()),\n };\n })();\n return shutdownReport;\n };\n\n return {\n hook,\n config: options.config,\n stateStore,\n sink: traceSink,\n logSink,\n ...(spool === undefined ? {} : { spool }),\n ...(logSpool === undefined ? {} : { logSpool }),\n privacy,\n deduplicator,\n usageAccumulator,\n spanCorrelator,\n janitor,\n process: process_,\n shutdown,\n health: (): OverallHealth => summarizeHealth(snapshots()),\n };\n};\n"],"mappings":";AAwDO,IAAM,sBAAsB,CACjC,WACA,UAAgC,CAAC,MACf;AAClB,QAAM,qBAAqB,QAAQ,qCAAqC;AACxE,MAAI,gBAAgB;AACpB,MAAI,gBAAgB;AACpB,MAAI,sBAAsB;AAC1B,MAAI;AACJ,MAAI;AACJ,MAAI;AAEJ,SA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AAgB,UAAU,CAAC;AAAA,EAC1D;AACF;","names":["z","z","z","owner","ExportResultCode","event","event","parent","result","event","z","z","usageKey","createHash","z","z","z","createHash","path","z","z","z","z","z","z","z","z","z","parsed","z","z","z","z","z","createHash","createHash","z","z","z","event","batch","randomBytes","createHash","randomBytes","randomBytes","mkdir","readFile","readdir","rename","unlink","writeFile","path","isErrnoException","mkdir","readdir","randomBytes","writeFile","rename","unlink","readFile","TRACE_ID_PATTERN","SPAN_ID_PATTERN","isFiniteNonNegative","isBoundedString","isPlainObject","TraceFlags","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_CACHE_CREATION_INPUT_TOKENS","ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS","ATTR_GEN_AI_USAGE_INPUT_TOKENS","ATTR_GEN_AI_USAGE_OUTPUT_TOKENS","ATTR_OTELHOOK_OUTCOME","ATTR_OTELHOOK_TOOL_KIND","ATTR_OTELHOOK_DELEGATION_DEPTH","ATTR_OTELHOOK_AGENT_NAME","ATTR_OTELHOOK_AGENT_VERSION","ATTR_OTELHOOK_COMPACTION_TRIGGER","codePointLength","sliceCodePoints","event","event","identityAttributes","ATTR_OTELHOOK_AGENT_NAME","ATTR_OTELHOOK_AGENT_VERSION","ATTR_GEN_AI_REQUEST_MODEL","ATTR_OTELHOOK_OUTCOME","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_OTELHOOK_TOOL_KIND","ATTR_OTELHOOK_DELEGATION_DEPTH","ATTR_OTELHOOK_COMPACTION_TRIGGER","ATTR_ERROR_TYPE","ATTR_GEN_AI_USAGE_INPUT_TOKENS","ATTR_GEN_AI_USAGE_OUTPUT_TOKENS","ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS","ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS","codePointLength","sliceCodePoints","hrTime","TraceFlags","TraceFlags","chunk","createDisabledSink","DEFAULT_STALE_CLAIM_MILLIS","event","options"]}
1
+ {"version":3,"sources":["../src/diagnostics/health.ts","../src/errors/index.ts","../src/model/primitives.ts","../src/errors/taxonomy.ts","../src/lifecycle/dedup.ts","../src/state/async-lock.ts","../src/state/store.ts","../src/lifecycle/keys.ts","../src/lifecycle/janitor.ts","../src/telemetry/semconv.ts","../node_modules/@opentelemetry/core/src/common/time.ts","../node_modules/@opentelemetry/core/src/ExportResult.ts","../src/version.ts","../src/telemetry/export-identity.ts","../src/lifecycle/span-correlator.ts","../src/model/usage.ts","../src/lifecycle/usage-accumulator.ts","../src/privacy/service.ts","../src/model/extensions.ts","../src/privacy/policy.ts","../src/runtime/clock.ts","../src/runtime/hook.ts","../src/config/schema.ts","../src/config/resource-attributes.ts","../src/model/content.ts","../src/model/identity.ts","../src/model/version.ts","../src/providers/adapter.ts","../src/model/events.ts","../src/model/target.ts","../src/providers/registry.ts","../src/runtime/delivery.ts","../src/runtime/ids.ts","../src/runtime/ports.ts","../src/runtime/logger.ts","../src/runtime/target-resolution.ts","../src/privacy/workspace.ts","../src/runtime/git-worktree.ts","../src/state/filesystem-store.ts","../src/state/keys.ts","../src/telemetry/spool-queue.ts","../src/telemetry/durable-log-spool.ts","../src/telemetry/durable-spool.ts","../src/telemetry/otlp-log-sink.ts","../src/telemetry/exporter-resource.ts","../src/telemetry/log-records.ts","../src/telemetry/otlp-sink.ts","../src/telemetry/signal-fanout.ts","../src/integration/hook-runtime.ts"],"sourcesContent":["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 { 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 { randomBytes } from \"node:crypto\";\n\nimport type { Attributes } from \"../model/primitives.js\";\nimport type { Clock, StateRecord, StateStore } from \"../runtime/ports.js\";\nimport { withOptionalSessionLock } from \"../state/store.js\";\nimport { dedupKey, dedupScanPrefix, dedupScopeOf } from \"./keys.js\";\n\nexport type DedupCheckResult = {\n /** True when `callbackId` was already marked seen for this scope. */\n readonly duplicate: boolean;\n};\n\nexport type DedupCleanupResult = {\n readonly removed: number;\n readonly scanned: number;\n /**\n * Aged-out records the sweep deliberately kept because they are uncommitted\n * claims younger than the stale-claim window — a live process may still be\n * working on them.\n *\n * Reported rather than merely not-removed, because the two are indistinguishable\n * in `removed` and only one of them means \"retention is configured shorter than\n * this installation's own export budget\". Absent when nothing was retained.\n */\n readonly retainedInFlight?: number;\n};\n\n/**\n * What happened when a delivery tried to take ownership of a callback id.\n *\n * - `fresh`: nothing had this id. The caller owns it and must `commit`.\n * - `duplicate`: a previous delivery ran this callback to completion.\n * - `in-flight`: another delivery holds the id right now — a concurrent process,\n * or one that has not committed yet. Treated as a duplicate.\n * - `reclaimed`: a claim was abandoned long enough ago to be assumed dead, and\n * this delivery has taken it over. The caller owns it and must `commit`.\n */\nexport type DeliveryClaimOutcome = \"fresh\" | \"duplicate\" | \"in-flight\" | \"reclaimed\";\n\nexport type DeliveryClaimResult = {\n readonly outcome: DeliveryClaimOutcome;\n /** True for `duplicate` and `in-flight`: the caller must not export or account. */\n readonly duplicate: boolean;\n /** True for `fresh` and `reclaimed`: the caller owns the id and should commit. */\n readonly owned: boolean;\n /** How many deliveries have claimed this id, including this one. */\n readonly attempt: number;\n /** Age of the claim that was taken over. Present only for `reclaimed`. */\n readonly abandonedForMillis?: number;\n /**\n * Opaque proof that *this* delivery owns the claim. Present when `owned`.\n *\n * No floor computation can be proven exact, so the stale window may still be too\n * short for some real installation. Passing this back to {@link\n * CallbackDeduplicator.commit} turns that from a silent double-count into a\n * detected, reported condition: if a peer reclaimed the id in the meantime the\n * record carries a different token, and the commit refuses rather than\n * overwriting the peer's in-flight work.\n */\n readonly owner?: string;\n};\n\n/** Whether a commit actually took effect. */\nexport type DeliveryCommitResult = {\n readonly status: \"committed\" | \"superseded\";\n /** The attempt number recorded, for diagnostics. */\n readonly attempt: number;\n};\n\nexport type DeliveryClaimOptions = {\n /**\n * How long an uncommitted claim is respected before it is assumed to belong to\n * a process that died mid-flight. Default 60,000ms.\n */\n readonly staleClaimMillis?: number;\n};\n\n/**\n * Delivery guard: suppresses a redelivered callback while local state is intact.\n *\n * Deliberately not described as \"exactly-once\". This records intent and completion\n * in a local store; the collector it protects is a separate system with no shared\n * transaction, so a process killed between an accepted export and `commit` leaves a\n * callback that will be exported again. What this guarantees is that a redelivery\n * seen by a *live* store is suppressed, and that a crash is recoverable rather than\n * either silently lost or permanently blocked.\n *\n * Coding-agent hosts redeliver callbacks — a retried hook invocation, a\n * duplicated event, a replayed transcript — and a deterministic identity makes\n * the replay recomputable, but something still has to remember which identities\n * have already been handled. This is that memory: a bounded, TTL-swept set of\n * seen ids per scope, independent of what the id actually names.\n *\n * Ownership is two-phase on purpose. `claim` records an intent before the caller\n * exports anything and `commit` records completion afterwards, so the window\n * where a crash could produce a double export does not exist: a second delivery\n * arriving in that window sees `in-flight` and stands down. The cost of that\n * choice is that a process killed between the two leaves an uncommitted claim,\n * which is why an old one is reclaimable rather than permanent — permanent would\n * turn every crash into silently lost telemetry.\n */\nexport interface CallbackDeduplicator {\n /**\n * Single-phase check: marks the id complete immediately and reports whether it\n * had been seen. Retained for callers that have nothing to protect between the\n * check and the side effect; `claim`/`commit` is the stronger guarantee.\n */\n checkAndMark(scope: string, callbackId: string): Promise<DedupCheckResult>;\n /** Take ownership of a callback id before acting on it. */\n claim(\n scope: string,\n callbackId: string,\n options?: DeliveryClaimOptions,\n ): Promise<DeliveryClaimResult>;\n /**\n * Record that a claimed callback ran to completion.\n *\n * `owner` is the token {@link DeliveryClaimResult.owner} handed out. Supplied and\n * matching, the claim completes. Supplied and *not* matching, the claim has been\n * reclaimed by a peer while this delivery was still working, and the commit is\n * refused — reported as `\"superseded\"` so the caller can say so instead of\n * silently marking a callback handled that somebody else is mid-flight on.\n */\n commit(scope: string, callbackId: string, owner?: string): Promise<DeliveryCommitResult>;\n /**\n * Give up a claim without completing it, so the next delivery of the same\n * callback is treated as fresh instead of waiting out the stale window.\n */\n release(scope: string, callbackId: string): Promise<void>;\n /**\n * Drop dedup records older than `maxAgeMillis`.\n *\n * An uncommitted claim is held back until it is also older than\n * `staleClaimMillis`, whatever the retention says. Retention is an operator's\n * answer to \"how long should a handled callback stay recognizable\"; the stale\n * window is a statement about how long one process's own work can take. Deleting\n * a claim inside that window would hand the callback to a concurrent delivery as\n * *fresh* while the holder is still exporting it — a retention setting silently\n * converting suppression into a double export, which is the opposite of what\n * tightening retention looks like it does.\n */\n cleanup(\n maxAgeMillis: number,\n options?: {\n readonly maxEntries?: number;\n readonly sessionId?: string;\n /** Floor on how long an uncommitted claim survives. Default 60,000ms. */\n readonly staleClaimMillis?: number;\n },\n ): Promise<DedupCleanupResult>;\n}\n\nexport type CallbackDeduplicatorDependencies = {\n readonly stateStore: StateStore;\n readonly clock: Clock;\n};\n\nconst DEFAULT_STALE_CLAIM_MILLIS = 60_000;\n\ntype DedupState = \"claimed\" | \"completed\";\n\n/**\n * Read the recorded state of a dedup record.\n *\n * A record written by an older release carries only `seenAt`, which meant\n * \"handled\". Absent a `state` field it is therefore read as `completed`, so an\n * upgrade never resurrects a callback the previous version had already exported.\n */\nconst stateOf = (record: StateRecord | undefined): DedupState | undefined => {\n if (record?.value.kind !== \"attributes\") {\n return undefined;\n }\n const declared = record.value.attributes.state;\n if (declared === \"claimed\" || declared === \"completed\") {\n return declared;\n }\n return \"completed\";\n};\n\nconst attemptOf = (record: StateRecord | undefined): number => {\n if (record?.value.kind !== \"attributes\") {\n return 0;\n }\n const attempt = record.value.attributes.attempt;\n return typeof attempt === \"number\" && Number.isInteger(attempt) && attempt > 0 ? attempt : 1;\n};\n\nconst ownerOf = (record: StateRecord | undefined): string | undefined => {\n if (record?.value.kind !== \"attributes\") {\n return undefined;\n }\n const owner = record.value.attributes.owner;\n return typeof owner === \"string\" && owner.length > 0 ? owner : undefined;\n};\n\nconst newOwnerToken = (): string => randomBytes(12).toString(\"hex\");\n\nconst claimedAtOf = (record: StateRecord | undefined): number | undefined => {\n if (record?.value.kind !== \"attributes\") {\n return undefined;\n }\n const claimedAt = record.value.attributes.claimedAt;\n return typeof claimedAt === \"number\" ? claimedAt : record.updatedAt;\n};\n\nexport const createCallbackDeduplicator = (\n deps: CallbackDeduplicatorDependencies,\n): CallbackDeduplicator => {\n const { stateStore, clock } = deps;\n\n const write = (key: string, attributes: Attributes): Promise<unknown> =>\n stateStore.write(key, { kind: \"attributes\", attributes });\n\n const checkAndMark = (scope: string, callbackId: string): Promise<DedupCheckResult> =>\n withOptionalSessionLock(stateStore, scope, async (): Promise<DedupCheckResult> => {\n const key = dedupKey(scope, callbackId);\n const existing = await stateStore.read(key);\n if (existing?.value.kind === \"attributes\") {\n return { duplicate: true };\n }\n const now = clock.now();\n await write(key, {\n state: \"completed\",\n attempt: 1,\n claimedAt: now,\n seenAt: now,\n owner: newOwnerToken(),\n });\n return { duplicate: false };\n });\n\n const claim = (\n scope: string,\n callbackId: string,\n options?: DeliveryClaimOptions,\n ): Promise<DeliveryClaimResult> =>\n withOptionalSessionLock(stateStore, scope, async (): Promise<DeliveryClaimResult> => {\n const staleClaimMillis = options?.staleClaimMillis ?? DEFAULT_STALE_CLAIM_MILLIS;\n const key = dedupKey(scope, callbackId);\n const existing = await stateStore.read(key);\n const state = stateOf(existing);\n const now = clock.now();\n\n if (state === \"completed\") {\n return { outcome: \"duplicate\", duplicate: true, owned: false, attempt: attemptOf(existing) };\n }\n\n if (state === \"claimed\") {\n const claimedAt = claimedAtOf(existing) ?? now;\n const age = now - claimedAt;\n if (age <= staleClaimMillis) {\n return {\n outcome: \"in-flight\",\n duplicate: true,\n owned: false,\n attempt: attemptOf(existing),\n };\n }\n const attempt = attemptOf(existing) + 1;\n const owner = newOwnerToken();\n await write(key, { state: \"claimed\", attempt, claimedAt: now, owner });\n return {\n outcome: \"reclaimed\",\n duplicate: false,\n owned: true,\n attempt,\n abandonedForMillis: age,\n owner,\n };\n }\n\n const owner = newOwnerToken();\n await write(key, { state: \"claimed\", attempt: 1, claimedAt: now, owner });\n return { outcome: \"fresh\", duplicate: false, owned: true, attempt: 1, owner };\n });\n\n const commit = (\n scope: string,\n callbackId: string,\n owner?: string,\n ): Promise<DeliveryCommitResult> =>\n withOptionalSessionLock(stateStore, scope, async (): Promise<DeliveryCommitResult> => {\n const key = dedupKey(scope, callbackId);\n const existing = await stateStore.read(key);\n const now = clock.now();\n const attempt = Math.max(attemptOf(existing), 1);\n\n const recordedOwner = ownerOf(existing);\n if (owner !== undefined && recordedOwner !== undefined && recordedOwner !== owner) {\n // A peer reclaimed this id while we were still working, which means the\n // stale window was shorter than this installation's real worst case.\n // Completing it now would tell that peer's delivery to stand down after it\n // has already exported. Refusing is the honest answer, and being able to\n // say so is the point of the token: no floor computation can be proven\n // exact, so the failure has to be detectable rather than merely unlikely.\n return { status: \"superseded\", attempt };\n }\n\n await write(key, {\n state: \"completed\",\n attempt,\n claimedAt: claimedAtOf(existing) ?? now,\n completedAt: now,\n seenAt: now,\n ...(recordedOwner === undefined ? {} : { owner: recordedOwner }),\n });\n return { status: \"committed\", attempt };\n });\n\n const release = (scope: string, callbackId: string): Promise<void> =>\n withOptionalSessionLock(stateStore, scope, async (): Promise<void> => {\n const key = dedupKey(scope, callbackId);\n // Only an uncommitted claim is droppable: releasing a completed record\n // would re-open a callback whose telemetry has already been exported.\n if (stateOf(await stateStore.read(key)) === \"claimed\") {\n await stateStore.delete(key);\n }\n });\n\n const cleanup = async (\n maxAgeMillis: number,\n options?: {\n readonly maxEntries?: number;\n readonly sessionId?: string;\n readonly staleClaimMillis?: number;\n },\n ): Promise<DedupCleanupResult> => {\n const keys = await stateStore.keys(dedupScanPrefix(options?.sessionId));\n const cap = options?.maxEntries ?? 1_000;\n const staleClaimMillis = options?.staleClaimMillis ?? DEFAULT_STALE_CLAIM_MILLIS;\n const now = clock.now();\n let removed = 0;\n let scanned = 0;\n let retainedInFlight = 0;\n\n /** Whether this record may be dropped, counting a live claim as it goes. */\n const isDroppable = (record: StateRecord | undefined, count: boolean): boolean => {\n if (record === undefined || now - record.updatedAt <= maxAgeMillis) {\n return false;\n }\n if (stateOf(record) === \"claimed\") {\n const age = now - (claimedAtOf(record) ?? record.updatedAt);\n if (age <= staleClaimMillis) {\n if (count) {\n retainedInFlight += 1;\n }\n return false;\n }\n }\n return true;\n };\n\n for (const key of keys) {\n if (scanned >= cap) {\n break;\n }\n scanned += 1;\n\n // Unlocked first pass. It decides only whether this key is worth locking for,\n // which is what keeps a sweep of a mostly-live store from paying a lock\n // acquisition per record: the common answer is \"not aged out, leave it\".\n if (!isDroppable(await stateStore.read(key), true)) {\n continue;\n }\n\n const scope = dedupScopeOf(key);\n if (scope === undefined) {\n // A key from a previous layout version: unreachable by any current read, so\n // there is no claim to race and no scope to lock on.\n await stateStore.delete(key);\n removed += 1;\n continue;\n }\n\n // Locked second pass, because a peer's `claim` takes this same lock and may\n // have refreshed the record since the first read. Deciding once, outside the\n // lock, would let a sweep delete a claim written microseconds earlier — and the\n // concurrent redelivery would then read `fresh` and export a second time.\n await withOptionalSessionLock(stateStore, scope, async (): Promise<void> => {\n if (!isDroppable(await stateStore.read(key), false)) {\n return;\n }\n await stateStore.delete(key);\n removed += 1;\n });\n }\n\n return {\n removed,\n scanned,\n ...(retainedInFlight === 0 ? {} : { retainedInFlight }),\n };\n };\n\n return { checkAndMark, claim, commit, release, cleanup };\n};\n","/**\n * Per-key async mutex.\n *\n * Ordinary promises already serialize a single caller's `await`s, but two\n * concurrent callers racing a read-modify-write against the same key (two\n * hook invocations updating the same session, in the same process) are not\n * serialized by anything. This chains each key's operations through a promise\n * tail so they run one at a time, in arrival order, without blocking unrelated\n * keys.\n */\nexport interface AsyncLock {\n /**\n * `timeoutMillis` bounds how long the caller waits to *acquire* the key.\n *\n * Two guarantees, and the boundary between them is the whole contract:\n *\n * - **A timed-out caller's `fn` never runs.** Giving up on the wait cancels the\n * queued operation. It has to: a caller that has been told \"I could not take\n * the lock\" will report contention and move on, and if `fn` then ran anyway it\n * would mutate state after the caller had already declared that nothing\n * happened. That is worse than either outcome on its own — the state changes\n * and nobody is watching.\n * - **Work is never cancelled after acquisition.** Once `fn` has started the\n * timeout is irrelevant; interrupting a read-modify-write partway through is\n * exactly the corruption a mutex exists to prevent. So the timeout bounds\n * *waiting*, never *exclusivity* and never *completion*.\n *\n * Cancellation does not let a waiter skip the queue: the cancelled slot still\n * settles in order, so everyone behind it keeps its place. A cancelled call\n * rejects with {@link LockWaitTimeoutError}, the same error a timed-out wait\n * produces, because from the caller's side they are one condition.\n */\n run<T>(key: string, fn: () => Promise<T>, timeoutMillis?: number): Promise<T>;\n}\n\nexport class LockWaitTimeoutError extends Error {\n public readonly lockKey: string;\n\n public constructor(key: string, timeoutMillis: number) {\n super(`lock wait exceeded ${timeoutMillis}ms`);\n this.name = \"LockWaitTimeoutError\";\n this.lockKey = key;\n }\n}\n\nexport const createAsyncLock = (): AsyncLock => {\n const tail = new Map<string, Promise<void>>();\n\n const run = async <T>(key: string, fn: () => Promise<T>, timeoutMillis?: number): Promise<T> => {\n const previous = tail.get(key) ?? Promise.resolve();\n const queued = previous.then(\n () => undefined,\n () => undefined,\n );\n\n /**\n * `entered` flips synchronously, immediately before `fn` is invoked, and\n * `cancelled` is only ever set from the timer while `entered` is false.\n *\n * That ordering is what makes the two guarantees exclusive rather than racy.\n * Microtasks drain before timers, so if this slot's turn has arrived at all,\n * the callback below has already run and set `entered` before any timer\n * callback can observe it — there is no window in which the timer sees a\n * not-yet-entered slot that is in fact about to run.\n */\n let cancelled = false;\n let entered = false;\n\n const current = queued.then((): T | Promise<T> => {\n if (cancelled) {\n // The waiter gave up before its turn came, so `fn` is skipped entirely.\n // The slot still settles here, in order, so nothing behind it is reordered.\n throw new LockWaitTimeoutError(key, timeoutMillis ?? 0);\n }\n entered = true;\n return fn();\n });\n\n const swallowed = current.then(\n () => undefined,\n () => undefined,\n );\n tail.set(key, swallowed);\n void swallowed.then(() => {\n if (tail.get(key) === swallowed) {\n tail.delete(key);\n }\n });\n\n if (timeoutMillis === undefined) {\n return current;\n }\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n if (!entered) {\n cancelled = true;\n }\n reject(new LockWaitTimeoutError(key, timeoutMillis));\n }, timeoutMillis);\n timer.unref?.();\n });\n try {\n // Raced against the queue gate, not against `current`: once the slot is\n // entered the caller waits for `fn` however long it takes.\n await Promise.race([queued, timeout]);\n } finally {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n }\n return current;\n };\n\n return { run };\n};\n","import type { Clock, StateStore } from \"../runtime/ports.js\";\nimport { LockWaitTimeoutError } from \"./async-lock.js\";\n\n/**\n * A lock could not be acquired within its wait bound because somebody else holds\n * it.\n *\n * Distinct from \"the store is broken\" on purpose, and the distinction is\n * load-bearing for callers that guard a read-modify-write with it. Contention\n * means a peer is plausibly *inside* the critical section right now, so\n * proceeding unlocked would produce exactly the lost update the lock exists to\n * prevent. A store that cannot lock at all — an unwritable directory, a full\n * disk — protects nothing, because the state the lock guards is equally\n * unreachable; there proceeding is the fail-open answer and costs nothing.\n */\nexport class StateLockTimeoutError extends Error {\n public readonly lockKey: string;\n\n public constructor(key: string, timeoutMillis: number) {\n super(`state store lock wait for \"${key}\" exceeded ${String(timeoutMillis)}ms`);\n this.name = \"StateLockTimeoutError\";\n this.lockKey = key;\n }\n}\n\n/**\n * Whether a thrown value means \"somebody else holds the lock\".\n *\n * Also true for {@link LockWaitTimeoutError}, the in-process variant, which\n * carries a second warning for callers: a timed-out wait does not cancel the\n * queued critical section, so it may still run afterwards. A caller that treats\n * contention as \"retry unlocked\" would therefore risk running the section twice.\n */\nexport const isStateLockContention = (thrown: unknown): boolean =>\n thrown instanceof StateLockTimeoutError || thrown instanceof LockWaitTimeoutError;\n\n/**\n * Optional capability beyond the frozen {@link StateStore} contract: a\n * session-scoped lock a caller can use to make a multi-step read-modify-write\n * atomic across an entire session, not just a single key.\n *\n * Deliberately keyed by an explicit `sessionId` the caller already knows,\n * rather than derived by parsing the store's own keys, so a store never has\n * to understand any particular key scheme.\n */\nexport interface LockingStateStore extends StateStore {\n withSessionLock<T>(\n sessionId: string,\n fn: () => Promise<T>,\n options?: { readonly timeoutMillis?: number },\n ): Promise<T>;\n}\n\nexport const isLockingStateStore = (store: StateStore): store is LockingStateStore =>\n typeof (store as Partial<LockingStateStore>).withSessionLock === \"function\";\n\n/** Runs `fn` under the store's session lock when it has one; otherwise runs it directly. */\nexport const withOptionalSessionLock = async <T>(\n store: StateStore,\n sessionId: string,\n fn: () => Promise<T>,\n options?: { readonly timeoutMillis?: number },\n): Promise<T> => {\n if (isLockingStateStore(store)) {\n return store.withSessionLock(sessionId, fn, options);\n }\n return fn();\n};\n\nexport type StateStoreDependencies = {\n readonly clock: Clock;\n};\n","/**\n * State key namespaces for lifecycle bookkeeping.\n *\n * Prefixed with `lifecycle:` so these keys can never collide with the\n * orchestrator's own `sequence:<sessionId>` and `usage:<sessionId>:...` keys\n * in the same {@link StateStore}, even though both share the store.\n *\n * Two properties are load-bearing here, because the store hashes a *whole\n * logical key* into one record: keys must be unambiguous, and a key space whose\n * layout changes must not be readable under its old meaning.\n */\nexport const LIFECYCLE_PREFIX = \"lifecycle\";\n\n/**\n * Layout version of the span key space.\n *\n * Bumped when the *segments* change, not when a record's contents do — that is\n * {@link SPAN_RECORD_VERSION}'s job. Version 2 inserted the provider segment,\n * so a v1 key must never be reachable: reading one would pair a span across\n * providers, which is exactly the attribution guess this library refuses.\n */\nexport const SPAN_KEY_VERSION = 2;\n\n/**\n * Layout version of the dedup key space.\n *\n * Version 2 re-scoped these keys from a session id to a delivery scope. The two\n * spaces are not interchangeable — a v1 key found under a v2 read would suppress\n * an unrelated callback — so the version segment keeps them disjoint.\n */\nexport const DEDUP_KEY_VERSION = 2;\n\n/**\n * Make a variable segment unambiguous within a `:`-delimited key.\n *\n * Without this, `dedupKey(\"a:b\", \"c\")` and `dedupKey(\"a\", \"b:c\")` produce the\n * identical logical key, and the store hashes both to one record — so one\n * delivery silently suppresses an unrelated one. That is reachable input, not a\n * theoretical one: `--callback-scope` is host-supplied, and a provider's session\n * or tool-call id is not required to avoid a colon.\n *\n * `%` is escaped first so the encoding stays injective, which makes this a true\n * bijection on segments rather than a lossy scrub. A segment containing neither\n * character encodes to itself, so keys already on disk keep their identity and\n * no cumulative baseline is reset by adopting this.\n */\nconst encodeSegment = (segment: string): string =>\n segment.replaceAll(\"%\", \"%25\").replaceAll(\":\", \"%3A\");\n\n/**\n * Session first, then provider: the janitor sweeps a whole session by prefix,\n * so the session segment has to lead. The provider segment below it is what\n * makes cross-provider pairing impossible by construction rather than only by\n * the runtime check in the span correlator.\n */\nexport const spanKey = (\n sessionId: string,\n providerId: string,\n scope: string,\n scopeKey: string,\n): string =>\n `${spanScanPrefix(sessionId)}${encodeSegment(providerId)}:${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;\n\n/**\n * The session-scoped prefix names one layout version; the bare prefix names\n * every one of them. That asymmetry is deliberate: a sweep must be able to\n * reclaim records written by a previous version, which a versioned prefix could\n * never match, while a *read* must never reach across a layout change.\n */\nexport const spanScanPrefix = (sessionId?: string): string =>\n sessionId === undefined\n ? `${LIFECYCLE_PREFIX}:span:`\n : `${LIFECYCLE_PREFIX}:span:v${String(SPAN_KEY_VERSION)}:${encodeSegment(sessionId)}:`;\n\n/**\n * Dedup keys are scoped by a *delivery scope*, not by a session id.\n *\n * A host-supplied delivery id carries its own namespace, and a provider-derived\n * one is scoped by a digest of provider, installation, and session — so neither\n * is a session id, and neither can be found by scanning for one.\n */\nexport const dedupKey = (scope: string, callbackId: string): string =>\n `${dedupScanPrefix(scope)}${encodeSegment(callbackId)}`;\n\nexport const dedupScanPrefix = (scope?: string): string =>\n scope === undefined\n ? `${LIFECYCLE_PREFIX}:dedup:`\n : `${LIFECYCLE_PREFIX}:dedup:v${String(DEDUP_KEY_VERSION)}:${encodeSegment(scope)}:`;\n\nconst decodeSegment = (segment: string): string =>\n segment.replaceAll(\"%3A\", \":\").replaceAll(\"%25\", \"%\");\n\n/**\n * Recover the delivery scope a dedup key belongs to.\n *\n * Needed by the sweep and nothing else. A sweep enumerates keys rather than being\n * handed a scope, but deleting a dedup record is a read-modify-write against the\n * same record a concurrent `claim` is deciding on — so the sweep has to take the\n * same per-scope lock, and to take it, it has to know the scope. Recovering it\n * from the key is safe precisely because {@link encodeSegment} is injective.\n *\n * Returns `undefined` for a key from a previous layout version, which no lock\n * protects because no current read can reach it.\n */\nexport const dedupScopeOf = (key: string): string | undefined => {\n const prefix = `${LIFECYCLE_PREFIX}:dedup:v${String(DEDUP_KEY_VERSION)}:`;\n if (!key.startsWith(prefix)) {\n return undefined;\n }\n // Exactly two segments follow the prefix, and neither can contain a raw `:`,\n // so the first `:` after the prefix is unambiguously the boundary.\n const rest = key.slice(prefix.length);\n const boundary = rest.indexOf(\":\");\n return boundary <= 0 ? undefined : decodeSegment(rest.slice(0, boundary));\n};\n\n/**\n * Usage rollup keys are escaped but deliberately *not* versioned: their layout\n * has not changed, and a version segment would orphan every cumulative token\n * baseline on disk — resetting usage accounting to fix a bug that escaping\n * already fixes.\n */\nexport const rollupUsageKey = (sessionId: string, scope: string, scopeKey: string): string =>\n `${rollupScanPrefix(sessionId)}${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;\n\nexport const rollupEpochKey = (sessionId: string, scope: string, scopeKey: string): string =>\n `${rollupEpochScanPrefix(sessionId)}${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;\n\nexport const rollupScanPrefix = (sessionId?: string): string =>\n sessionId === undefined\n ? `${LIFECYCLE_PREFIX}:usage:`\n : `${LIFECYCLE_PREFIX}:usage:${encodeSegment(sessionId)}:`;\n\nexport const rollupEpochScanPrefix = (sessionId?: string): string =>\n sessionId === undefined\n ? `${LIFECYCLE_PREFIX}:epoch:`\n : `${LIFECYCLE_PREFIX}:epoch:${encodeSegment(sessionId)}:`;\n","import type { CallbackDeduplicator } from \"./dedup.js\";\nimport type { SpanCorrelator } from \"./span-correlator.js\";\nimport type { UsageAccumulator } from \"./usage-accumulator.js\";\n\nconst DEFAULT_MAX_AGE_MILLIS = 24 * 60 * 60 * 1000;\nconst DEFAULT_MAX_ENTRIES_PER_COMPONENT = 1_000;\n\nexport type LifecycleJanitorOptions = {\n readonly spanCorrelator?: SpanCorrelator;\n readonly deduplicator?: CallbackDeduplicator;\n readonly usageAccumulator?: UsageAccumulator;\n readonly spanMaxAgeMillis?: number;\n readonly dedupMaxAgeMillis?: number;\n /**\n * Floor on how long an uncommitted delivery claim survives the sweep, whatever\n * `dedupMaxAgeMillis` says.\n *\n * Passed through rather than left to the deduplicator's default so it can be the\n * *effective* window the runtime computed, which is raised from the requested one\n * to cover a process's whole export budget. A sweep using a smaller number than\n * the claim path uses would delete claims the claim path still considers live.\n */\n readonly dedupStaleClaimMillis?: number;\n readonly usageMaxAgeMillis?: number;\n /** Caps how many keys any single component scans per sweep. */\n readonly maxEntriesPerComponent?: number;\n};\n\nexport type LifecycleSweepStats = {\n readonly removed: number;\n readonly scanned: number;\n /**\n * Span records dropped with a start and no end — spans that were never\n * exported. Reported only by the span sweep; see `SpanCleanupResult`.\n */\n readonly expiredOpen?: number;\n /**\n * Aged-out records kept back because they are delivery claims a live process may\n * still hold. Reported only by the dedup sweep; see `DedupCleanupResult`.\n */\n readonly retainedInFlight?: number;\n};\n\nexport type LifecycleCleanupReport = {\n readonly span?: LifecycleSweepStats;\n readonly dedup?: LifecycleSweepStats;\n readonly usage?: LifecycleSweepStats;\n};\n\n/**\n * Fans a single bounded cleanup pass out across whichever lifecycle\n * components are configured.\n *\n * Each component already bounds its own sweep (`maxEntries`); this exists so\n * a caller — a CLI subcommand, a periodic timer, an opportunistic call at the\n * end of `flush()` — can run \"the\" cleanup without wiring each component by\n * hand, and so the bound is enforced uniformly rather than per call site.\n */\nexport interface LifecycleJanitor {\n runOnce(sessionId?: string): Promise<LifecycleCleanupReport>;\n}\n\nexport const createLifecycleJanitor = (options: LifecycleJanitorOptions): LifecycleJanitor => {\n const maxEntries = options.maxEntriesPerComponent ?? DEFAULT_MAX_ENTRIES_PER_COMPONENT;\n const spanMaxAge = options.spanMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;\n const dedupMaxAge = options.dedupMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;\n const usageMaxAge = options.usageMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;\n\n const runOnce = async (sessionId?: string): Promise<LifecycleCleanupReport> => {\n const scope = { maxEntries, ...(sessionId === undefined ? {} : { sessionId }) };\n const [span, dedup, usage] = await Promise.all([\n options.spanCorrelator?.cleanup(spanMaxAge, scope),\n // Deduplication is deliberately swept across every scope rather than the\n // ending session's: a delivery scope is a host-chosen namespace or a\n // digest of provider/installation/session, never a session id, so scoping\n // this sweep by `sessionId` would match nothing and let records accumulate\n // forever. The sweep is TTL-driven and still bounded by `maxEntries`.\n options.deduplicator?.cleanup(dedupMaxAge, {\n maxEntries,\n ...(options.dedupStaleClaimMillis === undefined\n ? {}\n : { staleClaimMillis: options.dedupStaleClaimMillis }),\n }),\n options.usageAccumulator?.cleanup(usageMaxAge, scope),\n ]);\n return {\n ...(span === undefined ? {} : { span }),\n ...(dedup === undefined ? {} : { dedup }),\n ...(usage === undefined ? {} : { usage }),\n };\n };\n\n return { runOnce };\n};\n","import { createHash } from \"node:crypto\";\n\nimport { SpanKind, SpanStatusCode, TraceFlags, type Attributes, type SpanContext, type SpanStatus } from \"@opentelemetry/api\";\nimport { millisToHrTime } from \"@opentelemetry/core\";\nimport type { InstrumentationScope } from \"@opentelemetry/core\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport type { ReadableSpan } from \"@opentelemetry/sdk-trace\";\nimport {\n ATTR_ERROR_TYPE,\n ATTR_GEN_AI_OPERATION_NAME,\n ATTR_GEN_AI_REQUEST_MODEL,\n ATTR_GEN_AI_RESPONSE_MODEL,\n ATTR_GEN_AI_SYSTEM,\n ATTR_GEN_AI_TOOL_CALL_ID,\n ATTR_GEN_AI_TOOL_NAME,\n ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n} from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport type { CanonicalEvent, CanonicalEventType } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\nimport { VERSION } from \"../version.js\";\nimport {\n ATTR_OTELHOOK_TARGET_SOURCE,\n ATTR_OTELHOOK_TARGET_WORKSPACE_ID,\n ATTR_VCS_REF_HEAD_NAME,\n exportIdentityAttributes,\n targetAttributes,\n usageTemporalityAttributes,\n} from \"./export-identity.js\";\n\nconst SCOPE_NAME = \"@osfactory/otel-hook\";\n\nexport const DEFAULT_INSTRUMENTATION_SCOPE: InstrumentationScope = Object.freeze({\n name: SCOPE_NAME,\n version: VERSION,\n});\n\nconst ATTR_OTELHOOK_SPAN_PAIRED = \"otelhook.span.paired\";\nconst ATTR_OTELHOOK_SPAN_PAIRING = \"otelhook.span.pairing\";\nconst ATTR_OTELHOOK_SPAN_ORPHAN = \"otelhook.span.orphan\";\nconst ATTR_OTELHOOK_OUTCOME = \"otelhook.outcome\";\nconst ATTR_OTELHOOK_RESET_DETECTED = \"otelhook.usage.reset_detected\";\nconst ATTR_OTELHOOK_TOOL_KIND = \"otelhook.tool.kind\";\nconst ATTR_OTELHOOK_DELEGATION_DEPTH = \"otelhook.delegation_depth\";\nconst ATTR_OTELHOOK_COMPACTION_TRIGGER = \"otelhook.compaction.trigger\";\nconst ATTR_OTELHOOK_AGENT_NAME = \"otelhook.agent.name\";\nconst ATTR_OTELHOOK_AGENT_VERSION = \"otelhook.agent.version\";\nconst ATTR_OTELHOOK_GENERATION_ID = \"otelhook.generation.id\";\n\n/**\n * Pure, stateless canonical-event-to-span mapping.\n *\n * Isolated in one module so every other piece of the telemetry pipeline\n * — batching, retry, spooling — can change without touching what an attribute\n * means. Two edges of the same lifecycle scope are merged into one span when\n * they appear in the same batch; when they arrive in *different* short-lived\n * hook processes they are merged through a {@link SpanCorrelation} the caller\n * resolved from persisted state. Either way the mapping itself stays a pure\n * function: state is read by the correlator, never by this module.\n *\n * ## Identity of a span\n *\n * Trace and span ids are derived, never random, so two processes that never\n * meet still agree on them:\n *\n * - `traceId = H(providerId, sessionId)` — one trace per session per provider.\n * Deriving it from the session rather than the invocation is what lets a\n * `tool.end` emitted minutes later land in the same trace as its `tool.start`;\n * including the provider is what stops two providers that happen to reuse a\n * session id from being stitched into one trace.\n * - `spanId = H(providerId, sessionId, family, scopeKey)` — stable across\n * processes and idempotent under redelivery, so a collector that sees a\n * start-only span and later the completed span treats them as one span\n * rather than two.\n */\n// NUL, so joined parts cannot collide across a different split: no identifier\n// this library accepts can contain one, which a printable separator cannot\n// promise. Never emitted — only hashed, or used as an in-memory map key.\nconst FIELD_SEPARATOR = \"\\u0000\";\n\nconst digestHex = (parts: readonly string[], length: number): string =>\n createHash(\"sha256\").update(parts.join(FIELD_SEPARATOR)).digest(\"hex\").slice(0, length);\n\n/** Lifecycle scopes that pair a `*.start` edge with a later `*.end` edge. */\nexport type SpanFamily = \"session\" | \"generation\" | \"tool\" | \"subagent\";\n\n/** Identifies one lifecycle span within a session. */\nexport type SpanScopeRef = {\n readonly family: SpanFamily;\n readonly scopeKey: string;\n};\n\n/**\n * Why a lifecycle span is, or is not, a complete pair.\n *\n * Deliberately explicit rather than a bare boolean: \"we never saw the start\",\n * \"we saw it but it aged out of state\", and \"state could not be read at all\"\n * are different operational facts, and a dashboard that cannot tell them apart\n * cannot tell a broken host from a broken exporter.\n */\nexport type SpanOrphanClassification =\n /** Both edges are known — from this batch, or from persisted state. */\n | \"none\"\n /** The start is known; its end has not arrived yet. */\n | \"missing-end\"\n /** An end arrived and no start was ever recorded for this scope. */\n | \"missing-start\"\n /** A start was recorded but aged past the retention window before the end arrived. */\n | \"expired-start\"\n /** A start exists but was recorded by a different provider; pairing it would be a guess. */\n | \"provider-mismatch\"\n /** A second, distinct end arrived for a scope that was already closed. */\n | \"already-closed\"\n /** The persisted record was written by an incompatible version and was discarded. */\n | \"state-incompatible\"\n /** The persisted record could not be understood. */\n | \"state-corrupt\"\n /** State could not be consulted at all; the mapping degraded rather than failing. */\n | \"state-unavailable\";\n\nexport type SpanPairing =\n /** Both edges were present in this batch. */\n | \"in-batch\"\n /** The other edge came from state written by an earlier process. */\n | \"cross-process\"\n | \"unpaired\";\n\n/**\n * Whether this scope should produce an OTLP record now.\n *\n * OTLP has no notion of updating a span: a span is exported once, when it ends,\n * and a second record carrying the same trace and span id is not a revision of\n * the first — it is a duplicate that backends variously drop, keep the older of,\n * or display twice. Since every lifecycle span id here is *derived* from\n * `(provider, session, family, scopeKey)`, a `*.start` edge and its later `*.end`\n * edge compute the identical id, so exporting on both is precisely that\n * duplicate.\n *\n * `defer` is therefore the answer for a start whose end has not arrived: the\n * start is durable in the state store, and the end edge exports the one complete\n * span using the times recovered from it. Nothing is lost by waiting, and what is\n * gained is that the record a collector receives has a real duration.\n */\nexport type SpanDisposition =\n /** Export a record for this scope now. */\n | \"emit\"\n /** Hold: the start is recorded, and the end edge will export the complete span. */\n | \"defer\";\n\n/**\n * One scope's correlation facts, resolved from persisted state by the caller.\n *\n * Plain data on purpose: the telemetry layer must not reach into the state\n * store itself (ADR 0006), so it declares what it needs and the lifecycle layer\n * supplies it.\n */\nexport type SpanCorrelation = {\n readonly providerId: string;\n readonly sessionId: string;\n readonly ref: SpanScopeRef;\n readonly pairing: SpanPairing;\n readonly orphan: SpanOrphanClassification;\n /**\n * Whether to export a record for this scope now. Defaults to `emit` when a\n * correlation is supplied without one.\n */\n readonly disposition?: SpanDisposition;\n /**\n * Extra component mixed into the derived span id.\n *\n * Set only when this record is a genuinely *additional* observation of a scope\n * that has already been exported once — a second, distinct end for a scope that\n * was already closed. Both records are real, so neither is dropped, and the\n * discriminator keeps them from claiming the same span id.\n */\n readonly spanIdDiscriminator?: string;\n /** Start recovered from state; authoritative over the batch's own start edge. */\n readonly startMillis?: number;\n /** End recovered from state; authoritative so a redelivered end re-exports an identical span. */\n readonly endMillis?: number;\n /** Parent recorded at start time, so an end-only process hangs the span in the same place. */\n readonly parent?: SpanScopeRef;\n /** Attributes only the start edge could supply, recovered for an end-only span. */\n readonly attributes?: Attributes;\n};\n\n/**\n * Resolves persisted correlation for one batch.\n *\n * Must never reject: a state failure is a degraded span, never a lost export.\n */\nexport type SpanCorrelationResolver = (\n events: readonly CanonicalEvent[],\n) => Promise<readonly SpanCorrelation[]>;\n\n/**\n * Upper bound on how many start-edge attributes the correlator may carry\n * forward, so persisted state cannot grow with provider-controlled input.\n */\nexport const MAX_RECOVERED_START_ATTRIBUTES = 16;\n\nconst familyOf = (type: CanonicalEventType): SpanFamily | undefined => {\n switch (type) {\n case \"session.start\":\n case \"session.end\":\n return \"session\";\n case \"generation.start\":\n case \"generation.end\":\n return \"generation\";\n case \"tool.start\":\n case \"tool.end\":\n return \"tool\";\n case \"subagent.start\":\n case \"subagent.end\":\n return \"subagent\";\n default:\n return undefined;\n }\n};\n\n/** The lifecycle span an event is an edge of, or undefined for a point-in-time event. */\nexport const spanScopeRefOf = (event: CanonicalEvent): SpanScopeRef | undefined => {\n const family = familyOf(event.type);\n if (family === undefined) {\n return undefined;\n }\n switch (event.type) {\n case \"session.start\":\n case \"session.end\":\n return { family, scopeKey: event.sessionId };\n case \"generation.start\":\n case \"generation.end\":\n return { family, scopeKey: event.generationId };\n case \"tool.start\":\n case \"tool.end\":\n return { family, scopeKey: event.toolCallId };\n case \"subagent.start\":\n case \"subagent.end\":\n return { family, scopeKey: event.subagentInvocationId };\n default:\n return undefined;\n }\n};\n\n/**\n * Where a span hangs in the trace, judged from this event alone.\n *\n * Everything in a session descends from the session span. A tool call names its\n * generation only on `tool.start`, which is exactly why the correlator persists\n * the parent: the `tool.end` process would otherwise reparent the same span to\n * the session and produce a tree whose shape depends on which edge happened to\n * be exported last.\n */\nexport const parentScopeRefOf = (event: CanonicalEvent): SpanScopeRef | undefined => {\n if (event.type === \"session.start\" || event.type === \"session.end\") {\n return undefined;\n }\n if (event.type === \"tool.start\" && event.generationId !== undefined) {\n return { family: \"generation\", scopeKey: event.generationId };\n }\n return { family: \"session\", scopeKey: event.sessionId };\n};\n\n/**\n * Span attributes that only a `*.start` edge can supply.\n *\n * The correlator persists these verbatim so an end-only span in a later process\n * still carries the tool kind, requested model, delegation depth, or agent name\n * the start process saw. An allowlist, and bounded, so persisted state can\n * never become a second route for provider payload content to escape.\n */\nexport const startOnlySpanAttributes = (event: CanonicalEvent): Attributes => {\n switch (event.type) {\n 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 // The target is carried forward too: an end-only process may see a payload\n // with less to go on (no tool input), and the start's evidence still holds.\n case \"tool.start\":\n return { [ATTR_OTELHOOK_TOOL_KIND]: event.toolKind, ...targetAttributes(event) };\n case \"subagent.start\":\n return { [ATTR_OTELHOOK_DELEGATION_DEPTH]: event.delegationDepth };\n default:\n return {};\n }\n};\n\nconst deriveTraceId = (providerId: string, sessionId: string): string =>\n digestHex([\"otelhook/trace\", providerId, sessionId], 32);\n\nconst deriveSpanId = (providerId: string, sessionId: string, ref: SpanScopeRef): string =>\n digestHex([\"otelhook/span\", providerId, sessionId, ref.family, ref.scopeKey], 16);\n\nconst deriveStandaloneSpanId = (\n providerId: string,\n sessionId: string,\n eventType: string,\n eventId: string,\n): string => digestHex([\"otelhook/span\", providerId, sessionId, \"event\", eventType, eventId], 16);\n\nconst correlationKey = (providerId: string, sessionId: string, ref: SpanScopeRef): string =>\n [providerId, sessionId, ref.family, ref.scopeKey].join(FIELD_SEPARATOR);\n\nconst outcomeStatus = (outcome: string | undefined): SpanStatus => {\n if (outcome === undefined || outcome === \"ok\" || outcome === \"unknown\") {\n return { code: SpanStatusCode.UNSET };\n }\n if (outcome === \"cancelled\") {\n return { code: SpanStatusCode.UNSET };\n }\n return { code: SpanStatusCode.ERROR, message: outcome };\n};\n\nconst identityAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n ids: { readonly traceId: string; readonly spanId: string; readonly parentSpanId?: string },\n): Attributes => exportIdentityAttributes(event, resource, ids);\n\nconst usageAttributes = (usage: CanonicalUsage | undefined, resetDetected: boolean): Attributes => {\n if (usage === undefined) {\n return {};\n }\n return {\n [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: usage.inputTokens,\n [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: usage.outputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: usage.cachedInputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: usage.cacheCreationInputTokens,\n [ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]: usage.reasoningOutputTokens,\n ...usageTemporalityAttributes(usage),\n ...(resetDetected ? { [ATTR_OTELHOOK_RESET_DETECTED]: true } : {}),\n };\n};\n\n/** Evidence strength of a target source; see `targetSourceSchema`. */\nconst TARGET_SOURCE_RANK: Readonly<Record<string, number>> = Object.freeze({\n \"tool-path\": 3,\n \"shell-cwd\": 2,\n \"session-cwd\": 1,\n});\n\nconst TARGET_KEYS = [\n ATTR_OTELHOOK_TARGET_WORKSPACE_ID,\n ATTR_OTELHOOK_TARGET_SOURCE,\n ATTR_VCS_REF_HEAD_NAME,\n] as const;\n\nconst pickTarget = (attributes: Attributes): Attributes => {\n const picked: Attributes = {};\n for (const key of TARGET_KEYS) {\n if (attributes[key] !== undefined) {\n picked[key] = attributes[key];\n }\n }\n return picked;\n};\n\nconst withoutTarget = (attributes: Attributes): Attributes => {\n const rest: Attributes = { ...attributes };\n for (const key of TARGET_KEYS) {\n delete rest[key];\n }\n return rest;\n};\n\nconst rankOf = (candidate: Attributes): number => {\n const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];\n return typeof source === \"string\" && Object.hasOwn(TARGET_SOURCE_RANK, source)\n ? (TARGET_SOURCE_RANK[source] ?? 0)\n : 0;\n};\n\n/**\n * One tool span, one target: the strongest evidence among the recovered start,\n * the live start, and the live end — later wins a tie. A Cursor shell call's\n * start knows its `cwd` and its end does not; the span must keep the former,\n * not be downgraded to the workspace root by whichever edge exported last.\n */\nconst strongestTarget = (candidates: readonly Attributes[]): Attributes => {\n let best: Attributes = {};\n let bestRank = 0;\n for (const candidate of candidates) {\n const rank = rankOf(candidate);\n if (rank > 0 && rank >= bestRank) {\n best = candidate;\n bestRank = rank;\n }\n }\n return best;\n};\n\ntype SpanGroup = {\n readonly ref: SpanScopeRef;\n start?: CanonicalEvent;\n end?: CanonicalEvent;\n};\n\nconst buildSpanContext = (traceId: string, spanId: string): SpanContext => ({\n traceId,\n spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n});\n\nexport type ReadableSpanInput = {\n readonly name: string;\n readonly kind: SpanKind;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly attributes: Attributes;\n readonly status: SpanStatus;\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n};\n\n/** Reconstructs a {@link ReadableSpan} from plain, serializable fields. Used by the durable spool to replay a span it persisted earlier. */\nexport const assembleReadableSpan = (input: ReadableSpanInput): ReadableSpan => toReadableSpan(input);\n\nconst toReadableSpan = (input: ReadableSpanInput): ReadableSpan => {\n const startTime = millisToHrTime(input.startMillis);\n const endTime = millisToHrTime(Math.max(input.startMillis, input.endMillis));\n const duration = millisToHrTime(Math.max(0, input.endMillis - input.startMillis));\n return {\n name: input.name,\n kind: input.kind,\n spanContext: (): SpanContext => buildSpanContext(input.traceId, input.spanId),\n ...(input.parentSpanId === undefined\n ? {}\n : { parentSpanContext: buildSpanContext(input.traceId, input.parentSpanId) }),\n startTime,\n endTime,\n status: input.status,\n attributes: input.attributes,\n links: [],\n events: [],\n duration,\n ended: true,\n resource: input.resource,\n instrumentationScope: input.instrumentationScope,\n droppedAttributesCount: 0,\n droppedEventsCount: 0,\n droppedLinksCount: 0,\n };\n};\n\ntype ResolvedPairing = {\n readonly pairing: SpanPairing;\n readonly orphan: SpanOrphanClassification;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly parent: SpanScopeRef | undefined;\n readonly recovered: Attributes;\n};\n\nconst resolvePairing = (\n group: SpanGroup,\n anchor: CanonicalEvent,\n correlation: SpanCorrelation | undefined,\n): ResolvedPairing => {\n const inBatch = group.start !== undefined && group.end !== undefined;\n const batchStart = group.start?.occurredAt ?? anchor.occurredAt;\n const batchEnd = group.end?.occurredAt ?? anchor.occurredAt;\n\n if (correlation === undefined) {\n return {\n pairing: inBatch ? \"in-batch\" : \"unpaired\",\n orphan: inBatch ? \"none\" : group.start === undefined ? \"missing-start\" : \"missing-end\",\n startMillis: batchStart,\n endMillis: inBatch ? batchEnd : batchStart,\n parent: parentScopeRefOf(anchor),\n recovered: {},\n };\n }\n\n // A correlation that reports no start (an orphaned end) must not fabricate\n // one: the span collapses onto the end instant rather than claiming a\n // duration measured from an event nobody ever saw.\n const startMillis = correlation.startMillis ?? (inBatch ? batchStart : batchEnd);\n const endMillis = correlation.endMillis ?? (group.end === undefined ? startMillis : batchEnd);\n return {\n pairing: correlation.pairing,\n orphan: correlation.orphan,\n startMillis,\n endMillis,\n parent: correlation.parent ?? parentScopeRefOf(anchor),\n recovered: correlation.attributes ?? {},\n };\n};\n\nconst buildLifecycleSpan = (\n plan: GroupPlan,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan => {\n const group = plan.group;\n const anchor = plan.anchor;\n const correlation = plan.correlation;\n const providerId = anchor.provenance.providerId;\n const sessionId = anchor.sessionId;\n const resolved = resolvePairing(group, anchor, correlation);\n const traceId = plan.traceId;\n const spanId = plan.spanId;\n const parentSpanId =\n resolved.parent === undefined ? undefined : deriveSpanId(providerId, sessionId, resolved.parent);\n\n let name: string = group.ref.family;\n let kind: SpanKind = SpanKind.INTERNAL;\n let status: SpanStatus = { code: SpanStatusCode.UNSET };\n // Attributes recovered from the start process sit *beneath* whatever this\n // batch observed: a live edge always wins over a remembered one.\n let attributes: Attributes = {\n ...identityAttributes(anchor, resource, {\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n }),\n ...resolved.recovered,\n [ATTR_OTELHOOK_SPAN_PAIRED]: resolved.pairing !== \"unpaired\",\n [ATTR_OTELHOOK_SPAN_PAIRING]: resolved.pairing,\n [ATTR_OTELHOOK_SPAN_ORPHAN]: resolved.orphan,\n };\n\n switch (group.ref.family) {\n case \"session\": {\n const end = group.end?.type === \"session.end\" ? group.end : undefined;\n const start = group.start?.type === \"session.start\" ? group.start : undefined;\n name = \"session\";\n kind = SpanKind.INTERNAL;\n attributes = {\n ...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 // The provider's own id for this unit of work (Cursor generation,\n // Codex turn): the key a consumer stores a usage observation under.\n [ATTR_OTELHOOK_GENERATION_ID]: group.ref.scopeKey,\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...usageAttributes(end?.usage, false),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n case \"tool\": {\n const start = group.start?.type === \"tool.start\" ? group.start : undefined;\n const end = group.end?.type === \"tool.end\" ? group.end : undefined;\n const toolName = start?.toolName ?? end?.toolName ?? \"unknown\";\n name = `tool ${toolName}`;\n kind = SpanKind.CLIENT;\n attributes = {\n // Target keys are re-chosen below as one unit, never mixed across edges.\n ...withoutTarget(attributes),\n [ATTR_GEN_AI_TOOL_NAME]: toolName,\n [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,\n ...(start?.toolKind === undefined ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind }),\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...strongestTarget([\n pickTarget(resolved.recovered),\n start === undefined ? {} : targetAttributes(start),\n end === undefined ? {} : targetAttributes(end),\n ]),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n case \"subagent\": {\n const start = group.start?.type === \"subagent.start\" ? group.start : undefined;\n const end = group.end?.type === \"subagent.end\" ? group.end : undefined;\n name = \"subagent\";\n kind = SpanKind.INTERNAL;\n attributes = {\n ...attributes,\n ...(start?.delegationDepth === undefined\n ? {}\n : { [ATTR_OTELHOOK_DELEGATION_DEPTH]: start.delegationDepth }),\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...usageAttributes(end?.usage, false),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n }\n\n if (status.code === SpanStatusCode.ERROR) {\n attributes = { ...attributes, [ATTR_ERROR_TYPE]: status.message ?? \"error\" };\n }\n\n return toReadableSpan({\n name,\n kind,\n startMillis: resolved.startMillis,\n endMillis: resolved.endMillis,\n attributes,\n status,\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n resource,\n instrumentationScope: scope,\n });\n};\n\nconst buildStandaloneSpan = (\n event: CanonicalEvent,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan => {\n const providerId = event.provenance.providerId;\n const traceId = deriveTraceId(providerId, event.sessionId);\n const spanId = deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId);\n const parent = parentScopeRefOf(event);\n const parentSpanId =\n parent === undefined ? undefined : deriveSpanId(providerId, event.sessionId, parent);\n let attributes: Attributes = {\n ...identityAttributes(event, resource, {\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n }),\n [ATTR_OTELHOOK_SPAN_PAIRED]: true,\n };\n let status: SpanStatus = { code: SpanStatusCode.UNSET };\n let name: string = event.type;\n\n switch (event.type) {\n case \"prompt.submitted\":\n name = \"prompt\";\n attributes = { ...attributes, \"otelhook.prompt.source\": event.promptSource };\n break;\n case \"compaction.performed\":\n name = \"compaction\";\n attributes = {\n ...attributes,\n [ATTR_OTELHOOK_COMPACTION_TRIGGER]: event.trigger,\n ...usageAttributes(event.usage, false),\n };\n break;\n case \"error.raised\":\n name = \"error\";\n status = { code: SpanStatusCode.ERROR, message: event.errorCode };\n attributes = {\n ...attributes,\n [ATTR_ERROR_TYPE]: event.errorCode,\n \"otelhook.error.phase\": event.phase,\n \"otelhook.error.retryable\": event.retryable,\n };\n break;\n default:\n break;\n }\n\n return toReadableSpan({\n name,\n kind: SpanKind.INTERNAL,\n startMillis: event.occurredAt,\n endMillis: event.occurredAt,\n attributes,\n status,\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n resource,\n instrumentationScope: scope,\n });\n};\n\nexport type SemanticMappingOptions = {\n readonly resource: Resource;\n readonly instrumentationScope?: InstrumentationScope;\n /**\n * Cross-process pairing facts, at most one entry per lifecycle scope in\n * `events`. Omitted entirely, the mapping degrades to in-batch pairing only —\n * the behavior of a host that wired no state store.\n */\n readonly correlations?: readonly SpanCorrelation[];\n /**\n * Whether a correlator was consulted at all, and whether it answered.\n *\n * This is what separates \"the state store is holding this start, so the end edge\n * will publish it\" from \"nothing recorded this start\". Both look like an empty\n * `correlations` list, and only the first is safe to drop — dropping the second\n * would discard an observation that was neither persisted nor exported, while a\n * caller that saw zero rejections went on to mark the callback handled.\n *\n * - `true` — the correlator ran; an absent or non-`defer` entry means emit.\n * - `false` — the correlator failed; every unpaired start is emitted as an\n * explicitly labelled, uniquely identified fallback.\n * - omitted — no correlator is wired, so cross-process pairing was never on\n * offer and an unpaired start is deferred (the documented no-state-root\n * degradation).\n */\n readonly correlationAvailable?: boolean;\n};\n\n/**\n * Fill in a correlation for an unpaired start that nothing recorded.\n *\n * Reached when a correlator was consulted and either failed outright or reported\n * nothing for this scope. The synthesized entry says what is true — the state was\n * not consulted successfully, so this span is unpaired and no end can complete it\n * — and carries a discriminator so the record cannot claim the span id a later end\n * will publish for the same scope.\n */\nconst effectiveCorrelation = (\n group: SpanGroup,\n correlation: SpanCorrelation | undefined,\n): SpanCorrelation | undefined => {\n if (correlation !== undefined || group.end !== undefined || group.start === undefined) {\n return correlation;\n }\n return {\n providerId: group.start.provenance.providerId,\n sessionId: group.start.sessionId,\n ref: group.ref,\n pairing: \"unpaired\",\n orphan: \"state-unavailable\",\n disposition: \"emit\",\n spanIdDiscriminator: group.start.eventId,\n };\n};\n\n/** How one batch's events distribute over the lifecycle scopes they are edges of. */\ntype BatchLayout = {\n readonly groups: ReadonlyMap<string, SpanGroup>;\n readonly standalone: readonly CanonicalEvent[];\n /** Event id of each lifecycle edge, mapped to the group key it belongs to. */\n readonly groupOf: ReadonlyMap<string, string>;\n};\n\nconst layoutBatch = (events: readonly CanonicalEvent[]): BatchLayout => {\n const groups = new Map<string, SpanGroup>();\n const standalone: CanonicalEvent[] = [];\n const groupOf = new Map<string, string>();\n\n for (const event of events) {\n const ref = spanScopeRefOf(event);\n if (ref === undefined) {\n standalone.push(event);\n continue;\n }\n const groupKey = correlationKey(event.provenance.providerId, event.sessionId, ref);\n const group: SpanGroup = groups.get(groupKey) ?? { ref };\n if (event.type.endsWith(\".start\")) {\n group.start = event;\n } else {\n group.end = event;\n }\n groups.set(groupKey, group);\n groupOf.set(event.eventId, groupKey);\n }\n return { groups, standalone, groupOf };\n};\n\nconst indexCorrelations = (\n correlations: readonly SpanCorrelation[] | undefined,\n): ReadonlyMap<string, SpanCorrelation> => {\n const indexed = new Map<string, SpanCorrelation>();\n for (const correlation of correlations ?? []) {\n indexed.set(\n correlationKey(correlation.providerId, correlation.sessionId, correlation.ref),\n correlation,\n );\n }\n return indexed;\n};\n\n/**\n * What this batch does with one lifecycle scope, decided once.\n *\n * Both the span mapping and the log mapping need the *same* answer to \"which\n * span id identifies this scope, and is a record for it going out now?\" — a log\n * record whose `spanContext` names a span id the exporter never published would\n * dangle at the collector. Computing it in one place is what keeps the two\n * signals pointing at the same span rather than at two plausible derivations of\n * it.\n */\ntype GroupPlan = {\n readonly group: SpanGroup;\n /** The event the span's identity and provenance are read from. */\n readonly anchor: CanonicalEvent;\n /**\n * False when the start is deferred: the state store is holding it and the end\n * edge will publish the one complete span, so nothing is exported for it now.\n */\n readonly emits: boolean;\n readonly correlation: SpanCorrelation | undefined;\n readonly traceId: string;\n readonly spanId: string;\n};\n\nconst planGroup = (\n group: SpanGroup,\n correlation: SpanCorrelation | undefined,\n correlationAvailable: boolean | undefined,\n): GroupPlan | undefined => {\n const anchor = group.start ?? group.end;\n if (anchor === undefined) {\n // Unreachable: a group exists only because an event was filed into it.\n return undefined;\n }\n const providerId = anchor.provenance.providerId;\n const sessionId = anchor.sessionId;\n\n // A start with no end in this batch is dropped **only** when something states\n // that it is durably recorded, because its span id is a pure function of the\n // scope: emitting here and again at the end edge would put two records with one\n // id on the wire, and OTLP has no update operation.\n //\n // `defer` is that statement, and it is the correlator's to make — it just wrote\n // the record. Anything else means nothing is holding this start, so dropping it\n // would lose an observation that was neither persisted nor exported, while the\n // caller saw zero rejections and marked the callback handled. Those are exported\n // under a discriminated span id instead.\n const durablyRecorded =\n group.end === undefined &&\n (correlation?.disposition === \"defer\" ||\n // No correlator wired at all: cross-process pairing was never on offer, so\n // this is the documented no-state-root degradation rather than a failure to\n // persist something that should have been persisted.\n (correlation === undefined && correlationAvailable === undefined));\n\n // A deferred start keeps the scope's *plain* span id, because that is the id the\n // end edge will publish. Only a record actually going out now may claim a\n // discriminated one.\n const effective = durablyRecorded ? correlation : effectiveCorrelation(group, correlation);\n const discriminator = durablyRecorded ? undefined : effective?.spanIdDiscriminator;\n\n return {\n group,\n anchor,\n emits: !durablyRecorded,\n correlation: effective,\n traceId: deriveTraceId(providerId, sessionId),\n spanId:\n discriminator === undefined\n ? deriveSpanId(providerId, sessionId, group.ref)\n : digestHex(\n [\n \"otelhook/span\",\n providerId,\n sessionId,\n group.ref.family,\n group.ref.scopeKey,\n discriminator,\n ],\n 16,\n ),\n };\n};\n\n/** Trace and span a record derived from one canonical event belongs to. */\nexport type EventTraceIdentity = {\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n};\n\n/**\n * Resolve the trace and span identity of every event in one batch.\n *\n * Exposed for signals other than traces — a log record correlates by carrying\n * the *same* derived ids the span mapping would compute, including the deferred\n * and discriminated cases. Whole batch at once because a start's identity\n * depends on whether its end is in the same batch.\n *\n * Both ids come from the event's own `(providerId, sessionId)`, never from a\n * batch-level or module-level value, which is what makes cross-session\n * contamination structurally impossible: two sessions in one batch derive two\n * different trace ids.\n */\nexport const canonicalEventTraceIdentities = (\n events: readonly CanonicalEvent[],\n options: {\n readonly correlations?: readonly SpanCorrelation[];\n readonly correlationAvailable?: boolean;\n } = {},\n): ReadonlyMap<string, EventTraceIdentity> => {\n const layout = layoutBatch(events);\n const correlations = indexCorrelations(options.correlations);\n const plans = new Map<string, GroupPlan>();\n for (const [groupKey, group] of layout.groups) {\n const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);\n if (plan !== undefined) {\n plans.set(groupKey, plan);\n }\n }\n\n const identities = new Map<string, EventTraceIdentity>();\n for (const event of events) {\n const providerId = event.provenance.providerId;\n const groupKey = layout.groupOf.get(event.eventId);\n const plan = groupKey === undefined ? undefined : plans.get(groupKey);\n if (plan === undefined) {\n const parent = parentScopeRefOf(event);\n identities.set(event.eventId, {\n traceId: deriveTraceId(providerId, event.sessionId),\n spanId: deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId),\n ...(parent === undefined\n ? {}\n : { parentSpanId: deriveSpanId(providerId, event.sessionId, parent) }),\n });\n continue;\n }\n const parent = plan.correlation?.parent ?? parentScopeRefOf(event);\n identities.set(event.eventId, {\n traceId: plan.traceId,\n spanId: plan.spanId,\n ...(parent === undefined\n ? {}\n : { parentSpanId: deriveSpanId(providerId, event.sessionId, parent) }),\n });\n }\n return identities;\n};\n\n/** Maps one invocation's canonical event batch into OTLP-ready spans. */\nexport const canonicalEventsToReadableSpans = (\n events: readonly CanonicalEvent[],\n options: SemanticMappingOptions,\n): readonly ReadableSpan[] => {\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const layout = layoutBatch(events);\n const correlations = indexCorrelations(options.correlations);\n\n const spans: ReadableSpan[] = [];\n for (const [groupKey, group] of layout.groups) {\n const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);\n if (plan === undefined || !plan.emits) {\n continue;\n }\n spans.push(buildLifecycleSpan(plan, options.resource, scope));\n }\n for (const event of layout.standalone) {\n spans.push(buildStandaloneSpan(event, options.resource, scope));\n }\n return spans;\n};\n","/*\n * 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.4.1\";\n","import type { Attributes } from \"@opentelemetry/api\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport { ATTR_SESSION_ID } from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\n\n/**\n * W3C hex identity attributes on every log and span.\n *\n * Mission Control (and any consumer that decodes OTLP protobuf with a JSON\n * `toObject` that stringifies bytes as UTF-8) cannot recover a usable id from\n * the protobuf `trace_id` / `span_id` fields. These attributes are already hex\n * in the OpenTelemetry JS API; they are copied onto the attribute map so a\n * consumer never has to stringify binary ids.\n */\nexport const ATTR_TRACE_ID = \"trace_id\";\nexport const ATTR_SPAN_ID = \"span_id\";\nexport const ATTR_PARENT_SPAN_ID = \"parent_span_id\";\n\n/** Provider session id, kept when `session.id` is an externally supplied key. */\nexport const ATTR_OTELHOOK_SESSION_ID = \"otelhook.session.id\";\n/** Same provider session id under the gen_ai conversation attribute. */\nexport const ATTR_GEN_AI_CONVERSATION_ID = \"gen_ai.conversation.id\";\n\nexport const TRACE_ID_HEX_PATTERN = /^[0-9a-f]{32}$/;\nexport const SPAN_ID_HEX_PATTERN = /^[0-9a-f]{16}$/;\n\nconst ATTR_OTELHOOK_INVOCATION_ID = \"otelhook.invocation.id\";\nconst ATTR_OTELHOOK_PROVIDER_ID = \"otelhook.provider.id\";\nconst ATTR_OTELHOOK_PROVIDER_VERSION = \"otelhook.provider.version\";\nconst ATTR_OTELHOOK_WORKSPACE_ID = \"otelhook.workspace.id\";\n\nconst HAR_SESSION_KEY = \"har.session_key\";\n\n/**\n * The provider's own subagent id (Claude Code `agent_id`), on every record of an\n * event emitted inside a subagent. Same class as `session.id`: a provider-minted\n * opaque identifier, exported verbatim so a consumer can join it to the\n * provider's own per-subagent records.\n */\nexport const ATTR_OTELHOOK_SUBAGENT_ID = \"otelhook.subagent.id\";\n\n/**\n * Worktree a tool event targeted (ADR 0008). Branch under the OTel VCS\n * attribute; the worktree root only as a salted `git-root` handle.\n */\nexport const ATTR_VCS_REF_HEAD_NAME = \"vcs.ref.head.name\";\nexport const ATTR_OTELHOOK_TARGET_WORKSPACE_ID = \"otelhook.target.workspace.id\";\nexport const ATTR_OTELHOOK_TARGET_SOURCE = \"otelhook.target.source\";\n\n/** Whether `gen_ai.usage.*` on this record is a delta or a running total. */\nexport const ATTR_OTELHOOK_USAGE_TEMPORALITY = \"otelhook.usage.temporality\";\n\n/** Target attributes for a tool event; empty when the core resolved none. */\nexport const targetAttributes = (event: CanonicalEvent): Attributes => {\n if ((event.type !== \"tool.start\" && event.type !== \"tool.end\") || event.target === undefined) {\n return {};\n }\n const { target } = event;\n return {\n [ATTR_OTELHOOK_TARGET_WORKSPACE_ID]: target.workspaceId,\n [ATTR_OTELHOOK_TARGET_SOURCE]: target.source,\n ...(target.vcsBranchName === undefined ? {} : { [ATTR_VCS_REF_HEAD_NAME]: target.vcsBranchName }),\n };\n};\n\n/** Temporality of reported usage, so a consumer never sums running totals. */\nexport const usageTemporalityAttributes = (usage: CanonicalUsage | undefined): Attributes =>\n usage === undefined ? {} : { [ATTR_OTELHOOK_USAGE_TEMPORALITY]: usage.temporality };\n\nconst isPrimitiveAttribute = (value: unknown): value is string | number | boolean =>\n typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\";\n\n/**\n * Resource attributes a HAR (or similar) launcher put on the process.\n *\n * Copied onto every log and span so a consumer that reads record attributes\n * rather than the resource still sees them. Only `har.*` primitives are\n * forwarded; nothing is invented when they are absent.\n */\nexport const passthroughHarAttributes = (resource: Resource): Attributes => {\n const attributes: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(resource.attributes)) {\n if (key.startsWith(\"har.\") && isPrimitiveAttribute(value)) {\n attributes[key] = value;\n }\n }\n return attributes;\n};\n\n/**\n * Session id to put on `session.id`, preferring a HAR-supplied key.\n *\n * The provider's own session id is never discarded: it is returned separately\n * so callers can emit it as `otelhook.session.id` / `gen_ai.conversation.id`.\n */\nexport const resolveExportedSessionId = (\n eventSessionId: string,\n resource: Resource,\n): { readonly sessionId: string; readonly providerSessionId: string } => {\n const har = resource.attributes[HAR_SESSION_KEY];\n if (typeof har === \"string\") {\n const trimmed = har.trim();\n if (trimmed.length > 0) {\n return { sessionId: trimmed, providerSessionId: eventSessionId };\n }\n }\n return { sessionId: eventSessionId, providerSessionId: eventSessionId };\n};\n\nexport type ExportedTraceIds = {\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n};\n\n/**\n * Hex-only trace/span attributes. A value that is not W3C hex is omitted\n * rather than stringified — binary blobs must never appear in id fields.\n */\nexport const hexTraceAttributes = (ids: ExportedTraceIds): Attributes => ({\n ...(TRACE_ID_HEX_PATTERN.test(ids.traceId) ? { [ATTR_TRACE_ID]: ids.traceId } : {}),\n ...(SPAN_ID_HEX_PATTERN.test(ids.spanId) ? { [ATTR_SPAN_ID]: ids.spanId } : {}),\n ...(ids.parentSpanId !== undefined && SPAN_ID_HEX_PATTERN.test(ids.parentSpanId)\n ? { [ATTR_PARENT_SPAN_ID]: ids.parentSpanId }\n : {}),\n});\n\n/**\n * Identity attributes shared by the log and span mappings.\n *\n * `session.id` is the HAR session key when the resource carries one, otherwise\n * the provider session id. The provider id is always also emitted under\n * `otelhook.session.id` and `gen_ai.conversation.id`.\n */\nexport const exportIdentityAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n ids: ExportedTraceIds,\n): Attributes => {\n const { sessionId, providerSessionId } = resolveExportedSessionId(event.sessionId, resource);\n return {\n [ATTR_SESSION_ID]: sessionId,\n [ATTR_OTELHOOK_SESSION_ID]: providerSessionId,\n [ATTR_GEN_AI_CONVERSATION_ID]: providerSessionId,\n [ATTR_OTELHOOK_INVOCATION_ID]: event.invocationId,\n [ATTR_OTELHOOK_PROVIDER_ID]: event.provenance.providerId,\n ...(event.provenance.providerVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event.provenance.providerVersion }),\n [ATTR_OTELHOOK_WORKSPACE_ID]: event.workspace.workspaceId,\n ...(event.subagentId === undefined ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event.subagentId }),\n ...passthroughHarAttributes(resource),\n ...hexTraceAttributes(ids),\n };\n};\n","import type { Attributes as SpanAttributes } from \"@opentelemetry/api\";\n\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport {\n MAX_ATTRIBUTE_STRING_LENGTH,\n MAX_IDENTIFIER_LENGTH,\n type Attributes,\n} from \"../model/primitives.js\";\nimport type { Clock, StateStore, StateValue } from \"../runtime/ports.js\";\nimport { withOptionalSessionLock } from \"../state/store.js\";\nimport {\n MAX_RECOVERED_START_ATTRIBUTES,\n parentScopeRefOf,\n spanScopeRefOf,\n startOnlySpanAttributes,\n type SpanCorrelation,\n type SpanFamily,\n type SpanOrphanClassification,\n type SpanScopeRef,\n} from \"../telemetry/semconv.js\";\nimport { spanKey, spanScanPrefix } from \"./keys.js\";\n\n/** Correlation scopes that pair a `*.start` event with a later `*.end` event. */\nexport type LifecycleScope = SpanFamily;\n\n/**\n * Shape version of a persisted span record.\n *\n * A record written under a different version is discarded on read rather than\n * interpreted: guessing at an older layout is exactly the kind of silent\n * mis-attribution this library refuses to do. See `docs/state-retention.md`.\n */\nexport const SPAN_RECORD_VERSION = 2;\n\n/** Facts about a span recovered from, or written to, persisted state. */\nexport type SpanCorrelationFacts = {\n readonly startedAt?: number;\n readonly endedAt?: number;\n readonly parent?: SpanScopeRef;\n readonly attributes?: SpanAttributes;\n};\n\nexport type SpanStartInput = {\n readonly sessionId: string;\n /** Attribution boundary: a scope recorded by one provider never pairs with another's. */\n readonly providerId: string;\n readonly scope: LifecycleScope;\n readonly scopeKey: string;\n /** The canonical event id of the start event; used to detect redelivery. */\n readonly eventId: string;\n readonly occurredAt: number;\n /** Where this span hangs, so an end-only process reparents it identically. */\n readonly parent?: SpanScopeRef;\n /** Attributes only the start edge knows; carried forward to the end-side span. */\n readonly attributes?: SpanAttributes;\n};\n\nexport type SpanEndInput = {\n readonly sessionId: string;\n readonly providerId: string;\n readonly scope: LifecycleScope;\n readonly scopeKey: string;\n readonly eventId: string;\n readonly occurredAt: number;\n};\n\nexport type SpanStartResult =\n | { readonly status: \"recorded\"; readonly facts: SpanCorrelationFacts }\n /** The same start (by event id) was already recorded; state is unchanged. */\n | { readonly status: \"duplicate\"; readonly facts: SpanCorrelationFacts }\n /**\n * The record was completed, but an OTLP record for this scope has already been\n * published under its span id — so this edge must not export one.\n */\n | { readonly status: \"published\"; readonly facts: SpanCorrelationFacts }\n /** A different provider owns this scope key in this session; nothing was written. */\n | { readonly status: \"conflict\"; readonly reason: \"provider-mismatch\" };\n\n/** Why an end could not be paired with a recorded start. */\nexport type SpanEndOrphanReason =\n | \"no-start-recorded\"\n | \"start-expired\"\n | \"already-closed\"\n | \"provider-mismatch\"\n | \"state-incompatible\"\n | \"state-corrupt\";\n\nexport type SpanEndResult =\n | {\n readonly status: \"matched\";\n readonly startedAt: number;\n readonly durationMillis: number;\n readonly facts: SpanCorrelationFacts;\n }\n /** This exact end (by event id) was already applied; the same facts are replayed. */\n | { readonly status: \"duplicate\"; readonly facts: SpanCorrelationFacts }\n | {\n readonly status: \"orphaned\";\n readonly reason: SpanEndOrphanReason;\n readonly facts: SpanCorrelationFacts;\n };\n\nexport type SpanCleanupResult = {\n readonly removed: number;\n readonly scanned: number;\n /**\n * Records dropped that held a start and never received an end.\n *\n * These are the spans that will never be exported at all: the end edge is what\n * emits a lifecycle span, so a scope whose end never arrives — a session the\n * host killed, a tool call that outlived the retention window — produces no\n * OTLP record. That is the standard OpenTelemetry outcome for a span that never\n * ends, and it is deliberately not papered over with a synthetic end time,\n * because a fabricated duration is a wrong measurement rather than a missing\n * one. Counting them keeps the cost visible: a non-zero number here means real\n * activity went unreported, which is a signal about the host or the retention\n * window rather than noise. See `docs/state-retention.md`.\n */\n readonly expiredOpen: number;\n};\n\n/**\n * Cross-invocation start/end correlation for session, generation, tool, and\n * subagent scopes.\n *\n * A coding-agent hook fires once per lifecycle edge, usually as a separate\n * short-lived process for the start and for the end. This records an open span\n * in the shared state store so the end side can report a real start time,\n * duration, parent, and start-only attributes even though its process has no\n * memory of the start — and so a redelivered start or end (an at-least-once\n * host retry) re-exports an identical span instead of being double-counted.\n *\n * ## What it refuses to do\n *\n * - **Pair across sessions.** The state key is session-scoped, so two sessions\n * cannot see each other's open spans.\n * - **Pair across providers.** The key is provider-scoped *and* the record\n * carries the provider that wrote it, so a mismatch is reported rather than\n * guessed at — the same defense in depth the durable spool uses.\n * - **Trust a stale start.** A start older than `maxStartAgeMillis` when its end\n * arrives is dropped and classified `start-expired`, rather than reporting a\n * duration that really measures a machine suspend or a reused id.\n * - **Interpret a record it does not understand.** A corrupt or wrong-version\n * record is deleted and classified, never partially read.\n */\nexport interface SpanCorrelator {\n recordStart(input: SpanStartInput): Promise<SpanStartResult>;\n recordEnd(input: SpanEndInput): Promise<SpanEndResult>;\n /**\n * Records every lifecycle edge in a batch and reports what the exported spans\n * should say. Never rejects: a state failure degrades one scope to\n * `state-unavailable` rather than losing the batch (fail-open telemetry).\n */\n correlateBatch(events: readonly CanonicalEvent[]): Promise<readonly SpanCorrelation[]>;\n /** Bounded sweep: drops spans untouched for longer than `maxAgeMillis`. */\n cleanup(\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<SpanCleanupResult>;\n}\n\nexport type SpanCorrelatorDependencies = {\n readonly stateStore: StateStore;\n readonly clock: Clock;\n /**\n * A recorded start older than this when its end arrives is not trusted.\n * Default 24 hours, matching the janitor's retention window.\n */\n readonly maxStartAgeMillis?: number;\n};\n\nconst DEFAULT_MAX_START_AGE_MILLIS = 24 * 60 * 60 * 1000;\nconst ATTRIBUTE_PREFIX = \"a:\";\n\ntype SpanRecord = {\n readonly providerId: string;\n readonly startEventId?: string;\n readonly startedAt?: number;\n readonly endEventId?: string;\n readonly endedAt?: number;\n readonly parent?: SpanScopeRef;\n readonly attributes?: SpanAttributes;\n /**\n * True once an OTLP record has been produced for this scope under its derived\n * span id.\n *\n * Needed for the ordering nobody controls: the end edge can be mapped before\n * the start edge, and then the end has already exported an orphan carrying the\n * scope's canonical span id. Without this flag the late start would look like\n * the benign \"end raced ahead\" case and export a *second* record with that same\n * id — the duplicate the whole defer strategy exists to avoid. So the flag turns\n * \"was this scope already published?\" into a fact on disk rather than an\n * assumption about arrival order.\n */\n readonly exported?: boolean;\n};\n\ntype DecodedRecord =\n | { readonly kind: \"absent\" }\n | { readonly kind: \"incompatible\" }\n | { readonly kind: \"corrupt\" }\n | { readonly kind: \"present\"; readonly record: SpanRecord };\n\nconst SPAN_FAMILIES: readonly SpanFamily[] = [\"session\", \"generation\", \"tool\", \"subagent\"];\n\nconst isSpanFamily = (value: unknown): value is SpanFamily =>\n typeof value === \"string\" && (SPAN_FAMILIES as readonly string[]).includes(value);\n\nconst optionalNumber = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n\nconst optionalString = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 ? value : undefined;\n\n/**\n * Persisted attributes are flattened under a prefix rather than nested: the\n * state schema admits only flat primitives, which is what keeps a provider\n * payload from ever being smuggled through the state store.\n */\nconst encodeAttributes = (attributes: SpanAttributes | undefined): Attributes => {\n const encoded: Record<string, string | number | boolean> = {};\n let count = 0;\n for (const [key, value] of Object.entries(attributes ?? {})) {\n if (count >= MAX_RECOVERED_START_ATTRIBUTES) {\n break;\n }\n const encodedKey = `${ATTRIBUTE_PREFIX}${key}`;\n if (encodedKey.length > MAX_IDENTIFIER_LENGTH) {\n continue;\n }\n if (typeof value === \"string\") {\n encoded[encodedKey] = value.slice(0, MAX_ATTRIBUTE_STRING_LENGTH);\n } else if (typeof value === \"number\" && Number.isFinite(value)) {\n encoded[encodedKey] = value;\n } else if (typeof value === \"boolean\") {\n encoded[encodedKey] = value;\n } else {\n continue;\n }\n count += 1;\n }\n return encoded;\n};\n\nconst decodeAttributes = (attributes: Attributes): SpanAttributes | undefined => {\n const decoded: Record<string, string | number | boolean> = {};\n let count = 0;\n for (const [key, value] of Object.entries(attributes)) {\n if (!key.startsWith(ATTRIBUTE_PREFIX) || count >= MAX_RECOVERED_START_ATTRIBUTES) {\n continue;\n }\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n decoded[key.slice(ATTRIBUTE_PREFIX.length)] = value;\n count += 1;\n }\n }\n return count === 0 ? undefined : decoded;\n};\n\nconst encodeRecord = (record: SpanRecord): StateValue => ({\n kind: \"attributes\",\n attributes: {\n v: SPAN_RECORD_VERSION,\n providerId: record.providerId,\n ...(record.startEventId === undefined ? {} : { startEventId: record.startEventId }),\n ...(record.startedAt === undefined ? {} : { startedAt: record.startedAt }),\n ...(record.endEventId === undefined ? {} : { endEventId: record.endEventId }),\n ...(record.endedAt === undefined ? {} : { endedAt: record.endedAt }),\n ...(record.exported === true ? { exported: true } : {}),\n ...(record.parent === undefined\n ? {}\n : { parentFamily: record.parent.family, parentScopeKey: record.parent.scopeKey }),\n ...encodeAttributes(record.attributes),\n },\n});\n\nconst decodeRecord = (attributes: Attributes): DecodedRecord => {\n if (attributes[\"v\"] !== SPAN_RECORD_VERSION) {\n return { kind: \"incompatible\" };\n }\n const providerId = optionalString(attributes[\"providerId\"]);\n if (providerId === undefined) {\n return { kind: \"corrupt\" };\n }\n // A half-written edge (a timestamp with no event id, or the reverse) is not\n // an edge we can reason about; the record is refused rather than completed\n // with an invented half.\n const startedAt = optionalNumber(attributes[\"startedAt\"]);\n const startEventId = optionalString(attributes[\"startEventId\"]);\n if ((startedAt === undefined) !== (startEventId === undefined)) {\n return { kind: \"corrupt\" };\n }\n const endedAt = optionalNumber(attributes[\"endedAt\"]);\n const endEventId = optionalString(attributes[\"endEventId\"]);\n if ((endedAt === undefined) !== (endEventId === undefined)) {\n return { kind: \"corrupt\" };\n }\n const exported = attributes[\"exported\"] === true;\n const parentFamily = attributes[\"parentFamily\"];\n const parentScopeKey = optionalString(attributes[\"parentScopeKey\"]);\n const parent =\n isSpanFamily(parentFamily) && parentScopeKey !== undefined\n ? { family: parentFamily, scopeKey: parentScopeKey }\n : undefined;\n const decodedAttributes = decodeAttributes(attributes);\n return {\n kind: \"present\",\n record: {\n providerId,\n ...(startEventId === undefined ? {} : { startEventId }),\n ...(startedAt === undefined ? {} : { startedAt }),\n ...(endEventId === undefined ? {} : { endEventId }),\n ...(endedAt === undefined ? {} : { endedAt }),\n ...(parent === undefined ? {} : { parent }),\n ...(exported ? { exported: true } : {}),\n ...(decodedAttributes === undefined ? {} : { attributes: decodedAttributes }),\n },\n };\n};\n\nconst factsOf = (record: SpanRecord): SpanCorrelationFacts => ({\n ...(record.startedAt === undefined ? {} : { startedAt: record.startedAt }),\n ...(record.endedAt === undefined ? {} : { endedAt: record.endedAt }),\n ...(record.parent === undefined ? {} : { parent: record.parent }),\n ...(record.attributes === undefined ? {} : { attributes: record.attributes }),\n});\n\n/**\n * Persisted facts speak in event time (`startedAt`); a span speaks in the\n * milliseconds it is stamped with. Translated in one place so the two\n * vocabularies cannot silently drift apart.\n */\nconst correlationTimesOf = (\n facts: SpanCorrelationFacts,\n options: { readonly withStart: boolean } = { withStart: true },\n): Pick<SpanCorrelation, \"startMillis\" | \"endMillis\" | \"parent\" | \"attributes\"> => ({\n ...(facts.startedAt === undefined || !options.withStart ? {} : { startMillis: facts.startedAt }),\n ...(facts.endedAt === undefined ? {} : { endMillis: facts.endedAt }),\n ...(facts.parent === undefined ? {} : { parent: facts.parent }),\n ...(facts.attributes === undefined ? {} : { attributes: facts.attributes }),\n});\n\nconst orphanClassificationOf = (reason: SpanEndOrphanReason): SpanOrphanClassification => {\n switch (reason) {\n case \"no-start-recorded\":\n return \"missing-start\";\n case \"start-expired\":\n return \"expired-start\";\n case \"already-closed\":\n return \"already-closed\";\n case \"provider-mismatch\":\n return \"provider-mismatch\";\n case \"state-incompatible\":\n return \"state-incompatible\";\n case \"state-corrupt\":\n return \"state-corrupt\";\n }\n};\n\ntype BatchGroup = {\n readonly providerId: string;\n readonly sessionId: string;\n readonly ref: SpanScopeRef;\n start?: CanonicalEvent;\n end?: CanonicalEvent;\n};\n\nexport const createSpanCorrelator = (deps: SpanCorrelatorDependencies): SpanCorrelator => {\n const { stateStore, clock } = deps;\n const maxStartAgeMillis = deps.maxStartAgeMillis ?? DEFAULT_MAX_START_AGE_MILLIS;\n\n const keyFor = (input: {\n readonly sessionId: string;\n readonly providerId: string;\n readonly scope: LifecycleScope;\n readonly scopeKey: string;\n }): string => spanKey(input.sessionId, input.providerId, input.scope, input.scopeKey);\n\n /**\n * Reads and validates one record, deleting anything it refuses to interpret.\n * Self-healing on purpose: a single unreadable record must not make the same\n * scope unreadable forever.\n */\n const readRecord = async (key: string): Promise<DecodedRecord> => {\n const existing = await stateStore.read(key);\n if (existing === undefined) {\n return { kind: \"absent\" };\n }\n if (existing.value.kind !== \"attributes\") {\n await stateStore.delete(key);\n return { kind: \"corrupt\" };\n }\n const decoded = decodeRecord(existing.value.attributes);\n if (decoded.kind === \"corrupt\" || decoded.kind === \"incompatible\") {\n await stateStore.delete(key);\n }\n return decoded;\n };\n\n const recordStart = (input: SpanStartInput): Promise<SpanStartResult> =>\n withOptionalSessionLock(stateStore, input.sessionId, async (): Promise<SpanStartResult> => {\n const key = keyFor(input);\n const decoded = await readRecord(key);\n\n if (decoded.kind === \"present\") {\n const existing = decoded.record;\n if (existing.providerId !== input.providerId) {\n return { status: \"conflict\", reason: \"provider-mismatch\" };\n }\n if (existing.startEventId === input.eventId) {\n return { status: \"duplicate\", facts: factsOf(existing) };\n }\n if (existing.startEventId === undefined && existing.endEventId !== undefined) {\n // The end raced ahead of the start (two hook processes, no ordering\n // guarantee between them). Complete the record rather than treating\n // the late start as the beginning of a second span.\n //\n // If that end was already exported, the scope's canonical span id is\n // already on the wire and this start must stay silent: re-exporting a\n // now-complete span under the same id would be a duplicate, not a\n // correction, because OTLP has no update. The enrichment is lost and the\n // published record remains the orphan the end could honestly produce.\n const completed: SpanRecord = {\n ...existing,\n startEventId: input.eventId,\n startedAt: input.occurredAt,\n ...(input.parent === undefined ? {} : { parent: input.parent }),\n ...(input.attributes === undefined ? {} : { attributes: input.attributes }),\n };\n await stateStore.write(key, encodeRecord(completed));\n return existing.exported === true\n ? { status: \"published\", facts: factsOf(completed) }\n : { status: \"recorded\", facts: factsOf(completed) };\n }\n }\n\n // Either nothing was recorded, or a *different* start claims this scope\n // key: the previous span is superseded rather than merged into.\n const fresh: SpanRecord = {\n providerId: input.providerId,\n startEventId: input.eventId,\n startedAt: input.occurredAt,\n ...(input.parent === undefined ? {} : { parent: input.parent }),\n ...(input.attributes === undefined ? {} : { attributes: input.attributes }),\n };\n await stateStore.write(key, encodeRecord(fresh));\n return { status: \"recorded\", facts: factsOf(fresh) };\n });\n\n const recordEnd = (input: SpanEndInput): Promise<SpanEndResult> =>\n withOptionalSessionLock(stateStore, input.sessionId, async (): Promise<SpanEndResult> => {\n const key = keyFor(input);\n const decoded = await readRecord(key);\n\n if (decoded.kind === \"incompatible\" || decoded.kind === \"corrupt\") {\n const reason = decoded.kind === \"incompatible\" ? \"state-incompatible\" : \"state-corrupt\";\n return { status: \"orphaned\", reason, facts: { endedAt: input.occurredAt } };\n }\n if (decoded.kind === \"absent\") {\n // Remember the end anyway: a start that arrives late still deserves to\n // be paired rather than exported as a second orphan.\n const endOnly: SpanRecord = {\n providerId: input.providerId,\n endEventId: input.eventId,\n endedAt: input.occurredAt,\n // This end is about to be exported as an orphan under the scope's\n // canonical span id, so a start arriving later must not reuse it.\n exported: true,\n };\n await stateStore.write(key, encodeRecord(endOnly));\n return { status: \"orphaned\", reason: \"no-start-recorded\", facts: factsOf(endOnly) };\n }\n\n const existing = decoded.record;\n if (existing.providerId !== input.providerId) {\n return {\n status: \"orphaned\",\n reason: \"provider-mismatch\",\n facts: { endedAt: input.occurredAt },\n };\n }\n if (existing.endEventId === input.eventId) {\n // Idempotent replay: answer with the facts already on disk so the\n // re-exported span is byte-identical to the first one.\n return { status: \"duplicate\", facts: factsOf(existing) };\n }\n if (existing.endEventId !== undefined) {\n return {\n status: \"orphaned\",\n reason: \"already-closed\",\n facts: { endedAt: input.occurredAt },\n };\n }\n if (existing.startedAt === undefined) {\n const replaced: SpanRecord = {\n ...existing,\n endEventId: input.eventId,\n endedAt: input.occurredAt,\n exported: true,\n };\n await stateStore.write(key, encodeRecord(replaced));\n return { status: \"orphaned\", reason: \"no-start-recorded\", facts: factsOf(replaced) };\n }\n if (input.occurredAt - existing.startedAt > maxStartAgeMillis) {\n await stateStore.delete(key);\n return { status: \"orphaned\", reason: \"start-expired\", facts: { endedAt: input.occurredAt } };\n }\n\n const closed: SpanRecord = {\n ...existing,\n endEventId: input.eventId,\n endedAt: input.occurredAt,\n exported: true,\n };\n await stateStore.write(key, encodeRecord(closed));\n return {\n status: \"matched\",\n startedAt: existing.startedAt,\n durationMillis: Math.max(0, input.occurredAt - existing.startedAt),\n facts: factsOf(closed),\n };\n });\n\n const correlateGroup = async (group: BatchGroup): Promise<SpanCorrelation> => {\n const base = {\n providerId: group.providerId,\n sessionId: group.sessionId,\n ref: group.ref,\n } as const;\n const unpaired = (\n orphan: SpanOrphanClassification,\n facts: SpanCorrelationFacts,\n ): SpanCorrelation => ({\n ...base,\n pairing: \"unpaired\",\n orphan,\n // An unpaired span has no trustworthy start, so a start time is the one\n // fact it must not carry; everything else recovered is still true.\n ...correlationTimesOf(facts, { withStart: false }),\n });\n\n let startFacts: SpanCorrelationFacts | undefined;\n if (group.start !== undefined) {\n const parent = parentScopeRefOf(group.start);\n const result = await recordStart({\n sessionId: group.sessionId,\n providerId: group.providerId,\n scope: group.ref.family,\n scopeKey: group.ref.scopeKey,\n eventId: group.start.eventId,\n occurredAt: group.start.occurredAt,\n ...(parent === undefined ? {} : { parent }),\n attributes: startOnlySpanAttributes(group.start),\n });\n if (result.status === \"conflict\") {\n return unpaired(\"provider-mismatch\", {});\n }\n if (result.status === \"published\" && group.end === undefined) {\n // The end already exported this scope's span. Completing the record was\n // still worth doing (a redelivered end replays identical facts), but\n // emitting here would duplicate a span id already on the wire.\n return { ...unpaired(\"already-closed\", result.facts), disposition: \"defer\" };\n }\n startFacts = result.facts;\n }\n\n if (group.end === undefined) {\n const facts = startFacts ?? {};\n // A start whose end already landed (the racing-process case) closes a\n // complete span, even though only the start is in this batch.\n if (facts.endedAt !== undefined) {\n return {\n ...base,\n pairing: \"cross-process\",\n orphan: \"none\",\n disposition: \"emit\",\n ...correlationTimesOf(facts),\n };\n }\n // The end has not arrived. The start is durable now, so the end edge will\n // export one complete span under this scope's derived id; exporting a\n // zero-duration record here as well would put two records with that same id\n // on the wire, and OTLP cannot revise a span.\n return { ...unpaired(\"missing-end\", facts), disposition: \"defer\" };\n }\n\n const result = await recordEnd({\n sessionId: group.sessionId,\n providerId: group.providerId,\n scope: group.ref.family,\n scopeKey: group.ref.scopeKey,\n eventId: group.end.eventId,\n occurredAt: group.end.occurredAt,\n });\n\n if (result.status === \"orphaned\") {\n const orphan = orphanClassificationOf(result.reason);\n // `already-closed` means a *second, distinct* end for a scope whose first\n // end has already been exported under this scope's derived span id. Both\n // ends are real observations, so neither is dropped — but the second must\n // not reuse that id. Keying the discriminator on the end event id keeps a\n // redelivery of this same second end idempotent, since it recomputes the\n // same id rather than inventing a third.\n return orphan === \"already-closed\"\n ? {\n ...unpaired(orphan, result.facts),\n disposition: \"emit\",\n spanIdDiscriminator: group.end.eventId,\n }\n : { ...unpaired(orphan, result.facts), disposition: \"emit\" };\n }\n if (result.status === \"duplicate\" && result.facts.startedAt === undefined) {\n // A replayed end that never had a start is still an orphan.\n return { ...unpaired(\"missing-start\", result.facts), disposition: \"emit\" };\n }\n return {\n ...base,\n pairing: group.start === undefined ? \"cross-process\" : \"in-batch\",\n orphan: \"none\",\n disposition: \"emit\",\n ...correlationTimesOf(result.facts),\n };\n };\n\n const correlateBatch = async (\n events: readonly CanonicalEvent[],\n ): Promise<readonly SpanCorrelation[]> => {\n const groups = new Map<string, BatchGroup>();\n for (const event of events) {\n const ref = spanScopeRefOf(event);\n if (ref === undefined) {\n continue;\n }\n const providerId = event.provenance.providerId;\n const groupKey = [providerId, event.sessionId, ref.family, ref.scopeKey].join(\"\\u0000\");\n const group: BatchGroup = groups.get(groupKey) ?? {\n providerId,\n sessionId: event.sessionId,\n ref,\n };\n if (event.type.endsWith(\".start\")) {\n group.start = event;\n } else {\n group.end = event;\n }\n groups.set(groupKey, group);\n }\n\n const correlations: SpanCorrelation[] = [];\n for (const group of groups.values()) {\n try {\n correlations.push(await correlateGroup(group));\n } catch {\n // Fail open: an unreachable, locked, or unwritable state store costs a\n // span its pairing, never the whole export.\n //\n // A start whose record could not be written is the case that needs care.\n // It is *not* deferrable — deferring means \"the state store is holding\n // this, the end edge will publish it\", and here the state store is exactly\n // what failed. So it must be exported, and it must not use the scope's\n // canonical span id: nothing recorded this start, so a later end will\n // publish that id itself as an orphan, and reusing it would put two\n // records with one identity on the wire. Discriminating by the start's own\n // event id makes this record honest and collision-free.\n const unrecordedStart = group.start !== undefined && group.end === undefined;\n correlations.push({\n providerId: group.providerId,\n sessionId: group.sessionId,\n ref: group.ref,\n pairing: \"unpaired\",\n orphan: \"state-unavailable\",\n disposition: \"emit\",\n ...(unrecordedStart && group.start !== undefined\n ? { spanIdDiscriminator: group.start.eventId }\n : {}),\n });\n }\n }\n return correlations;\n };\n\n const cleanup = async (\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<SpanCleanupResult> => {\n const keys = await stateStore.keys(spanScanPrefix(options?.sessionId));\n const cap = options?.maxEntries ?? 1_000;\n const now = clock.now();\n let removed = 0;\n let scanned = 0;\n let expiredOpen = 0;\n for (const key of keys) {\n if (scanned >= cap) {\n break;\n }\n scanned += 1;\n const record = await stateStore.read(key);\n if (record !== undefined && now - record.updatedAt > maxAgeMillis) {\n // Classified before deletion: a record with a start and no end is a span\n // that will never be exported, which is worth counting rather than\n // discarding silently.\n if (record.value.kind === \"attributes\") {\n const decoded = decodeRecord(record.value.attributes);\n if (\n decoded.kind === \"present\" &&\n decoded.record.startedAt !== undefined &&\n decoded.record.endedAt === undefined\n ) {\n expiredOpen += 1;\n }\n }\n await stateStore.delete(key);\n removed += 1;\n }\n }\n return { removed, scanned, expiredOpen };\n };\n\n return { recordStart, recordEnd, correlateBatch, cleanup };\n};\n","import { z } from \"zod\";\n\nimport { tokenCountSchema } from \"./primitives.js\";\n\n/**\n * Whether an observation reports the change since the previous observation\n * (`delta`) or the running total for the session/generation (`cumulative`).\n *\n * The canonical model keeps temporality explicit rather than assuming one:\n * summing cumulative observations double-counts, and diffing delta observations\n * silently loses tokens.\n */\nexport const usageTemporalitySchema = z.enum([\"delta\", \"cumulative\"]);\nexport type UsageTemporality = z.infer<typeof usageTemporalitySchema>;\n\n/**\n * Whether the provider counts cache-creation tokens inside its input total or\n * reports them as a disjoint bucket.\n *\n * - `included-in-input`: `cacheCreationInputTokens` is a subset of `inputTokens`.\n * - `disjoint-from-input`: cache-creation tokens are billed in addition to\n * `inputTokens` and must be added when computing a total.\n * - `not-reported`: the provider exposes no cache-creation counter; the field is\n * pinned to zero.\n */\nexport const cacheCreationAccountingSchema = z.enum([\n \"included-in-input\",\n \"disjoint-from-input\",\n \"not-reported\",\n]);\nexport type CacheCreationAccounting = z.infer<typeof cacheCreationAccountingSchema>;\n\n/** Whether a provider-reported total agrees with the canonical computation. */\nexport const providerTotalAgreementSchema = z.enum([\"unreported\", \"agrees\", \"disagrees\"]);\nexport type ProviderTotalAgreement = z.infer<typeof providerTotalAgreementSchema>;\n\n/**\n * What an adapter reports, before normalization.\n *\n * `inputTokens` is *inclusive*: it counts every input token the provider\n * attributes to the call, including cache reads (and cache creation when the\n * provider folds it in). `outputTokens` is likewise inclusive of reasoning\n * output. Subset fields describe portions of those totals, never additions.\n */\nexport const usageReportSchema = z.strictObject({\n temporality: usageTemporalitySchema,\n /** Inclusive input tokens. */\n inputTokens: tokenCountSchema.optional(),\n /** Subset of `inputTokens` served from a prompt cache. */\n cachedInputTokens: tokenCountSchema.optional(),\n /** Tokens written to a prompt cache. */\n cacheCreationInputTokens: tokenCountSchema.optional(),\n /** Required when `cacheCreationInputTokens` is present and non-zero. */\n cacheCreationAccounting: cacheCreationAccountingSchema.optional(),\n /** Inclusive output tokens. */\n outputTokens: tokenCountSchema.optional(),\n /** Subset of `outputTokens` spent on reasoning. */\n reasoningOutputTokens: tokenCountSchema.optional(),\n /** Total exactly as the provider reported it, if it reported one. */\n providerTotalTokens: tokenCountSchema.optional(),\n});\nexport type UsageReport = z.infer<typeof usageReportSchema>;\n\n/**\n * Fully normalized usage.\n *\n * Derived fields (`uncachedInputTokens`, `totalTokens`,\n * `providerTotalAgreement`) are part of the schema and are re-checked on parse,\n * so an inconsistent object cannot exist. Construct values with\n * {@link normalizeUsage} rather than by hand.\n */\nexport const canonicalUsageSchema = z\n .strictObject({\n temporality: usageTemporalitySchema,\n inputTokens: tokenCountSchema,\n cachedInputTokens: tokenCountSchema,\n cacheCreationInputTokens: tokenCountSchema,\n cacheCreationAccounting: cacheCreationAccountingSchema,\n outputTokens: tokenCountSchema,\n reasoningOutputTokens: tokenCountSchema,\n /** Derived: input tokens that were neither cache reads nor cache writes. */\n uncachedInputTokens: tokenCountSchema,\n /** Derived: canonical billable total. */\n totalTokens: tokenCountSchema,\n providerTotalTokens: tokenCountSchema.optional(),\n providerTotalAgreement: providerTotalAgreementSchema,\n })\n .check((ctx) => {\n const usage = ctx.value;\n const push = (message: string): void => {\n ctx.issues.push({ code: \"custom\", input: usage, message });\n };\n\n if (usage.cachedInputTokens > usage.inputTokens) {\n push(\"cachedInputTokens must not exceed inputTokens (it is a subset)\");\n }\n if (usage.reasoningOutputTokens > usage.outputTokens) {\n push(\"reasoningOutputTokens must not exceed outputTokens (it is a subset)\");\n }\n if (usage.cacheCreationAccounting === \"not-reported\" && usage.cacheCreationInputTokens !== 0) {\n push(\"cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported\");\n }\n const creationInsideInput =\n usage.cacheCreationAccounting === \"included-in-input\" ? usage.cacheCreationInputTokens : 0;\n if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {\n push(\n \"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input\",\n );\n }\n const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;\n if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {\n push(`uncachedInputTokens must equal ${expectedUncached}`);\n }\n const creationOutsideInput =\n usage.cacheCreationAccounting === \"disjoint-from-input\" ? usage.cacheCreationInputTokens : 0;\n const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;\n if (usage.totalTokens !== expectedTotal) {\n push(`totalTokens must equal ${expectedTotal}`);\n }\n const expectedAgreement: ProviderTotalAgreement =\n usage.providerTotalTokens === undefined\n ? \"unreported\"\n : usage.providerTotalTokens === expectedTotal\n ? \"agrees\"\n : \"disagrees\";\n if (usage.providerTotalAgreement !== expectedAgreement) {\n push(`providerTotalAgreement must be ${expectedAgreement}`);\n }\n });\nexport type CanonicalUsage = z.infer<typeof canonicalUsageSchema>;\n\nexport type UsageNormalizationIssue = {\n readonly code:\n | \"invalid-report\"\n | \"cached-exceeds-input\"\n | \"reasoning-exceeds-output\"\n | \"cache-creation-exceeds-input\"\n | \"cache-creation-accounting-missing\";\n readonly message: string;\n};\n\nexport type UsageNormalizationResult =\n | { readonly status: \"ok\"; readonly usage: CanonicalUsage; readonly notes: readonly string[] }\n | { readonly status: \"invalid\"; readonly issues: readonly UsageNormalizationIssue[] };\n\n/**\n * Normalize a provider usage report into canonical usage.\n *\n * Deterministic rules:\n * 1. Absent counters default to `0`; `providerTotalTokens` stays absent.\n * 2. Non-integer, negative, or non-finite counters are rejected.\n * 3. A subset exceeding its total is rejected — never clamped — because\n * clamping would silently invent a billing story.\n * 4. `cacheCreationAccounting` defaults to `not-reported` when no cache-creation\n * tokens are reported, and is *required* when they are: guessing whether the\n * bucket is disjoint would mis-total every downstream cost calculation.\n * 5. A provider total that disagrees with the canonical total is preserved as\n * reported and flagged `disagrees`. Both numbers survive; neither is edited.\n */\nexport const normalizeUsage = (report: unknown): UsageNormalizationResult => {\n const parsed = usageReportSchema.safeParse(report);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map((issue) => ({\n code: \"invalid-report\" as const,\n message: `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n })),\n };\n }\n\n const input = parsed.data;\n const issues: UsageNormalizationIssue[] = [];\n const notes: string[] = [];\n\n const inputTokens = input.inputTokens ?? 0;\n const cachedInputTokens = input.cachedInputTokens ?? 0;\n const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;\n const outputTokens = input.outputTokens ?? 0;\n const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;\n\n let accounting: CacheCreationAccounting;\n if (cacheCreationInputTokens === 0) {\n accounting = input.cacheCreationAccounting ?? \"not-reported\";\n if (accounting !== \"not-reported\") {\n notes.push(\n `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`,\n );\n }\n } else if (input.cacheCreationAccounting === undefined) {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message:\n \"cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred\",\n });\n accounting = \"not-reported\";\n } else if (input.cacheCreationAccounting === \"not-reported\") {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message: \"cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens\",\n });\n accounting = \"not-reported\";\n } else {\n accounting = input.cacheCreationAccounting;\n }\n\n if (cachedInputTokens > inputTokens) {\n issues.push({\n code: \"cached-exceeds-input\",\n message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n if (reasoningOutputTokens > outputTokens) {\n issues.push({\n code: \"reasoning-exceeds-output\",\n message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`,\n });\n }\n\n const creationInsideInput = accounting === \"included-in-input\" ? cacheCreationInputTokens : 0;\n if (cachedInputTokens + creationInsideInput > inputTokens) {\n issues.push({\n code: \"cache-creation-exceeds-input\",\n message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const creationOutsideInput = accounting === \"disjoint-from-input\" ? cacheCreationInputTokens : 0;\n const totalTokens = inputTokens + creationOutsideInput + outputTokens;\n const providerTotalAgreement: ProviderTotalAgreement =\n input.providerTotalTokens === undefined\n ? \"unreported\"\n : input.providerTotalTokens === totalTokens\n ? \"agrees\"\n : \"disagrees\";\n\n if (providerTotalAgreement === \"disagrees\") {\n notes.push(\n `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`,\n );\n }\n\n const usage: CanonicalUsage = {\n temporality: input.temporality,\n inputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens,\n reasoningOutputTokens,\n uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,\n totalTokens,\n ...(input.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: input.providerTotalTokens }),\n providerTotalAgreement,\n };\n\n return { status: \"ok\", usage, notes };\n};\n\nexport class UsageNormalizationError extends Error {\n public readonly issues: readonly UsageNormalizationIssue[];\n\n public constructor(issues: readonly UsageNormalizationIssue[]) {\n super(`invalid usage report: ${issues.map((issue) => issue.message).join(\"; \")}`);\n this.name = \"UsageNormalizationError\";\n this.issues = issues;\n }\n}\n\n/** Convenience wrapper for call sites that treat invalid usage as a bug. */\nexport const normalizeUsageOrThrow = (report: unknown): CanonicalUsage => {\n const result = normalizeUsage(report);\n if (result.status === \"invalid\") {\n throw new UsageNormalizationError(result.issues);\n }\n return result.usage;\n};\n\nexport const EMPTY_DELTA_USAGE: CanonicalUsage = Object.freeze(\n normalizeUsageOrThrow({ temporality: \"delta\" }),\n);\n\nexport type UsageDeltaResult = {\n readonly usage: CanonicalUsage;\n /**\n * True when the current snapshot is smaller than the previous one on any\n * counter. That means the cumulative series restarted (new session, replayed\n * transcript, provider reset), so the current snapshot is emitted as the delta\n * instead of a negative difference.\n */\n readonly resetDetected: boolean;\n};\n\nconst requireCumulative = (usage: CanonicalUsage, label: string): void => {\n if (usage.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: `${label} must have cumulative temporality` },\n ]);\n }\n};\n\n/**\n * Convert two cumulative snapshots into a delta observation.\n *\n * Replay safety: re-processing the same snapshot yields an all-zero delta, and a\n * decreasing series is reported as a reset rather than a negative delta.\n * Accounting mode must match; mixing modes would make the subtraction meaningless.\n */\nexport const cumulativeToDelta = (\n previous: CanonicalUsage,\n current: CanonicalUsage,\n): UsageDeltaResult => {\n requireCumulative(previous, \"previous usage\");\n requireCumulative(current, \"current usage\");\n\n if (\n previous.cacheCreationAccounting !== current.cacheCreationAccounting &&\n previous.cacheCreationInputTokens !== 0 &&\n current.cacheCreationInputTokens !== 0\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot diff cumulative usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const resetDetected =\n current.inputTokens < previous.inputTokens ||\n current.cachedInputTokens < previous.cachedInputTokens ||\n current.cacheCreationInputTokens < previous.cacheCreationInputTokens ||\n current.outputTokens < previous.outputTokens ||\n current.reasoningOutputTokens < previous.reasoningOutputTokens;\n\n if (resetDetected) {\n return {\n usage: normalizeUsageOrThrow({ ...toReport(current), temporality: \"delta\" }),\n resetDetected: true,\n };\n }\n\n const usage = normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: current.inputTokens - previous.inputTokens,\n cachedInputTokens: current.cachedInputTokens - previous.cachedInputTokens,\n cacheCreationInputTokens:\n current.cacheCreationInputTokens - previous.cacheCreationInputTokens,\n cacheCreationAccounting: current.cacheCreationAccounting,\n outputTokens: current.outputTokens - previous.outputTokens,\n reasoningOutputTokens: current.reasoningOutputTokens - previous.reasoningOutputTokens,\n });\n\n return { usage, resetDetected: false };\n};\n\n/** Project canonical usage back onto the reported shape. */\nexport const toReport = (usage: CanonicalUsage): UsageReport => ({\n temporality: usage.temporality,\n inputTokens: usage.inputTokens,\n cachedInputTokens: usage.cachedInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n cacheCreationAccounting: usage.cacheCreationAccounting,\n outputTokens: usage.outputTokens,\n reasoningOutputTokens: usage.reasoningOutputTokens,\n ...(usage.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: usage.providerTotalTokens }),\n});\n\n/**\n * Add two delta observations. Cumulative usage is never summed, because two\n * running totals do not compose.\n */\nexport const addUsage = (a: CanonicalUsage, b: CanonicalUsage): CanonicalUsage => {\n if (a.temporality !== \"delta\" || b.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"only delta usage may be summed\" },\n ]);\n }\n const accounting =\n a.cacheCreationInputTokens === 0 && a.cacheCreationAccounting === \"not-reported\"\n ? b.cacheCreationAccounting\n : b.cacheCreationInputTokens === 0 && b.cacheCreationAccounting === \"not-reported\"\n ? a.cacheCreationAccounting\n : a.cacheCreationAccounting;\n\n if (\n a.cacheCreationInputTokens !== 0 &&\n b.cacheCreationInputTokens !== 0 &&\n a.cacheCreationAccounting !== b.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot sum usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n a.providerTotalTokens === undefined && b.providerTotalTokens === undefined\n ? undefined\n : (a.providerTotalTokens ?? 0) + (b.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: a.inputTokens + b.inputTokens,\n cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,\n cacheCreationInputTokens: a.cacheCreationInputTokens + b.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: a.outputTokens + b.outputTokens,\n reasoningOutputTokens: a.reasoningOutputTokens + b.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n","import {\n UsageNormalizationError,\n normalizeUsageOrThrow,\n type CanonicalUsage,\n} from \"../model/usage.js\";\nimport type { Attributes } from \"../model/primitives.js\";\nimport type { Clock, StateStore } from \"../runtime/ports.js\";\nimport { withOptionalSessionLock } from \"../state/store.js\";\nimport { rollupEpochKey, rollupEpochScanPrefix, rollupScanPrefix, rollupUsageKey } from \"./keys.js\";\n\nexport type UsageAccumulatorKey = {\n readonly sessionId: string;\n readonly scope: string;\n readonly scopeKey: string;\n};\n\nexport type UsageAccumulatorSnapshot = {\n readonly total: CanonicalUsage;\n /** Increments every time {@link UsageAccumulator.recordReset} is called for this key. */\n readonly epoch: number;\n};\n\nexport type RollupCleanupResult = { readonly removed: number; readonly scanned: number };\n\n/**\n * Which delivery an accumulation belongs to, and which of its observations this is.\n *\n * Supplying it makes the accumulation idempotent for *that delivery*: a second\n * application of the same `(callbackId, ordinal)` is a no-op that returns the\n * current total. Omitting it keeps the old unconditional behaviour, which is right\n * for a caller that has no delivery identity to key on — there is nothing to\n * recognize a repeat by, and refusing to accumulate would lose a real observation.\n *\n * `callbackId` must be an opaque digest, not a raw host or provider id: it is\n * written into a state record.\n */\nexport type DeliveryStamp = {\n readonly callbackId: string;\n /** Zero-based index of this observation within the delivery, per rollup key. */\n readonly ordinal: number;\n};\n\nexport type AccumulateOptions = { readonly delivery?: DeliveryStamp };\n\n/**\n * Rolls a stream of `delta` usage observations up into a running `cumulative`\n * total per scope, independent of the orchestrator's own per-scope\n * cumulative-to-delta baseline (`docs/usage-semantics.md`) — that baseline\n * answers \"what changed since last time\"; this answers \"what is the running\n * total\", which a diagnostics view or a parent scope (tool -> generation ->\n * session) needs and the core does not compute.\n *\n * A provider counter can restart mid-session (a process restart, a replayed\n * transcript). Rather than let a smaller cumulative total silently deflate the\n * running rollup, {@link UsageAccumulator.recordReset} starts a new epoch: the\n * total resets to zero and the epoch number increments, so a downstream\n * consumer can tell \"the counter restarted\" from \"usage actually decreased\"\n * and never sums across the boundary as if it were one continuous series.\n */\nexport interface UsageAccumulator {\n /**\n * Fold `delta` into the running total for `key`.\n *\n * With `options.delivery`, folding is idempotent for that delivery: a redelivered\n * callback whose claim was reclaimed or superseded re-derives the same delta and\n * would otherwise count it twice. The marker lives in the same record as the total\n * it describes, so the check and the write are one atomic operation — which is the\n * only reason this is expressible without a multi-key transaction. What it does\n * *not* cover is a delivery whose marker a later, different delivery has since\n * overwritten: only the most recent delivery per rollup key is recognizable, which\n * is exactly the retry window and nothing beyond it.\n */\n accumulateDelta(\n key: UsageAccumulatorKey,\n delta: CanonicalUsage,\n options?: AccumulateOptions,\n ): Promise<UsageAccumulatorSnapshot>;\n /** Start a new epoch. Idempotent per delivery when `options.delivery` is given. */\n recordReset(key: UsageAccumulatorKey, options?: AccumulateOptions): Promise<{ readonly epoch: number }>;\n read(key: UsageAccumulatorKey): Promise<UsageAccumulatorSnapshot | undefined>;\n cleanup(\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<RollupCleanupResult>;\n}\n\nexport type UsageAccumulatorDependencies = {\n readonly stateStore: StateStore;\n readonly clock: Clock;\n};\n\nconst EMPTY_CUMULATIVE_USAGE: CanonicalUsage = normalizeUsageOrThrow({ temporality: \"cumulative\" });\n\nconst combineCumulativeWithDelta = (total: CanonicalUsage, delta: CanonicalUsage): CanonicalUsage => {\n if (total.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"usage rollup total must have cumulative temporality\" },\n ]);\n }\n if (delta.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"usage accumulator only accepts delta observations\" },\n ]);\n }\n\n const accounting =\n total.cacheCreationInputTokens === 0 && total.cacheCreationAccounting === \"not-reported\"\n ? delta.cacheCreationAccounting\n : delta.cacheCreationInputTokens === 0 && delta.cacheCreationAccounting === \"not-reported\"\n ? total.cacheCreationAccounting\n : total.cacheCreationAccounting;\n\n if (\n total.cacheCreationInputTokens !== 0 &&\n delta.cacheCreationInputTokens !== 0 &&\n total.cacheCreationAccounting !== delta.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot roll up usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n total.providerTotalTokens === undefined && delta.providerTotalTokens === undefined\n ? undefined\n : (total.providerTotalTokens ?? 0) + (delta.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"cumulative\",\n inputTokens: total.inputTokens + delta.inputTokens,\n cachedInputTokens: total.cachedInputTokens + delta.cachedInputTokens,\n cacheCreationInputTokens: total.cacheCreationInputTokens + delta.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: total.outputTokens + delta.outputTokens,\n reasoningOutputTokens: total.reasoningOutputTokens + delta.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n\nexport const createUsageAccumulator = (deps: UsageAccumulatorDependencies): UsageAccumulator => {\n const { stateStore, clock } = deps;\n\n /**\n * The epoch record's own delivery marker.\n *\n * Kept in the epoch record for the same reason the total's marker is kept in the\n * total: one write, so the counter and the statement about who moved it cannot\n * disagree. The epoch record is an `attributes` value, so the two fields are\n * flat rather than nested.\n */\n const readEpochMarker = (\n attributes: Attributes,\n ): { readonly callbackId: string; readonly applications: number } | undefined => {\n const callbackId = attributes.resetDelivery;\n const applications = attributes.resetApplications;\n if (\n typeof callbackId !== \"string\" ||\n callbackId.length === 0 ||\n typeof applications !== \"number\" ||\n !Number.isInteger(applications) ||\n applications < 1\n ) {\n return undefined;\n }\n return { callbackId, applications };\n };\n\n const readEpoch = async (key: UsageAccumulatorKey): Promise<number> => {\n const record = await stateStore.read(rollupEpochKey(key.sessionId, key.scope, key.scopeKey));\n if (record?.value.kind === \"attributes\" && typeof record.value.attributes.epoch === \"number\") {\n return record.value.attributes.epoch;\n }\n return 0;\n };\n\n /**\n * Whether this delivery's observation number `ordinal` is already folded in.\n *\n * The comparison is `<` rather than `===` because observations are applied in\n * order: `applications` is the count folded in so far, so any ordinal below it has\n * been seen. A marker naming a *different* delivery means this rollup has moved on\n * and nothing can be recognized.\n */\n const alreadyApplied = (\n marker: { readonly callbackId: string; readonly applications: number } | undefined,\n delivery: DeliveryStamp | undefined,\n ): boolean =>\n delivery !== undefined &&\n marker !== undefined &&\n marker.callbackId === delivery.callbackId &&\n delivery.ordinal < marker.applications;\n\n const markerFor = (\n delivery: DeliveryStamp | undefined,\n ): { readonly appliedDelivery?: { readonly callbackId: string; readonly applications: number } } =>\n delivery === undefined\n ? {}\n : {\n appliedDelivery: { callbackId: delivery.callbackId, applications: delivery.ordinal + 1 },\n };\n\n const accumulateDelta = (\n key: UsageAccumulatorKey,\n delta: CanonicalUsage,\n options?: AccumulateOptions,\n ): Promise<UsageAccumulatorSnapshot> =>\n withOptionalSessionLock(stateStore, key.sessionId, async (): Promise<UsageAccumulatorSnapshot> => {\n const usageKey = rollupUsageKey(key.sessionId, key.scope, key.scopeKey);\n const existing = await stateStore.read(usageKey);\n const previousTotal =\n existing?.value.kind === \"usage-cumulative\" ? existing.value.usage : EMPTY_CUMULATIVE_USAGE;\n\n if (\n existing?.value.kind === \"usage-cumulative\" &&\n alreadyApplied(existing.value.appliedDelivery, options?.delivery)\n ) {\n // This exact observation of this exact delivery is already in the total.\n // Reporting the total unchanged is the honest answer: the caller asked for\n // the running figure after its delta, and that is what this is.\n return { total: previousTotal, epoch: await readEpoch(key) };\n }\n\n const total = combineCumulativeWithDelta(previousTotal, delta);\n await stateStore.write(usageKey, {\n kind: \"usage-cumulative\",\n usage: total,\n ...markerFor(options?.delivery),\n });\n return { total, epoch: await readEpoch(key) };\n });\n\n const recordReset = (\n key: UsageAccumulatorKey,\n options?: AccumulateOptions,\n ): Promise<{ readonly epoch: number }> =>\n withOptionalSessionLock(stateStore, key.sessionId, async (): Promise<{ readonly epoch: number }> => {\n const epochKey = rollupEpochKey(key.sessionId, key.scope, key.scopeKey);\n const existingEpoch = await stateStore.read(epochKey);\n const marker =\n existingEpoch?.value.kind === \"attributes\"\n ? readEpochMarker(existingEpoch.value.attributes)\n : undefined;\n\n if (alreadyApplied(marker, options?.delivery)) {\n // A replayed reset must not open a second epoch: the epoch number is what a\n // consumer uses to refuse summing across a counter restart, and inflating it\n // twice for one restart makes a real series look like two.\n return { epoch: await readEpoch(key) };\n }\n\n const epoch = (await readEpoch(key)) + 1;\n const applied = markerFor(options?.delivery).appliedDelivery;\n await stateStore.write(epochKey, {\n kind: \"attributes\",\n attributes: {\n epoch,\n ...(applied === undefined\n ? {}\n : { resetDelivery: applied.callbackId, resetApplications: applied.applications }),\n },\n });\n await stateStore.delete(rollupUsageKey(key.sessionId, key.scope, key.scopeKey));\n return { epoch };\n });\n\n const read = async (key: UsageAccumulatorKey): Promise<UsageAccumulatorSnapshot | undefined> => {\n const record = await stateStore.read(rollupUsageKey(key.sessionId, key.scope, key.scopeKey));\n if (record?.value.kind !== \"usage-cumulative\") {\n return undefined;\n }\n return { total: record.value.usage, epoch: await readEpoch(key) };\n };\n\n const cleanup = async (\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<RollupCleanupResult> => {\n const cap = options?.maxEntries ?? 1_000;\n const now = clock.now();\n let removed = 0;\n let scanned = 0;\n\n const sweep = async (keys: readonly string[]): Promise<void> => {\n for (const key of keys) {\n if (scanned >= cap) {\n return;\n }\n scanned += 1;\n const record = await stateStore.read(key);\n if (record !== undefined && now - record.updatedAt > maxAgeMillis) {\n await stateStore.delete(key);\n removed += 1;\n }\n }\n };\n\n await sweep(await stateStore.keys(rollupScanPrefix(options?.sessionId)));\n await sweep(await stateStore.keys(rollupEpochScanPrefix(options?.sessionId)));\n return { removed, scanned };\n };\n\n return { accumulateDelta, recordReset, read, cleanup };\n};\n","import { createHash } from \"node:crypto\";\n\nimport type { ContentFact, ContentKind, ContentRole } from \"../model/content.js\";\nimport { isValidExtensionKey } from \"../model/extensions.js\";\nimport {\n attributeValueSchema,\n MAX_ATTRIBUTE_ARRAY_LENGTH,\n MAX_ATTRIBUTE_STRING_LENGTH,\n type AttributePrimitive,\n type Attributes,\n type AttributeValue,\n} from \"../model/primitives.js\";\nimport {\n CONTENT_MODE_DISCLOSURE,\n resolvePrivacyPolicy,\n type PrivacyLimits,\n type PrivacyPolicy,\n} from \"./policy.js\";\n\nexport type SanitizedValue =\n | string\n | number\n | boolean\n | null\n | readonly SanitizedValue[]\n | { readonly [key: string]: SanitizedValue };\n\nexport type SanitizeStats = {\n readonly truncatedStrings: number;\n readonly truncatedArrays: number;\n readonly truncatedObjects: number;\n readonly redactedKeys: number;\n readonly depthExceeded: number;\n readonly droppedValues: number;\n readonly circularReferences: number;\n};\n\nexport type SanitizeResult = {\n readonly value: SanitizedValue;\n readonly stats: SanitizeStats;\n};\n\nexport type DescribeContentInput = {\n readonly kind: ContentKind;\n readonly text: string;\n readonly role?: ContentRole;\n readonly label?: string;\n};\n\nexport type DescribeStructuredInput = {\n readonly kind: ContentKind;\n readonly value: unknown;\n readonly role?: ContentRole;\n readonly label?: string;\n};\n\nexport type SanitizeExtensionsResult = {\n readonly extensions: Record<string, AttributeValue>;\n readonly droppedKeys: readonly string[];\n};\n\n/**\n * Single point through which every piece of potentially sensitive data passes.\n *\n * Provider adapters receive this service and are expected to describe content\n * with it rather than copying text into events themselves. That keeps the\n * disclosure decision in one auditable place.\n */\nexport interface PrivacyService {\n readonly policy: PrivacyPolicy;\n /** Notes about deterministic policy downgrades applied at construction. */\n readonly policyNotes: readonly string[];\n /** Stable salted digest, formatted `sha256:<hex>`. */\n hash(value: string): string;\n /** Opaque namespaced handle suitable for a workspace or resource id. */\n deriveOpaqueId(namespace: string, value: string): string;\n describeContent(input: DescribeContentInput): ContentFact;\n /**\n * A content fact for a kind the event can carry when the provider sent no\n * text. Distinct from describing an empty string: there is nothing to\n * disclose under any content mode, so the fact is always omitted.\n */\n describeUnavailableContent(input: Omit<DescribeContentInput, \"text\">): ContentFact;\n describeStructured(input: DescribeStructuredInput): ContentFact;\n isSecretKey(key: string): boolean;\n sanitizeStructured(value: unknown): SanitizeResult;\n /** Attribute-safe projection of a sanitized value, with dotted paths. */\n flattenToAttributes(value: SanitizedValue, prefix: string): Attributes;\n sanitizeAttributes(value: Readonly<Record<string, unknown>>): Attributes;\n sanitizeExtensions(value: Readonly<Record<string, unknown>>): SanitizeExtensionsResult;\n /** Bound a string to the policy limit, reporting whether it was cut. */\n boundString(value: string): { readonly text: string; readonly truncated: boolean };\n}\n\nconst compilePatterns = (sources: readonly string[], flags: string): readonly RegExp[] => {\n const compiled: RegExp[] = [];\n for (const source of sources) {\n try {\n compiled.push(new RegExp(source, flags));\n } catch {\n // An unusable pattern must not disable the whole privacy service; the\n // remaining patterns still apply. Skipping is the conservative choice for\n // key patterns only because a bad pattern would otherwise match nothing\n // anyway.\n continue;\n }\n }\n return compiled;\n};\n\nconst codePointLength = (value: string): number => [...value].length;\n\nconst isSanitizedArray = (value: SanitizedValue): value is readonly SanitizedValue[] =>\n Array.isArray(value);\n\nconst sliceCodePoints = (value: string, max: number): string => {\n if (max <= 0) {\n return \"\";\n }\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\nconst stableStringify = (value: unknown): string => {\n const seen = new WeakSet<object>();\n const walk = (input: unknown): string => {\n if (input === null) {\n return \"null\";\n }\n if (typeof input === \"string\") {\n return JSON.stringify(input);\n }\n if (typeof input === \"number\") {\n return Number.isFinite(input) ? JSON.stringify(input) : \"null\";\n }\n if (typeof input === \"boolean\") {\n return input ? \"true\" : \"false\";\n }\n if (typeof input === \"bigint\") {\n return JSON.stringify(input.toString());\n }\n if (typeof input !== \"object\") {\n return \"null\";\n }\n if (seen.has(input)) {\n return '\"<circular>\"';\n }\n seen.add(input);\n if (Array.isArray(input)) {\n return `[${input.map((entry) => walk(entry)).join(\",\")}]`;\n }\n const record = input as Record<string, unknown>;\n const keys = Object.keys(record).sort();\n return `{${keys\n .map((key) => `${JSON.stringify(key)}:${walk(record[key])}`)\n .join(\",\")}}`;\n };\n return walk(value);\n};\n\ntype MutableStats = {\n truncatedStrings: number;\n truncatedArrays: number;\n truncatedObjects: number;\n redactedKeys: number;\n depthExceeded: number;\n droppedValues: number;\n circularReferences: number;\n};\n\nconst emptyStats = (): MutableStats => ({\n truncatedStrings: 0,\n truncatedArrays: 0,\n truncatedObjects: 0,\n redactedKeys: 0,\n depthExceeded: 0,\n droppedValues: 0,\n circularReferences: 0,\n});\n\nexport const createPrivacyService = (policyInput: PrivacyPolicy): PrivacyService => {\n const { policy, notes } = resolvePrivacyPolicy(policyInput);\n const limits: PrivacyLimits = policy.limits;\n const secretKeyPatterns = compilePatterns(policy.secretKeyPatterns, \"i\");\n const secretValuePatterns = compilePatterns(policy.secretValuePatterns, \"g\");\n\n const hash = (value: string): string =>\n `sha256:${createHash(\"sha256\").update(policy.hashSalt).update(\"\\0\").update(value, \"utf8\").digest(\"hex\")}`;\n\n const isSecretKey = (key: string): boolean =>\n secretKeyPatterns.some((pattern) => pattern.test(key));\n\n const boundString = (value: string): { text: string; truncated: boolean } => {\n const length = codePointLength(value);\n if (length <= limits.maxStringLength) {\n return { text: value, truncated: false };\n }\n return { text: sliceCodePoints(value, limits.maxStringLength), truncated: true };\n };\n\n const redactSecretSpans = (value: string): { text: string; count: number } => {\n let count = 0;\n let text = value;\n for (const pattern of secretValuePatterns) {\n text = text.replace(new RegExp(pattern.source, pattern.flags), () => {\n count += 1;\n return policy.redactionPlaceholder;\n });\n }\n return { text, count };\n };\n\n const maskText = (value: string): string =>\n Array.from(value, (char) => (/\\s/.test(char) ? char : policy.maskCharacter)).join(\"\");\n\n const disclose = (\n original: string,\n ): { text: string | undefined; truncated: boolean; secretsRedacted: number } => {\n switch (policy.contentMode) {\n case \"omit\":\n return { text: undefined, truncated: false, secretsRedacted: 0 };\n case \"mask\": {\n const bounded = boundString(original);\n return { text: maskText(bounded.text), truncated: bounded.truncated, secretsRedacted: 0 };\n }\n case \"redact\": {\n const redacted = redactSecretSpans(original);\n const bounded = boundString(redacted.text);\n return {\n text: bounded.text,\n truncated: bounded.truncated,\n secretsRedacted: redacted.count,\n };\n }\n case \"raw\": {\n const bounded = boundString(original);\n return { text: bounded.text, truncated: bounded.truncated, secretsRedacted: 0 };\n }\n }\n };\n\n const describeText = (input: DescribeContentInput): ContentFact => {\n const disclosed = disclose(input.text);\n return {\n kind: input.kind,\n ...(input.role === undefined ? {} : { role: input.role }),\n characterLength: codePointLength(input.text),\n byteLength: Buffer.byteLength(input.text, \"utf8\"),\n contentHash: hash(input.text),\n disclosure: CONTENT_MODE_DISCLOSURE[policy.contentMode],\n ...(disclosed.text === undefined ? {} : { text: disclosed.text }),\n truncated: disclosed.truncated,\n secretsRedacted: disclosed.secretsRedacted,\n ...(input.label === undefined ? {} : { label: input.label }),\n };\n };\n\n const sanitizeValue = (value: unknown, depth: number, stats: MutableStats, seen: WeakSet<object>): SanitizedValue => {\n if (value === null) {\n return null;\n }\n switch (typeof value) {\n case \"string\": {\n const bounded = boundString(value);\n if (bounded.truncated) {\n stats.truncatedStrings += 1;\n }\n return bounded.text;\n }\n case \"number\":\n if (!Number.isFinite(value)) {\n stats.droppedValues += 1;\n return null;\n }\n return value;\n case \"boolean\":\n return value;\n case \"bigint\":\n return value.toString();\n case \"undefined\":\n case \"function\":\n case \"symbol\":\n stats.droppedValues += 1;\n return null;\n default:\n break;\n }\n\n if (depth >= limits.maxDepth) {\n stats.depthExceeded += 1;\n return \"<depth-exceeded>\";\n }\n if (seen.has(value)) {\n stats.circularReferences += 1;\n return \"<circular>\";\n }\n seen.add(value);\n\n if (Array.isArray(value)) {\n const entries = value.slice(0, limits.maxArrayLength);\n if (value.length > limits.maxArrayLength) {\n stats.truncatedArrays += 1;\n }\n return entries.map((entry) => sanitizeValue(entry, depth + 1, stats, seen));\n }\n\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const retained = keys.slice(0, limits.maxObjectKeys);\n if (keys.length > limits.maxObjectKeys) {\n stats.truncatedObjects += 1;\n }\n const result: Record<string, SanitizedValue> = {};\n for (const key of retained) {\n if (isSecretKey(key)) {\n stats.redactedKeys += 1;\n result[key] = policy.redactionPlaceholder;\n continue;\n }\n result[key] = sanitizeValue(record[key], depth + 1, stats, seen);\n }\n return result;\n };\n\n const sanitizeStructured = (value: unknown): SanitizeResult => {\n const stats = emptyStats();\n const sanitized = sanitizeValue(value, 0, stats, new WeakSet<object>());\n return { value: sanitized, stats };\n };\n\n const toAttributePrimitive = (value: SanitizedValue): AttributePrimitive | undefined => {\n if (typeof value === \"string\") {\n return value.slice(0, MAX_ATTRIBUTE_STRING_LENGTH);\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n return undefined;\n };\n\n const flattenToAttributes = (value: SanitizedValue, prefix: string): Attributes => {\n const attributes: Record<string, AttributeValue> = {};\n const walk = (current: SanitizedValue, path: string): void => {\n if (\n typeof current === \"string\" ||\n typeof current === \"number\" ||\n typeof current === \"boolean\"\n ) {\n const primitive = toAttributePrimitive(current);\n if (primitive !== undefined) {\n attributes[path] = primitive;\n }\n return;\n }\n if (current === null) {\n return;\n }\n if (isSanitizedArray(current)) {\n const primitives: AttributePrimitive[] = [];\n let uniform = true;\n for (const entry of current) {\n const entryPrimitive = toAttributePrimitive(entry);\n if (entryPrimitive === undefined) {\n uniform = false;\n break;\n }\n primitives.push(entryPrimitive);\n }\n if (uniform) {\n attributes[path] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);\n return;\n }\n for (const [index, entry] of current.entries()) {\n walk(entry, `${path}.${index}`);\n }\n return;\n }\n for (const [key, entry] of Object.entries(current)) {\n walk(entry, path === \"\" ? key : `${path}.${key}`);\n }\n };\n walk(value, prefix);\n return attributes;\n };\n\n const sanitizeAttributes = (value: Readonly<Record<string, unknown>>): Attributes => {\n const attributes: Record<string, AttributeValue> = {};\n for (const [key, entry] of Object.entries(value)) {\n if (isSecretKey(key)) {\n attributes[key] = policy.redactionPlaceholder;\n continue;\n }\n const sanitized = sanitizeStructured(entry).value;\n const primitive = toAttributePrimitive(sanitized);\n if (primitive !== undefined) {\n attributes[key] = primitive;\n continue;\n }\n const flattened = flattenToAttributes(sanitized, key);\n Object.assign(attributes, flattened);\n }\n return attributes;\n };\n\n const sanitizeExtensions = (\n value: Readonly<Record<string, unknown>>,\n ): SanitizeExtensionsResult => {\n const extensions: Record<string, AttributeValue> = {};\n const droppedKeys: string[] = [];\n for (const [key, entry] of Object.entries(value)) {\n if (!isValidExtensionKey(key)) {\n droppedKeys.push(key);\n continue;\n }\n if (isSecretKey(key)) {\n extensions[key] = policy.redactionPlaceholder;\n continue;\n }\n const sanitized = sanitizeStructured(entry).value;\n const candidate = attributeValueSchema.safeParse(sanitized);\n if (candidate.success) {\n extensions[key] = candidate.data;\n } else {\n droppedKeys.push(key);\n }\n }\n return { extensions, droppedKeys };\n };\n\n return {\n policy,\n policyNotes: notes,\n hash,\n deriveOpaqueId: (namespace: string, value: string): string =>\n hash(`${namespace}\\0${value}`),\n describeContent: describeText,\n describeUnavailableContent: (input: Omit<DescribeContentInput, \"text\">): ContentFact => ({\n kind: input.kind,\n ...(input.role === undefined ? {} : { role: input.role }),\n characterLength: 0,\n byteLength: 0,\n contentHash: hash(\"\"),\n disclosure: \"omitted\",\n truncated: false,\n secretsRedacted: 0,\n ...(input.label === undefined ? {} : { label: input.label }),\n }),\n describeStructured: (input: DescribeStructuredInput): ContentFact => {\n const serialized = stableStringify(input.value);\n const sanitized = sanitizeStructured(input.value);\n const base = describeText({\n kind: input.kind,\n text: serialized,\n ...(input.role === undefined ? {} : { role: input.role }),\n ...(input.label === undefined ? {} : { label: input.label }),\n });\n if (base.text === undefined) {\n return base;\n }\n // Disclose the sanitized projection rather than the raw serialization, so\n // secret-keyed values never appear even in `raw` mode.\n const disclosed = disclose(stableStringify(sanitized.value));\n return {\n ...base,\n ...(disclosed.text === undefined ? {} : { text: disclosed.text }),\n truncated: base.truncated || disclosed.truncated,\n secretsRedacted: disclosed.secretsRedacted + sanitized.stats.redactedKeys,\n };\n },\n isSecretKey,\n sanitizeStructured,\n flattenToAttributes,\n sanitizeAttributes,\n sanitizeExtensions,\n boundString,\n };\n};\n","import { z } from \"zod\";\n\nimport { attributeValueSchema, type AttributeValue } from \"./primitives.js\";\n\n/**\n * Extension keys must be namespaced: at least one dot-separated segment before\n * the leaf, e.g. `acme.deployment-tier`. Namespacing keeps provider- and\n * consumer-specific fields from colliding with core fields or each other.\n */\nexport const EXTENSION_KEY_PATTERN =\n /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;\n\n/** Namespaces owned by the core model; extensions may not use them. */\nexport const RESERVED_EXTENSION_NAMESPACES: readonly string[] = Object.freeze([\n \"otelhook\",\n \"otel\",\n \"telemetry\",\n]);\n\nexport const MAX_EXTENSION_ENTRIES = 64;\n\nexport const extensionKeyNamespace = (key: string): string => key.slice(0, key.indexOf(\".\"));\n\nexport const isReservedExtensionNamespace = (key: string): boolean =>\n RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));\n\nexport const isValidExtensionKey = (key: string): boolean =>\n EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);\n\n/**\n * Namespaced extension bag.\n *\n * Values are restricted to attribute primitives, so extensions cannot carry\n * nested provider payloads.\n */\nexport const extensionsSchema = z\n .record(z.string(), attributeValueSchema)\n .check((ctx) => {\n const keys = Object.keys(ctx.value);\n if (keys.length > MAX_EXTENSION_ENTRIES) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`,\n });\n }\n for (const key of keys) {\n if (!EXTENSION_KEY_PATTERN.test(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. \"acme.tier\"`,\n });\n continue;\n }\n if (isReservedExtensionNamespace(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`,\n });\n }\n }\n });\n\nexport type Extensions = Record<string, AttributeValue>;\n\nexport const EMPTY_EXTENSIONS: Extensions = Object.freeze({});\n\nexport const emptyExtensions = (): Extensions => ({});\n","import { z } from \"zod\";\n\nimport 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 { epochMillisSchema, type EpochMillis } from \"../model/primitives.js\";\nimport type { Clock } from \"./ports.js\";\n\n/** Clock backed by the host process. */\nexport const createSystemClock = (): Clock => ({\n now: (): EpochMillis => epochMillisSchema.parse(Date.now()),\n monotonicMillis: (): number => Number(process.hrtime.bigint() / 1_000_000n),\n});\n\nexport type FixedClockOptions = {\n readonly startMillis?: number;\n /** Milliseconds added to the wall clock on each `now()` call. */\n readonly tickMillis?: number;\n};\n\n/**\n * Deterministic clock for tests.\n *\n * `advance` moves both readings together so duration arithmetic stays coherent.\n */\nexport interface FixedClock extends Clock {\n advance(millis: number): void;\n set(millis: number): void;\n}\n\nexport const createFixedClock = (options: FixedClockOptions = {}): FixedClock => {\n let wall = options.startMillis ?? 1_700_000_000_000;\n let monotonic = 0;\n const tick = options.tickMillis ?? 0;\n\n return {\n now: (): EpochMillis => {\n const current = wall;\n wall += tick;\n monotonic += tick;\n return epochMillisSchema.parse(current);\n },\n monotonicMillis: (): number => monotonic,\n advance: (millis: number): void => {\n wall += millis;\n monotonic += millis;\n },\n set: (millis: number): void => {\n wall = millis;\n },\n };\n};\n","import { z } from \"zod\";\n\nimport { DEFAULT_CONFIG, type OtelHookConfig } from \"../config/schema.js\";\nimport {\n createErrorInfo,\n errorInfoFromThrown,\n type AttributionOutcome,\n type AttributionReason,\n type OtelHookErrorInfo,\n} from \"../errors/index.js\";\nimport {\n isContentFactConsistent,\n isUnavailableContentFact,\n type ContentFact,\n} from \"../model/content.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport {\n resolveInvocationIdentity,\n sourceProvenanceSchema,\n unknownWorkspaceIdentity,\n type IdentityClaim,\n type InvocationIdentity,\n type WorkspaceIdentity,\n} from \"../model/identity.js\";\nimport {\n type DetectionConfidence,\n type EventId,\n type ResolvedProviderId,\n type SourceTransport,\n} from \"../model/primitives.js\";\nimport {\n cumulativeToDelta,\n normalizeUsage,\n toReport,\n type CanonicalUsage,\n type UsageTemporality,\n} from \"../model/usage.js\";\nimport { CANONICAL_SCHEMA_VERSION } from \"../model/version.js\";\nimport { CONTENT_MODE_DISCLOSURE } from \"../privacy/policy.js\";\nimport { createPrivacyService, type PrivacyService } from \"../privacy/service.js\";\nimport {\n readDeliveryClaim,\n readDeliveryGap,\n SILENT_HOOK_RESPONSE,\n type ProviderAdapter,\n type ProviderContext,\n type ProviderDetection,\n type ProviderHookResponse,\n} from \"../providers/adapter.js\";\nimport { createProviderRegistry, BUILT_IN_PROVIDERS, type ProviderRegistry } from \"../providers/registry.js\";\nimport { createSystemClock } from \"./clock.js\";\nimport { resolveDeliveryIdentity, type DeliveryResolution } from \"./delivery.js\";\nimport { createDeterministicIdGenerator } from \"./ids.js\";\nimport { createNullLogger } from \"./logger.js\";\nimport type {\n Clock,\n IdGenerator,\n Logger,\n StateStore,\n TelemetrySink,\n WorktreeLocator,\n} from \"./ports.js\";\nimport type { TargetHint } from \"../model/target.js\";\nimport {\n DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS,\n resolveEventTargets,\n} from \"./target-resolution.js\";\nimport { isStateLockContention, withOptionalSessionLock } from \"../state/store.js\";\n\nexport const usageScopeSchema = z.enum([\"session\", \"generation\", \"subagent\"]);\nexport type UsageScope = z.infer<typeof usageScopeSchema>;\n\n/**\n * Which series a provider's cumulative counters accumulate over. Mirrors\n * `ProviderCapabilities.cumulativeUsageSeries`, defaulting to `event-scope`\n * for the adapters that do not declare one.\n */\nexport type CumulativeUsageSeries = \"event-scope\" | \"session-lifetime\";\n\n/**\n * Delta usage derived for one event.\n *\n * Events keep whatever the provider reported. Deltas are produced alongside them\n * rather than rewritten into them, so a cumulative report and its derived delta\n * are both auditable.\n */\nexport type UsageObservation = {\n readonly eventId: EventId;\n readonly sequence: number;\n readonly scope: UsageScope;\n readonly scopeKey: string;\n readonly reportedTemporality: UsageTemporality;\n readonly delta: CanonicalUsage;\n /** True when the cumulative series restarted; see `cumulativeToDelta`. */\n readonly resetDetected: boolean;\n};\n\nexport type HookIngestInput = {\n /** Decoded provider payload. Only the selected adapter interprets it. */\n readonly payload: unknown;\n readonly transport: SourceTransport;\n readonly environment?: Readonly<Record<string, string | undefined>>;\n readonly providerHint?: string;\n /** Caller-supplied identity claims, arbitrated with the adapter's claims. */\n readonly identityClaims?: readonly IdentityClaim[];\n /** Opaque consumer metadata; sanitized, then carried through unchanged. */\n readonly consumerAttributes?: Readonly<Record<string, unknown>>;\n readonly workspace?: WorkspaceIdentity;\n};\n\n/**\n * The terminal fate of one callback's telemetry, and the only thing a caller\n * should base a commit-or-retry decision on.\n *\n * The distinction that matters is **any** versus **all**, not success versus\n * failure. A batch is chunked before export, so it can be part accepted and part\n * refused — and once a single span has reached a collector or the spool, retrying\n * the callback would re-export that span. So a partial result is *terminal*: the\n * callback is committed, the loss is reported, and nothing is retried. Only a\n * result where nothing at all survived is safe to retry, precisely because there\n * is nothing to duplicate.\n */\nexport type DeliveryDurability =\n /** Suppressed, or no events to export. There is nothing to lose or retry. */\n | \"nothing-to-deliver\"\n /** Every span reached the collector or the spool. */\n | \"delivered\"\n /**\n * Some spans survived and some did not. Terminal: committing loses the refused\n * spans, retrying duplicates the accepted ones, and duplicating an accepted\n * span silently corrupts a total while a reported loss can be acted on.\n */\n | \"partial\"\n /** Nothing survived, so a retry cannot duplicate anything. */\n | \"lost\";\n\nexport const classifyDurability = (input: {\n readonly attempted: boolean;\n readonly accepted: number;\n readonly rejected: number;\n}): DeliveryDurability => {\n if (!input.attempted) {\n return \"nothing-to-deliver\";\n }\n if (input.rejected === 0) {\n return input.accepted === 0 ? \"nothing-to-deliver\" : \"delivered\";\n }\n return input.accepted === 0 ? \"lost\" : \"partial\";\n};\n\n/** Whether this fate permits committing the callback and its accounting. */\nexport const isCommittable = (durability: DeliveryDurability): boolean =>\n durability !== \"lost\";\n\nexport type HookIngestOutcome = {\n /**\n * Always `true`. The hook cannot fail the host agent; look at `attribution`\n * and `diagnostics` to see what actually happened (ADR 0004).\n */\n readonly ok: true;\n readonly attribution: AttributionOutcome;\n readonly attributionReason?: AttributionReason;\n readonly providerId: ResolvedProviderId;\n readonly detectionConfidence: DetectionConfidence;\n readonly identity?: InvocationIdentity;\n readonly events: readonly CanonicalEvent[];\n readonly usageObservations: readonly UsageObservation[];\n /**\n * OTLP records the sink accepted, summed over every wired signal.\n *\n * A count of *records*, never of canonical events: two edges of one lifecycle\n * scope produce one span, and one event carrying three content facts produces\n * three log records. With the logs signal enabled a batch therefore reports both\n * signals' records here — which is what makes {@link durability} correct across\n * them, and why nothing should read this as \"how many events were observed\".\n */\n readonly emitted: number;\n /**\n * Records the sink could neither export nor durably spool.\n *\n * The distinction `emitted` cannot make: a successful spool enqueue counts as\n * emitted, because the batch is safe on disk and a later invocation will retry\n * it. A non-zero value here means those observations are **gone** unless the\n * callback is delivered again — which is what lets a caller decide whether a\n * delivery claim may be committed or has to be released for retry.\n */\n readonly exportRejected: number;\n /**\n * The terminal fate of this callback's telemetry.\n *\n * The field a caller should branch on. `emitted` and `exportRejected` are the\n * raw counts behind it; this is the decision they add up to, computed in one\n * place so a caller cannot get the any-versus-all boundary wrong.\n */\n readonly durability: DeliveryDurability;\n readonly dropped: number;\n readonly hookResponse: ProviderHookResponse;\n readonly diagnostics: readonly OtelHookErrorInfo[];\n};\n\nexport type HookIngestOptions = {\n /**\n * Parse and answer the provider, but export nothing and mutate no canonical\n * state.\n *\n * For a callback that deduplication has already identified as a redelivery.\n * The adapter still runs, so the provider's protocol response comes from a real\n * parse of the real payload rather than a guess — but the session sequence\n * counter is not advanced and no cumulative usage baseline is rewritten,\n * because both are *canonical state* and a redelivery is by definition not a\n * new observation. Advancing the sequence would renumber every later event in\n * the session and change its derived event id, which is exactly the\n * replay-stability the dedup guard exists to protect.\n */\n readonly suppress?: boolean;\n};\n\n/** Public runtime surface. */\nexport interface OtelHook {\n /**\n * Report the replay-stable delivery identity of an input without ingesting it.\n *\n * Synchronous, side-effect free, and never throws. It exists as a separate\n * step because deduplication has to decide *before* anything is exported or\n * accounted, and `ingest` exports as part of its own work — a caller that\n * learned the identity afterwards could only ever suppress a duplicate it had\n * already sent. Only `detect` and `deliveryIdentity` run here; the payload is\n * never parsed.\n */\n resolveDelivery(input: HookIngestInput): DeliveryResolution;\n /** Process one provider observation. Never throws, never rejects. */\n ingest(input: HookIngestInput, options?: HookIngestOptions): Promise<HookIngestOutcome>;\n /** Best-effort delivery of buffered telemetry. Never throws. */\n flush(): Promise<void>;\n /** Flush, then release resources. Never throws; idempotent. */\n shutdown(): Promise<void>;\n /** Resolved configuration in force. Read-only. */\n readonly config: OtelHookConfig;\n}\n\nexport type OtelHookDependencies = {\n readonly sink: TelemetrySink;\n readonly stateStore: StateStore;\n readonly config?: OtelHookConfig;\n readonly registry?: ProviderRegistry;\n readonly clock?: Clock;\n readonly ids?: IdGenerator;\n /** Overrides `config.privacy` when supplied; must already be configured. */\n readonly privacy?: PrivacyService;\n readonly logger?: Logger;\n /**\n * Namespace separating one deployment's derived delivery identities from\n * another's. Not identity: it never reaches an event, and no session or\n * workspace is derived from it. Defaults to `\"default\"`.\n */\n readonly installationId?: string;\n /**\n * Resolves tool events' target hints to the git worktree they touched\n * (ADR 0008). Absent means no resolution: events carry no `target`. The\n * filesystem implementation is `createFilesystemWorktreeLocator`.\n */\n readonly worktreeLocator?: WorktreeLocator;\n /** Ceiling on target resolution per callback. Default 50ms. */\n readonly targetResolutionBudgetMillis?: number;\n};\n\nconst MAX_ERROR_EVENTS = 8;\n\nconst collectContentFacts = (event: CanonicalEvent): readonly ContentFact[] => {\n const facts: ContentFact[] = [];\n const push = (fact: ContentFact | undefined): void => {\n if (fact !== undefined) {\n facts.push(fact);\n }\n };\n switch (event.type) {\n case \"prompt.submitted\":\n push(event.content);\n break;\n case \"generation.start\":\n facts.push(...(event.inputContent ?? []));\n break;\n case \"generation.end\":\n facts.push(...(event.outputContent ?? []));\n break;\n case \"tool.start\":\n push(event.input);\n break;\n case \"tool.end\":\n push(event.output);\n break;\n case \"error.raised\":\n push(event.message);\n break;\n default:\n break;\n }\n return facts;\n};\n\nconst usageScopeOf = (\n event: CanonicalEvent,\n): { readonly scope: UsageScope; readonly scopeKey: string; readonly usage: CanonicalUsage } | undefined => {\n switch (event.type) {\n case \"session.end\":\n return event.usage === undefined\n ? undefined\n : { scope: \"session\", scopeKey: event.sessionId, usage: event.usage };\n case \"compaction.performed\":\n return event.usage === undefined\n ? undefined\n : { scope: \"session\", scopeKey: event.sessionId, usage: event.usage };\n case \"generation.end\":\n return event.usage === undefined\n ? undefined\n : { scope: \"generation\", scopeKey: event.generationId, usage: event.usage };\n case \"subagent.end\":\n return event.usage === undefined\n ? undefined\n : { scope: \"subagent\", scopeKey: event.subagentInvocationId, usage: event.usage };\n default:\n return undefined;\n }\n};\n\nconst sequenceKey = (sessionId: string): string => `sequence:${sessionId}`;\nconst usageKey = (sessionId: string, scope: UsageScope, scopeKey: string): string =>\n `usage:${sessionId}:${scope}:${scopeKey}`;\n\n/**\n * Where the cumulative baseline for an observation is stored.\n *\n * This is deliberately *not* the same thing as the observation's own scope. The\n * derived delta belongs to the event that reported it — a turn's token spend is\n * attributed to that turn — but the snapshot it must be diffed against belongs\n * to whichever series the provider is actually accumulating.\n *\n * For a `session-lifetime` provider (Codex: every hook carries the session-wide\n * `total_token_usage`), keying the baseline by `generationId` would mean every\n * turn's snapshot found no predecessor and was emitted whole, billing the entire\n * session again on each turn. Redirecting `generation` to the session series\n * makes successive turns diff against each other.\n */\nconst baselineScopeOf = (\n scope: UsageScope,\n scopeKey: string,\n sessionId: string,\n series: CumulativeUsageSeries,\n): { readonly scope: UsageScope; readonly scopeKey: string } =>\n series === \"session-lifetime\" && scope === \"generation\"\n ? { scope: \"session\", scopeKey: sessionId }\n : { scope, scopeKey };\n\n/**\n * Minimal orchestrator wiring detection, identity, parsing, privacy checks,\n * usage derivation, and export.\n *\n * Every step is contained: a throwing adapter, an unavailable state store, or a\n * rejecting sink degrades the telemetry, never the host agent.\n */\nexport const createOtelHook = (deps: OtelHookDependencies): OtelHook => {\n const config = deps.config ?? DEFAULT_CONFIG;\n const registry = deps.registry ?? createProviderRegistry(BUILT_IN_PROVIDERS);\n const clock = deps.clock ?? createSystemClock();\n const ids = deps.ids ?? createDeterministicIdGenerator();\n const privacy = deps.privacy ?? createPrivacyService(config.privacy);\n const logger = deps.logger ?? createNullLogger();\n const installationId = deps.installationId ?? \"default\";\n const limits = privacy.policy.limits;\n const expectedDisclosure = CONTENT_MODE_DISCLOSURE[privacy.policy.contentMode];\n\n const providerContext: ProviderContext = { privacy, clock, ids, logger, limits };\n let shutdownCompleted = false;\n\n const hookResponseFor = (\n adapter: ProviderAdapter | undefined,\n detection: ProviderDetection | undefined,\n attribution: AttributionOutcome,\n attributionReason: AttributionReason | undefined,\n emittedEvents: number,\n errors: readonly OtelHookErrorInfo[],\n ): ProviderHookResponse => {\n if (adapter === undefined) {\n return SILENT_HOOK_RESPONSE;\n }\n try {\n return adapter.hookResponse(\n {\n attribution,\n ...(attributionReason === undefined ? {} : { attributionReason }),\n ...(detection === undefined ? {} : { detection }),\n emittedEvents,\n errors,\n },\n providerContext,\n );\n } catch {\n // A provider that cannot describe its own response gets the silent one.\n return SILENT_HOOK_RESPONSE;\n }\n };\n\n const readSequenceBase = async (\n sessionId: string,\n diagnostics: OtelHookErrorInfo[],\n ): Promise<number> => {\n try {\n const record = await deps.stateStore.read(sequenceKey(sessionId));\n if (record?.value.kind === \"sequence\") {\n return record.value.next;\n }\n return 0;\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, { code: \"state-store-failure\", phase: \"state\", occurredAt: clock.now() }),\n );\n return 0;\n }\n };\n\n /**\n * Derive per-event deltas, advancing the stored cumulative baseline.\n *\n * `suppress` makes this read-only: a redelivered callback must still be able to\n * report what it *would* have counted, but rewriting the baseline would make\n * the next genuine observation diff against the wrong snapshot and report a\n * zero — or negative — delta. Callers run this inside the session lock.\n */\n const deriveUsage = async (\n events: readonly CanonicalEvent[],\n diagnostics: OtelHookErrorInfo[],\n suppress: boolean,\n series: CumulativeUsageSeries,\n ): Promise<readonly UsageObservation[]> => {\n const observations: UsageObservation[] = [];\n for (const event of events) {\n const scoped = usageScopeOf(event);\n if (scoped === undefined) {\n continue;\n }\n if (scoped.usage.temporality === \"delta\") {\n observations.push({\n eventId: event.eventId,\n sequence: event.sequence,\n scope: scoped.scope,\n scopeKey: scoped.scopeKey,\n reportedTemporality: \"delta\",\n delta: scoped.usage,\n resetDetected: false,\n });\n continue;\n }\n\n const baselineScope = baselineScopeOf(scoped.scope, scoped.scopeKey, event.sessionId, series);\n const key = usageKey(event.sessionId, baselineScope.scope, baselineScope.scopeKey);\n let baseline: CanonicalUsage | undefined;\n try {\n const record = await deps.stateStore.read(key);\n if (record?.value.kind === \"usage-cumulative\") {\n baseline = record.value.usage;\n }\n } catch (thrown) {\n // Without a baseline the difference is unknowable. Emitting the raw\n // snapshot as a delta would double-count, so the observation is dropped.\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"state-store-failure\",\n phase: \"state\",\n occurredAt: clock.now(),\n }),\n );\n continue;\n }\n\n let delta: CanonicalUsage;\n let resetDetected = false;\n if (baseline === undefined) {\n const normalized = normalizeUsage({ ...toReport(scoped.usage), temporality: \"delta\" });\n if (normalized.status === \"invalid\") {\n diagnostics.push(\n createErrorInfo({\n code: \"usage-invalid\",\n phase: \"normalization\",\n detail: normalized.issues.map((issue) => issue.message).join(\"; \").slice(0, 400),\n details: { \"event.id\": event.eventId, \"usage.scope\": scoped.scope },\n occurredAt: clock.now(),\n }),\n );\n continue;\n }\n delta = normalized.usage;\n } else {\n try {\n const diffed = cumulativeToDelta(baseline, scoped.usage);\n delta = diffed.usage;\n resetDetected = diffed.resetDetected;\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"usage-invalid\",\n phase: \"normalization\",\n occurredAt: clock.now(),\n }),\n );\n continue;\n }\n }\n\n try {\n if (!suppress) {\n await deps.stateStore.write(key, { kind: \"usage-cumulative\", usage: scoped.usage });\n }\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"state-store-failure\",\n phase: \"state\",\n occurredAt: clock.now(),\n }),\n );\n }\n\n observations.push({\n eventId: event.eventId,\n sequence: event.sequence,\n scope: scoped.scope,\n scopeKey: scoped.scopeKey,\n reportedTemporality: \"cumulative\",\n delta,\n resetDetected,\n });\n }\n return observations;\n };\n\n const screenEvents = (\n events: readonly CanonicalEvent[],\n identity: InvocationIdentity,\n sequenceBase: number,\n diagnostics: OtelHookErrorInfo[],\n ): { readonly kept: readonly CanonicalEvent[]; readonly dropped: number } => {\n const kept: CanonicalEvent[] = [];\n let dropped = 0;\n let expectedSequence = sequenceBase;\n\n for (const event of events) {\n const reject = (code: \"schema-validation-failed\" | \"privacy-policy-violation\" | \"limit-exceeded\", detail: string): void => {\n dropped += 1;\n diagnostics.push(\n createErrorInfo({\n code,\n phase: code === \"privacy-policy-violation\" ? \"privacy\" : \"parsing\",\n detail,\n details: { \"event.type\": event.type, \"event.sequence\": event.sequence },\n occurredAt: clock.now(),\n }),\n );\n };\n\n if (kept.length >= limits.maxEventsPerInvocation) {\n reject(\"limit-exceeded\", `event dropped: maxEventsPerInvocation=${limits.maxEventsPerInvocation}`);\n continue;\n }\n if (event.schemaVersion !== CANONICAL_SCHEMA_VERSION) {\n reject(\"schema-validation-failed\", \"event carries an unexpected schema version\");\n continue;\n }\n if (event.invocationId !== identity.invocationId || event.sessionId !== identity.sessionId) {\n // Fail closed: an adapter may only describe the invocation it was given.\n reject(\"schema-validation-failed\", \"event identity does not match the resolved invocation\");\n continue;\n }\n if (event.provenance.providerId !== identity.provenance.providerId) {\n reject(\"schema-validation-failed\", \"event provenance does not match the detected provider\");\n continue;\n }\n if (event.sequence !== expectedSequence) {\n reject(\n \"schema-validation-failed\",\n `event sequence ${event.sequence} is not consecutive from ${expectedSequence}`,\n );\n continue;\n }\n\n const facts = collectContentFacts(event);\n const offending = facts.find(\n (fact) =>\n !isUnavailableContentFact(fact) &&\n (fact.disclosure !== expectedDisclosure || !isContentFactConsistent(fact)),\n );\n if (offending !== undefined) {\n reject(\n \"privacy-policy-violation\",\n `content fact disclosure ${offending.disclosure} violates policy ${expectedDisclosure}`,\n );\n continue;\n }\n\n expectedSequence += 1;\n kept.push(event);\n }\n return { kept, dropped };\n };\n\n const detectionInputFor = (input: HookIngestInput): {\n readonly payload: unknown;\n readonly transport: SourceTransport;\n readonly environment: Readonly<Record<string, string | undefined>>;\n readonly providerHint?: string;\n } => ({\n payload: input.payload,\n transport: input.transport,\n environment: input.environment ?? {},\n ...(input.providerHint === undefined ? {} : { providerHint: input.providerHint }),\n });\n\n const resolveDelivery = (input: HookIngestInput): DeliveryResolution => {\n let detected;\n try {\n detected = registry.detect(detectionInputFor(input), providerContext, config.detection);\n } catch {\n return { status: \"unavailable\", reason: \"provider-unattributed\" };\n }\n if (detected.status !== \"selected\") {\n return { status: \"unavailable\", reason: \"provider-unattributed\" };\n }\n\n const { adapter, detection } = detected;\n const capability = adapter.capabilities.deliveryIdentifier;\n // Named once, then reused: an unavailable resolution says *which* callback it\n // is talking about, because \"not identifiable\" without a callback name leaves\n // an operator auditing coverage nowhere to go.\n const named = {\n providerId: detection.providerId,\n capability,\n ...(detection.sourceEventName === undefined\n ? {}\n : { sourceEventName: detection.sourceEventName }),\n };\n const gap = readDeliveryGap(adapter, detection.sourceEventName);\n\n if (capability === \"none\") {\n return {\n status: \"unavailable\",\n reason: \"provider-declares-none\",\n ...named,\n ...(gap === undefined ? {} : { detail: gap }),\n };\n }\n\n const read = readDeliveryClaim(adapter, { ...detectionInputFor(input), detection }, providerContext);\n if (read.rejection !== undefined) {\n return {\n status: \"unavailable\",\n reason: \"claim-rejected\",\n ...named,\n detail: read.rejection,\n };\n }\n if (read.claim === undefined) {\n return {\n status: \"unavailable\",\n reason: \"callback-not-identifiable\",\n ...named,\n ...(gap === undefined ? {} : { detail: gap }),\n };\n }\n return {\n status: \"resolved\",\n identity: resolveDeliveryIdentity({\n ids,\n providerId: detection.providerId,\n installationId,\n claim: read.claim,\n }),\n };\n };\n\n const ingest = async (\n input: HookIngestInput,\n ingestOptions?: HookIngestOptions,\n ): Promise<HookIngestOutcome> => {\n const suppress = ingestOptions?.suppress === true;\n const diagnostics: OtelHookErrorInfo[] = [];\n const environment = input.environment ?? {};\n const detectionInput = {\n payload: input.payload,\n transport: input.transport,\n environment,\n ...(input.providerHint === undefined ? {} : { providerHint: input.providerHint }),\n };\n\n try {\n const detected = registry.detect(detectionInput, providerContext, config.detection);\n diagnostics.push(...detected.errors);\n\n if (detected.status !== \"selected\") {\n const reason: AttributionReason =\n detected.status === \"ambiguous\" ? \"provider-detection-ambiguous\" : \"provider-unknown\";\n diagnostics.push(\n createErrorInfo({\n code: detected.status === \"ambiguous\" ? \"provider-detection-ambiguous\" : \"provider-unknown\",\n phase: \"detection\",\n detail: detected.detection.reasons.join(\"; \").slice(0, 400),\n details: { \"detection.candidates\": detected.candidates.length },\n occurredAt: clock.now(),\n }),\n );\n logger.warn(\"provider not attributed\", {\n \"detection.status\": detected.status,\n \"detection.candidates\": detected.candidates.length,\n });\n return {\n ok: true,\n attribution: \"declined\",\n attributionReason: reason,\n providerId: \"unknown\",\n detectionConfidence: detected.detection.confidence,\n events: [],\n usageObservations: [],\n emitted: 0,\n exportRejected: 0,\n durability: \"nothing-to-deliver\" as const,\n dropped: 0,\n hookResponse: SILENT_HOOK_RESPONSE,\n diagnostics,\n };\n }\n\n const { adapter, detection } = detected;\n const provenance = sourceProvenanceSchema.parse({\n providerId: detection.providerId,\n ...(detection.providerVersion === undefined\n ? {}\n : { providerVersion: detection.providerVersion }),\n adapterId: adapter.id,\n adapterVersion: adapter.version,\n detectionConfidence: detection.confidence,\n ...(detection.sourceEventName === undefined\n ? {}\n : { sourceEventName: detection.sourceEventName }),\n transport: input.transport,\n });\n\n let adapterClaims: readonly IdentityClaim[] = [];\n try {\n adapterClaims = adapter.identify({ ...detectionInput, detection }, providerContext);\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"provider-adapter-failure\",\n phase: \"identity\",\n occurredAt: clock.now(),\n }),\n );\n }\n\n const resolution = resolveInvocationIdentity({\n claims: [...adapterClaims, ...(input.identityClaims ?? [])],\n provenance,\n fallback: {\n startedAt: clock.now(),\n workspace: input.workspace ?? unknownWorkspaceIdentity(),\n },\n consumerAttributes: privacy.sanitizeAttributes(input.consumerAttributes ?? {}),\n });\n\n if (resolution.status !== \"resolved\") {\n const reason: AttributionReason =\n resolution.status === \"conflict\" ? \"identity-conflict\" : \"identity-incomplete\";\n const detail =\n resolution.status === \"conflict\"\n ? `conflicting fields: ${resolution.conflicts.map((conflict) => conflict.field).join(\", \")}`\n : resolution.status === \"incomplete\"\n ? `missing fields: ${resolution.missing.join(\", \")}`\n : `invalid claims: ${resolution.issues.join(\"; \")}`;\n diagnostics.push(\n createErrorInfo({\n code: resolution.status === \"conflict\" ? \"identity-conflict\" : \"identity-incomplete\",\n phase: \"identity\",\n detail: detail.slice(0, 400),\n details: { \"provider.id\": detection.providerId },\n occurredAt: clock.now(),\n }),\n );\n logger.warn(\"attribution declined\", {\n \"identity.status\": resolution.status,\n \"provider.id\": detection.providerId,\n });\n return {\n ok: true,\n attribution: \"declined\",\n attributionReason: reason,\n providerId: detection.providerId,\n detectionConfidence: detection.confidence,\n events: [],\n usageObservations: [],\n emitted: 0,\n exportRejected: 0,\n durability: \"nothing-to-deliver\" as const,\n dropped: 0,\n hookResponse: hookResponseFor(adapter, detection, \"declined\", reason, 0, diagnostics),\n diagnostics,\n };\n }\n\n const identity = resolution.identity;\n\n /**\n * Result of the session-state critical section: either a finished outcome\n * (the adapter declined to produce events) or a batch ready to export.\n */\n type Prepared =\n | { readonly kind: \"early\"; readonly outcome: HookIngestOutcome }\n | {\n readonly kind: \"ready\";\n readonly batch: readonly CanonicalEvent[];\n readonly dropped: number;\n readonly targetHints?: ReadonlyMap<EventId, TargetHint>;\n };\n\n /**\n * Read this session's sequence, stamp a batch from it, derive usage against\n * the stored baselines, and commit the new sequence — as one unit.\n *\n * These are read-modify-write cycles on state shared by every process\n * handling the same session, and hook processes genuinely run concurrently\n * (a tool callback and a generation callback firing together). Unserialized,\n * two processes both read sequence *n*, both stamp events from *n*, and both\n * write *n + k*: the second batch reuses the first's sequence numbers, so\n * both derive the *same* event ids and a collector sees one event twice\n * while another is never numbered at all. The cumulative usage baseline\n * races the same way, and there the lost update is a wrong token delta\n * rather than a duplicate id.\n *\n * Export deliberately happens *after* this returns, outside the lock. Two\n * reasons, one correctness and one liveness: the span correlator takes this\n * same session lock from inside the sink, so exporting in here would be a\n * non-reentrant self-deadlock; and an unreachable collector must not hold a\n * session's state lock for the length of its timeout. Committing the\n * sequence before exporting means a failed export leaves a gap in the\n * numbering rather than a reused number — a gap is invisible to a\n * collector, a reused id is a corrupted trace.\n */\n const prepare = async (): Promise<Prepared> => {\n const sequenceBase = await readSequenceBase(identity.sessionId, diagnostics);\n\n let parsed;\n try {\n parsed = adapter.parse(\n { ...detectionInput, detection, identity, sequenceBase },\n providerContext,\n );\n } catch (thrown) {\n const info = errorInfoFromThrown(thrown, {\n code: \"provider-adapter-failure\",\n phase: \"parsing\",\n occurredAt: clock.now(),\n });\n diagnostics.push(info);\n return {\n kind: \"early\",\n outcome: {\n ok: true,\n attribution: \"failed\",\n attributionReason: \"adapter-failure\",\n providerId: detection.providerId,\n detectionConfidence: detection.confidence,\n identity,\n events: [],\n usageObservations: [],\n emitted: 0,\n exportRejected: 0,\n durability: \"nothing-to-deliver\" as const,\n dropped: 0,\n hookResponse: hookResponseFor(adapter, detection, \"failed\", \"adapter-failure\", 0, diagnostics),\n diagnostics,\n },\n };\n }\n\n if (parsed.status === \"ignored\") {\n logger.debug(\"adapter ignored input\", {\n \"provider.id\": detection.providerId,\n \"adapter.reason\": parsed.reason.slice(0, 160),\n });\n return {\n kind: \"early\",\n outcome: {\n ok: true,\n attribution: \"not-applicable\",\n attributionReason: \"adapter-ignored-input\",\n providerId: detection.providerId,\n detectionConfidence: detection.confidence,\n identity,\n events: [],\n usageObservations: [],\n emitted: 0,\n exportRejected: 0,\n durability: \"nothing-to-deliver\" as const,\n dropped: 0,\n hookResponse: hookResponseFor(\n adapter,\n detection,\n \"not-applicable\",\n \"adapter-ignored-input\",\n 0,\n diagnostics,\n ),\n diagnostics,\n },\n };\n }\n\n if (parsed.status === \"failed\") {\n diagnostics.push(parsed.error);\n return {\n kind: \"early\",\n outcome: {\n ok: true,\n attribution: \"failed\",\n attributionReason: \"adapter-failure\",\n providerId: detection.providerId,\n detectionConfidence: detection.confidence,\n identity,\n events: [],\n usageObservations: [],\n emitted: 0,\n exportRejected: 0,\n durability: \"nothing-to-deliver\" as const,\n dropped: 0,\n hookResponse: hookResponseFor(adapter, detection, \"failed\", \"adapter-failure\", 0, diagnostics),\n diagnostics,\n },\n };\n }\n\n if (parsed.warnings !== undefined && parsed.warnings.length > 0) {\n // An adapter reports a warning when it understood the payload but had to\n // decline part of it — a counter outside its declared capabilities, a\n // breakdown that disagrees with the total it itemizes. Not a diagnostic:\n // the observation is intact and nothing failed, so raising an error-severity\n // code would misreport a healthy invocation. But not nothing either, which\n // is what these were before: a harness whose attached field is being ignored\n // has no other way to find out.\n logger.warn(\"adapter declined part of the payload it understood\", {\n \"provider.id\": detection.providerId,\n \"adapter.warnings\": parsed.warnings.slice(0, 8).map((warning) => warning.slice(0, 200)),\n });\n }\n\n const screened = screenEvents(parsed.events, identity, sequenceBase, diagnostics);\n\n let batch: readonly CanonicalEvent[] = screened.kept;\n if (config.diagnostics.emitErrorEvents && diagnostics.length > 0) {\n batch = [...batch, ...buildErrorEvents(diagnostics, identity, sequenceBase + batch.length, ids, privacy)];\n }\n\n if (!suppress) {\n try {\n await deps.stateStore.write(sequenceKey(identity.sessionId), {\n kind: \"sequence\",\n next: sequenceBase + batch.length,\n });\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"state-store-failure\",\n phase: \"state\",\n occurredAt: clock.now(),\n }),\n );\n }\n }\n\n return {\n kind: \"ready\",\n batch,\n dropped: screened.dropped,\n ...(parsed.targetHints === undefined ? {} : { targetHints: parsed.targetHints }),\n };\n };\n\n let prepared: Prepared;\n try {\n prepared = await withOptionalSessionLock(deps.stateStore, identity.sessionId, prepare);\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"state-store-failure\",\n phase: \"state\",\n occurredAt: clock.now(),\n }),\n );\n\n if (!isStateLockContention(thrown)) {\n // The store cannot lock because it cannot be used at all — an unwritable\n // directory, a full disk. There is no peer inside the critical section\n // and no state to lose an update to, so the lock protects nothing here\n // and fail-open wins: process unlocked and export. Each individual read\n // and write inside still degrades to its own diagnostic.\n logger.warn(\"state store unusable; processing without session serialization\", {\n \"provider.id\": detection.providerId,\n });\n prepared = await prepare();\n } else {\n // Genuine contention. Proceeding unlocked would reintroduce exactly the\n // interleaving the lock exists to prevent, so the observation is declined\n // and said out loud — the provider still gets its protocol response, and a\n // caller holding a delivery claim releases it, turning a lock collision\n // into a retry rather than a corrupted sequence.\n //\n // A contended acquisition *cancels* its queued critical section\n // (`AsyncLock.run`), so this is now a provable statement rather than a\n // hopeful one: nothing was read, reserved, or written, which is what makes\n // the retry safe rather than a second half-application.\n logger.warn(\"session state lock contended; observation declined for retry\", {\n \"provider.id\": detection.providerId,\n });\n return {\n ok: true,\n attribution: \"failed\",\n attributionReason: \"internal-error\",\n providerId: detection.providerId,\n detectionConfidence: detection.confidence,\n identity,\n events: [],\n usageObservations: [],\n emitted: 0,\n // Nothing was exported, nothing was reserved, and nothing is on disk,\n // so the caller must see this as a total loss and retry it.\n exportRejected: 1,\n durability: \"lost\",\n dropped: 0,\n hookResponse: hookResponseFor(adapter, detection, \"failed\", \"internal-error\", 0, diagnostics),\n diagnostics,\n };\n }\n }\n\n if (prepared.kind === \"early\") {\n return prepared.outcome;\n }\n const { dropped } = prepared;\n let batch = prepared.batch;\n\n // Outside the session lock on purpose: this is filesystem I/O, bounded by\n // its own budget, and must not lengthen the critical section peers wait on.\n if (\n !suppress &&\n deps.worktreeLocator !== undefined &&\n prepared.targetHints !== undefined &&\n prepared.targetHints.size > 0\n ) {\n const targeted = await resolveEventTargets({\n events: batch,\n hints: prepared.targetHints,\n locator: deps.worktreeLocator,\n privacy,\n budgetMillis: deps.targetResolutionBudgetMillis ?? DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS,\n });\n batch = targeted.events;\n if (targeted.timedOut) {\n logger.debug(\"worktree target resolution exceeded its budget\", {\n \"provider.id\": detection.providerId,\n \"target.resolved\": targeted.resolved,\n });\n }\n }\n\n let emitted = 0;\n let exportRejected = 0;\n if (!suppress && batch.length > 0) {\n try {\n const result = await deps.sink.emit(batch);\n emitted = result.accepted;\n exportRejected = result.rejected;\n diagnostics.push(...result.errors);\n } catch (thrown) {\n // A throwing sink delivered nothing and spooled nothing.\n exportRejected = batch.length;\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"telemetry-export-failure\",\n phase: \"export\",\n occurredAt: clock.now(),\n }),\n );\n }\n }\n\n const durability = classifyDurability({\n attempted: !suppress && batch.length > 0,\n accepted: emitted,\n rejected: exportRejected,\n });\n\n /**\n * Usage accounting is the *commit* half of the transaction, so it runs here\n * and not in `prepare`.\n *\n * Deriving a delta advances the stored cumulative baseline, which is a\n * one-way move: once it points at this snapshot, the difference this callback\n * represented is no longer recoverable from state. Doing that before knowing\n * whether the telemetry survived means a fully rejected callback releases its\n * claim having *already* consumed its own usage — so the retry diffs against\n * the advanced baseline, reports roughly zero, and the tokens are gone. Delta\n * usage has the mirror-image failure: it needs no baseline, so a retry\n * accumulates the same delta a second time.\n *\n * Nothing exported depends on these numbers — a span carries the usage the\n * provider *reported*, never the derived delta — so deferring costs nothing\n * and buys exactly-once accounting. The read of the baseline, the diff, and\n * the write back all stay inside one critical section, so two concurrent\n * processes cannot both diff against the same snapshot.\n *\n * A suppressed redelivery and a fully rejected attempt both skip this\n * entirely, which is what leaves the baseline where the next real attempt\n * needs it.\n */\n let usageObservations: readonly UsageObservation[] = [];\n if (durability !== \"lost\" && !suppress && batch.length > 0) {\n try {\n usageObservations = await withOptionalSessionLock(\n deps.stateStore,\n identity.sessionId,\n () =>\n deriveUsage(\n batch,\n diagnostics,\n false,\n adapter.capabilities.cumulativeUsageSeries ?? \"event-scope\",\n ),\n );\n } catch (thrown) {\n // The accounting could not be committed. The telemetry is already out, so\n // this is a reporting gap rather than a lost observation: it is said out\n // loud and the callback stays committed, because retrying it would\n // re-export spans a collector has already accepted.\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"state-store-failure\",\n phase: \"state\",\n occurredAt: clock.now(),\n }),\n );\n logger.warn(\"usage accounting could not be committed for a delivered callback\", {\n \"provider.id\": detection.providerId,\n });\n }\n }\n\n return {\n ok: true,\n attribution: \"attributed\",\n providerId: detection.providerId,\n detectionConfidence: detection.confidence,\n identity,\n events: batch,\n usageObservations,\n emitted,\n exportRejected,\n durability,\n dropped,\n hookResponse: hookResponseFor(adapter, detection, \"attributed\", undefined, emitted, diagnostics),\n diagnostics,\n };\n } catch (thrown) {\n // Last line of defence: anything unanticipated becomes a diagnostic.\n const info = errorInfoFromThrown(thrown, { code: \"internal-error\", phase: \"parsing\" });\n diagnostics.push(info);\n logger.error(\"ingest contained an unexpected failure\", {\n \"error.code\": info.code,\n ...(info.details ?? {}),\n });\n return {\n ok: true,\n attribution: \"failed\",\n attributionReason: \"internal-error\",\n providerId: \"unknown\",\n detectionConfidence: \"none\",\n events: [],\n usageObservations: [],\n emitted: 0,\n exportRejected: 0,\n durability: \"nothing-to-deliver\" as const,\n dropped: 0,\n hookResponse: SILENT_HOOK_RESPONSE,\n diagnostics,\n };\n }\n };\n\n const flush = async (): Promise<void> => {\n try {\n await deps.sink.flush();\n } catch (thrown) {\n const info = errorInfoFromThrown(thrown, { code: \"telemetry-export-failure\", phase: \"export\" });\n logger.warn(\"flush failed\", { \"error.code\": info.code });\n }\n };\n\n const shutdown = async (): Promise<void> => {\n if (shutdownCompleted) {\n return;\n }\n shutdownCompleted = true;\n await flush();\n try {\n await deps.sink.shutdown();\n } catch (thrown) {\n const info = errorInfoFromThrown(thrown, {\n code: \"telemetry-export-failure\",\n phase: \"shutdown\",\n });\n logger.warn(\"shutdown failed\", { \"error.code\": info.code });\n }\n };\n\n return { resolveDelivery, ingest, flush, shutdown, config };\n};\n\nconst buildErrorEvents = (\n diagnostics: readonly OtelHookErrorInfo[],\n identity: InvocationIdentity,\n sequenceBase: number,\n ids: IdGenerator,\n privacy: PrivacyService,\n): readonly CanonicalEvent[] => {\n const events: CanonicalEvent[] = [];\n for (const [index, info] of diagnostics.slice(0, MAX_ERROR_EVENTS).entries()) {\n const sequence = sequenceBase + index;\n events.push({\n schemaVersion: CANONICAL_SCHEMA_VERSION,\n eventId: ids.newEventId({\n invocationId: identity.invocationId,\n sequence,\n eventType: \"error.raised\",\n discriminator: info.code,\n }),\n invocationId: identity.invocationId,\n sessionId: identity.sessionId,\n sequence,\n occurredAt: info.occurredAt ?? identity.startedAt,\n provenance: identity.provenance,\n workspace: identity.workspace,\n extensions: {},\n type: \"error.raised\",\n errorCode: info.code,\n severity: info.severity,\n phase: info.phase,\n retryable: info.retryable,\n // The message is already a fixed-vocabulary summary, but it still passes\n // through the privacy service so one policy governs every disclosure.\n message: privacy.describeContent({ kind: \"error-message\", text: info.message }),\n detail: info.code,\n });\n }\n return events;\n};\n","import { z } from \"zod\";\n\nimport { detectionConfidenceSchema, nonEmptyStringSchema } from \"../model/primitives.js\";\nimport {\n contentModeSchema,\n DEFAULT_PRIVACY_POLICY,\n privacyPolicySchema,\n} from \"../privacy/policy.js\";\nimport { EMPTY_RESOURCE_ATTRIBUTES, resourceAttributesSchema } from \"./resource-attributes.js\";\n\n/**\n * Policy for the OTLP logs signal.\n *\n * Two switches rather than one, because they answer different questions and an\n * operator needs to be able to answer them differently:\n *\n * - `enabled` — whether a second signal leaves this host at all. Off by default:\n * an installation that upgrades must not silently start sending a new stream to a\n * collector whose receivers, quotas, and retention were sized for traces.\n * - `includeContent` — whether *disclosed* text may appear in a log body. Also off\n * by default, and deliberately not the same knob as `privacy.contentMode`: spans\n * carry no content in any content mode, so an installation that set\n * `contentMode` to get a hash and a length has never had content on the wire.\n * Reusing that setting to also mean \"publish prompts\" would change what an\n * existing configuration discloses without anybody editing it.\n *\n * `raw` content additionally requires the pre-existing `privacy.allowRawContent`\n * opt-in, which the privacy service enforces before a fact is ever built and the\n * log mapping re-checks at the wire.\n */\nexport const logsPolicySchema = z.strictObject({\n enabled: z.boolean(),\n /**\n * Full URL for the logs signal.\n *\n * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes\n * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.\n */\n endpoint: z.string().url().max(2048).optional(),\n includeContent: z.boolean(),\n maxBatchSize: z.number().int().min(1).max(4096),\n});\nexport type LogsPolicy = z.infer<typeof logsPolicySchema>;\n\nexport const DEFAULT_LOGS_POLICY: LogsPolicy = Object.freeze({\n enabled: false,\n includeContent: false,\n maxBatchSize: 128,\n});\n\n/**\n * Runtime exporter policy.\n *\n * This describes *where and how* telemetry goes. It deliberately contains no\n * session, invocation, or workspace field: see ADR 0001. Mixing the two would\n * make identity globally reachable through configuration.\n */\nexport const exporterPolicySchema = z.strictObject({\n enabled: z.boolean(),\n protocol: z.enum([\"http/protobuf\", \"http/json\", \"none\"]),\n endpoint: z.string().url().max(2048).optional(),\n /**\n * Header names only. Values are supplied separately at construction time and\n * are never part of a resolved-config snapshot, which is logged and exported.\n */\n headerNames: z.array(nonEmptyStringSchema).max(32).readonly(),\n timeoutMillis: z.number().int().min(1).max(600_000),\n maxBatchSize: z.number().int().min(1).max(4096),\n maxQueueSize: z.number().int().min(1).max(65_536),\n maxRetryAttempts: z.number().int().min(0).max(10),\n serviceName: nonEmptyStringSchema,\n serviceNamespace: nonEmptyStringSchema.optional(),\n /**\n * Custom attributes merged into the exported OTLP Resource.\n *\n * Bounded and validated, and refusing `service.name`/`service.namespace`,\n * which are the two fields above. Distinct from an invocation's\n * `consumerAttributes`: this describes the emitting deployment, carries no\n * identity, and is the same for every span this process exports.\n */\n resourceAttributes: resourceAttributesSchema,\n /**\n * The logs signal. Nested under the exporter because it shares the endpoint,\n * headers, timeout, protocol, service identity, and resource attributes above —\n * a second top-level section would invite two of each to drift apart.\n */\n logs: logsPolicySchema,\n});\nexport type ExporterPolicy = z.infer<typeof exporterPolicySchema>;\n\nexport const detectionPolicySchema = z.strictObject({\n /** Detections below this confidence resolve to the unknown provider. */\n minimumConfidence: detectionConfidenceSchema,\n /** When false, an ambiguous detection is an error rather than unknown. */\n allowAmbiguousFallback: z.boolean(),\n /** Optional allow-list of provider ids; empty means \"any registered\". */\n allowedProviderIds: z.array(nonEmptyStringSchema).max(32).readonly(),\n});\nexport type DetectionPolicy = z.infer<typeof detectionPolicySchema>;\n\nexport const diagnosticsPolicySchema = z.strictObject({\n logLevel: z.enum([\"silent\", \"error\", \"warn\", \"info\", \"debug\"]),\n /** Emit `error.raised` events for contained failures. */\n emitErrorEvents: z.boolean(),\n});\nexport type DiagnosticsPolicy = z.infer<typeof diagnosticsPolicySchema>;\n\nexport const otelHookConfigSchema = z.strictObject({\n exporter: exporterPolicySchema,\n privacy: privacyPolicySchema,\n detection: detectionPolicySchema,\n diagnostics: diagnosticsPolicySchema,\n});\nexport type OtelHookConfig = z.infer<typeof otelHookConfigSchema>;\n\n/** Partial overlay accepted from a configuration layer. */\nexport const otelHookConfigPatchSchema = z.strictObject({\n // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:\n // merging happens per leaf, so a layer must be able to set `logs.enabled` alone\n // without also restating the endpoint and the batch size.\n exporter: exporterPolicySchema\n .omit({ logs: true })\n .partial()\n .extend({ logs: logsPolicySchema.partial().optional() })\n .optional(),\n privacy: privacyPolicySchema\n .omit({ limits: true })\n .partial()\n .extend({ limits: privacyPolicySchema.shape.limits.partial().optional() })\n .optional(),\n detection: detectionPolicySchema.partial().optional(),\n diagnostics: diagnosticsPolicySchema.partial().optional(),\n});\nexport type OtelHookConfigPatch = z.infer<typeof otelHookConfigPatchSchema>;\n\nexport const DEFAULT_EXPORTER_POLICY: ExporterPolicy = Object.freeze({\n enabled: true,\n protocol: \"http/protobuf\",\n headerNames: Object.freeze([]),\n timeoutMillis: 10_000,\n maxBatchSize: 128,\n maxQueueSize: 2048,\n maxRetryAttempts: 2,\n serviceName: \"coding-agent\",\n resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,\n logs: DEFAULT_LOGS_POLICY,\n});\n\nexport const DEFAULT_DETECTION_POLICY: DetectionPolicy = Object.freeze({\n minimumConfidence: \"strong\",\n allowAmbiguousFallback: true,\n allowedProviderIds: Object.freeze([]),\n});\n\nexport const DEFAULT_DIAGNOSTICS_POLICY: DiagnosticsPolicy = Object.freeze({\n logLevel: \"warn\",\n emitErrorEvents: true,\n});\n\nexport const DEFAULT_CONFIG: OtelHookConfig = Object.freeze({\n exporter: DEFAULT_EXPORTER_POLICY,\n privacy: DEFAULT_PRIVACY_POLICY,\n detection: DEFAULT_DETECTION_POLICY,\n diagnostics: DEFAULT_DIAGNOSTICS_POLICY,\n});\n\n/** Content mode is re-exported for callers building patches. */\nexport { contentModeSchema };\n","import { z } from \"zod\";\n\nimport { 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 { nonEmptyStringSchema } from \"./primitives.js\";\n\n/** What kind of conversational or tool content a fact describes. */\nexport const contentKindSchema = z.enum([\n \"prompt\",\n \"response\",\n \"reasoning\",\n \"tool-input\",\n \"tool-output\",\n \"error-message\",\n \"system-instruction\",\n \"attachment\",\n]);\nexport type ContentKind = z.infer<typeof contentKindSchema>;\n\nexport const contentRoleSchema = z.enum([\"user\", \"assistant\", \"system\", \"tool\", \"unknown\"]);\nexport type ContentRole = z.infer<typeof contentRoleSchema>;\n\n/**\n * How much of the original content this fact discloses.\n *\n * - `omitted`: no text at all (the default posture).\n * - `masked`: a shape-preserving mask; non-whitespace characters replaced.\n * - `redacted`: text with secret-looking spans replaced by a placeholder.\n * - `raw`: verbatim text. Only reachable through explicit opt-in.\n */\nexport const contentDisclosureSchema = z.enum([\"omitted\", \"masked\", \"redacted\", \"raw\"]);\nexport type ContentDisclosure = z.infer<typeof contentDisclosureSchema>;\n\nexport const CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;\n\n/**\n * A privacy-safe description of content.\n *\n * Lengths and a stable hash are always present so consumers can measure and\n * correlate volume without receiving the content itself. `text` is present only\n * when the resolved privacy policy allows disclosure, and is produced solely by\n * the central privacy service.\n */\nexport const contentFactSchema = z.strictObject({\n kind: contentKindSchema,\n role: contentRoleSchema.optional(),\n /** Unicode code point count of the original content. */\n characterLength: z.number().int().min(0),\n /** UTF-8 byte length of the original content. */\n byteLength: z.number().int().min(0),\n /** Stable salted digest of the original content. */\n contentHash: z.string().regex(CONTENT_HASH_PATTERN),\n disclosure: contentDisclosureSchema,\n /** Disclosed text, bounded by the privacy policy. Absent when omitted. */\n text: z.string().optional(),\n /** True when `text` was cut short by the configured string bound. */\n truncated: z.boolean(),\n /** Number of secret-looking spans replaced while producing `text`. */\n secretsRedacted: z.number().int().min(0),\n /** Optional non-sensitive label, e.g. a MIME type or tool name. */\n label: nonEmptyStringSchema.optional(),\n});\nexport type ContentFact = z.infer<typeof contentFactSchema>;\n\nexport const contentFactsSchema = z.array(contentFactSchema).max(64);\n\n/**\n * Guard used in tests and at the sink boundary: an omitted fact must not carry\n * text, and a disclosing fact must carry it.\n */\nexport const isContentFactConsistent = (fact: ContentFact): boolean =>\n fact.disclosure === \"omitted\" ? fact.text === undefined : fact.text !== undefined;\n\n/**\n * A fact for a content kind the event can carry when the provider sent no text.\n *\n * Always `omitted` with zero length, regardless of the installation's content\n * mode: there is nothing to mask, redact, or export.\n */\nexport const isUnavailableContentFact = (fact: ContentFact): boolean =>\n fact.disclosure === \"omitted\" &&\n fact.text === undefined &&\n fact.characterLength === 0 &&\n fact.byteLength === 0;\n","import { z } from \"zod\";\n\nimport {\n attributesSchema,\n detectionConfidenceSchema,\n DETECTION_CONFIDENCE_RANK,\n epochMillisSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n resolvedProviderIdSchema,\n sessionIdSchema,\n sourceTransportSchema,\n workspaceIdSchema,\n type DetectionConfidence,\n type InvocationId,\n type SessionId,\n type WorkspaceId,\n} from \"./primitives.js\";\n\n/**\n * Where a workspace identifier came from.\n *\n * Ordered from most to least stable. The source is recorded so consumers can\n * tell a repository-scoped identity from a directory-scoped one instead of\n * assuming they are comparable.\n */\nexport const workspaceKeySourceSchema = z.enum([\n \"git-remote\",\n \"git-root\",\n \"working-directory\",\n \"explicit\",\n \"unknown\",\n]);\nexport type WorkspaceKeySource = z.infer<typeof workspaceKeySourceSchema>;\n\n/**\n * Privacy-safe workspace identity.\n *\n * Only opaque handles and explicitly allowed labels are modelled. There is no\n * field for a filesystem path, so paths cannot be exported through this type.\n */\nexport const workspaceIdentitySchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n keySource: workspaceKeySourceSchema,\n /** Repository name only; never an owner path or URL with credentials. */\n repositoryName: nonEmptyStringSchema.optional(),\n vcsBranchName: nonEmptyStringSchema.optional(),\n /** Opaque handle for the checked-out revision. */\n vcsRevisionId: nonEmptyStringSchema.optional(),\n })\n .readonly();\nexport type WorkspaceIdentity = z.infer<typeof workspaceIdentitySchema>;\n\nexport const UNKNOWN_WORKSPACE_ID = \"unknown:0000000000000000\" as WorkspaceId;\n\nexport const unknownWorkspaceIdentity = (): WorkspaceIdentity =>\n workspaceIdentitySchema.parse({\n workspaceId: UNKNOWN_WORKSPACE_ID,\n keySource: \"unknown\",\n });\n\n/**\n * Provenance of an observation: which provider produced it and which adapter\n * interpreted it, with the confidence of that attribution.\n */\nexport const sourceProvenanceSchema = z\n .strictObject({\n providerId: resolvedProviderIdSchema,\n providerVersion: nonEmptyStringSchema.optional(),\n adapterId: nonEmptyStringSchema,\n adapterVersion: nonEmptyStringSchema,\n detectionConfidence: detectionConfidenceSchema,\n /** The provider's own name for the source event, e.g. a hook event name. */\n sourceEventName: nonEmptyStringSchema.optional(),\n transport: sourceTransportSchema,\n })\n .readonly();\nexport type SourceProvenance = z.infer<typeof sourceProvenanceSchema>;\n\n/**\n * Opaque, immutable metadata supplied by the embedding consumer.\n *\n * The library never interprets these values; it only carries and exports them.\n */\nexport const consumerAttributesSchema = attributesSchema.readonly();\nexport type ConsumerAttributes = z.infer<typeof consumerAttributesSchema>;\n\n/**\n * Immutable identity of a single hook invocation.\n *\n * Frozen on parse. There is deliberately no setter, no builder that mutates in\n * place, and no module-level instance: identity is passed explicitly so two\n * concurrent invocations can never observe each other's fields.\n */\nexport const invocationIdentitySchema = z\n .strictObject({\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Set when this invocation runs beneath another agent invocation. */\n parentInvocationId: invocationIdSchema.optional(),\n /** Root of the session tree when the provider exposes one. */\n rootSessionId: sessionIdSchema.optional(),\n /** Stable handle for the agent process/instance, when available. */\n agentInstanceId: nonEmptyStringSchema.optional(),\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n startedAt: epochMillisSchema,\n consumerAttributes: consumerAttributesSchema,\n })\n .readonly();\nexport type InvocationIdentity = z.infer<typeof invocationIdentitySchema>;\n\n/** Fields an identity claim may contribute. */\nexport const identityClaimFieldsSchema = z.strictObject({\n invocationId: invocationIdSchema.optional(),\n sessionId: sessionIdSchema.optional(),\n parentInvocationId: invocationIdSchema.optional(),\n rootSessionId: sessionIdSchema.optional(),\n agentInstanceId: nonEmptyStringSchema.optional(),\n workspace: workspaceIdentitySchema.optional(),\n startedAt: epochMillisSchema.optional(),\n});\nexport type IdentityClaimFields = z.infer<typeof identityClaimFieldsSchema>;\n\n/**\n * A claim about invocation identity from one source.\n *\n * Claims are evidence, not truth. Resolution keeps the highest-confidence claim\n * per field and refuses to merge disagreeing peers.\n */\nexport const identityClaimSchema = z.strictObject({\n /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */\n source: nonEmptyStringSchema,\n confidence: detectionConfidenceSchema,\n fields: identityClaimFieldsSchema,\n});\nexport type IdentityClaim = z.infer<typeof identityClaimSchema>;\n\nexport type IdentityConflict = {\n readonly field: keyof IdentityClaimFields;\n readonly confidence: DetectionConfidence;\n /** Rendered, non-sensitive representations of the disagreeing values. */\n readonly values: readonly string[];\n readonly sources: readonly string[];\n};\n\nexport type IdentityResolution =\n | { readonly status: \"resolved\"; readonly identity: InvocationIdentity }\n | {\n readonly status: \"conflict\";\n readonly conflicts: readonly IdentityConflict[];\n }\n | {\n readonly status: \"incomplete\";\n readonly missing: readonly (keyof IdentityClaimFields)[];\n }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nconst CLAIM_FIELDS = [\n \"invocationId\",\n \"sessionId\",\n \"parentInvocationId\",\n \"rootSessionId\",\n \"agentInstanceId\",\n \"workspace\",\n \"startedAt\",\n] as const satisfies readonly (keyof IdentityClaimFields)[];\n\nconst renderClaimValue = (value: unknown): string => {\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (value !== null && typeof value === \"object\" && \"workspaceId\" in value) {\n const { workspaceId } = value;\n return typeof workspaceId === \"string\" ? workspaceId : \"<workspace>\";\n }\n return \"<opaque>\";\n};\n\nexport type ResolveIdentityInput = {\n readonly claims: readonly IdentityClaim[];\n readonly provenance: SourceProvenance;\n /** Used only for fields no claim provides and that have a safe default. */\n readonly fallback?: {\n readonly startedAt?: number;\n readonly workspace?: WorkspaceIdentity;\n };\n readonly consumerAttributes?: Readonly<Record<string, unknown>>;\n};\n\n/**\n * Resolve identity from claims, failing closed.\n *\n * Rules:\n * 1. For each field, only claims at the highest confidence that provided it are\n * considered. Lower-confidence claims never fill in or override.\n * 2. Two distinct values at that highest confidence produce a `conflict`. The\n * invocation is then not attributed at all — a mislabelled session is worse\n * than a missing one.\n * 3. `invocationId` and `sessionId` are mandatory. Missing either yields\n * `incomplete`; neither is invented here.\n * 4. `startedAt` and `workspace` may come from an explicit fallback, because a\n * clock reading and an `unknown` workspace handle assert nothing false.\n */\nexport const resolveInvocationIdentity = (input: ResolveIdentityInput): IdentityResolution => {\n const parsedClaims: IdentityClaim[] = [];\n const issues: string[] = [];\n for (const [index, claim] of input.claims.entries()) {\n const parsed = identityClaimSchema.safeParse(claim);\n if (parsed.success) {\n parsedClaims.push(parsed.data);\n } else {\n issues.push(\n `claim[${index}]: ${parsed.error.issues.map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`).join(\", \")}`,\n );\n }\n }\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const conflicts: IdentityConflict[] = [];\n const selected: Record<string, unknown> = {};\n\n for (const field of CLAIM_FIELDS) {\n const contributors = parsedClaims.filter((claim) => claim.fields[field] !== undefined);\n if (contributors.length === 0) {\n continue;\n }\n const bestRank = Math.max(\n ...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence]),\n );\n const best = contributors.filter(\n (claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank,\n );\n const rendered = new Map<string, string[]>();\n for (const claim of best) {\n const key = JSON.stringify(claim.fields[field]);\n const sources = rendered.get(key) ?? [];\n sources.push(claim.source);\n rendered.set(key, sources);\n }\n if (rendered.size > 1) {\n const [firstBest] = best;\n conflicts.push({\n field,\n confidence: firstBest?.confidence ?? \"none\",\n values: best.map((claim) => renderClaimValue(claim.fields[field])),\n sources: best.map((claim) => claim.source),\n });\n continue;\n }\n const [winner] = best;\n if (winner !== undefined) {\n selected[field] = winner.fields[field];\n }\n }\n\n if (conflicts.length > 0) {\n return { status: \"conflict\", conflicts };\n }\n\n const missing: (keyof IdentityClaimFields)[] = [];\n if (selected.invocationId === undefined) {\n missing.push(\"invocationId\");\n }\n if (selected.sessionId === undefined) {\n missing.push(\"sessionId\");\n }\n if (missing.length > 0) {\n return { status: \"incomplete\", missing };\n }\n\n const startedAt = (selected.startedAt as number | undefined) ?? input.fallback?.startedAt;\n if (startedAt === undefined) {\n return { status: \"incomplete\", missing: [\"startedAt\"] };\n }\n const workspace =\n (selected.workspace as WorkspaceIdentity | undefined) ??\n input.fallback?.workspace ??\n unknownWorkspaceIdentity();\n\n const candidate = {\n invocationId: selected.invocationId as InvocationId,\n sessionId: selected.sessionId as SessionId,\n ...(selected.parentInvocationId === undefined\n ? {}\n : { parentInvocationId: selected.parentInvocationId as InvocationId }),\n ...(selected.rootSessionId === undefined\n ? {}\n : { rootSessionId: selected.rootSessionId as SessionId }),\n ...(selected.agentInstanceId === undefined\n ? {}\n : { agentInstanceId: selected.agentInstanceId as string }),\n provenance: input.provenance,\n workspace,\n startedAt,\n consumerAttributes: input.consumerAttributes ?? {},\n };\n\n const parsed = invocationIdentitySchema.safeParse(candidate);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n }\n return { status: \"resolved\", identity: parsed.data };\n};\n","import { z } from \"zod\";\n\n/**\n * Version of the canonical event model.\n *\n * Every emitted event carries this value. Consumers must treat an unknown\n * version as unreadable rather than guessing field semantics.\n *\n * Compatibility rules:\n * - Additive optional fields do not change the version.\n * - Renaming, removing, or re-interpreting a field increments the version.\n */\nexport const CANONICAL_SCHEMA_VERSION = 1 as const;\n\nexport type CanonicalSchemaVersion = typeof CANONICAL_SCHEMA_VERSION;\n\nexport const canonicalSchemaVersionSchema = z.literal(CANONICAL_SCHEMA_VERSION);\n","import { z } from \"zod\";\n\nimport type { AttributionOutcome, AttributionReason, OtelHookErrorInfo } from \"../errors/index.js\";\nimport { canonicalEventTypeSchema, type CanonicalEvent, type CanonicalEventType } from \"../model/events.js\";\nimport type { IdentityClaim, InvocationIdentity } from \"../model/identity.js\";\nimport type { TargetHint } from \"../model/target.js\";\nimport {\n detectionConfidenceSchema,\n nonEmptyStringSchema,\n providerIdSchema,\n resolvedProviderIdSchema,\n type EventId,\n type ProviderId,\n type ResolvedProviderId,\n type SourceTransport,\n} from \"../model/primitives.js\";\nimport { cacheCreationAccountingSchema, usageTemporalitySchema, type UsageTemporality } from \"../model/usage.js\";\nimport type { PrivacyLimits } from \"../privacy/policy.js\";\nimport type { PrivacyService } from \"../privacy/service.js\";\nimport type { Clock, IdGenerator, Logger } from \"../runtime/ports.js\";\n\n/** Raw input offered to adapters. `payload` is `unknown` on purpose. */\nexport type ProviderDetectionInput = {\n /** Decoded but uninterpreted provider payload. Must not escape the adapter. */\n readonly payload: unknown;\n readonly transport: SourceTransport;\n readonly environment: Readonly<Record<string, string | undefined>>;\n /** Caller's assertion of the provider, e.g. from a CLI flag. */\n readonly providerHint?: string;\n};\n\nexport const providerDetectionSchema = z.strictObject({\n providerId: resolvedProviderIdSchema,\n confidence: detectionConfidenceSchema,\n /**\n * Short, non-sensitive justifications, e.g. `\"payload.hook_event_name present\"`.\n * Reasons are exported in diagnostics, so they must not quote payload values.\n */\n reasons: z.array(z.string().min(1).max(160)).max(8),\n providerVersion: nonEmptyStringSchema.optional(),\n /** The provider's own name for this event, when the payload states one. */\n sourceEventName: nonEmptyStringSchema.optional(),\n});\nexport type ProviderDetection = z.infer<typeof providerDetectionSchema>;\n\n/**\n * How much of a provider's hook traffic carries an identifier that survives a\n * redelivery.\n *\n * - `none`: no callback carries one. Redelivery is undetectable from the\n * payload, and deduplication needs a host-supplied delivery id.\n * - `partial`: some callbacks do and some do not — typically per-tool-call and\n * per-turn events do, while session and compaction edges do not.\n * - `all`: every callback the adapter recognizes carries one.\n *\n * Declared rather than probed for the same reason as the usage capabilities\n * below: \"this callback has no stable id\" and \"this adapter never looked\" are\n * indistinguishable downstream, and only the first is safe to build on.\n */\nexport const deliveryIdentifierSupportSchema = z.enum([\"none\", \"partial\", \"all\"]);\nexport type DeliveryIdentifierSupport = z.infer<typeof deliveryIdentifierSupportSchema>;\n\n/**\n * Shape a delivery-identity component must have.\n *\n * Deliberately narrow. Provider identifiers, integer counters, hook event\n * names, and ISO-8601 timestamps all satisfy it; prose and filesystem paths do\n * not, because neither spaces nor `/` are allowed. So an adapter that\n * accidentally seeds a delivery identity with a prompt, a tool response, or a\n * home directory produces a *rejected claim* rather than a privacy incident —\n * the guard is structural, not a review convention.\n */\nexport const DELIVERY_COMPONENT_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;\n\nexport const deliveryComponentSchema = z\n .string()\n .regex(\n DELIVERY_COMPONENT_PATTERN,\n \"delivery component must be identifier-shaped: no whitespace, no path separators\",\n );\n\n/** Most identifier-shaped fields one callback identity may be built from. */\nexport const MAX_DELIVERY_COMPONENTS = 8;\n\n/**\n * An adapter's assertion that this callback has a replay-stable identity.\n *\n * The adapter reports *components* rather than a finished id: it knows which\n * payload fields are trustworthy, and the runtime owns how they are combined,\n * scoped, and digested. That split is what keeps a raw provider identifier from\n * becoming an on-disk key or a diagnostic attribute (see\n * `resolveDeliveryIdentity`).\n *\n * Returning nothing is always safe. Claiming an identity that is not actually\n * stable is not: it makes the runtime suppress a *genuine* second callback as if\n * it were a redelivery, which silently loses telemetry.\n */\nexport const providerDeliveryClaimSchema = z.strictObject({\n /**\n * The provider's own session/conversation id. Scopes the callback identity, so\n * two sessions reusing one tool-call id never collide.\n */\n sessionId: nonEmptyStringSchema,\n /** The provider's own name for this callback, e.g. `PostToolUse`. */\n sourceEventName: deliveryComponentSchema,\n /**\n * Identifier-shaped payload fields that, together with `sourceEventName`,\n * name this callback within the session exactly once.\n */\n components: z.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),\n /**\n * Short, non-sensitive justifications, e.g. `\"payload.tool_use_id names one\n * tool call\"`. Evidence reaches diagnostics, so it must name fields, never\n * quote their values.\n */\n evidence: z.array(z.string().min(1).max(160)).min(1).max(4).readonly(),\n});\nexport type ProviderDeliveryClaim = z.infer<typeof providerDeliveryClaimSchema>;\n\n/**\n * Shape a per-callback delivery *gap* explanation must have.\n *\n * These strings reach a diagnostic, so the same reasoning that constrains\n * {@link deliveryComponentSchema} applies for the opposite purpose: a component\n * must be identifier-shaped, a gap reason must be prose that cannot smuggle a\n * filesystem path or a newline-delimited payload dump into stderr. Spaces are\n * allowed — it is a sentence — and `/`, `\\`, and control characters are not,\n * which is what keeps a home directory out of a message an adapter author writes\n * by hand.\n */\nexport const DELIVERY_GAP_REASON_PATTERN = /^[^\\n\\r\\t\\\\/]{1,240}$/;\n\nexport const deliveryGapReasonSchema = z\n .string()\n .regex(\n DELIVERY_GAP_REASON_PATTERN,\n \"delivery gap reason must be one line of prose: no path separators, no control characters\",\n );\n\n/** Most callbacks one adapter may document a delivery gap for. */\nexport const MAX_DELIVERY_GAPS = 48;\n\n/**\n * Why each of an adapter's callbacks carries no replay-stable identity.\n *\n * Keyed by the provider's *own* event name — the same value `detect` reports as\n * `sourceEventName` — so the runtime can look up the reason for the callback in\n * front of it without parsing the payload a second time.\n *\n * This exists because `callback-not-identifiable` on its own is a true statement\n * that helps nobody: an operator auditing coverage with `--require-callback-id`\n * needs to know *which* callback and *what field would have to exist*, and only\n * the adapter knows that. Keeping it declarative rather than computed means the\n * answer is reviewable next to the protocol it describes, and an exhaustiveness\n * test can insist that adding a hook event without deciding its delivery status\n * reads as an omission.\n */\nexport const providerDeliveryGapsSchema = z\n .record(deliveryComponentSchema, deliveryGapReasonSchema)\n .refine((gaps) => Object.keys(gaps).length <= MAX_DELIVERY_GAPS, {\n message: `at most ${String(MAX_DELIVERY_GAPS)} delivery gaps may be declared`,\n });\nexport type ProviderDeliveryGaps = z.infer<typeof providerDeliveryGapsSchema>;\n\n/**\n * What an adapter can actually observe.\n *\n * Capabilities are declared rather than probed so consumers can distinguish\n * \"this provider reports no cached tokens\" from \"this session used no cache\" —\n * the two look identical in the data.\n */\nexport const providerCapabilitiesSchema = z.strictObject({\n /** Event types the adapter can produce. */\n lifecycleEvents: z.array(canonicalEventTypeSchema).max(32).readonly(),\n usageTemporality: usageTemporalitySchema,\n /**\n * Which accumulator series a `cumulative` report continues — that is, which\n * previous snapshot the next one should be diffed against.\n *\n * Only meaningful when `usageTemporality` is `cumulative`; omit otherwise.\n *\n * - `event-scope` (the default when omitted) — each event scope keeps its own\n * running total, so a `generation.end` snapshot is diffed against the\n * previous snapshot *for that same generation*.\n * - `session-lifetime` — the provider maintains **one** running total for the\n * whole session and stamps it onto whichever callback happens to report it.\n * Diffing such a snapshot per event scope would restart the baseline on\n * every new generation id and re-count the entire session total each turn,\n * so session-level and generation-level snapshots share one baseline.\n * Subagent snapshots keep their own series regardless: a delegated agent's\n * counter is not a point on the parent session's curve.\n */\n cumulativeUsageSeries: z.enum([\"event-scope\", \"session-lifetime\"]).optional(),\n reportsCachedInput: z.boolean(),\n reportsCacheCreation: z.boolean(),\n cacheCreationAccounting: cacheCreationAccountingSchema,\n reportsReasoningOutput: z.boolean(),\n reportsProviderTotal: z.boolean(),\n reportsCost: z.boolean(),\n emitsSubagentEvents: z.boolean(),\n emitsCompactionEvents: z.boolean(),\n /** True when the provider reads a structured response from stdout. */\n requiresHookResponse: z.boolean(),\n /** How much of this provider's hook traffic is replay-identifiable. */\n deliveryIdentifier: deliveryIdentifierSupportSchema,\n});\nexport type ProviderCapabilities = z.infer<typeof providerCapabilitiesSchema>;\n\n/** Services an adapter is given. Note the absence of a filesystem or network. */\nexport type ProviderContext = {\n readonly privacy: PrivacyService;\n readonly clock: Clock;\n readonly ids: IdGenerator;\n readonly logger: Logger;\n readonly limits: PrivacyLimits;\n};\n\nexport type ProviderIdentityInput = ProviderDetectionInput & {\n readonly detection: ProviderDetection;\n};\n\nexport type ProviderParseInput = ProviderDetectionInput & {\n readonly detection: ProviderDetection;\n /** Resolved by the core; adapters never resolve identity themselves. */\n readonly identity: InvocationIdentity;\n /**\n * First sequence number the adapter may use. Sequences must be assigned\n * consecutively from here so event ids stay stable across replays.\n */\n readonly sequenceBase: number;\n};\n\nexport type ProviderParseResult =\n | {\n readonly status: \"parsed\";\n readonly events: readonly CanonicalEvent[];\n readonly warnings?: readonly string[];\n /**\n * Where tool events pointed, keyed by event id (ADR 0008). The one\n * canonical value that carries local paths: the core resolves each into\n * the event's `target` and discards it. Use `EventFactory.targetHints()`.\n */\n readonly targetHints?: ReadonlyMap<EventId, TargetHint>;\n }\n /** The input was recognized but carries no telemetry. Not an error. */\n | { readonly status: \"ignored\"; readonly reason: string }\n | { readonly status: \"failed\"; readonly error: OtelHookErrorInfo };\n\nexport const providerHookResponseSchema = z.strictObject({\n /**\n * Always 0. A telemetry hook that can fail the host agent is a liability, so\n * the type forbids expressing anything else (ADR 0004).\n */\n exitCode: z.literal(0),\n /** Protocol response text. Omit to write nothing at all. */\n stdout: z.string().max(8192).optional(),\n /** Non-sensitive diagnostic text for stderr. */\n stderr: z.string().max(8192).optional(),\n /** Declares which of the two stdout contracts this response follows. */\n contract: z.enum([\"silent\", \"provider-protocol\"]),\n});\nexport type ProviderHookResponse = z.infer<typeof providerHookResponseSchema>;\n\n/** The silent response: nothing on stdout, success to the host. */\nexport const SILENT_HOOK_RESPONSE: ProviderHookResponse = Object.freeze({\n exitCode: 0 as const,\n contract: \"silent\" as const,\n});\n\nexport type ProviderHookResponseInput = {\n readonly attribution: AttributionOutcome;\n readonly attributionReason?: AttributionReason;\n readonly detection?: ProviderDetection;\n readonly emittedEvents: number;\n readonly errors: readonly OtelHookErrorInfo[];\n};\n\n/**\n * Contract every provider adapter implements.\n *\n * The four methods are deliberately separate: detection must be cheap and\n * side-effect free, identity must be expressible as claims the core can\n * arbitrate, parsing must be the only place that reads the payload, and the hook\n * response must be derivable from the outcome alone.\n */\nexport interface ProviderAdapter {\n readonly id: ProviderId;\n readonly version: string;\n readonly capabilities: ProviderCapabilities;\n /**\n * Report whether this adapter recognizes the input. Must not throw; must not\n * read files or the network. Return `none` rather than guessing.\n */\n detect(input: ProviderDetectionInput, context: ProviderContext): ProviderDetection;\n /**\n * Contribute identity claims. Returning fewer claims is always safe;\n * fabricating a session id is not.\n */\n identify(input: ProviderIdentityInput, context: ProviderContext): readonly IdentityClaim[];\n /**\n * Report this callback's replay-stable identity, when the payload carries one.\n *\n * Called before `parse`, must be cheap and side-effect free, and must not\n * throw. Return `undefined` whenever the payload's identifying fields are\n * absent or would not survive a redelivery — under-reporting costs\n * deduplication, over-reporting loses real telemetry.\n */\n deliveryIdentity?(\n input: ProviderIdentityInput,\n context: ProviderContext,\n ): ProviderDeliveryClaim | undefined;\n /**\n * Why each callback that {@link ProviderAdapter.deliveryIdentity} declines\n * carries no replay-stable identity, keyed by the provider's own event name.\n *\n * Static data, not control flow: it never decides whether a callback is\n * deduplicated, only what the runtime can *say* when it is not. An adapter that\n * declares `deliveryIdentifier: \"none\"` should still populate this — the gap is\n * then the whole story, and \"the protocol has no request id\" is a far more\n * actionable diagnostic than \"not identifiable\".\n */\n readonly deliveryGaps?: ProviderDeliveryGaps;\n /** Interpret the payload into canonical events. */\n parse(input: ProviderParseInput, context: ProviderContext): ProviderParseResult;\n /** Provider-specific hook response for the given outcome. */\n hookResponse(input: ProviderHookResponseInput, context: ProviderContext): ProviderHookResponse;\n}\n\nexport const adapterSupports = (\n adapter: ProviderAdapter,\n eventType: CanonicalEventType,\n): boolean => adapter.capabilities.lifecycleEvents.includes(eventType);\n\nexport type AdapterDescription = {\n readonly id: ResolvedProviderId;\n readonly version: string;\n readonly lifecycleEvents: readonly string[];\n readonly usageTemporality: UsageTemporality;\n readonly deliveryIdentifier: DeliveryIdentifierSupport;\n};\n\nexport const describeAdapter = (adapter: ProviderAdapter): AdapterDescription => ({\n id: adapter.id,\n version: adapter.version,\n lifecycleEvents: [...adapter.capabilities.lifecycleEvents],\n usageTemporality: adapter.capabilities.usageTemporality,\n deliveryIdentifier: adapter.capabilities.deliveryIdentifier,\n});\n\n/**\n * Ask an adapter for a delivery claim, containing anything it does wrong.\n *\n * A `deliveryIdentity` that throws, or that returns a claim the schema rejects\n * (a component carrying prose, more components than the cap), degrades to \"no\n * stable identity available\" rather than failing the invocation: deduplication\n * is an optimization, and the host's telemetry is not.\n */\nexport const readDeliveryClaim = (\n adapter: ProviderAdapter,\n input: ProviderIdentityInput,\n context: ProviderContext,\n): { readonly claim?: ProviderDeliveryClaim; readonly rejection?: string } => {\n if (adapter.deliveryIdentity === undefined) {\n return {};\n }\n let candidate: ProviderDeliveryClaim | undefined;\n try {\n candidate = adapter.deliveryIdentity(input, context);\n } catch {\n return { rejection: `adapter ${adapter.id} threw while reporting a delivery identity` };\n }\n if (candidate === undefined) {\n return {};\n }\n const parsed = providerDeliveryClaimSchema.safeParse(candidate);\n if (!parsed.success) {\n return {\n rejection: `adapter ${adapter.id} reported a malformed delivery identity: ${parsed.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`)\n .join(\"; \")}`.slice(0, 240),\n };\n }\n return { claim: parsed.data };\n};\n\n/**\n * Look up why this callback has no replay-stable identity, containing anything\n * the adapter got wrong.\n *\n * Validated on the way out rather than trusted, for the same reason a claim is:\n * the string ends up in a diagnostic an operator reads, and an adapter that pasted\n * a path or a payload excerpt into its own gap table must produce *no detail*\n * rather than a disclosure. Returning `undefined` costs a sentence of explanation\n * and nothing else — the reason code is reported either way.\n */\nexport const readDeliveryGap = (\n adapter: ProviderAdapter,\n sourceEventName: string | undefined,\n): string | undefined => {\n if (sourceEventName === undefined || adapter.deliveryGaps === undefined) {\n return undefined;\n }\n // A prototype-polluting event name must not reach a bare property read: the\n // event name comes from a payload, and `__proto__` is a string like any other.\n if (!Object.prototype.hasOwnProperty.call(adapter.deliveryGaps, sourceEventName)) {\n return undefined;\n }\n const parsed = deliveryGapReasonSchema.safeParse(adapter.deliveryGaps[sourceEventName]);\n return parsed.success ? parsed.data : undefined;\n};\n\nexport const asProviderId = (value: string): ProviderId => providerIdSchema.parse(value);\n\nexport const unknownDetection = (\n reasons: readonly string[] = [\"no adapter recognized the input\"],\n): ProviderDetection =>\n providerDetectionSchema.parse({\n providerId: \"unknown\",\n confidence: \"none\",\n reasons: reasons.slice(0, 8),\n });\n","import { z } from \"zod\";\n\nimport {\n errorPhaseSchema,\n errorSeveritySchema,\n otelHookErrorCodeSchema,\n} from \"../errors/taxonomy.js\";\nimport { contentFactSchema, contentFactsSchema } from \"./content.js\";\nimport { extensionsSchema, emptyExtensions } from \"./extensions.js\";\nimport { sourceProvenanceSchema, workspaceIdentitySchema } from \"./identity.js\";\nimport { subagentIdSchema, workspaceTargetSchema } from \"./target.js\";\nimport {\n durationMillisSchema,\n epochMillisSchema,\n eventIdSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n sequenceNumberSchema,\n sessionIdSchema,\n tokenCountSchema,\n} from \"./primitives.js\";\nimport { canonicalUsageSchema, type CanonicalUsage } from \"./usage.js\";\nimport { canonicalSchemaVersionSchema } from \"./version.js\";\n\n/** Model being invoked. Model identifiers are not treated as sensitive. */\nexport const modelDescriptorSchema = z.strictObject({\n modelId: nonEmptyStringSchema,\n /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */\n vendor: nonEmptyStringSchema.optional(),\n family: nonEmptyStringSchema.optional(),\n});\nexport type ModelDescriptor = z.infer<typeof modelDescriptorSchema>;\n\nexport const costFactsSchema = z.strictObject({\n /** ISO 4217 code. */\n currency: z.string().length(3),\n amount: z.number().min(0).finite(),\n source: z.enum([\"provider-reported\", \"computed\"]),\n});\nexport type CostFacts = z.infer<typeof costFactsSchema>;\n\nexport const canonicalEventTypeSchema = z.enum([\n \"session.start\",\n \"session.end\",\n \"prompt.submitted\",\n \"generation.start\",\n \"generation.end\",\n \"tool.start\",\n \"tool.end\",\n \"subagent.start\",\n \"subagent.end\",\n \"compaction.performed\",\n \"error.raised\",\n]);\nexport type CanonicalEventType = z.infer<typeof canonicalEventTypeSchema>;\n\nexport const CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;\n\nconst outcomeSchema = z.enum([\"ok\", \"error\", \"cancelled\", \"timeout\", \"denied\", \"unknown\"]);\nexport type EventOutcome = z.infer<typeof outcomeSchema>;\n\n/**\n * Fields present on every canonical event.\n *\n * Identity fields are duplicated onto each event rather than referenced through\n * shared state, so an event is self-describing once it leaves the process.\n */\nconst baseEventFields = {\n schemaVersion: canonicalSchemaVersionSchema,\n eventId: eventIdSchema,\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Per-invocation ordering key. Stable across replays of the same input. */\n sequence: sequenceNumberSchema,\n occurredAt: epochMillisSchema,\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n /**\n * The provider's own id for the subagent this event was emitted inside (e.g.\n * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event\n * factory, never by hand.\n */\n subagentId: subagentIdSchema.optional(),\n extensions: extensionsSchema.default(emptyExtensions),\n} as const;\n\nconst event = <TShape extends z.ZodRawShape>(shape: TShape) =>\n z.strictObject({ ...baseEventFields, ...shape });\n\nexport const sessionStartEventSchema = event({\n type: z.literal(\"session.start\"),\n sessionKind: z.enum([\"interactive\", \"non-interactive\", \"unknown\"]),\n agentName: nonEmptyStringSchema.optional(),\n agentVersion: nonEmptyStringSchema.optional(),\n model: modelDescriptorSchema.optional(),\n});\n\nexport const sessionEndEventSchema = event({\n type: z.literal(\"session.end\"),\n reason: z.enum([\"completed\", \"aborted\", \"error\", \"timeout\", \"unknown\"]),\n durationMillis: durationMillisSchema.optional(),\n /** Session totals, typically cumulative. */\n usage: canonicalUsageSchema.optional(),\n cost: costFactsSchema.optional(),\n});\n\nexport const promptSubmittedEventSchema = event({\n type: z.literal(\"prompt.submitted\"),\n promptSource: z.enum([\"user\", \"automation\", \"resumed\", \"unknown\"]),\n content: contentFactSchema.optional(),\n turnIndex: z.number().int().min(0).optional(),\n});\n\nexport const generationStartEventSchema = event({\n type: z.literal(\"generation.start\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n requestedMaxOutputTokens: tokenCountSchema.optional(),\n inputContent: contentFactsSchema.optional(),\n});\n\nexport const generationEndEventSchema = event({\n type: z.literal(\"generation.end\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n outcome: outcomeSchema,\n stopReason: nonEmptyStringSchema.optional(),\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n cost: costFactsSchema.optional(),\n outputContent: contentFactsSchema.optional(),\n});\n\nexport const toolKindSchema = z.enum([\n \"read\",\n \"write\",\n \"execute\",\n \"search\",\n \"network\",\n \"delegate\",\n \"other\",\n \"unknown\",\n]);\nexport type ToolKind = z.infer<typeof toolKindSchema>;\n\nexport const toolStartEventSchema = event({\n type: z.literal(\"tool.start\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n toolKind: toolKindSchema,\n generationId: nonEmptyStringSchema.optional(),\n input: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const toolEndEventSchema = event({\n type: z.literal(\"tool.end\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n /** Present when the host asked for or recorded a permission decision. */\n permissionDecision: z.enum([\"allowed\", \"denied\", \"deferred\", \"not-required\"]).optional(),\n output: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const subagentStartEventSchema = event({\n type: z.literal(\"subagent.start\"),\n subagentInvocationId: invocationIdSchema,\n subagentType: nonEmptyStringSchema.optional(),\n /** 0 for the top-level agent; 1 for its direct children. */\n delegationDepth: z.number().int().min(0).max(64),\n model: modelDescriptorSchema.optional(),\n});\n\nexport const subagentEndEventSchema = event({\n type: z.literal(\"subagent.end\"),\n subagentInvocationId: invocationIdSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const compactionPerformedEventSchema = event({\n type: z.literal(\"compaction.performed\"),\n trigger: z.enum([\"automatic\", \"manual\", \"unknown\"]),\n /** Provider-reported context size before and after compaction, if known. */\n contextTokensBefore: tokenCountSchema.optional(),\n contextTokensAfter: tokenCountSchema.optional(),\n droppedMessageCount: z.number().int().min(0).optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const errorRaisedEventSchema = event({\n type: z.literal(\"error.raised\"),\n errorCode: otelHookErrorCodeSchema,\n severity: errorSeveritySchema,\n phase: errorPhaseSchema,\n retryable: z.boolean(),\n /** Error text is content: it is described, never embedded verbatim by default. */\n message: contentFactSchema.optional(),\n /** Non-sensitive, provider-agnostic short label. */\n detail: nonEmptyStringSchema.optional(),\n});\n\nexport const canonicalEventSchema = z.discriminatedUnion(\"type\", [\n sessionStartEventSchema,\n sessionEndEventSchema,\n promptSubmittedEventSchema,\n generationStartEventSchema,\n generationEndEventSchema,\n toolStartEventSchema,\n toolEndEventSchema,\n subagentStartEventSchema,\n subagentEndEventSchema,\n compactionPerformedEventSchema,\n errorRaisedEventSchema,\n]);\n\nexport type CanonicalEvent = z.infer<typeof canonicalEventSchema>;\nexport type CanonicalEventInput = z.input<typeof canonicalEventSchema>;\n\nexport type SessionStartEvent = z.infer<typeof sessionStartEventSchema>;\nexport type SessionEndEvent = z.infer<typeof sessionEndEventSchema>;\nexport type PromptSubmittedEvent = z.infer<typeof promptSubmittedEventSchema>;\nexport type GenerationStartEvent = z.infer<typeof generationStartEventSchema>;\nexport type GenerationEndEvent = z.infer<typeof generationEndEventSchema>;\nexport type ToolStartEvent = z.infer<typeof toolStartEventSchema>;\nexport type ToolEndEvent = z.infer<typeof toolEndEventSchema>;\nexport type SubagentStartEvent = z.infer<typeof subagentStartEventSchema>;\nexport type SubagentEndEvent = z.infer<typeof subagentEndEventSchema>;\nexport type CompactionPerformedEvent = z.infer<typeof compactionPerformedEventSchema>;\nexport type ErrorRaisedEvent = z.infer<typeof errorRaisedEventSchema>;\n\nexport type CanonicalEventOfType<TType extends CanonicalEventType> = Extract<\n CanonicalEvent,\n { type: TType }\n>;\n\nexport type EventValidationResult =\n | { readonly status: \"ok\"; readonly event: CanonicalEvent }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nexport const validateCanonicalEvent = (value: unknown): EventValidationResult => {\n const parsed = canonicalEventSchema.safeParse(value);\n if (parsed.success) {\n return { status: \"ok\", event: parsed.data };\n }\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n};\n\n/** Parse or throw. Intended for fixtures and tests, not the hook path. */\nexport const parseCanonicalEvent = (value: unknown): CanonicalEvent =>\n canonicalEventSchema.parse(value);\n\n/** Usage carried by an event, if the event type can carry any. */\nexport const eventUsage = (event: CanonicalEvent): CanonicalUsage | undefined =>\n \"usage\" in event ? event.usage : undefined;\n\n/** Stable ordering: by sequence, then by timestamp, then by event id. */\nexport const compareEvents = (a: CanonicalEvent, b: CanonicalEvent): number =>\n a.sequence - b.sequence || a.occurredAt - b.occurredAt || a.eventId.localeCompare(b.eventId);\n","import { z } from \"zod\";\n\nimport { nonEmptyStringSchema, workspaceIdSchema } from \"./primitives.js\";\n\n/**\n * Per-event workspace targeting (ADR 0008).\n *\n * A session's `workspace` is where the agent was *started*. An agent routinely\n * works somewhere else — in a linked git worktree beside the checkout it was\n * launched from — and the session-level identity cannot show that. A tool event\n * can: the file it edited, or the directory its shell command ran in, names the\n * worktree it actually touched.\n *\n * Two values model that, and the split between them is the privacy boundary:\n *\n * - {@link TargetHint} is what an adapter observed — local paths. It is an\n * in-process value only: it is never part of a {@link CanonicalEvent}, never\n * persisted, never exported. The core resolves it and drops it.\n * - {@link WorkspaceTarget} is what the core resolved — a salted worktree handle,\n * the checked-out branch, and what the evidence was. It travels on the event.\n */\n\n/**\n * What a target was derived from, strongest evidence first.\n *\n * - `tool-path` — a path the tool call itself named (an edited or read file, a\n * patch header).\n * - `shell-cwd` — the working directory the provider reports a shell command ran in.\n * - `session-cwd` — only the session's own directory was known; the event may\n * have reached elsewhere (e.g. a shell `cd`) without the provider saying so.\n */\nexport const targetSourceSchema = z.enum([\"tool-path\", \"shell-cwd\", \"session-cwd\"]);\nexport type TargetSource = z.infer<typeof targetSourceSchema>;\n\n/** Most paths one hint may name; a bound, not a sampling rule (all must agree). */\nexport const MAX_TARGET_HINT_PATHS = 8;\n\n/** Longest local path a hint may carry. Longer input is dropped, never truncated. */\nexport const MAX_TARGET_PATH_LENGTH = 4096;\n\nconst localPathSchema = z\n .string()\n .min(1)\n .max(MAX_TARGET_PATH_LENGTH)\n .refine((value) => !value.includes(\"\\u0000\"), \"path must not contain NUL\");\n\n/**\n * An adapter's observation of where a tool event pointed. **Carries local paths**\n * — in-process only, see the module note.\n *\n * Every path in one hint must resolve to the same worktree, or the event gets no\n * target at all: a patch touching two worktrees did not target either of them.\n */\nexport const targetHintSchema = z\n .strictObject({\n source: targetSourceSchema,\n paths: z.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),\n /** Absolute directory that relative `paths` resolve against. */\n baseDirectory: localPathSchema.optional(),\n })\n .readonly();\nexport type TargetHint = z.infer<typeof targetHintSchema>;\n\n/**\n * The git worktree a tool event targeted. Exported; carries no path.\n *\n * `workspaceId` is derived exactly like a `git-root` workspace identity, so a\n * consumer holding the same salt can match it against one it derived itself.\n */\nexport const workspaceTargetSchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n /** Branch checked out in that worktree; absent on a detached HEAD. */\n vcsBranchName: nonEmptyStringSchema.optional(),\n source: targetSourceSchema,\n })\n .readonly();\nexport type WorkspaceTarget = z.infer<typeof workspaceTargetSchema>;\n\n/**\n * Shape a provider's own subagent identifier must have to be exported.\n *\n * Identifier-shaped on purpose — no whitespace, no path separators — so a\n * malformed payload field cannot carry prose or a path onto the wire under an id\n * attribute. A value that does not fit is dropped, not repaired.\n */\nexport const SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;\nexport const subagentIdSchema = z.string().regex(SUBAGENT_ID_PATTERN);\nexport type SubagentId = z.infer<typeof subagentIdSchema>;\n","import type { DetectionPolicy } from \"../config/schema.js\";\nimport { createErrorInfo, errorInfoFromThrown, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport {\n DETECTION_CONFIDENCE_RANK,\n type ProviderId,\n} from \"../model/primitives.js\";\nimport {\n providerDetectionSchema,\n unknownDetection,\n type ProviderAdapter,\n type ProviderContext,\n type ProviderDetection,\n type ProviderDetectionInput,\n} from \"./adapter.js\";\n\nexport type DetectionCandidate = {\n readonly adapter: ProviderAdapter;\n readonly detection: ProviderDetection;\n};\n\nexport type RegistryDetectionResult =\n | {\n readonly status: \"selected\";\n readonly adapter: ProviderAdapter;\n readonly detection: ProviderDetection;\n readonly candidates: readonly DetectionCandidate[];\n readonly errors: readonly OtelHookErrorInfo[];\n }\n | {\n readonly status: \"unknown\";\n readonly reason:\n | \"no-adapters-registered\"\n | \"no-candidates\"\n | \"below-minimum-confidence\"\n | \"provider-not-allowed\";\n readonly detection: ProviderDetection;\n readonly candidates: readonly DetectionCandidate[];\n readonly errors: readonly OtelHookErrorInfo[];\n }\n | {\n readonly status: \"ambiguous\";\n readonly detection: ProviderDetection;\n readonly candidates: readonly DetectionCandidate[];\n readonly errors: readonly OtelHookErrorInfo[];\n };\n\n/**\n * Immutable set of adapters.\n *\n * A registry is a value passed to the runtime, not a mutable module-level\n * singleton: two hooks in one process may legitimately be configured with\n * different adapter sets, and a global would let one silently reconfigure the\n * other.\n */\nexport interface ProviderRegistry {\n readonly adapters: readonly ProviderAdapter[];\n get(id: string): ProviderAdapter | undefined;\n detect(\n input: ProviderDetectionInput,\n context: ProviderContext,\n policy: DetectionPolicy,\n ): RegistryDetectionResult;\n}\n\nexport const createProviderRegistry = (\n adapters: readonly ProviderAdapter[],\n): ProviderRegistry => {\n const byId = new Map<string, ProviderAdapter>();\n for (const adapter of adapters) {\n if (byId.has(adapter.id)) {\n throw createDuplicateAdapterError(adapter.id);\n }\n byId.set(adapter.id, adapter);\n }\n const frozen = Object.freeze([...adapters]);\n\n return {\n adapters: frozen,\n get: (id: string): ProviderAdapter | undefined => byId.get(id),\n detect: (\n input: ProviderDetectionInput,\n context: ProviderContext,\n policy: DetectionPolicy,\n ): RegistryDetectionResult => {\n const errors: OtelHookErrorInfo[] = [];\n const candidates: DetectionCandidate[] = [];\n\n if (frozen.length === 0) {\n return {\n status: \"unknown\",\n reason: \"no-adapters-registered\",\n detection: unknownDetection([\"no adapters registered\"]),\n candidates,\n errors,\n };\n }\n\n // Reasons from adapters that recognized the callback well enough to\n // explain why they declined it — as opposed to one that never looked at\n // this payload shape at all. Kept only for the \"no-candidates\" outcome\n // below: a payload every adapter genuinely ignores should still read as\n // the generic message, but a payload one adapter recognized and rejected\n // (e.g. Cursor's own envelope contract) must not be flattened into that\n // same generic message — that is the difference between \"provider\n // unknown\" and \"provider known, payload rejected for a stated reason\",\n // and only the raw per-adapter `detect()` result carries the latter.\n const nearMisses: string[] = [];\n\n for (const adapter of frozen) {\n let detection: ProviderDetection;\n try {\n detection = providerDetectionSchema.parse(adapter.detect(input, context));\n } catch (thrown) {\n // A misbehaving adapter must not suppress its peers.\n errors.push(errorInfoFromThrown(thrown, { code: \"provider-adapter-failure\", phase: \"detection\" }));\n continue;\n }\n if (detection.confidence === \"none\") {\n for (const reason of detection.reasons) {\n const prefixed = `${adapter.id}: ${reason}`;\n nearMisses.push(prefixed.length <= 160 ? prefixed : `${prefixed.slice(0, 159)}…`);\n }\n continue;\n }\n if (detection.providerId !== adapter.id) {\n errors.push(\n createErrorInfo({\n code: \"provider-adapter-failure\",\n phase: \"detection\",\n detail: `adapter ${adapter.id} claimed provider id ${detection.providerId}`,\n details: { \"adapter.id\": adapter.id, \"detection.provider_id\": detection.providerId },\n }),\n );\n continue;\n }\n candidates.push({ adapter, detection });\n }\n\n if (candidates.length === 0) {\n return {\n status: \"unknown\",\n reason: \"no-candidates\",\n detection: unknownDetection(nearMisses.length === 0 ? undefined : nearMisses.slice(0, 8)),\n candidates,\n errors,\n };\n }\n\n const bestRank = Math.max(\n ...candidates.map((candidate) => DETECTION_CONFIDENCE_RANK[candidate.detection.confidence]),\n );\n const best = candidates.filter(\n (candidate) => DETECTION_CONFIDENCE_RANK[candidate.detection.confidence] === bestRank,\n );\n\n if (best.length > 1) {\n return {\n status: \"ambiguous\",\n detection: unknownDetection([\n `${best.length} adapters matched at equal confidence`,\n ...best.map((candidate) => `candidate ${candidate.adapter.id}`),\n ]),\n candidates,\n errors,\n };\n }\n\n const [winner] = best;\n if (winner === undefined) {\n return {\n status: \"unknown\",\n reason: \"no-candidates\",\n detection: unknownDetection(),\n candidates,\n errors,\n };\n }\n\n if (bestRank < DETECTION_CONFIDENCE_RANK[policy.minimumConfidence]) {\n return {\n status: \"unknown\",\n reason: \"below-minimum-confidence\",\n detection: unknownDetection([\n `best confidence ${winner.detection.confidence} is below required ${policy.minimumConfidence}`,\n ]),\n candidates,\n errors,\n };\n }\n\n if (\n policy.allowedProviderIds.length > 0 &&\n !policy.allowedProviderIds.includes(winner.adapter.id)\n ) {\n return {\n status: \"unknown\",\n reason: \"provider-not-allowed\",\n detection: unknownDetection([`provider ${winner.adapter.id} is not in the allow-list`]),\n candidates,\n errors,\n };\n }\n\n return {\n status: \"selected\",\n adapter: winner.adapter,\n detection: winner.detection,\n candidates,\n errors,\n };\n },\n };\n};\n\nconst createDuplicateAdapterError = (id: ProviderId): Error =>\n new Error(`duplicate provider adapter id: ${id}`);\n\n/**\n * Built-in adapters.\n *\n * Empty by design in the core package: provider support is added by dedicated\n * adapter modules, and the core must remain testable without any of them.\n */\nexport const BUILT_IN_PROVIDERS: readonly ProviderAdapter[] = Object.freeze([]);\n","import type { DeliveryIdentifierSupport, ProviderDeliveryClaim } from \"../providers/adapter.js\";\nimport type { IdGenerator } from \"./ports.js\";\n\n/**\n * Where a delivery identity came from.\n *\n * `host` is an id the embedding host passed in; `provider` is one normalized\n * from payload fields the selected adapter vouched for. The two are kept\n * distinguishable because they carry different guarantees: a host id is unique\n * by construction, a provider-derived one is only as good as the adapter's\n * evidence.\n */\nexport type DeliveryOrigin = \"host\" | \"provider\";\n\n/**\n * A delivery identity reduced to the two opaque strings deduplication needs.\n *\n * Both are digests, never raw payload values. That matters because the pair\n * becomes a state-store key and a diagnostic attribute: a provider's session id,\n * tool-call id, or turn id would otherwise be written to disk and logged as a\n * side effect of deduplication, which is not a disclosure anybody asked for.\n */\nexport type ResolvedDeliveryIdentity = {\n /** Namespace the callback id is unique within. */\n readonly scope: string;\n /** Opaque identity of this callback within that scope. */\n readonly callbackId: string;\n readonly origin: DeliveryOrigin;\n /** Non-sensitive justifications, for diagnostics. Empty for a host id. */\n readonly evidence: readonly string[];\n};\n\n/** Why no replay-stable delivery identity could be established. */\nexport type DeliveryUnavailableReason =\n /** No adapter was selected, so nothing could vouch for an identifier. */\n | \"provider-unattributed\"\n /** The adapter declares that no callback of this provider carries one. */\n | \"provider-declares-none\"\n /** The adapter supports some callbacks, but not this one. */\n | \"callback-not-identifiable\"\n /** The adapter offered an identity that failed the contract's own guards. */\n | \"claim-rejected\"\n /**\n * An identity was established but the state store could not be read or written,\n * so nothing could be claimed against it.\n */\n | \"state-unavailable\";\n\nexport type DeliveryResolution =\n | { readonly status: \"resolved\"; readonly identity: ResolvedDeliveryIdentity }\n | {\n readonly status: \"unavailable\";\n readonly reason: DeliveryUnavailableReason;\n /** Present once a provider has been selected. */\n readonly providerId?: string;\n /** The adapter's declared coverage, when there is an adapter. */\n readonly capability?: DeliveryIdentifierSupport;\n /**\n * The provider's own name for the callback that could not be identified.\n *\n * Taken from the detection, which already carries it into span attributes\n * and provenance, so it discloses nothing new — and it is the difference\n * between a diagnostic an operator can act on and one that only restates\n * that something is missing.\n */\n readonly sourceEventName?: string;\n /**\n * Why, in the adapter's own words: a rejected claim's failure, or the\n * per-callback gap the adapter documents. Never contains payload values.\n */\n readonly detail?: string;\n };\n\n/**\n * Scope prefix for provider-derived identities.\n *\n * Kept distinct from a host-chosen scope so the two id spaces cannot be\n * confused, and so a host that starts supplying `--callback-id` does not inherit\n * whatever the adapter had already recorded for the same callbacks.\n */\nconst PROVIDER_SCOPE_PREFIX = \"provider-session\";\n\n/**\n * Namespace a host-supplied delivery id.\n *\n * Deliberately *not* scoped by session or installation: the host documented its\n * id as unique between distinct callbacks, so narrowing the scope here would\n * make a host id that repeats across two sessions stop being recognized as the\n * redelivery the host said it was.\n */\nexport const hostDeliveryIdentity = (\n callbackId: string,\n scope?: string,\n): ResolvedDeliveryIdentity => ({\n scope: scope ?? \"delivery\",\n callbackId,\n origin: \"host\",\n evidence: [],\n});\n\n/**\n * Reduce an adapter's delivery claim to an opaque, replay-stable identity.\n *\n * Scoping runs provider id, installation, and the provider's own session id\n * through the digest, so the same tool-call id observed by two installations, two\n * providers, or two sessions is three different callbacks. The callback digest\n * covers the event name and the adapter's components, so a `PreToolUse` and a\n * `PostToolUse` sharing one `tool_use_id` stay distinct.\n *\n * The digest comes from the injected {@link IdGenerator}, which is\n * content-addressed by default — that is precisely what makes the identity\n * survive a process restart: a later process with the same namespace recomputes\n * the identical pair without reading any state.\n */\nexport const resolveDeliveryIdentity = (input: {\n readonly ids: IdGenerator;\n readonly providerId: string;\n readonly installationId: string;\n readonly claim: ProviderDeliveryClaim;\n}): ResolvedDeliveryIdentity => {\n const { ids, providerId, installationId, claim } = input;\n return {\n scope: `${PROVIDER_SCOPE_PREFIX}:${ids.newOpaqueId([\n \"delivery-scope\",\n providerId,\n installationId,\n claim.sessionId,\n ])}`,\n callbackId: ids.newOpaqueId([\n \"delivery-callback\",\n providerId,\n claim.sessionId,\n claim.sourceEventName,\n ...claim.components,\n ]),\n origin: \"provider\",\n evidence: [...claim.evidence],\n };\n};\n","import { createHash, randomUUID } from \"node:crypto\";\n\nimport {\n eventIdSchema,\n invocationIdSchema,\n type EventId,\n type InvocationId,\n} from \"../model/primitives.js\";\nimport type { EventIdSeed, IdGenerator, InvocationIdSeed } from \"./ports.js\";\n\nconst digest = (namespace: string, parts: readonly (string | number | undefined)[]): string => {\n const hash = createHash(\"sha256\");\n hash.update(namespace);\n for (const part of parts) {\n hash.update(\"\\0\");\n hash.update(part === undefined ? \"\" : String(part));\n }\n return hash.digest(\"hex\");\n};\n\nexport type DeterministicIdOptions = {\n /**\n * Namespace mixed into every id. Two deployments using different namespaces\n * produce different ids for identical input, which prevents cross-tenant id\n * collisions in a shared collector.\n */\n readonly namespace?: string;\n /** Hex characters retained. 32 gives a 128-bit id. */\n readonly length?: number;\n};\n\n/**\n * Content-addressed id generator.\n *\n * Ids are a pure function of their seed, so re-running a hook on the same input\n * — a retry, a replayed transcript, a duplicated delivery — yields identical\n * ids. That makes the pipeline idempotent at the collector instead of relying on\n * exactly-once delivery, which hooks cannot provide.\n */\nexport const createDeterministicIdGenerator = (\n options: DeterministicIdOptions = {},\n): IdGenerator => {\n const namespace = options.namespace ?? \"otel-hook\";\n const length = Math.min(Math.max(options.length ?? 32, 16), 64);\n const truncate = (hex: string): string => hex.slice(0, length);\n\n return {\n newInvocationId: (seed: InvocationIdSeed): InvocationId =>\n invocationIdSchema.parse(\n `inv_${truncate(\n digest(`${namespace}/invocation`, [\n seed.providerId,\n seed.sessionId,\n seed.sourceEventName,\n seed.occurredAt,\n seed.discriminator,\n ]),\n )}`,\n ),\n newEventId: (seed: EventIdSeed): EventId =>\n eventIdSchema.parse(\n `evt_${truncate(\n digest(`${namespace}/event`, [\n seed.invocationId,\n seed.sequence,\n seed.eventType,\n seed.discriminator,\n ]),\n )}`,\n ),\n newOpaqueId: (parts: readonly string[]): string =>\n truncate(digest(`${namespace}/opaque`, parts)),\n };\n};\n\n/**\n * Random id generator.\n *\n * Use only when no stable seed exists; it is not replay-safe, so duplicate\n * deliveries become duplicate events.\n */\nexport const createRandomIdGenerator = (): IdGenerator => ({\n newInvocationId: (): InvocationId => invocationIdSchema.parse(`inv_${randomUUID()}`),\n newEventId: (): EventId => eventIdSchema.parse(`evt_${randomUUID()}`),\n newOpaqueId: (): string => randomUUID().replace(/-/g, \"\"),\n});\n","import { z } from \"zod\";\n\nimport type { OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport {\n attributesSchema,\n epochMillisSchema,\n sequenceNumberSchema,\n type Attributes,\n type EpochMillis,\n type EventId,\n type InvocationId,\n} from \"../model/primitives.js\";\nimport { canonicalUsageSchema } from \"../model/usage.js\";\n\n/**\n * Time source.\n *\n * Injected rather than read from `Date.now()` so tests are deterministic and so\n * a host with its own time authority can supply it.\n */\nexport interface Clock {\n /** Wall-clock time in whole milliseconds since the Unix epoch. */\n now(): EpochMillis;\n /** Monotonic reading for durations; unrelated to wall clock. */\n monotonicMillis(): number;\n}\n\n/** Stable inputs from which an invocation id is derived. */\nexport type InvocationIdSeed = {\n readonly providerId: string;\n readonly sessionId: string;\n readonly sourceEventName?: string;\n readonly occurredAt: number;\n /** Provider-supplied uniqueness, e.g. a request id. */\n readonly discriminator?: string;\n};\n\n/** Stable inputs from which an event id is derived. */\nexport type EventIdSeed = {\n readonly invocationId: string;\n readonly sequence: number;\n readonly eventType: string;\n readonly discriminator?: string;\n};\n\n/**\n * Identifier factory.\n *\n * Seeds are structured rather than free-form so the default implementation can\n * be a pure function of its inputs: replaying the same source data produces the\n * same ids, which lets a collector dedupe instead of double-counting.\n */\nexport interface IdGenerator {\n newInvocationId(seed: InvocationIdSeed): InvocationId;\n newEventId(seed: EventIdSeed): EventId;\n /** Short opaque id for spans and generations, derived from its parts. */\n newOpaqueId(parts: readonly string[]): string;\n}\n\n/**\n * Which delivery's observations are already folded into a stored total.\n *\n * The reason this rides *inside* the total's own record rather than beside it: the\n * store has no multi-key transaction, so a marker in a second key could be written\n * without the total or the other way round, and a marker that can disagree with\n * what it describes is worse than none. In one record the two move together under a\n * single write, which is what makes re-applying a redelivered callback's usage a\n * no-op instead of a double count.\n *\n * `callbackId` is an opaque digest supplied by the caller, never a host's raw\n * delivery id: a state record is somewhere a raw provider or host identifier must\n * not appear as a side effect of deduplicating on it.\n */\nexport const appliedDeliverySchema = z.strictObject({\n callbackId: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/),\n /** How many of that delivery's observations are folded in, counted from one. */\n applications: z.number().int().min(1).max(4_096),\n});\nexport type AppliedDelivery = z.infer<typeof appliedDeliverySchema>;\n\n/** Values the state store may hold. Restricted so state stays inspectable. */\nexport const stateValueSchema = z.discriminatedUnion(\"kind\", [\n z.strictObject({\n kind: z.literal(\"usage-cumulative\"),\n usage: canonicalUsageSchema,\n /**\n * Optional: absent on every record written before this field existed, which\n * reads as \"unknown provenance\" and simply forgoes the idempotency check\n * rather than resetting a baseline to gain it.\n */\n appliedDelivery: appliedDeliverySchema.optional(),\n }),\n z.strictObject({\n kind: z.literal(\"sequence\"),\n next: sequenceNumberSchema,\n }),\n z.strictObject({\n kind: z.literal(\"attributes\"),\n attributes: attributesSchema,\n }),\n]);\nexport type StateValue = z.infer<typeof stateValueSchema>;\n\nexport const stateRecordSchema = z.strictObject({\n /** Incremented on each write; lets callers detect lost updates. */\n revision: z.number().int().min(0),\n updatedAt: epochMillisSchema,\n value: stateValueSchema,\n});\nexport type StateRecord = z.infer<typeof stateRecordSchema>;\n\n/**\n * Durable-ish key/value state.\n *\n * Needed because a hook process is short-lived but usage accounting spans an\n * entire session. The interface is intentionally minimal: no transactions, no\n * queries, nothing a file or a KV row cannot provide.\n */\nexport interface StateStore {\n read(key: string): Promise<StateRecord | undefined>;\n /** Writes unconditionally, returning the stored record. */\n write(key: string, value: StateValue): Promise<StateRecord>;\n delete(key: string): Promise<void>;\n keys(prefix: string): Promise<readonly string[]>;\n}\n\nexport type TelemetryEmitResult = {\n readonly accepted: number;\n readonly rejected: number;\n readonly errors: readonly OtelHookErrorInfo[];\n};\n\n/**\n * Destination for canonical events.\n *\n * The sink receives canonical events only — never provider payloads — so an\n * exporter cannot become a second, unaudited disclosure path.\n */\nexport interface TelemetrySink {\n emit(events: readonly CanonicalEvent[]): Promise<TelemetryEmitResult>;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nexport const logLevelSchema = z.enum([\"silent\", \"error\", \"warn\", \"info\", \"debug\"]);\nexport type LogLevel = z.infer<typeof logLevelSchema>;\n\nexport const LOG_LEVEL_RANK: Readonly<Record<LogLevel, number>> = Object.freeze({\n silent: 0,\n error: 1,\n warn: 2,\n info: 3,\n debug: 4,\n});\n\n/**\n * Diagnostic logger.\n *\n * Fields are attribute values, not arbitrary objects, so a log line cannot\n * become a way to print a provider payload. Implementations must never write to\n * stdout (ADR 0004).\n */\nexport interface Logger {\n error(message: string, fields?: Attributes): void;\n warn(message: string, fields?: Attributes): void;\n info(message: string, fields?: Attributes): void;\n debug(message: string, fields?: Attributes): void;\n}\n\n/** A git worktree found on the local filesystem. Holds a path: never exported. */\nexport type LocatedWorktree = {\n /** Absolute path of the worktree's top-level directory (the one holding `.git`). */\n readonly root: string;\n /** Branch checked out there, from `HEAD`; absent when HEAD is detached. */\n readonly branch?: string;\n};\n\n/**\n * Finds the git worktree containing a local path (ADR 0008).\n *\n * The only port that reads the filesystem on behalf of event content, which is\n * why it is a port: the core decides *when* to ask and what of the answer may be\n * exported, the implementation only answers. Implementations must never throw or\n * reject — any failure is `undefined` — and must not spawn processes.\n */\nexport interface WorktreeLocator {\n locate(absolutePath: string): Promise<LocatedWorktree | undefined>;\n}\n","import type { Attributes } from \"../model/primitives.js\";\nimport { LOG_LEVEL_RANK, type Logger, type LogLevel } from \"./ports.js\";\n\nexport const createNullLogger = (): Logger => ({\n error: (): void => undefined,\n warn: (): void => undefined,\n info: (): void => undefined,\n debug: (): void => undefined,\n});\n\nexport type StderrLoggerOptions = {\n readonly level?: LogLevel;\n /** Injected for tests; defaults to `process.stderr.write`. */\n readonly write?: (line: string) => void;\n};\n\n/**\n * Diagnostic logger that writes to stderr only.\n *\n * stdout belongs to the host agent's hook protocol: anything written there can\n * be parsed as a hook response and change the agent's behaviour (ADR 0004).\n */\nexport const createStderrLogger = (options: StderrLoggerOptions = {}): Logger => {\n const level = options.level ?? \"warn\";\n const write =\n options.write ??\n ((line: string): void => {\n process.stderr.write(line);\n });\n const threshold = LOG_LEVEL_RANK[level];\n\n const log = (entryLevel: LogLevel, message: string, fields?: Attributes): void => {\n if (LOG_LEVEL_RANK[entryLevel] > threshold || threshold === 0) {\n return;\n }\n const payload =\n fields === undefined || Object.keys(fields).length === 0\n ? { level: entryLevel, message }\n : { level: entryLevel, message, fields };\n write(`${JSON.stringify(payload)}\\n`);\n };\n\n return {\n error: (message: string, fields?: Attributes): void => {\n log(\"error\", message, fields);\n },\n warn: (message: string, fields?: Attributes): void => {\n log(\"warn\", message, fields);\n },\n info: (message: string, fields?: Attributes): void => {\n log(\"info\", message, fields);\n },\n debug: (message: string, fields?: Attributes): void => {\n log(\"debug\", message, fields);\n },\n };\n};\n","import * as path from \"node:path\";\n\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { EventId } from \"../model/primitives.js\";\nimport { workspaceTargetSchema, type TargetHint, type WorkspaceTarget } from \"../model/target.js\";\nimport type { PrivacyService } from \"../privacy/service.js\";\nimport { deriveWorkspaceIdentity } from \"../privacy/workspace.js\";\nimport type { LocatedWorktree, WorktreeLocator } from \"./ports.js\";\n\n/**\n * Turns adapters' target hints into exported worktree targets (ADR 0008).\n *\n * This is where local paths stop. A hint's paths are resolved to a worktree\n * root and branch through the injected {@link WorktreeLocator}; only the salted\n * `git-root` handle of that root and the branch name survive onto the event.\n *\n * Fail-open in both directions that matter: a slow or failing filesystem costs\n * the event its target, never the event — and never the host more than the\n * time budget. Fail-closed on meaning: a hint whose paths land in two different\n * worktrees, or that names a relative path with nothing to resolve it against,\n * yields no target rather than a guess.\n */\n\n/** Default ceiling on target resolution per callback. */\nexport const DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS = 50;\n\nconst absolutePathsOf = (hint: TargetHint): readonly string[] | undefined => {\n const base =\n hint.baseDirectory !== undefined && path.isAbsolute(hint.baseDirectory)\n ? hint.baseDirectory\n : undefined;\n const resolved: string[] = [];\n for (const candidate of hint.paths) {\n if (path.isAbsolute(candidate)) {\n resolved.push(path.resolve(candidate));\n } else if (base !== undefined) {\n resolved.push(path.resolve(base, candidate));\n } else {\n return undefined;\n }\n }\n return resolved;\n};\n\nconst resolveHint = async (\n hint: TargetHint,\n locator: WorktreeLocator,\n privacy: PrivacyService,\n): Promise<WorkspaceTarget | undefined> => {\n const paths = absolutePathsOf(hint);\n if (paths === undefined) {\n return undefined;\n }\n const located: (LocatedWorktree | undefined)[] = await Promise.all(\n [...new Set(paths)].map((candidate) => locator.locate(candidate)),\n );\n const [first] = located;\n if (first === undefined || located.some((entry) => entry?.root !== first.root)) {\n return undefined;\n }\n const identity = deriveWorkspaceIdentity(\n privacy,\n { kind: \"git-root\", absolutePath: first.root },\n first.branch === undefined ? {} : { vcsBranchName: first.branch },\n );\n if (identity.keySource !== \"git-root\") {\n return undefined;\n }\n const parsed = workspaceTargetSchema.safeParse({\n workspaceId: identity.workspaceId,\n ...(identity.vcsBranchName === undefined ? {} : { vcsBranchName: identity.vcsBranchName }),\n source: hint.source,\n });\n return parsed.success ? parsed.data : undefined;\n};\n\nexport type ResolveEventTargetsInput = {\n readonly events: readonly CanonicalEvent[];\n readonly hints: ReadonlyMap<EventId, TargetHint>;\n readonly locator: WorktreeLocator;\n readonly privacy: PrivacyService;\n readonly budgetMillis: number;\n};\n\nexport type ResolveEventTargetsResult = {\n readonly events: readonly CanonicalEvent[];\n /** Hints that produced a target. */\n readonly resolved: number;\n /** True when the time budget expired before every hint was answered. */\n readonly timedOut: boolean;\n};\n\n/**\n * Attach a `target` to each tool event that has a resolvable hint. Never\n * throws or rejects; events without a hint, or whose hint does not resolve,\n * are returned unchanged.\n */\nexport const resolveEventTargets = async (\n input: ResolveEventTargetsInput,\n): Promise<ResolveEventTargetsResult> => {\n const pending = input.events.filter(\n (event) =>\n (event.type === \"tool.start\" || event.type === \"tool.end\") && input.hints.has(event.eventId),\n );\n if (pending.length === 0) {\n return { events: input.events, resolved: 0, timedOut: false };\n }\n\n const targets = new Map<EventId, WorkspaceTarget>();\n const work = Promise.all(\n pending.map(async (event) => {\n const hint = input.hints.get(event.eventId);\n if (hint === undefined) {\n return;\n }\n try {\n const target = await resolveHint(hint, input.locator, input.privacy);\n if (target !== undefined) {\n targets.set(event.eventId, target);\n }\n } catch {\n // A locator that broke its no-throw contract costs this event its target.\n }\n }),\n ).then(() => \"done\" as const);\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), Math.max(0, input.budgetMillis));\n timer.unref?.();\n });\n const finished = await Promise.race([work, deadline]);\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n\n // Snapshot: a resolution landing after the deadline must not mutate a batch\n // that is already on its way out.\n const settled = new Map(targets);\n const events = input.events.map((event): CanonicalEvent => {\n const target = settled.get(event.eventId);\n if (target === undefined || (event.type !== \"tool.start\" && event.type !== \"tool.end\")) {\n return event;\n }\n return { ...event, target };\n });\n return { events, resolved: settled.size, timedOut: finished === \"timeout\" };\n};\n","import {\n workspaceIdentitySchema,\n type WorkspaceIdentity,\n type WorkspaceKeySource,\n} from \"../model/identity.js\";\nimport type { PrivacyService } from \"./service.js\";\n\n/**\n * Raw material a caller can offer for workspace identification.\n *\n * Paths and remote URLs are accepted here and immediately hashed. Neither is\n * retained, so a home directory cannot reach an exporter through this path.\n */\nexport type WorkspaceKeyInput =\n | { readonly kind: \"git-remote\"; readonly remoteUrl: string }\n | { readonly kind: \"git-root\"; readonly absolutePath: string }\n | { readonly kind: \"working-directory\"; readonly absolutePath: string }\n | { readonly kind: \"explicit\"; readonly value: string }\n | { readonly kind: \"unknown\" };\n\nexport type WorkspaceLabels = {\n /** Bare repository name, e.g. `otel-hook`. Never an owner path or URL. */\n readonly repositoryName?: string;\n readonly vcsBranchName?: string;\n /** Revision identifier; hashed before it is stored. */\n readonly vcsRevisionId?: string;\n};\n\n/**\n * Canonicalize a git remote so equivalent spellings hash identically:\n * scheme, credentials, port, trailing `.git`, and case are removed.\n */\nexport const canonicalizeGitRemote = (remoteUrl: string): string => {\n const trimmed = remoteUrl.trim();\n const scpLike = /^([^@/]+)@([^:]+):(.+)$/.exec(trimmed);\n const withoutScheme = scpLike\n ? `${scpLike[2] ?? \"\"}/${scpLike[3] ?? \"\"}`\n : trimmed.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\\/\\//, \"\").replace(/^[^@/]+@/, \"\");\n return withoutScheme\n .replace(/:\\d+\\//, \"/\")\n .replace(/\\/+$/, \"\")\n .replace(/\\.git$/i, \"\")\n .replace(/\\/+$/, \"\")\n .toLowerCase();\n};\n\nconst keySourceOf = (input: WorkspaceKeyInput): WorkspaceKeySource => {\n switch (input.kind) {\n case \"git-remote\":\n return \"git-remote\";\n case \"git-root\":\n return \"git-root\";\n case \"working-directory\":\n return \"working-directory\";\n case \"explicit\":\n return \"explicit\";\n case \"unknown\":\n return \"unknown\";\n }\n};\n\nconst keyMaterialOf = (input: WorkspaceKeyInput): string | undefined => {\n switch (input.kind) {\n case \"git-remote\":\n return canonicalizeGitRemote(input.remoteUrl);\n case \"git-root\":\n case \"working-directory\":\n return input.absolutePath.replace(/[/\\\\]+$/, \"\");\n case \"explicit\":\n return input.value;\n case \"unknown\":\n return undefined;\n }\n};\n\n/**\n * Derive privacy-safe workspace identity.\n *\n * The identifier is a salted hash namespaced by key source, so a directory-keyed\n * workspace and a remote-keyed workspace never collide even if the underlying\n * strings match.\n */\nexport const deriveWorkspaceIdentity = (\n privacy: PrivacyService,\n input: WorkspaceKeyInput,\n labels: WorkspaceLabels = {},\n): WorkspaceIdentity => {\n const keySource = keySourceOf(input);\n const material = keyMaterialOf(input);\n const workspaceId =\n material === undefined || material === \"\"\n ? \"unknown:0000000000000000\"\n : privacy.deriveOpaqueId(`workspace/${keySource}`, material);\n\n return workspaceIdentitySchema.parse({\n workspaceId,\n keySource: material === undefined || material === \"\" ? \"unknown\" : keySource,\n ...(labels.repositoryName === undefined\n ? {}\n : { repositoryName: labels.repositoryName.slice(0, 128) }),\n ...(labels.vcsBranchName === undefined\n ? {}\n : { vcsBranchName: labels.vcsBranchName.slice(0, 128) }),\n ...(labels.vcsRevisionId === undefined\n ? {}\n : { vcsRevisionId: privacy.deriveOpaqueId(\"workspace/revision\", labels.vcsRevisionId) }),\n });\n};\n","import { open, stat } from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport type { LocatedWorktree, WorktreeLocator } from \"./ports.js\";\n\n/**\n * Filesystem {@link WorktreeLocator}: finds the git worktree containing a path\n * by reading the files git itself reads, without spawning `git` (ADR 0008).\n *\n * From the path upward, the first directory holding a `.git` entry is the\n * worktree root:\n *\n * - `.git` is a **directory** — the main worktree; its git dir is that directory.\n * - `.git` is a **file** — a linked worktree (or a submodule): it holds\n * `gitdir: <path>`, relative to the worktree root when not absolute.\n *\n * The branch is read from `<gitdir>/HEAD`: `ref: refs/heads/<name>` names a\n * branch; anything else (a detached commit id) names none. A `.git` entry that\n * cannot be read, points nowhere, or has no readable `HEAD` makes the answer\n * `undefined` — a broken worktree is not evidence, and the walk does not skip\n * past it to an enclosing repository that the event did not target.\n *\n * Everything is bounded: walk depth, bytes read per file, and cache size. Every\n * failure is `undefined`; nothing throws.\n */\n\n/** Deepest directory chain walked before giving up. */\nexport const MAX_WORKTREE_WALK_DEPTH = 128;\n/** Bytes read from a `.git` file or a `HEAD`; both are one short line. */\nconst MAX_GIT_FILE_BYTES = 4096;\n/** Directories remembered before the cache is cleared and refilled. */\nconst MAX_CACHE_ENTRIES = 1024;\n/** Default lifetime of a cached probe. Short: a branch can be switched. */\nexport const DEFAULT_WORKTREE_CACHE_TTL_MILLIS = 5_000;\n/** Longest branch name accepted; git refs are far shorter in practice. */\nconst MAX_BRANCH_NAME_LENGTH = 255;\n\ntype Probe =\n | { readonly kind: \"absent\" }\n | { readonly kind: \"worktree\"; readonly located: LocatedWorktree }\n | { readonly kind: \"invalid\" };\n\nconst ABSENT: Probe = Object.freeze({ kind: \"absent\" });\nconst INVALID: Probe = Object.freeze({ kind: \"invalid\" });\n\nconst readBounded = async (filePath: string): Promise<string | undefined> => {\n let handle;\n try {\n handle = await open(filePath, \"r\");\n const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);\n const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);\n return buffer.subarray(0, bytesRead).toString(\"utf8\");\n } catch {\n return undefined;\n } finally {\n await handle?.close().catch(() => undefined);\n }\n};\n\n/** `ref: refs/heads/<name>` → `<name>`; anything else → no branch. */\nexport const parseHeadBranch = (head: string): string | undefined => {\n const line = head.split(/\\r?\\n/, 1)[0]?.trim() ?? \"\";\n const match = /^ref:\\s*refs\\/heads\\/(.+)$/.exec(line);\n const branch = match?.[1];\n if (\n branch === undefined ||\n branch.length === 0 ||\n branch.length > MAX_BRANCH_NAME_LENGTH ||\n // git forbids these in ref names; their presence means this is not one.\n [...branch].some((char) => char.charCodeAt(0) < 0x20 || char.charCodeAt(0) === 0x7f) ||\n /[ ~^:?*[\\\\]/.test(branch)\n ) {\n return undefined;\n }\n return branch;\n};\n\n/** `gitdir: <path>` → the path, resolved against the worktree root. */\nexport const parseGitDirFile = (content: string, worktreeRoot: string): string | undefined => {\n const line = content.split(/\\r?\\n/, 1)[0]?.trim() ?? \"\";\n // A prefix check, not a regex: `gitdir:` followed by long runs of spaces made\n // the former `/^gitdir:\\s*(.+)$/` backtrack polynomially (CodeQL).\n const target = line.startsWith(\"gitdir:\") ? line.slice(\"gitdir:\".length).trim() : undefined;\n if (target === undefined || target.length === 0 || target.includes(\"\\u0000\")) {\n return undefined;\n }\n return path.resolve(worktreeRoot, target);\n};\n\nconst probeDirectory = async (directory: string): Promise<Probe> => {\n const dotGit = path.join(directory, \".git\");\n let info;\n try {\n info = await stat(dotGit);\n } catch {\n // ENOENT, ENOTDIR (the \"directory\" is a file), EACCES: no worktree here.\n return ABSENT;\n }\n let gitDir: string | undefined;\n if (info.isDirectory()) {\n gitDir = dotGit;\n } else if (info.isFile()) {\n const content = await readBounded(dotGit);\n gitDir = content === undefined ? undefined : parseGitDirFile(content, directory);\n }\n if (gitDir === undefined) {\n return INVALID;\n }\n const head = await readBounded(path.join(gitDir, \"HEAD\"));\n if (head === undefined) {\n return INVALID;\n }\n const branch = parseHeadBranch(head);\n return {\n kind: \"worktree\",\n located: { root: directory, ...(branch === undefined ? {} : { branch }) },\n };\n};\n\nexport type FilesystemWorktreeLocatorOptions = {\n /** Monotonic milliseconds for cache expiry. Defaults to `performance.now()`. */\n readonly monotonicMillis?: () => number;\n readonly cacheTtlMillis?: number;\n};\n\n/**\n * Create a locator with its own cache. The cache is instance state, never\n * module state: two hooks in one process do not share it.\n */\nexport const createFilesystemWorktreeLocator = (\n options: FilesystemWorktreeLocatorOptions = {},\n): WorktreeLocator => {\n const now = options.monotonicMillis ?? ((): number => performance.now());\n const ttl = options.cacheTtlMillis ?? DEFAULT_WORKTREE_CACHE_TTL_MILLIS;\n const cache = new Map<string, { readonly at: number; readonly probe: Promise<Probe> }>();\n\n const cachedProbe = (directory: string): Promise<Probe> => {\n const hit = cache.get(directory);\n const at = now();\n if (hit !== undefined && at - hit.at <= ttl) {\n return hit.probe;\n }\n if (cache.size >= MAX_CACHE_ENTRIES) {\n cache.clear();\n }\n const probe = probeDirectory(directory).catch((): Probe => INVALID);\n cache.set(directory, { at, probe });\n return probe;\n };\n\n const locate = async (absolutePath: string): Promise<LocatedWorktree | undefined> => {\n try {\n if (!path.isAbsolute(absolutePath) || absolutePath.includes(\"\\u0000\")) {\n return undefined;\n }\n let directory = path.resolve(absolutePath);\n for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {\n const probe = await cachedProbe(directory);\n if (probe.kind === \"worktree\") {\n return probe.located;\n }\n if (probe.kind === \"invalid\") {\n return undefined;\n }\n const parent = path.dirname(directory);\n if (parent === directory) {\n return undefined;\n }\n directory = parent;\n }\n return undefined;\n } catch {\n return undefined;\n }\n };\n\n return { locate };\n};\n","import { randomBytes } from \"node:crypto\";\nimport { mkdir, open, readFile, readdir, rename, unlink, writeFile } from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport type { Clock, Logger, StateRecord, StateValue } from \"../runtime/ports.js\";\nimport { stateRecordSchema } from \"../runtime/ports.js\";\nimport { createAsyncLock } from \"./async-lock.js\";\nimport { keyDigest, namespaceSegments, sanitizeSegment, type StoreNamespace } from \"./keys.js\";\nimport { StateLockTimeoutError, type LockingStateStore } from \"./store.js\";\n\nexport type FilesystemStateStoreOptions = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Bounds how long a write, read, or session lock waits. Default 5,000ms. */\n readonly lockTimeoutMillis?: number;\n /** A lock file older than this is assumed to belong to a crashed process and is reclaimed. Default 30,000ms. */\n readonly lockStaleMillis?: number;\n /** Delay between lock acquisition attempts. Default 25ms. */\n readonly lockPollIntervalMillis?: number;\n};\n\nexport interface FilesystemStateStore extends LockingStateStore {\n readonly recordsDir: string;\n readonly quarantineDir: string;\n /** Bounded sweep: removes records untouched for longer than `maxAgeMillis`. */\n pruneStale(\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number },\n ): Promise<{ readonly removed: number; readonly scanned: number }>;\n}\n\ntype Envelope = { readonly key: string; readonly record: StateRecord };\n\nconst isErrnoException = (thrown: unknown, code: string): boolean =>\n thrown instanceof Error && (thrown as NodeJS.ErrnoException).code === code;\n\nconst sleep = (millis: number): Promise<void> =>\n new Promise((resolve) => {\n const timer = setTimeout(resolve, millis);\n timer.unref?.();\n });\n\nconst wrapFsError = (thrown: unknown, operation: string): Error => {\n if (thrown instanceof Error) {\n return new Error(`filesystem state store ${operation} failed: ${thrown.name}`, { cause: thrown });\n }\n return new Error(`filesystem state store ${operation} failed`);\n};\n\n/**\n * Crash-safe filesystem {@link StateStore}.\n *\n * Every write lands via a temp file plus `rename`, which POSIX guarantees is\n * atomic within one directory: a reader never observes a half-written record,\n * and a process killed mid-write leaves only an orphaned temp file, never a\n * corrupt one. A record that still fails to parse (disk corruption, a manual\n * edit, a future incompatible version) is quarantined rather than thrown from\n * `read`, so a single bad file degrades one key instead of the whole store.\n *\n * Locking is layered: an in-process {@link createAsyncLock} orders same-process\n * callers, and a lock file with a staleness timeout orders across processes\n * and recovers automatically if the holder crashed while holding it.\n */\nexport const createFilesystemStateStore = (\n options: FilesystemStateStoreOptions,\n): FilesystemStateStore => {\n const [providerSegment, installationSegment] = namespaceSegments(options);\n const baseDir = path.join(options.rootDir, providerSegment, installationSegment);\n const recordsDir = path.join(baseDir, \"records\");\n const quarantineDir = path.join(baseDir, \"quarantine\");\n const locksDir = path.join(baseDir, \"locks\");\n\n const lockTimeoutMillis = options.lockTimeoutMillis ?? 5_000;\n const lockStaleMillis = options.lockStaleMillis ?? 30_000;\n const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;\n\n const keyLock = createAsyncLock();\n const sessionLock = createAsyncLock();\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(recordsDir, { recursive: true });\n await mkdir(quarantineDir, { recursive: true });\n await mkdir(locksDir, { recursive: true });\n })();\n dirsReady = promise;\n try {\n await promise;\n } catch (thrown) {\n dirsReady = undefined;\n throw wrapFsError(thrown, \"ensure-dirs\");\n }\n };\n\n const recordPath = (key: string): string => path.join(recordsDir, `${keyDigest(key)}.json`);\n const tempPath = (key: string): string =>\n path.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes(6).toString(\"hex\")}.json`);\n const lockPath = (sessionId: string): string =>\n path.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);\n\n const quarantine = async (filePath: string, key: string, reason: string): Promise<void> => {\n const dest = path.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);\n try {\n await rename(filePath, dest);\n } catch {\n await unlink(filePath).catch(() => undefined);\n }\n options.logger?.warn(\"filesystem state record quarantined\", { \"state.reason\": reason });\n };\n\n const readUnlocked = async (key: string): Promise<StateRecord | undefined> => {\n await ensureDirs();\n const filePath = recordPath(key);\n let raw: string;\n try {\n raw = await readFile(filePath, \"utf8\");\n } catch (thrown) {\n if (isErrnoException(thrown, \"ENOENT\")) {\n return undefined;\n }\n throw wrapFsError(thrown, \"read\");\n }\n\n let parsedJson: unknown;\n try {\n parsedJson = JSON.parse(raw);\n } catch {\n await quarantine(filePath, key, \"invalid-json\");\n return undefined;\n }\n\n const envelope = parsedJson as Partial<Envelope>;\n if (envelope.key !== key) {\n await quarantine(filePath, key, \"key-mismatch\");\n return undefined;\n }\n const parsed = stateRecordSchema.safeParse(envelope.record);\n if (!parsed.success) {\n await quarantine(filePath, key, \"schema-invalid\");\n return undefined;\n }\n return parsed.data;\n };\n\n const writeUnlocked = async (key: string, value: StateValue): Promise<StateRecord> => {\n await ensureDirs();\n const previous = await readUnlocked(key);\n const record = stateRecordSchema.parse({\n revision: (previous?.revision ?? 0) + 1,\n updatedAt: options.clock.now(),\n value,\n });\n const envelope: Envelope = { key, record };\n const tmp = tempPath(key);\n try {\n await writeFile(tmp, JSON.stringify(envelope), \"utf8\");\n await rename(tmp, recordPath(key));\n } catch (thrown) {\n await unlink(tmp).catch(() => undefined);\n throw wrapFsError(thrown, \"write\");\n }\n return record;\n };\n\n const acquireFileLock = async (\n sessionId: string,\n timeoutMillis: number,\n ): Promise<() => Promise<void>> => {\n await ensureDirs();\n const filePath = lockPath(sessionId);\n const startedAt = options.clock.monotonicMillis();\n\n for (;;) {\n try {\n const handle = await open(filePath, \"wx\");\n try {\n await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));\n } finally {\n await handle.close();\n }\n return async (): Promise<void> => {\n await unlink(filePath).catch(() => undefined);\n };\n } catch (thrown) {\n if (!isErrnoException(thrown, \"EEXIST\")) {\n throw wrapFsError(thrown, \"lock\");\n }\n }\n\n const stale = await (async (): Promise<boolean> => {\n try {\n const raw = await readFile(filePath, \"utf8\");\n const parsed = JSON.parse(raw) as { acquiredAt?: unknown };\n return (\n typeof parsed.acquiredAt !== \"number\" ||\n options.clock.now() - parsed.acquiredAt > lockStaleMillis\n );\n } catch {\n return true;\n }\n })();\n if (stale) {\n await unlink(filePath).catch(() => undefined);\n continue;\n }\n\n if (options.clock.monotonicMillis() - startedAt >= timeoutMillis) {\n // A typed error, so a caller can tell \"a peer holds this\" apart from \"the\n // store is unusable\" — the two demand opposite responses.\n throw new StateLockTimeoutError(sessionId, timeoutMillis);\n }\n await sleep(lockPollIntervalMillis);\n }\n };\n\n return {\n recordsDir,\n quarantineDir,\n read: (key: string): Promise<StateRecord | undefined> =>\n keyLock.run(key, () => readUnlocked(key), lockTimeoutMillis),\n write: (key: string, value: StateValue): Promise<StateRecord> =>\n keyLock.run(key, () => writeUnlocked(key, value), lockTimeoutMillis),\n delete: (key: string): Promise<void> =>\n keyLock.run(\n key,\n async (): Promise<void> => {\n await ensureDirs();\n await unlink(recordPath(key)).catch((thrown: unknown) => {\n if (!isErrnoException(thrown, \"ENOENT\")) {\n throw wrapFsError(thrown, \"delete\");\n }\n });\n },\n lockTimeoutMillis,\n ),\n keys: async (prefix: string): Promise<readonly string[]> => {\n await ensureDirs();\n let entries: string[];\n try {\n entries = await readdir(recordsDir);\n } catch (thrown) {\n if (isErrnoException(thrown, \"ENOENT\")) {\n return [];\n }\n throw wrapFsError(thrown, \"keys\");\n }\n const found: string[] = [];\n for (const entry of entries) {\n if (!entry.endsWith(\".json\") || entry.startsWith(\".tmp-\")) {\n continue;\n }\n let raw: string;\n try {\n raw = await readFile(path.join(recordsDir, entry), \"utf8\");\n } catch {\n continue;\n }\n try {\n const envelope = JSON.parse(raw) as Partial<Envelope>;\n if (typeof envelope.key === \"string\" && envelope.key.startsWith(prefix)) {\n found.push(envelope.key);\n }\n } catch {\n continue;\n }\n }\n return found.sort();\n },\n withSessionLock: async <T>(\n sessionId: string,\n fn: () => Promise<T>,\n lockOptions?: { readonly timeoutMillis?: number },\n ): Promise<T> => {\n const timeoutMillis = lockOptions?.timeoutMillis ?? lockTimeoutMillis;\n return sessionLock.run(\n sessionId,\n async (): Promise<T> => {\n const release = await acquireFileLock(sessionId, timeoutMillis);\n try {\n return await fn();\n } finally {\n await release();\n }\n },\n timeoutMillis,\n );\n },\n pruneStale: async (\n maxAgeMillis: number,\n pruneOptions?: { readonly maxEntries?: number },\n ): Promise<{ readonly removed: number; readonly scanned: number }> => {\n await ensureDirs();\n const cap = pruneOptions?.maxEntries ?? 5_000;\n const now = options.clock.now();\n let removed = 0;\n let scanned = 0;\n\n let entries: string[];\n try {\n entries = await readdir(recordsDir);\n } catch (thrown) {\n if (!isErrnoException(thrown, \"ENOENT\")) {\n throw wrapFsError(thrown, \"prune\");\n }\n entries = [];\n }\n for (const entry of entries) {\n if (scanned >= cap) {\n break;\n }\n if (!entry.endsWith(\".json\") || entry.startsWith(\".tmp-\")) {\n continue;\n }\n scanned += 1;\n const filePath = path.join(recordsDir, entry);\n try {\n // Ages are measured against the record's own `updatedAt`, taken from\n // the injected clock at write time, never the OS mtime: a test (or a\n // host) using a clock other than the wall clock would otherwise be\n // compared against a completely unrelated time source.\n const raw = await readFile(filePath, \"utf8\");\n const envelope = JSON.parse(raw) as Partial<Envelope>;\n const updatedAt = envelope.record?.updatedAt;\n if (typeof updatedAt === \"number\" && now - updatedAt > maxAgeMillis) {\n await unlink(filePath).catch(() => undefined);\n removed += 1;\n }\n } catch {\n continue;\n }\n }\n\n let lockEntries: string[];\n try {\n lockEntries = await readdir(locksDir);\n } catch {\n lockEntries = [];\n }\n for (const entry of lockEntries) {\n const filePath = path.join(locksDir, entry);\n try {\n const raw = await readFile(filePath, \"utf8\");\n const parsed = JSON.parse(raw) as { acquiredAt?: unknown };\n if (typeof parsed.acquiredAt === \"number\" && now - parsed.acquiredAt > lockStaleMillis) {\n await unlink(filePath).catch(() => undefined);\n }\n } catch {\n continue;\n }\n }\n\n return { removed, scanned };\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 { 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 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 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 { 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 { 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 { 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_CACHE_CREATION_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n} from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport type { ContentFact } from \"../model/content.js\";\nimport type { CanonicalEvent, CanonicalEventType } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\nimport {\n exportIdentityAttributes,\n targetAttributes,\n usageTemporalityAttributes,\n} from \"./export-identity.js\";\nimport {\n canonicalEventTraceIdentities,\n DEFAULT_INSTRUMENTATION_SCOPE,\n type SpanCorrelation,\n} from \"./semconv.js\";\n\n/**\n * Pure, stateless canonical-event-to-OTLP-log-record mapping.\n *\n * The counterpart of `semconv.ts` for the logs signal, and deliberately the same\n * shape: no state is read here, no clock is consulted, and the only inputs are\n * the batch plus the correlations the caller already resolved. Batching, retry,\n * spooling, and delivery live in `otlp-log-sink.ts`.\n *\n * ## Why logs at all, when traces already exist\n *\n * A span reports that a tool call happened, how long it took, and whether it\n * failed. It does not report *what was in it*, and it cannot: span attributes are\n * a flat bounded map, one record per span, exported once. A conversation turn is a\n * sequence of distinct pieces of content — a prompt, a response, reasoning, a tool\n * input, a tool output — each with its own role, its own length, and its own\n * disclosure decision. That is a log stream, and OTLP has one.\n *\n * So this mapping emits **one record per content fact**, plus one record per event\n * that carries no content, and correlates every record to the span the same batch\n * produced (or will produce). Nothing here decides *whether* content is\n * disclosed — the privacy service already did that, upstream, once — but the\n * gate is re-checked here because this is the last boundary before the wire.\n *\n * ## Identity and correlation\n *\n * Every record carries the same identity attributes a span does, and a\n * `spanContext` built from {@link canonicalEventTraceIdentities}: the trace id and\n * span id are derived from the event's own `(providerId, sessionId)` and its\n * lifecycle scope, so a record lands in the same trace as its span without either\n * signal knowing about the other. Two sessions in one batch derive two trace ids;\n * there is no batch-level or module-level trace state to contaminate.\n */\n\n/**\n * Version of this mapping.\n *\n * Consumers pin it. Bumped on any change to what an existing attribute or signal\n * *means*; adding a new attribute or a new signal value does not bump it, on the\n * same additive-compatibility rule the canonical model follows\n * (`CANONICAL_SCHEMA_VERSION`). Every record carries it as\n * `otelhook.log.mapping_version`, so a consumer never has to infer which\n * vocabulary it is reading.\n */\nexport const LOG_MAPPING_VERSION = 1 as const;\n\n/**\n * Coarse routing key for one log record.\n *\n * The fact's own `otelhook.content.kind` states precisely what the content is;\n * this states which *pipeline* it belongs to, so an operator can route or drop a\n * whole class (\"no tool output off this host\") with one collector rule rather\n * than an enumeration of event types.\n */\nexport const LOG_SIGNALS = [\n \"session\",\n \"prompt\",\n \"response\",\n \"reasoning\",\n \"tool\",\n \"shell\",\n \"file-operation\",\n \"mcp\",\n \"delegation\",\n \"compaction\",\n \"error\",\n] as const;\nexport type LogSignal = (typeof LOG_SIGNALS)[number];\n\n/**\n * Naming convention that marks a tool call as MCP-mediated.\n *\n * The canonical model has no \"this went through MCP\" field, because no provider\n * contract this package has verified carries one: what they carry is a *tool\n * name*, and three of the four non-synthetic contracts (Claude Code, Codex,\n * Gemini CLI) name MCP tools `mcp__<server>__<tool>`. So the convention is the\n * evidence, matched on the canonical tool name rather than on any provider's\n * payload.\n *\n * This deliberately **under-reports**: a provider whose MCP tool names do not\n * follow the convention classifies as `tool`, which is true but less specific.\n * The alternative — per-provider branching in the canonical layer, or a canonical\n * field no adapter can populate from a verified contract — would either leak\n * provider knowledge across the boundary or invent a contract. See\n * `docs/canonical-log-mapping.md`.\n */\nexport const MCP_TOOL_NAME_PATTERN = /^mcp__/i;\n\n/**\n * Most records one event may produce.\n *\n * Matches `contentFactsSchema`'s own cap, so in practice the mapping never drops\n * a fact an adapter produced; it is the backstop for a hand-built event, not a\n * routine truncation.\n */\nexport const MAX_LOG_RECORDS_PER_EVENT = 64;\n\n/** Most records one batch may produce, whatever the batch contains. */\nexport const MAX_LOG_RECORDS_PER_BATCH = 2_048;\n\n/**\n * Longest disclosed body this mapping will put on the wire.\n *\n * Separate from, and stricter than, the privacy policy's `maxStringLength` (which\n * may be configured up to 64Ki characters): a policy bound is about *disclosure*,\n * this is about the size of one OTLP record. A body cut here is reported as\n * `otelhook.content.body_truncated` rather than as the fact's own `truncated`\n * flag, so \"the privacy policy shortened this\" and \"the log record shortened\n * this\" stay distinguishable.\n */\nexport const MAX_LOG_BODY_CHARACTERS = 8_192;\n\nconst ATTR_OTELHOOK_EVENT_TYPE = \"otelhook.event.type\";\nconst ATTR_OTELHOOK_EVENT_ID = \"otelhook.event.id\";\nconst ATTR_OTELHOOK_EVENT_SEQUENCE = \"otelhook.event.sequence\";\nconst ATTR_OTELHOOK_LOG_SIGNAL = \"otelhook.log.signal\";\nconst ATTR_OTELHOOK_LOG_MAPPING_VERSION = \"otelhook.log.mapping_version\";\nconst ATTR_OTELHOOK_OUTCOME = \"otelhook.outcome\";\nconst ATTR_OTELHOOK_TOOL_KIND = \"otelhook.tool.kind\";\nconst ATTR_OTELHOOK_TOOL_PERMISSION = \"otelhook.tool.permission_decision\";\nconst ATTR_OTELHOOK_DELEGATION_DEPTH = \"otelhook.delegation_depth\";\nconst ATTR_OTELHOOK_SUBAGENT_TYPE = \"otelhook.subagent.type\";\nconst ATTR_OTELHOOK_AGENT_NAME = \"otelhook.agent.name\";\nconst ATTR_OTELHOOK_AGENT_VERSION = \"otelhook.agent.version\";\nconst ATTR_OTELHOOK_SESSION_KIND = \"otelhook.session.kind\";\nconst ATTR_OTELHOOK_PROMPT_SOURCE = \"otelhook.prompt.source\";\nconst ATTR_OTELHOOK_PROMPT_TURN_INDEX = \"otelhook.prompt.turn_index\";\nconst ATTR_OTELHOOK_GENERATION_ID = \"otelhook.generation.id\";\nconst ATTR_OTELHOOK_STOP_REASON = \"otelhook.generation.stop_reason\";\nconst ATTR_OTELHOOK_COMPACTION_TRIGGER = \"otelhook.compaction.trigger\";\nconst ATTR_OTELHOOK_CONTEXT_TOKENS_BEFORE = \"otelhook.compaction.context_tokens_before\";\nconst ATTR_OTELHOOK_CONTEXT_TOKENS_AFTER = \"otelhook.compaction.context_tokens_after\";\nconst ATTR_OTELHOOK_DROPPED_MESSAGES = \"otelhook.compaction.dropped_message_count\";\nconst ATTR_OTELHOOK_ERROR_PHASE = \"otelhook.error.phase\";\nconst ATTR_OTELHOOK_ERROR_RETRYABLE = \"otelhook.error.retryable\";\nconst ATTR_OTELHOOK_ERROR_SEVERITY = \"otelhook.error.severity\";\n\nconst ATTR_CONTENT_KIND = \"otelhook.content.kind\";\nconst ATTR_CONTENT_ROLE = \"otelhook.content.role\";\nconst ATTR_CONTENT_DISCLOSURE = \"otelhook.content.disclosure\";\nconst ATTR_CONTENT_CHARACTER_LENGTH = \"otelhook.content.character_length\";\nconst ATTR_CONTENT_BYTE_LENGTH = \"otelhook.content.byte_length\";\nconst ATTR_CONTENT_HASH = \"otelhook.content.hash\";\nconst ATTR_CONTENT_TRUNCATED = \"otelhook.content.truncated\";\nconst ATTR_CONTENT_SECRETS_REDACTED = \"otelhook.content.secrets_redacted\";\nconst ATTR_CONTENT_LABEL = \"otelhook.content.label\";\nconst ATTR_CONTENT_WITHHELD = \"otelhook.content.withheld\";\nconst ATTR_CONTENT_BODY_TRUNCATED = \"otelhook.content.body_truncated\";\n\n/**\n * Why a content fact reached the wire without its text.\n *\n * Stated rather than left as an absence, because \"this prompt was empty\", \"this\n * deployment omits content\", and \"this deployment discloses content but not to\n * the logs pipeline\" are three different operational facts that all look like a\n * missing body.\n */\nexport type ContentWithholdingReason =\n /** The privacy policy produced no text at all — the default `omit` posture. */\n | \"privacy-policy\"\n /** Content is disclosed elsewhere, but the logs pipeline is not permitted it. */\n | \"logs-content-disabled\"\n /** The fact carries verbatim text and `allowRawContent` is not set. */\n | \"raw-not-permitted\";\n\n/**\n * Whether disclosed content text may reach a log body.\n *\n * Two gates rather than one, and both must open. `includeContent` is the logs\n * pipeline's own switch, and it exists because spans carry no content in *any*\n * content mode: without it, turning on `privacy.contentMode` to get a hash and a\n * length — which is all it ever bought before — would start putting prompts on\n * the wire. `allowRawContent` is the pre-existing verbatim-content opt-in,\n * re-checked here because the sink is the last boundary before the wire and a\n * hand-built fact could otherwise carry `disclosure: \"raw\"` past a policy that\n * never permitted it.\n */\nexport type LogContentPolicy = {\n readonly includeContent: boolean;\n readonly allowRawContent: boolean;\n};\n\n/** Content disabled, which is what an unconfigured installation gets. */\nexport const NO_LOG_CONTENT: LogContentPolicy = Object.freeze({\n includeContent: false,\n allowRawContent: false,\n});\n\nconst codePointLength = (value: string): number => [...value].length;\n\nconst sliceCodePoints = (value: string, max: number): string => {\n let result = \"\";\n let count = 0;\n for (const char of value) {\n if (count >= max) {\n break;\n }\n result += char;\n count += 1;\n }\n return result;\n};\n\n/**\n * Which pipeline an event's records belong to.\n *\n * `factKind` refines the answer where one event type carries more than one kind\n * of content: a `generation.end` holds the response *and*, on providers that\n * report it, the reasoning that produced it, and collapsing those into one signal\n * would make \"drop reasoning, keep responses\" unexpressible.\n */\nexport const logSignalOf = (event: CanonicalEvent, factKind?: ContentFact[\"kind\"]): LogSignal => {\n switch (event.type) {\n case \"session.start\":\n case \"session.end\":\n return \"session\";\n case \"prompt.submitted\":\n return \"prompt\";\n case \"generation.start\":\n return factKind === \"reasoning\" ? \"reasoning\" : \"prompt\";\n case \"generation.end\":\n return factKind === \"reasoning\" ? \"reasoning\" : \"response\";\n case \"subagent.start\":\n case \"subagent.end\":\n return \"delegation\";\n case \"compaction.performed\":\n return \"compaction\";\n case \"error.raised\":\n return \"error\";\n case \"tool.start\":\n return toolSignal(event.toolName, event.toolKind);\n case \"tool.end\":\n // A `tool.end` carries no `toolKind`: only the start edge does. Classifying\n // from the name alone is what the canonical model permits here, so a shell\n // or file operation whose name does not say so lands on `tool` — and the\n // span for the same scope, which *did* recover the kind from state, is where\n // that detail is authoritative.\n return toolSignal(event.toolName, undefined);\n }\n};\n\nconst toolSignal = (\n toolName: string,\n toolKind: Extract<CanonicalEvent, { type: \"tool.start\" }>[\"toolKind\"] | undefined,\n): LogSignal => {\n if (MCP_TOOL_NAME_PATTERN.test(toolName)) {\n return \"mcp\";\n }\n switch (toolKind) {\n case \"execute\":\n return \"shell\";\n case \"read\":\n case \"write\":\n return \"file-operation\";\n case \"delegate\":\n return \"delegation\";\n default:\n return \"tool\";\n }\n};\n\n/**\n * Log signals an adapter declaring these lifecycle events can produce.\n *\n * Derived from the adapter's existing `lifecycleEvents` declaration rather than\n * declared separately, which is the whole point: a hand-maintained second list\n * can disagree with the first, and a capability declaration that has gone stale is\n * worse than none — a consumer cannot tell \"this provider reports no tool output\"\n * from \"this declaration was never updated\".\n *\n * The tool refinements (`shell`, `file-operation`, `mcp`) are reported whenever\n * the adapter emits tool events at all, because which of them a given callback\n * produces depends on the payload, not on the adapter. So this is a statement\n * about what *may* appear, not what always will.\n */\nexport const logSignalsForLifecycleEvents = (\n lifecycleEvents: readonly CanonicalEventType[],\n): readonly LogSignal[] => {\n const signals = new Set<LogSignal>();\n const add = (...values: readonly LogSignal[]): void => {\n for (const value of values) {\n signals.add(value);\n }\n };\n for (const type of lifecycleEvents) {\n switch (type) {\n case \"session.start\":\n case \"session.end\":\n add(\"session\");\n break;\n case \"prompt.submitted\":\n add(\"prompt\");\n break;\n case \"generation.start\":\n add(\"prompt\");\n break;\n case \"generation.end\":\n add(\"response\", \"reasoning\");\n break;\n case \"tool.start\":\n case \"tool.end\":\n add(\"tool\", \"shell\", \"file-operation\", \"mcp\", \"delegation\");\n break;\n case \"subagent.start\":\n case \"subagent.end\":\n add(\"delegation\");\n break;\n case \"compaction.performed\":\n add(\"compaction\");\n break;\n case \"error.raised\":\n add(\"error\");\n break;\n }\n }\n return LOG_SIGNALS.filter((signal) => signals.has(signal));\n};\n\nconst severityFor = (event: CanonicalEvent): SeverityNumber => {\n switch (event.type) {\n case \"error.raised\":\n return event.severity === \"error\" ? SeverityNumber.ERROR : SeverityNumber.WARN;\n case \"session.end\":\n return event.reason === \"error\" || event.reason === \"timeout\"\n ? SeverityNumber.ERROR\n : event.reason === \"aborted\"\n ? SeverityNumber.WARN\n : SeverityNumber.INFO;\n case \"generation.end\":\n case \"tool.end\":\n case \"subagent.end\":\n return event.outcome === \"error\" || event.outcome === \"timeout\"\n ? SeverityNumber.ERROR\n : event.outcome === \"denied\" || event.outcome === \"cancelled\"\n ? SeverityNumber.WARN\n : SeverityNumber.INFO;\n default:\n return SeverityNumber.INFO;\n }\n};\n\nconst SEVERITY_TEXT: Readonly<Record<number, string>> = Object.freeze({\n [SeverityNumber.INFO]: \"INFO\",\n [SeverityNumber.WARN]: \"WARN\",\n [SeverityNumber.ERROR]: \"ERROR\",\n});\n\nconst identityAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n ids: { readonly traceId: string; readonly spanId: string; readonly parentSpanId?: string },\n): LogAttributes => exportIdentityAttributes(event, resource, ids);\n\n/**\n * Attributes describing the event itself, independent of any content it carries.\n *\n * Every attribute here is a closed vocabulary, an identifier this library\n * derived, a count, or a boolean — the same restriction the privacy service\n * applies everywhere else, so an attribute can never become a second disclosure\n * path alongside the body.\n */\nconst eventAttributes = (event: CanonicalEvent): 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 ...targetAttributes(event),\n };\n case \"tool.end\":\n return {\n [ATTR_GEN_AI_TOOL_NAME]: event.toolName,\n [ATTR_GEN_AI_TOOL_CALL_ID]: event.toolCallId,\n [ATTR_OTELHOOK_OUTCOME]: event.outcome,\n ...(event.permissionDecision === undefined\n ? {}\n : { [ATTR_OTELHOOK_TOOL_PERMISSION]: event.permissionDecision }),\n ...targetAttributes(event),\n };\n case \"subagent.start\":\n return {\n [ATTR_OTELHOOK_DELEGATION_DEPTH]: event.delegationDepth,\n ...(event.subagentType === undefined\n ? {}\n : { [ATTR_OTELHOOK_SUBAGENT_TYPE]: event.subagentType }),\n ...(event.model === undefined ? {} : { [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId }),\n };\n case \"subagent.end\":\n return {\n [ATTR_OTELHOOK_OUTCOME]: event.outcome,\n ...usageAttributes(event.usage),\n };\n case \"compaction.performed\":\n return {\n [ATTR_OTELHOOK_COMPACTION_TRIGGER]: event.trigger,\n ...(event.contextTokensBefore === undefined\n ? {}\n : { [ATTR_OTELHOOK_CONTEXT_TOKENS_BEFORE]: event.contextTokensBefore }),\n ...(event.contextTokensAfter === undefined\n ? {}\n : { [ATTR_OTELHOOK_CONTEXT_TOKENS_AFTER]: event.contextTokensAfter }),\n ...(event.droppedMessageCount === undefined\n ? {}\n : { [ATTR_OTELHOOK_DROPPED_MESSAGES]: event.droppedMessageCount }),\n ...usageAttributes(event.usage),\n };\n case \"error.raised\":\n return {\n [ATTR_ERROR_TYPE]: event.errorCode,\n [ATTR_OTELHOOK_ERROR_PHASE]: event.phase,\n [ATTR_OTELHOOK_ERROR_RETRYABLE]: event.retryable,\n [ATTR_OTELHOOK_ERROR_SEVERITY]: event.severity,\n };\n }\n};\n\nconst usageAttributes = (usage: CanonicalUsage | undefined): 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 [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: usage.cachedInputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: usage.cacheCreationInputTokens,\n ...usageTemporalityAttributes(usage),\n };\n\n/** Content facts an event carries, paired with the field they came from. */\nconst contentFactsOf = (event: CanonicalEvent): readonly ContentFact[] => {\n switch (event.type) {\n case \"prompt.submitted\":\n return event.content === undefined ? [] : [event.content];\n case \"generation.start\":\n return event.inputContent ?? [];\n case \"generation.end\":\n return event.outputContent ?? [];\n case \"tool.start\":\n return event.input === undefined ? [] : [event.input];\n case \"tool.end\":\n return event.output === undefined ? [] : [event.output];\n case \"error.raised\":\n return event.message === undefined ? [] : [event.message];\n default:\n return [];\n }\n};\n\ntype DisclosedBody =\n | { readonly text: string; readonly truncated: boolean }\n | { readonly withheld: ContentWithholdingReason }\n | { readonly metadataOnly: true };\n\nconst discloseBody = (fact: ContentFact, policy: LogContentPolicy): DisclosedBody => {\n if (fact.text === undefined && fact.characterLength === 0) {\n // The provider sent no text. Distinct from a privacy omit of real content:\n // there is nothing to withhold, and the record must say metadata_only.\n return { metadataOnly: true };\n }\n if (fact.text === undefined) {\n return { withheld: \"privacy-policy\" };\n }\n if (!policy.includeContent) {\n return { withheld: \"logs-content-disabled\" };\n }\n if (fact.disclosure === \"raw\" && !policy.allowRawContent) {\n // Belt to the privacy service's braces: `resolvePrivacyPolicy` already\n // downgrades `raw` without the opt-in, so reaching here means a fact was built\n // outside that path. Refusing rather than trusting it keeps the opt-in a\n // property of the wire, not of one code path.\n return { withheld: \"raw-not-permitted\" };\n }\n const length = codePointLength(fact.text);\n return length <= MAX_LOG_BODY_CHARACTERS\n ? { text: fact.text, truncated: false }\n : { text: sliceCodePoints(fact.text, MAX_LOG_BODY_CHARACTERS), truncated: true };\n};\n\nconst contentAttributes = (fact: ContentFact, body: DisclosedBody): LogAttributes => ({\n [ATTR_CONTENT_KIND]: fact.kind,\n ...(fact.role === undefined ? {} : { [ATTR_CONTENT_ROLE]: fact.role }),\n [ATTR_CONTENT_DISCLOSURE]: \"metadataOnly\" in body ? \"metadata_only\" : fact.disclosure,\n [ATTR_CONTENT_CHARACTER_LENGTH]: fact.characterLength,\n [ATTR_CONTENT_BYTE_LENGTH]: fact.byteLength,\n [ATTR_CONTENT_HASH]: fact.contentHash,\n [ATTR_CONTENT_TRUNCATED]: fact.truncated,\n [ATTR_CONTENT_SECRETS_REDACTED]: fact.secretsRedacted,\n ...(fact.label === undefined ? {} : { [ATTR_CONTENT_LABEL]: fact.label }),\n ...(\"withheld\" in body\n ? { [ATTR_CONTENT_WITHHELD]: body.withheld }\n : \"metadataOnly\" in body\n ? {}\n : { [ATTR_CONTENT_BODY_TRUNCATED]: body.truncated }),\n});\n\nexport type LogMappingOptions = {\n readonly resource: Resource;\n readonly instrumentationScope?: InstrumentationScope;\n /** Whether disclosed text may reach a body. Defaults to {@link NO_LOG_CONTENT}. */\n readonly content?: LogContentPolicy;\n /**\n * The same cross-process pairing facts the span mapping is given, so a record's\n * `spanContext` names the span id that batch actually exported.\n */\n readonly correlations?: readonly SpanCorrelation[];\n /** See `SemanticMappingOptions.correlationAvailable`. */\n readonly correlationAvailable?: boolean;\n};\n\nexport type LogMappingResult = {\n readonly records: readonly ReadableLogRecord[];\n /**\n * Content facts no record was produced for, because a bound was reached.\n *\n * Reported rather than truncated silently: a caller that logged \"N records\n * exported\" and nothing else would read a clipped batch as a complete one.\n */\n readonly droppedFacts: number;\n};\n\nconst buildRecord = (input: {\n readonly event: CanonicalEvent;\n readonly signal: LogSignal;\n readonly attributes: LogAttributes;\n readonly body?: string;\n readonly spanContext: SpanContext;\n readonly parentSpanId?: string;\n readonly resource: Resource;\n readonly scope: InstrumentationScope;\n}): ReadableLogRecord => {\n const severityNumber = severityFor(input.event);\n const hrTime = millisToHrTime(input.event.occurredAt);\n return {\n hrTime,\n // A hook observes an event that already happened, and this mapping is pure —\n // there is no clock here to read a real observation time from. Reporting the\n // occurrence time for both is the honest answer: it says \"this is when it\n // happened\" twice rather than inventing a second, wrong timestamp.\n hrTimeObserved: hrTime,\n spanContext: input.spanContext,\n severityNumber,\n severityText: SEVERITY_TEXT[severityNumber] ?? \"INFO\",\n ...(input.body === undefined ? {} : { body: input.body }),\n eventName: `otelhook.${input.event.type}`,\n resource: input.resource,\n instrumentationScope: input.scope,\n attributes: {\n ...identityAttributes(input.event, input.resource, {\n traceId: input.spanContext.traceId,\n spanId: input.spanContext.spanId,\n ...(input.parentSpanId === undefined ? {} : { parentSpanId: input.parentSpanId }),\n }),\n [ATTR_OTELHOOK_EVENT_TYPE]: input.event.type,\n [ATTR_OTELHOOK_EVENT_ID]: input.event.eventId,\n [ATTR_OTELHOOK_EVENT_SEQUENCE]: input.event.sequence,\n [ATTR_OTELHOOK_LOG_SIGNAL]: input.signal,\n [ATTR_OTELHOOK_LOG_MAPPING_VERSION]: LOG_MAPPING_VERSION,\n ...input.attributes,\n },\n droppedAttributesCount: 0,\n };\n};\n\n/**\n * Map one invocation's canonical event batch into OTLP-ready log records.\n *\n * One record per content fact, and one record per event that carries none, so an\n * event is never silently absent from the stream just because the provider\n * reported no text for it.\n */\nexport const canonicalEventsToLogRecords = (\n events: readonly CanonicalEvent[],\n options: LogMappingOptions,\n): LogMappingResult => {\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const content = options.content ?? NO_LOG_CONTENT;\n const identities = canonicalEventTraceIdentities(events, {\n ...(options.correlations === undefined ? {} : { correlations: options.correlations }),\n ...(options.correlationAvailable === undefined\n ? {}\n : { correlationAvailable: options.correlationAvailable }),\n });\n\n const records: ReadableLogRecord[] = [];\n let droppedFacts = 0;\n\n for (const event of events) {\n const identity = identities.get(event.eventId);\n if (identity === undefined) {\n // Unreachable: every event in the batch is given an identity above.\n continue;\n }\n const spanContext: SpanContext = {\n traceId: identity.traceId,\n spanId: identity.spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n };\n const shared = eventAttributes(event);\n const facts = contentFactsOf(event);\n\n if (facts.length === 0) {\n if (records.length >= MAX_LOG_RECORDS_PER_BATCH) {\n droppedFacts += 1;\n continue;\n }\n records.push(\n buildRecord({\n event,\n signal: logSignalOf(event),\n attributes:\n event.type === \"generation.end\"\n ? { ...shared, [ATTR_CONTENT_KIND]: \"response\", [ATTR_CONTENT_DISCLOSURE]: \"metadata_only\" }\n : shared,\n spanContext,\n ...(identity.parentSpanId === undefined ? {} : { parentSpanId: identity.parentSpanId }),\n resource: options.resource,\n scope,\n }),\n );\n continue;\n }\n\n let perEvent = 0;\n for (const fact of facts) {\n if (perEvent >= MAX_LOG_RECORDS_PER_EVENT || records.length >= MAX_LOG_RECORDS_PER_BATCH) {\n droppedFacts += 1;\n continue;\n }\n perEvent += 1;\n const body = discloseBody(fact, content);\n records.push(\n buildRecord({\n event,\n signal: logSignalOf(event, fact.kind),\n attributes: { ...shared, ...contentAttributes(fact, body) },\n ...(\"text\" in body ? { body: body.text } : {}),\n spanContext,\n ...(identity.parentSpanId === undefined ? {} : { parentSpanId: identity.parentSpanId }),\n resource: options.resource,\n scope,\n }),\n );\n }\n }\n\n return { records, droppedFacts };\n};\n","import { 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 type { DeliveryHealthSnapshot } from \"../diagnostics/health.js\";\nimport type { OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { TelemetryEmitResult, TelemetrySink } from \"../runtime/ports.js\";\nimport type { OtlpLogTelemetrySink } from \"./otlp-log-sink.js\";\nimport type { OtlpTelemetrySink } from \"./otlp-sink.js\";\nimport type { SpanCorrelation, SpanCorrelationResolver } from \"./semconv.js\";\n\n/**\n * One canonical batch, two OTLP signals.\n *\n * A hook has a single {@link TelemetrySink} seam, and both signals map the *same*\n * canonical events — so this fans one batch out rather than making the orchestrator\n * aware that there is more than one destination.\n *\n * ## Durability adds up across signals\n *\n * The counts are summed rather than taken from the primary signal, because the\n * caller's question is \"may I commit this callback?\" and the answer turns on whether\n * *anything* reached a collector or a spool. Summing gives `classifyDurability`\n * exactly the right inputs:\n *\n * - both signals delivered → `delivered`\n * - neither delivered → `lost`, and the callback is safe to retry precisely because\n * there is nothing to duplicate\n * - one delivered and one did not → `partial`, which is terminal: retrying would\n * re-export what the healthy signal already delivered, and a duplicate silently\n * corrupts a total whereas a reported loss is a number somebody can act on\n *\n * A disabled sink accepts everything, so an installation with logs off behaves\n * exactly as it did before logs existed.\n *\n * ## Correlation must be resolved once per batch\n *\n * Both sinks want the same pairing facts, and `SpanCorrelator.correlateBatch` is not\n * a read — it records a start edge, marks a scope published, and takes the session\n * lock to do it. Wrap the correlator in {@link shareCorrelationPerBatch} and give\n * *the same wrapped function* to both sinks; `emit` here is sequential so the first\n * sink resolves it and the second is served the memoized answer.\n */\n\nexport type SignalFanoutOptions = {\n readonly traces: OtlpTelemetrySink;\n readonly logs: OtlpLogTelemetrySink;\n};\n\nexport interface SignalFanoutSink extends TelemetrySink {\n /** One snapshot per wired signal, in a stable order: traces, then logs. */\n health(): readonly DeliveryHealthSnapshot[];\n}\n\nexport const createSignalFanout = (options: SignalFanoutOptions): SignalFanoutSink => {\n const emit = async (events: readonly CanonicalEvent[]): Promise<TelemetryEmitResult> => {\n // Sequential, not concurrent: the first sink to ask resolves correlation, and\n // the second must be served that answer rather than race to start a second\n // resolution against the same state.\n const traces = await options.traces.emit(events);\n const logs = await options.logs.emit(events);\n const errors: readonly OtelHookErrorInfo[] = [...traces.errors, ...logs.errors];\n return {\n accepted: traces.accepted + logs.accepted,\n rejected: traces.rejected + logs.rejected,\n errors,\n };\n };\n\n const flush = async (): Promise<void> => {\n // Each signal's flush is already best-effort and non-throwing; awaiting both\n // unconditionally means a stuck logs endpoint cannot skip the trace flush.\n await options.traces.flush().catch(() => undefined);\n await options.logs.flush().catch(() => undefined);\n };\n\n const shutdown = async (): Promise<void> => {\n await options.traces.shutdown().catch(() => undefined);\n await options.logs.shutdown().catch(() => undefined);\n };\n\n return {\n emit,\n flush,\n shutdown,\n health: (): readonly DeliveryHealthSnapshot[] => [\n options.traces.health(),\n options.logs.health(),\n ],\n };\n};\n\n/**\n * Wrap a correlation resolver so one batch resolves at most once.\n *\n * Memoized on the identity of the `events` array, which is what makes it correct\n * without a reset: every batch is a distinct array, so a new batch cannot be served\n * a previous one's answer, and a retry of the *same* array deliberately is. The\n * promise is cached rather than its value, so two callers arriving before the first\n * resolution completes still share it.\n *\n * Exported because the one-call-per-batch property is a requirement of the\n * correlator, not a convenience of the fanout: a host wiring its own pair of sinks\n * needs to be able to express it too.\n */\nexport const shareCorrelationPerBatch = (\n correlate: SpanCorrelationResolver,\n): SpanCorrelationResolver => {\n let pending:\n | {\n readonly events: readonly CanonicalEvent[];\n readonly result: Promise<readonly SpanCorrelation[]>;\n }\n | undefined;\n return (events): Promise<readonly SpanCorrelation[]> => {\n if (pending?.events === events) {\n return pending.result;\n }\n const result = correlate(events);\n pending = { events, result };\n return result;\n };\n};\n","import type { OtelHookConfig } from \"../config/schema.js\";\nimport { summarizeHealth, type DeliveryHealthSnapshot, type OverallHealth } from \"../diagnostics/health.js\";\nimport { createErrorInfo, errorInfoFromThrown, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport {\n createCallbackDeduplicator,\n type CallbackDeduplicator,\n type DeliveryClaimOutcome,\n} from \"../lifecycle/dedup.js\";\nimport { createLifecycleJanitor, type LifecycleCleanupReport, type LifecycleJanitor } from \"../lifecycle/janitor.js\";\nimport { createSpanCorrelator, type SpanCorrelator } from \"../lifecycle/span-correlator.js\";\nimport {\n createUsageAccumulator,\n type UsageAccumulator,\n type UsageAccumulatorSnapshot,\n} from \"../lifecycle/usage-accumulator.js\";\nimport { createPrivacyService, type PrivacyService } from \"../privacy/service.js\";\nimport type { ProviderRegistry } from \"../providers/registry.js\";\nimport { createSystemClock } from \"../runtime/clock.js\";\nimport {\n createOtelHook,\n isCommittable,\n type HookIngestInput,\n type HookIngestOutcome,\n type OtelHook,\n type UsageObservation,\n} from \"../runtime/hook.js\";\nimport {\n hostDeliveryIdentity,\n type DeliveryOrigin,\n type DeliveryResolution,\n type DeliveryUnavailableReason,\n type ResolvedDeliveryIdentity,\n} from \"../runtime/delivery.js\";\nimport { createDeterministicIdGenerator } from \"../runtime/ids.js\";\nimport { createNullLogger } from \"../runtime/logger.js\";\nimport { createFilesystemWorktreeLocator } from \"../runtime/git-worktree.js\";\nimport type { Clock, IdGenerator, Logger, WorktreeLocator } from \"../runtime/ports.js\";\nimport { createAsyncLock } from \"../state/async-lock.js\";\nimport { createFilesystemStateStore, type FilesystemStateStore } from \"../state/filesystem-store.js\";\nimport {\n createFileDurableLogSpool,\n type DurableLogSpool,\n} from \"../telemetry/durable-log-spool.js\";\nimport { createFileDurableSpool, type DurableSpool } from \"../telemetry/durable-spool.js\";\nimport { createOtlpLogSink, type OtlpLogTelemetrySink } from \"../telemetry/otlp-log-sink.js\";\nimport { createOtlpTraceSink, type OtlpTelemetrySink } from \"../telemetry/otlp-sink.js\";\nimport {\n createSignalFanout,\n shareCorrelationPerBatch,\n} from \"../telemetry/signal-fanout.js\";\n\n/**\n * A hook process lives for milliseconds and then exits, but the facts it needs\n * — the previous cumulative token baseline, the next sequence number, a running\n * per-scope rollup, which deliveries have already been handled — span a whole\n * session. This module is the wiring that makes those two facts coexist without\n * a daemon: filesystem-backed state, a filesystem spool for batches an\n * unreachable collector refused, and a *bounded* flush so a hanging collector\n * costs the host a known number of milliseconds rather than a stalled agent.\n *\n * ## Delivery deduplication\n *\n * A redelivered callback must not be exported or accounted twice, and it must\n * stay suppressed across a process restart — which rules out anything held in\n * memory. Two identities can carry that:\n *\n * 1. An explicit, host-supplied delivery id ({@link HookProcessInput.delivery}),\n * unique by construction because only the host knows it.\n * 2. One normalized from payload fields the selected adapter vouches for — a\n * `tool_use_id`, an `agent_id`, a `prompt_id`. Adapters declare coverage as\n * `deliveryIdentifier` and report components per callback, and the runtime\n * digests them into an opaque, installation-and-session-scoped pair.\n *\n * Neither `invocationId` nor `eventId` can serve: some adapters seed the former\n * with a clock reading (Claude Code documents each hook firing as a distinct\n * invocation), and the latter is seeded with a session sequence number that has\n * already advanced by the time a redelivery arrives.\n *\n * Ownership is taken *before* `ingest` and committed only once the batch is\n * somewhere durable: a delivery arriving inside the window sees the claim and\n * stands down, and a batch that reached neither the collector nor the spool\n * releases its claim for retry instead of committing a loss.\n *\n * **This is at-least-once export, not exactly-once.** The collector is a separate\n * system and there is no transaction spanning an OTLP acceptance and a local state\n * write, so a process killed after the collector took a batch and before the claim\n * commits will re-export on redelivery. That ordering is deliberate: a duplicate\n * carries the same derived trace and span id and can be dropped at the collector,\n * whereas committing first would turn the same window into silent loss. Local\n * accounting *is* at-most-once, because it commits under the claim's own lock.\n *\n * ## Ordering and locks\n *\n * Two locks, always acquired in one order — delivery-scope lock, then state lock —\n * and never nested one state lock inside another:\n *\n * - An in-process lock on the delivery scope serializes same-scope deliveries in\n * arrival order, so deduplication never reorders what it lets through.\n * - `ingest` holds the store's *cross-process* session lock across the session\n * state critical section, which is what stops two hook processes from stamping\n * two batches with one sequence range. Export happens after that lock is\n * released: the span correlator takes the same session lock from inside the sink,\n * and it is not reentrant.\n *\n * ## Deliberate limitations\n *\n * 1. **Deduplication coverage is per provider, and partial for every adapter.** An\n * adapter that declares `deliveryIdentifier: \"partial\"` identifies only the\n * callbacks carrying a field that separates a genuine second firing from a\n * redelivery — for most that means per-tool-call and per-subagent edges, and for\n * the Gemini CLI, whose protocol has no such field at all, only the\n * once-per-session edges. The rest are exported without the at-most-once\n * guarantee unless the host supplies a delivery id; with `requireCallbackId` the\n * runtime says so per callback instead of leaving it to be inferred.\n * 2. **Cross-process span pairing needs a durable state root.** The\n * {@link SpanCorrelator} is wired into the sink, so a `*.end` emitted by a\n * later process carries its start time, duration, parent, and start-only\n * attributes. That correlation lives entirely in the state store: point two\n * invocations at different `stateRootDir`s and each exports a lone,\n * explicitly classified orphan instead. A disabled exporter records nothing,\n * since there is no span to pair.\n */\n\nexport type HookRuntimeDelivery = {\n /**\n * Host-supplied identifier for *this* delivery of a hook callback. Stable\n * across a redelivery of the same callback, unique between distinct\n * callbacks. Nothing derives it: only the host knows it.\n */\n readonly callbackId: string;\n /** Namespace the id is unique within. Defaults to `\"delivery\"`. */\n readonly scope?: string;\n};\n\nexport type HookProcessInput = HookIngestInput & {\n readonly delivery?: HookRuntimeDelivery;\n};\n\n/**\n * What deduplication did with this callback.\n *\n * Reported rather than inferred: \"exported once because it was fresh\" and\n * \"exported once because nothing could tell it apart from a redelivery\" produce\n * identical telemetry, and only the first is a guarantee.\n */\nexport type DeliveryReport = {\n /**\n * True when a replay-stable identity was established and a claim enforced.\n *\n * Not a promise of exactly-once export: see this module's note on crash\n * semantics. It means a redelivery arriving *while local state is intact* is\n * suppressed.\n */\n readonly deduplicated: boolean;\n /** Where the identity came from. Absent when none was established. */\n readonly origin?: DeliveryOrigin;\n /** How the claim resolved. Absent when no identity was established. */\n readonly outcome?: DeliveryClaimOutcome;\n /** Why no identity was established. Absent when one was. */\n readonly reason?: DeliveryUnavailableReason;\n /** The adapter's declared coverage, when a provider was selected. */\n readonly capability?: string;\n /**\n * The provider's own name for the callback that could not be identified.\n *\n * Present only alongside `reason`. Coverage is per callback, so a host auditing\n * its own gaps needs the callback name to act on the report at all — the\n * provider id and the capability are the same for every one of them.\n */\n readonly sourceEventName?: string;\n /**\n * The adapter's own account of why this callback has no identity, and what field\n * would close the gap. Absent when the adapter documents none.\n */\n readonly detail?: string;\n /** Adapter-supplied justifications for a provider-derived identity. */\n readonly evidence?: readonly string[];\n /**\n * True when a claim was released because the batch reached neither the\n * collector nor the spool, so redelivering this callback is expected to\n * re-export it rather than be suppressed.\n */\n readonly retryable?: boolean;\n /**\n * Spans permanently lost on a callback that is nonetheless **committed**.\n *\n * Present only for a partial batch: some spans reached the collector or the\n * spool and some did not. The callback is not retried, because retrying would\n * re-export the accepted spans, so these observations are gone. Reported as a\n * number rather than folded into `retryable` because the two demand opposite\n * responses — a retryable callback needs redelivering, a partial loss needs\n * investigating.\n */\n readonly partialLoss?: number;\n /**\n * True when another process reclaimed this callback's claim before this one\n * committed.\n *\n * Deduplication did not hold for this callback: both deliveries may have\n * exported it. Reported rather than hidden, because the cause is a\n * configured stale window that is too short for this installation and only an\n * operator can fix that.\n */\n readonly superseded?: boolean;\n};\n\nexport type HookProcessOutcome = {\n readonly ingest: HookIngestOutcome;\n /**\n * True when a matching delivery id had already been handled, so this\n * invocation's events were deliberately not exported. `ingest.emitted` is 0 in\n * that case; the provider's hook response is still produced normally, because\n * a redelivered callback still expects its protocol response.\n */\n readonly duplicateDelivery: boolean;\n /** Why this callback was, or was not, deduplicated. */\n readonly delivery: DeliveryReport;\n /** Running per-scope totals after applying this invocation's deltas. */\n readonly usageRollups: readonly UsageRollup[];\n /** Cleanup performed opportunistically; absent when no sweep ran. */\n readonly cleanup?: LifecycleCleanupReport;\n /** Diagnostics raised by this module, in addition to `ingest.diagnostics`. */\n readonly diagnostics: readonly OtelHookErrorInfo[];\n};\n\nexport type UsageRollup = {\n readonly scope: UsageObservation[\"scope\"];\n readonly scopeKey: string;\n readonly snapshot: UsageAccumulatorSnapshot;\n};\n\nexport type HookShutdownReport = {\n /** False when the bounded flush window elapsed before delivery finished. */\n readonly flushCompleted: boolean;\n readonly flushTimeoutMillis: number;\n readonly health: OverallHealth;\n};\n\nexport interface HookRuntime {\n readonly hook: OtelHook;\n readonly config: OtelHookConfig;\n readonly stateStore: FilesystemStateStore;\n /** The traces signal. Named `sink` because it is the one every installation has. */\n readonly sink: OtlpTelemetrySink;\n /** The logs signal. A no-op sink unless `exporter.logs.enabled` is set. */\n readonly logSink: OtlpLogTelemetrySink;\n readonly spool?: DurableSpool;\n /** Retry queue for the logs signal. Absent when spooling or logs are disabled. */\n readonly logSpool?: DurableLogSpool;\n readonly privacy: PrivacyService;\n readonly deduplicator: CallbackDeduplicator;\n readonly usageAccumulator: UsageAccumulator;\n /** Backs the cross-process pairing the sink applies to every exported span. */\n readonly spanCorrelator: SpanCorrelator;\n readonly janitor: LifecycleJanitor;\n /** Ingest one observation, then apply lifecycle accumulation. Never throws. */\n process(input: HookProcessInput): Promise<HookProcessOutcome>;\n /** Bounded flush + shutdown. Never throws; idempotent. */\n shutdown(): Promise<HookShutdownReport>;\n health(): OverallHealth;\n}\n\nexport type HookRuntimeOptions = {\n readonly config: OtelHookConfig;\n readonly registry: ProviderRegistry;\n /** Root of the state and spool trees. One directory per provider/installation below it. */\n readonly stateRootDir: string;\n /**\n * Namespace separating one deployment's state from another's. Not identity: it\n * never reaches an event, and no session or workspace is derived from it.\n */\n readonly installationId: string;\n /** State/spool namespace segment; the selected provider id, or a placeholder. */\n readonly providerNamespace: string;\n /** Exporter header *values*, deliberately absent from the config snapshot. */\n readonly headers?: Readonly<Record<string, string>>;\n readonly clock?: Clock;\n readonly ids?: IdGenerator;\n readonly logger?: Logger;\n readonly privacy?: PrivacyService;\n /** Upper bound on flush + shutdown. Default 2,000ms. */\n readonly flushTimeoutMillis?: number;\n /** Persist batches an unreachable collector refused. Default true. */\n readonly enableSpool?: boolean;\n /** Bounded lock waits keep a stuck peer from stalling the host. Default 1,000ms. */\n readonly stateLockTimeoutMillis?: number;\n /** Sweep expired lifecycle state when a session ends. Default true. */\n readonly sweepOnSessionEnd?: boolean;\n readonly lifecycleMaxAgeMillis?: number;\n /**\n * Normalize a delivery identity from the adapter when the host supplies none.\n * Default true. Set false to keep deduplication strictly opt-in per callback.\n */\n readonly deriveDeliveryIdentity?: boolean;\n /**\n * Raise `delivery-identifier-unavailable` for every callback that could not be\n * deduplicated, naming the provider and the capability that is missing. Default\n * false: without it, an unidentifiable callback is a silent absence of a\n * guarantee, which is exactly what a host auditing its own coverage cannot see.\n */\n readonly requireCallbackId?: boolean;\n /**\n * How long an uncommitted claim is respected before a later delivery may\n * assume the process that took it died. Default 60,000ms.\n */\n readonly staleClaimMillis?: number;\n /** TTL for dedup records specifically. Defaults to `lifecycleMaxAgeMillis`. */\n readonly deliveryRetentionMillis?: number;\n /**\n * Resolve the git worktree each tool event targeted (ADR 0008). Defaults to a\n * filesystem locator that reads `.git` and `HEAD` without spawning git; pass\n * `null` to disable resolution entirely.\n */\n readonly worktreeLocator?: WorktreeLocator | null;\n};\n\nconst DEFAULT_FLUSH_TIMEOUT_MILLIS = 2_000;\nconst DEFAULT_STATE_LOCK_TIMEOUT_MILLIS = 1_000;\nconst DEFAULT_LIFECYCLE_MAX_AGE_MILLIS = 24 * 60 * 60 * 1000;\nconst DEFAULT_STALE_CLAIM_MILLIS = 60_000;\n\nconst delay = (millis: number): Promise<\"timeout\"> =>\n new Promise((resolve) => {\n const timer = setTimeout(() => resolve(\"timeout\"), millis);\n timer.unref?.();\n });\n\nconst containsSessionEnd = (events: readonly CanonicalEvent[]): boolean =>\n events.some((event) => event.type === \"session.end\");\n\n/** Delivery is this module's own concern; `ingest` never sees it. */\nconst withoutDelivery = (input: HookProcessInput): HookIngestInput => {\n const { delivery, ...ingestInput } = input;\n void delivery;\n return ingestInput;\n};\n\n/**\n * Smallest stale-claim window that cannot expire while a live process is still\n * working on the callback it claimed.\n *\n * A claim is taken before `ingest` and committed after export, so the window has\n * to cover the whole of that: waiting for the session state lock, the adapter's\n * work, then every export attempt the exporter policy permits, then the bounded\n * flush. If `staleClaimMillis` is shorter than that, a second delivery arriving\n * mid-flight declares the first one abandoned and *reclaims* it — and then both\n * processes export the same callback. That is not a smaller guarantee, it is the\n * opposite of the one being advertised, produced by a configuration value that\n * looks like a harmless tuning knob.\n *\n * So the floor is derived from the same policy the work is bounded by, rather\n * than being a constant that a later timeout change could silently outgrow. The\n * multiplier on the export timeout counts the first attempt plus each retry.\n */\n/**\n * Bounded lock acquisitions between `claim` and `commit`, counted rather than\n * guessed.\n *\n * Each one can cost a full `stateLockTimeoutMillis` under contention, so the floor\n * has to include all of them. Enumerated so that adding a locked step without\n * revisiting this number is visibly an omission:\n *\n * 1. `ingest` phase 1 — the session-state critical section (read sequence, parse,\n * reserve).\n * 2. `ingest` phase 3 — the usage-accounting critical section.\n * 3. the span correlator, called from inside the sink during export.\n * 4. `deduplicator.commit` itself.\n */\nconst POST_CLAIM_LOCK_ACQUISITIONS = 4;\n\n/**\n * Locked operations the *accounting* phase performs, per usage observation.\n *\n * `recordReset` then `accumulateDelta`, each taking the session lock on its own.\n * Multiplied by the observation cap below rather than by the raw event limit: usage\n * lands on end-edge events only, so the cap is generous rather than exact.\n */\nconst ACCOUNTING_LOCKS_PER_OBSERVATION = 2;\n\n/**\n * How many usage observations the floor budgets for.\n *\n * Deliberately not `limits.maxEventsPerInvocation` (512 by default): summing 1,024\n * lock timeouts would put the floor in the tens of minutes, and a floor that large\n * is its own problem — it delays recovery of genuinely crashed claims by that long.\n * A real hook callback carries a handful of usage-bearing events, so this is the\n * conservative-but-useful bound, and the ownership check below is what covers the\n * case where reality exceeds it: a claim reclaimed under a live holder is *detected*\n * at commit rather than silently double-counted.\n */\nconst BUDGETED_USAGE_OBSERVATIONS = 8;\n\n/**\n * Smallest stale-claim window that cannot expire while a live process is still\n * working on the callback it claimed.\n *\n * A claim is taken before `ingest` and committed after accounting, so the window has\n * to cover the whole of that: every bounded lock acquisition on the way, every\n * export attempt the exporter policy permits, the spool write that follows a refused\n * export, and the bounded flush. If `staleClaimMillis` is shorter, a second delivery\n * arriving mid-flight declares the first one abandoned and *reclaims* it — and then\n * both processes export the same callback. That is not a smaller guarantee, it is\n * the opposite of the one being advertised, produced by a value that looks like a\n * harmless tuning knob.\n *\n * Derived from the same policy the work is bounded by, rather than a constant a\n * later timeout change could silently outgrow. It is a *floor*, not a prediction:\n * being generous costs only recovery latency after a crash, while being short costs\n * correctness.\n */\nexport const minimumStaleClaimMillis = (input: {\n readonly exportTimeoutMillis: number;\n readonly maxRetryAttempts: number;\n readonly flushTimeoutMillis: number;\n readonly stateLockTimeoutMillis: number;\n}): number => {\n const exportBudget = input.exportTimeoutMillis * (input.maxRetryAttempts + 1);\n const lockBudget =\n input.stateLockTimeoutMillis *\n (POST_CLAIM_LOCK_ACQUISITIONS +\n ACCOUNTING_LOCKS_PER_OBSERVATION * BUDGETED_USAGE_OBSERVATIONS);\n // A refused export writes the batch to the spool before returning, and the\n // janitor may sweep on a session-end callback. Both are bounded but neither has\n // its own configured timeout, so they share one allowance.\n const spoolAndSweepAllowance = 2 * input.stateLockTimeoutMillis;\n // A margin so a value derived from the same numbers is not exactly on the\n // boundary; process scheduling alone can cost tens of milliseconds.\n const margin = 1_000;\n return lockBudget + exportBudget + input.flushTimeoutMillis + spoolAndSweepAllowance + margin;\n};\n\nconst DELIVERY_UNAVAILABLE_DETAIL: Readonly<Record<DeliveryUnavailableReason, string>> =\n Object.freeze({\n \"provider-unattributed\":\n \"no provider was attributed, so no adapter could vouch for a replay-stable identifier\",\n \"provider-declares-none\":\n \"the selected adapter declares deliveryIdentifier=none: no callback of this provider carries a replay-stable identifier, so only --callback-id can deduplicate it\",\n \"callback-not-identifiable\":\n \"the selected adapter identifies some callbacks but not this one; it carries no field that separates a redelivery from a genuine second firing\",\n \"claim-rejected\":\n \"the selected adapter offered a delivery identity that failed the contract's own guards\",\n \"state-unavailable\":\n \"a delivery identity was established but the state store could not record a claim against it\",\n });\n\nexport const createHookRuntime = (options: HookRuntimeOptions): HookRuntime => {\n const clock = options.clock ?? createSystemClock();\n const ids = options.ids ?? createDeterministicIdGenerator();\n const logger = options.logger ?? createNullLogger();\n const privacy = options.privacy ?? createPrivacyService(options.config.privacy);\n const flushTimeoutMillis = options.flushTimeoutMillis ?? DEFAULT_FLUSH_TIMEOUT_MILLIS;\n const lifecycleMaxAge = options.lifecycleMaxAgeMillis ?? DEFAULT_LIFECYCLE_MAX_AGE_MILLIS;\n const stateLockTimeoutMillis = options.stateLockTimeoutMillis ?? DEFAULT_STATE_LOCK_TIMEOUT_MILLIS;\n\n // Raised, never lowered, and reported when raised: silently honouring a window\n // shorter than one process's own work would turn suppression into a double\n // export. See `minimumStaleClaimMillis`.\n const staleClaimFloor = minimumStaleClaimMillis({\n exportTimeoutMillis: options.config.exporter.timeoutMillis,\n maxRetryAttempts: options.config.exporter.maxRetryAttempts,\n flushTimeoutMillis,\n stateLockTimeoutMillis,\n });\n const requestedStaleClaim = options.staleClaimMillis ?? DEFAULT_STALE_CLAIM_MILLIS;\n const staleClaimMillis = Math.max(requestedStaleClaim, staleClaimFloor);\n if (staleClaimMillis > requestedStaleClaim) {\n logger.warn(\"staleClaimMillis raised to cover this installation's own export budget\", {\n \"delivery.stale_claim_requested_millis\": requestedStaleClaim,\n \"delivery.stale_claim_effective_millis\": staleClaimMillis,\n });\n }\n\n const stateStore = createFilesystemStateStore({\n rootDir: options.stateRootDir,\n providerId: options.providerNamespace,\n installationId: options.installationId,\n clock,\n logger,\n lockTimeoutMillis: stateLockTimeoutMillis,\n });\n\n const spool =\n options.enableSpool === false\n ? undefined\n : createFileDurableSpool({\n rootDir: options.stateRootDir,\n providerId: options.providerNamespace,\n installationId: options.installationId,\n clock,\n logger,\n });\n\n // A separate queue from the trace spool, so a logs outage cannot consume the\n // capacity the primary signal's retries need. Only built when logs are on: a\n // default installation must not create a directory for a signal it never emits.\n const logSpool =\n options.enableSpool === false || !options.config.exporter.logs.enabled\n ? undefined\n : createFileDurableLogSpool({\n rootDir: options.stateRootDir,\n providerId: options.providerNamespace,\n installationId: options.installationId,\n clock,\n logger,\n });\n\n const spanCorrelator = createSpanCorrelator({\n stateStore,\n clock,\n maxStartAgeMillis: lifecycleMaxAge,\n });\n\n /**\n * One correlation resolution per batch, shared by both signals.\n *\n * `correlateBatch` records the start edge and marks a scope published, so two\n * calls for one batch would have the second see the first's writes and report a\n * start it just recorded as a duplicate — leaving the two signals pointing at\n * different span ids for the same scope.\n */\n const correlate = shareCorrelationPerBatch((events) => spanCorrelator.correlateBatch(events));\n\n const traceSink = createOtlpTraceSink({\n exporter: options.config.exporter,\n ...(options.headers === undefined ? {} : { headers: options.headers }),\n providerId: options.providerNamespace,\n installationId: options.installationId,\n clock,\n logger,\n ...(spool === undefined ? {} : { spool }),\n correlate,\n });\n\n const logSink = createOtlpLogSink({\n exporter: options.config.exporter,\n ...(options.headers === undefined ? {} : { headers: options.headers }),\n providerId: options.providerNamespace,\n installationId: options.installationId,\n clock,\n logger,\n ...(logSpool === undefined ? {} : { spool: logSpool }),\n content: {\n includeContent: options.config.exporter.logs.includeContent,\n // The pre-existing verbatim-content opt-in, passed through rather than\n // re-derived: `raw` disclosure in a log body is governed by the same flag it\n // has always been governed by.\n allowRawContent: privacy.policy.allowRawContent,\n },\n correlate,\n });\n\n const sink = createSignalFanout({ traces: traceSink, logs: logSink });\n\n const hookDeps = {\n stateStore,\n config: options.config,\n registry: options.registry,\n clock,\n ids,\n privacy,\n logger,\n installationId: options.installationId,\n ...(options.worktreeLocator === null\n ? {}\n : {\n worktreeLocator:\n options.worktreeLocator ??\n createFilesystemWorktreeLocator({ monotonicMillis: () => clock.monotonicMillis() }),\n }),\n };\n const hook = createOtelHook({ ...hookDeps, sink });\n\n const deduplicator = createCallbackDeduplicator({ stateStore, clock });\n const usageAccumulator = createUsageAccumulator({ stateStore, clock });\n const deliveryRetentionMillis = options.deliveryRetentionMillis ?? lifecycleMaxAge;\n if (deliveryRetentionMillis < staleClaimMillis) {\n // Not raised, only reported: an operator who wants dedup records gone in a\n // minute is entitled to that, and the sweep already refuses to drop a claim\n // inside the stale window. What they are not entitled to is a *silent* gap —\n // a completed record that expires before a redelivery could plausibly arrive\n // stops suppressing it, and this is the number that explains why.\n logger.warn(\"delivery retention is shorter than the stale-claim window\", {\n \"delivery.retention_millis\": deliveryRetentionMillis,\n \"delivery.stale_claim_effective_millis\": staleClaimMillis,\n });\n }\n const janitor = createLifecycleJanitor({\n spanCorrelator,\n deduplicator,\n usageAccumulator,\n spanMaxAgeMillis: lifecycleMaxAge,\n dedupMaxAgeMillis: deliveryRetentionMillis,\n // The *effective* window, not the requested one: a sweep that considered a\n // claim dead earlier than the claim path does would hand a live callback to a\n // peer as fresh.\n dedupStaleClaimMillis: staleClaimMillis,\n usageMaxAgeMillis: lifecycleMaxAge,\n });\n\n const deliveryLock = createAsyncLock();\n\n const stateDiagnostic = (thrown: unknown): OtelHookErrorInfo =>\n errorInfoFromThrown(thrown, { code: \"state-store-failure\", phase: \"state\", occurredAt: clock.now() });\n\n /**\n * Opaque, replay-stable token for a delivery, safe to write into a state record.\n *\n * Digested rather than used directly, because a *host-supplied* callback id is a\n * raw external identifier and a rollup record's contents are not a place one may\n * appear as a side effect of deduplicating on it. The digest is content-addressed,\n * so a later process recomputes the same token — which is the whole point: the\n * retry has to recognize its own earlier application.\n */\n const rollupDeliveryToken = (identity: ResolvedDeliveryIdentity): string | undefined => {\n // Clamped to the shape the state schema admits, because `ids` is injected: the\n // default generator returns a hex digest, but a host's own could return anything.\n // An unusable token must cost the *idempotency check* and nothing else — writing\n // it would fail validation and take the whole rollup down with it, which trades a\n // possible double count for a certain lost one.\n const token = ids\n .newOpaqueId([\"usage-delivery\", identity.scope, identity.callbackId])\n .replace(/[^A-Za-z0-9_-]/g, \"\")\n .slice(0, 128);\n return token.length === 0 ? undefined : token;\n };\n\n const applyRollups = async (\n sessionId: string,\n observations: readonly UsageObservation[],\n diagnostics: OtelHookErrorInfo[],\n deliveryToken?: string,\n ): Promise<readonly UsageRollup[]> => {\n const rollups: UsageRollup[] = [];\n // Per rollup key, because idempotency is per record: two observations landing on\n // one key are the first and second application *to that key*, whatever their\n // position in the batch.\n const ordinals = new Map<string, number>();\n for (const observation of observations) {\n const key = { sessionId, scope: observation.scope, scopeKey: observation.scopeKey };\n const rollupId = `${observation.scope}\u0000${observation.scopeKey}`;\n const ordinal = ordinals.get(rollupId) ?? 0;\n ordinals.set(rollupId, ordinal + 1);\n // Absent when no delivery identity was established: there is then nothing to\n // recognize a repeat by, and declining to accumulate would lose a real\n // observation rather than avoid a duplicate one.\n const options =\n deliveryToken === undefined\n ? undefined\n : { delivery: { callbackId: deliveryToken, ordinal } };\n try {\n if (observation.resetDetected) {\n // A restarted provider counter starts a new epoch rather than\n // deflating the running total (see createUsageAccumulator).\n await usageAccumulator.recordReset(key, options);\n }\n const snapshot = await usageAccumulator.accumulateDelta(key, observation.delta, options);\n rollups.push({ scope: observation.scope, scopeKey: observation.scopeKey, snapshot });\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"usage-invalid\",\n phase: \"normalization\",\n occurredAt: clock.now(),\n }),\n );\n }\n }\n return rollups;\n };\n\n /**\n * Establish this callback's delivery identity.\n *\n * A host-supplied id always wins: the host knows things about its own\n * redelivery that no payload states. Only when there is none does the adapter\n * get asked, and only if derivation is enabled.\n */\n const identifyDelivery = (\n input: HookProcessInput,\n ): { readonly identity?: ResolvedDeliveryIdentity; readonly unavailable?: DeliveryResolution } => {\n if (input.delivery !== undefined) {\n return {\n identity: hostDeliveryIdentity(input.delivery.callbackId, input.delivery.scope),\n };\n }\n if (options.deriveDeliveryIdentity === false) {\n return {};\n }\n const resolution = hook.resolveDelivery(withoutDelivery(input));\n return resolution.status === \"resolved\"\n ? { identity: resolution.identity }\n : { unavailable: resolution };\n };\n\n const reportUnavailable = (\n resolution: DeliveryResolution | undefined,\n diagnostics: OtelHookErrorInfo[],\n ): DeliveryReport => {\n if (resolution === undefined || resolution.status === \"resolved\") {\n // Either an identity was established, or none was even attempted because the\n // host supplied its own id or switched derivation off. Neither is a provider\n // gap, so `requireCallbackId` has nothing to report.\n return { deduplicated: false };\n }\n if (options.requireCallbackId === true) {\n // The generic sentence explains the *reason code*; the adapter's own gap\n // explains the *callback*. Both are useful and they answer different\n // questions, so the detail carries the general statement and then the\n // specific one rather than replacing either.\n const generic = DELIVERY_UNAVAILABLE_DETAIL[resolution.reason];\n const detail =\n resolution.detail === undefined ? generic : `${generic}; ${resolution.detail}`;\n diagnostics.push(\n createErrorInfo({\n code: \"delivery-identifier-unavailable\",\n phase: \"identity\",\n detail: detail.slice(0, 400),\n details: {\n \"delivery.reason\": resolution.reason,\n ...(resolution.providerId === undefined ? {} : { \"provider.id\": resolution.providerId }),\n ...(resolution.capability === undefined\n ? {}\n : { \"provider.delivery_identifier\": resolution.capability }),\n ...(resolution.sourceEventName === undefined\n ? {}\n : { \"delivery.source_event_name\": resolution.sourceEventName }),\n \"delivery.remedy\": \"pass an explicit host delivery id (--callback-id)\",\n },\n occurredAt: clock.now(),\n }),\n );\n }\n return {\n deduplicated: false,\n reason: resolution.reason,\n ...(resolution.capability === undefined ? {} : { capability: resolution.capability }),\n ...(resolution.sourceEventName === undefined\n ? {}\n : { sourceEventName: resolution.sourceEventName }),\n ...(resolution.detail === undefined ? {} : { detail: resolution.detail }),\n };\n };\n\n const runProcess = async (\n input: HookProcessInput,\n identity: ResolvedDeliveryIdentity | undefined,\n report: DeliveryReport,\n diagnostics: OtelHookErrorInfo[],\n ): Promise<HookProcessOutcome> => {\n let delivery = report;\n let owned = false;\n let claimOwner: string | undefined;\n\n if (identity !== undefined) {\n try {\n const claimed = await deduplicator.claim(identity.scope, identity.callbackId, {\n staleClaimMillis,\n });\n owned = claimed.owned;\n claimOwner = claimed.owner;\n delivery = {\n deduplicated: true,\n origin: identity.origin,\n outcome: claimed.outcome,\n ...(identity.evidence.length === 0 ? {} : { evidence: identity.evidence }),\n };\n if (claimed.outcome === \"reclaimed\") {\n logger.warn(\"took over a delivery claim no process ever completed\", {\n \"delivery.origin\": identity.origin,\n \"delivery.attempt\": claimed.attempt,\n \"delivery.abandoned_for_millis\": claimed.abandonedForMillis ?? 0,\n });\n }\n if (claimed.duplicate) {\n logger.info(\"delivery already handled; telemetry suppressed\", {\n \"delivery.origin\": identity.origin,\n \"delivery.outcome\": claimed.outcome,\n });\n }\n } catch (thrown) {\n // An unreadable dedup record must not drop telemetry: exporting a\n // possible duplicate is recoverable at the collector, losing a real\n // observation is not. Deduplication is what lapses here, so\n // the report says so rather than claiming a guarantee that did not hold.\n diagnostics.push(stateDiagnostic(thrown));\n delivery = { deduplicated: false, origin: identity.origin, reason: \"state-unavailable\" };\n }\n }\n\n const duplicateDelivery = delivery.outcome === \"duplicate\" || delivery.outcome === \"in-flight\";\n // A redelivery is parsed but changes nothing: no export, no sequence advance,\n // no cumulative-usage rewrite. Suppressing inside `ingest` rather than at the\n // sink is what makes that true — a discarding sink still let the orchestrator\n // renumber the session and move the usage baseline, so a redelivered callback\n // silently shifted every later event's derived id.\n const ingest = await hook.ingest(withoutDelivery(input), { suppress: duplicateDelivery });\n\n let usageRollups: readonly UsageRollup[] = [];\n if (!duplicateDelivery && ingest.identity !== undefined && ingest.usageObservations.length > 0) {\n // The rollup is the one piece of accounting that sits *outside* `ingest`'s\n // own transaction, in a second critical section — the accumulator takes the\n // same non-reentrant session lock. That leaves this the only place a retried\n // or reclaimed delivery could apply its numbers twice, so it is the one place\n // that gets stamped with the delivery it belongs to.\n usageRollups = await applyRollups(\n ingest.identity.sessionId,\n ingest.usageObservations,\n diagnostics,\n identity === undefined ? undefined : rollupDeliveryToken(identity),\n );\n }\n\n if (owned && identity !== undefined) {\n // Committing means \"this callback is accounted for; never process it again\",\n // so the decision turns on whether *anything* survived rather than whether\n // everything did — see `DeliveryDurability`.\n //\n // A partially delivered batch is terminal, and that is the uncomfortable but\n // correct answer. Releasing it would retry the whole callback and re-export\n // every span a collector already accepted, turning a reported loss into a\n // silent double-count; a duplicated span corrupts a total that nobody can\n // reconstruct, whereas a reported loss is a number somebody can act on. So\n // the callback commits and the loss is stated.\n try {\n if (isCommittable(ingest.durability)) {\n const committed = await deduplicator.commit(\n identity.scope,\n identity.callbackId,\n claimOwner,\n );\n if (committed.status === \"superseded\") {\n // The stale window was shorter than this installation's real worst\n // case, so a peer took the claim over mid-flight and both of us may have\n // exported. No floor computation can rule this out, so it is reported\n // rather than assumed away.\n delivery = { ...delivery, deduplicated: false, superseded: true };\n diagnostics.push(\n createErrorInfo({\n code: \"delivery-claim-superseded\",\n phase: \"state\",\n detail:\n \"another process reclaimed this delivery claim before it was committed; raise staleClaimMillis\",\n details: {\n \"delivery.origin\": identity.origin,\n \"delivery.attempt\": committed.attempt,\n },\n occurredAt: clock.now(),\n }),\n );\n logger.warn(\"delivery claim superseded before commit; deduplication did not hold\", {\n \"delivery.origin\": identity.origin,\n \"delivery.attempt\": committed.attempt,\n });\n }\n if (ingest.durability === \"partial\") {\n delivery = { ...delivery, partialLoss: ingest.exportRejected };\n logger.warn(\"delivery partially lost; committed to avoid re-exporting accepted spans\", {\n \"delivery.origin\": identity.origin,\n \"export.accepted\": ingest.emitted,\n \"export.rejected\": ingest.exportRejected,\n });\n }\n } else {\n // Nothing survived, so a retry cannot duplicate anything. Released rather\n // than left to age out, so the next delivery is treated as fresh\n // immediately instead of standing down for the whole stale window against\n // a process that is no longer running.\n await deduplicator.release(identity.scope, identity.callbackId);\n delivery = { ...delivery, deduplicated: false, retryable: true };\n logger.warn(\"delivery not durably recorded; claim released for retry\", {\n \"delivery.origin\": identity.origin,\n \"export.rejected\": ingest.exportRejected,\n });\n }\n } catch (thrown) {\n diagnostics.push(stateDiagnostic(thrown));\n }\n }\n\n let cleanup: LifecycleCleanupReport | undefined;\n if (\n (options.sweepOnSessionEnd ?? true) &&\n ingest.identity !== undefined &&\n containsSessionEnd(ingest.events)\n ) {\n try {\n cleanup = await janitor.runOnce(ingest.identity.sessionId);\n const neverExported = cleanup.span?.expiredOpen ?? 0;\n if (neverExported > 0) {\n // A start that aged out without its end never produced a span at all.\n // Said out loud, because the alternative reading of the same silence is\n // \"nothing happened\".\n logger.warn(\"expired lifecycle spans were never completed, so never exported\", {\n \"lifecycle.expired_open_spans\": neverExported,\n });\n }\n } catch (thrown) {\n diagnostics.push(stateDiagnostic(thrown));\n }\n }\n\n return {\n ingest,\n duplicateDelivery,\n delivery,\n usageRollups,\n ...(cleanup === undefined ? {} : { cleanup }),\n diagnostics,\n };\n };\n\n const process_ = async (input: HookProcessInput): Promise<HookProcessOutcome> => {\n const diagnostics: OtelHookErrorInfo[] = [];\n const identified = identifyDelivery(input);\n const report = reportUnavailable(identified.unavailable, diagnostics);\n\n if (identified.identity === undefined) {\n return runProcess(input, undefined, report, diagnostics);\n }\n\n // Deliveries sharing a scope run one at a time, in arrival order: a claim\n // that is only decided after a peer has already exported is not a claim.\n // Unrelated scopes stay concurrent, and this is an in-process lock layered\n // over the store's cross-process one, so it never contends with itself.\n return deliveryLock.run(identified.identity.scope, () =>\n runProcess(input, identified.identity, report, diagnostics),\n );\n };\n\n const snapshots = (): readonly DeliveryHealthSnapshot[] => sink.health();\n\n let shutdownReport: Promise<HookShutdownReport> | undefined;\n const shutdown = (): Promise<HookShutdownReport> => {\n shutdownReport ??= (async (): Promise<HookShutdownReport> => {\n const raced = await Promise.race([\n hook.shutdown().then(() => \"completed\" as const),\n delay(flushTimeoutMillis),\n ]);\n if (raced === \"timeout\") {\n // Not an error the host should ever feel: the batch is either spooled\n // for a later invocation or reported unhealthy, and either way the hook\n // returns within a bounded time.\n logger.warn(\"bounded flush window elapsed before delivery completed\", {\n \"shutdown.flush_timeout_millis\": flushTimeoutMillis,\n });\n }\n return {\n flushCompleted: raced === \"completed\",\n flushTimeoutMillis,\n health: summarizeHealth(snapshots()),\n };\n })();\n return shutdownReport;\n };\n\n return {\n hook,\n config: options.config,\n stateStore,\n sink: traceSink,\n logSink,\n ...(spool === undefined ? {} : { spool }),\n ...(logSpool === undefined ? {} : { logSpool }),\n privacy,\n deduplicator,\n usageAccumulator,\n spanCorrelator,\n janitor,\n process: process_,\n shutdown,\n health: (): OverallHealth => summarizeHealth(snapshots()),\n };\n};\n"],"mappings":";AAwDO,IAAM,sBAAsB,CACjC,WACA,UAAgC,CAAC,MACf;AAClB,QAAM,qBAAqB,QAAQ,qCAAqC;AACxE,MAAI,gBAAgB;AACpB,MAAI,gBAAgB;AACpB,MAAI,sBAAsB;AAC1B,MAAI;AACJ,MAAI;AACJ,MAAI;AAEJ,SAAO;AAAA,IACL,eAAe,CAAC,QAAQ,GAAG,OAAsB;AAC/C,uBAAiB;AACjB,4BAAsB;AACtB,UAAI,OAAO,QAAW;AACpB,wBAAgB;AAAA,MAClB;AAAA,IACF;AAAA,IACA,eAAe,CAAC,MAAyB,QAAQ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Q,MAAM,QAAQ,KAAK;AAAA,QAC/B,KAAK,SAAS,EAAE,KAAK,MAAM,WAAoB;AAAA,QAC/C,MAAM,kBAAkB;AAAA,MAC1B,CAAC;AACD,UAAI,UAAU,WAAW;AAIvB,eAAO,KAAK,0DAA0D;AAAA,UACpE,iCAAiC;AAAA,QACnC,CAAC;AAAA,MACH;AACA,aAAO;AAAA,QACL,gBAAgB,UAAU;AAAA,QAC1B;AAAA,QACA,QAAQ,gBAAgB,UAAU,CAAC;AAAA,MACrC;AAAA,IACF,GAAG;AACH,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL;AAAA,IACA,QAAQ,QAAQ;AAAA,IAChB;AAAA,IACA,MAAM;AAAA,IACN;AAAA,IACA,GAAI,UAAU,SAAY,CAAC,IAAI,EAAE,MAAM;AAAA,IACvC,GAAI,aAAa,SAAY,CAAC,IAAI,EAAE,SAAS;AAAA,IAC7C;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS;AAAA,IACT;AAAA,IACA,QAAQ,MAAqB,gBAAgB,UAAU,CAAC;AAAA,EAC1D;AACF;","names":["z","z","z","owner","ExportResultCode","event","event","parent","result","event","z","z","usageKey","createHash","z","z","z","createHash","path","z","z","z","z","z","z","z","z","z","parsed","z","z","z","z","z","z","z","createHash","createHash","z","z","event","resolve","z","event","batch","path","randomBytes","open","path","createHash","resolve","randomBytes","open","randomBytes","mkdir","readFile","readdir","rename","unlink","writeFile","path","isErrnoException","mkdir","readdir","randomBytes","writeFile","rename","unlink","readFile","TRACE_ID_PATTERN","SPAN_ID_PATTERN","isFiniteNonNegative","isBoundedString","isPlainObject","TraceFlags","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_CACHE_CREATION_INPUT_TOKENS","ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS","ATTR_GEN_AI_USAGE_INPUT_TOKENS","ATTR_GEN_AI_USAGE_OUTPUT_TOKENS","ATTR_OTELHOOK_OUTCOME","ATTR_OTELHOOK_TOOL_KIND","ATTR_OTELHOOK_DELEGATION_DEPTH","ATTR_OTELHOOK_AGENT_NAME","ATTR_OTELHOOK_AGENT_VERSION","ATTR_OTELHOOK_GENERATION_ID","ATTR_OTELHOOK_COMPACTION_TRIGGER","codePointLength","sliceCodePoints","event","event","identityAttributes","ATTR_OTELHOOK_AGENT_NAME","ATTR_OTELHOOK_AGENT_VERSION","ATTR_GEN_AI_REQUEST_MODEL","ATTR_OTELHOOK_OUTCOME","usageAttributes","ATTR_GEN_AI_OPERATION_NAME","ATTR_OTELHOOK_GENERATION_ID","ATTR_GEN_AI_SYSTEM","ATTR_GEN_AI_RESPONSE_MODEL","ATTR_GEN_AI_TOOL_NAME","ATTR_GEN_AI_TOOL_CALL_ID","ATTR_OTELHOOK_TOOL_KIND","ATTR_OTELHOOK_DELEGATION_DEPTH","ATTR_OTELHOOK_COMPACTION_TRIGGER","ATTR_ERROR_TYPE","ATTR_GEN_AI_USAGE_INPUT_TOKENS","ATTR_GEN_AI_USAGE_OUTPUT_TOKENS","ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS","ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS","codePointLength","sliceCodePoints","hrTime","TraceFlags","TraceFlags","resolve","chunk","createDisabledSink","resolve","DEFAULT_STALE_CLAIM_MILLIS","resolve","event","options"]}