@osfactory/otel-hook 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +6 -4
  2. package/dist/{adapter-DQiPu8xF.d.ts → adapter-DyCb7y1N.d.ts} +1 -1
  3. package/dist/cli.js +137 -44
  4. package/dist/cli.js.map +1 -1
  5. package/dist/{export-destinations-CI7z4n3i.d.ts → export-destinations-Bey2djRk.d.ts} +2 -2
  6. package/dist/{filesystem-store-CmnUlj1O.d.ts → filesystem-store-B3CpiIRl.d.ts} +1 -1
  7. package/dist/{hook-vM_cgqS2.d.ts → hook-D5imE0Qc.d.ts} +3 -3
  8. package/dist/index.d.ts +10 -10
  9. package/dist/index.js +137 -44
  10. package/dist/index.js.map +1 -1
  11. package/dist/install.d.ts +3 -3
  12. package/dist/install.js +10 -1
  13. package/dist/install.js.map +1 -1
  14. package/dist/integration.d.ts +7 -7
  15. package/dist/integration.js +107 -41
  16. package/dist/integration.js.map +1 -1
  17. package/dist/lifecycle.d.ts +2 -2
  18. package/dist/lifecycle.js +1 -1
  19. package/dist/lifecycle.js.map +1 -1
  20. package/dist/{memory-DdU1U91y.d.ts → memory-B3r6sZtC.d.ts} +1 -1
  21. package/dist/{metric-model-C9lLqqpI.d.ts → metric-model-CFIeUwqd.d.ts} +2 -1
  22. package/dist/{payload-BT19hiVZ.d.ts → payload-CdDKeRpH.d.ts} +1 -1
  23. package/dist/{ports-C3k_5eOQ.d.ts → ports-DhpSDIkp.d.ts} +8 -1
  24. package/dist/providers.d.ts +27 -11
  25. package/dist/providers.js +121 -41
  26. package/dist/providers.js.map +1 -1
  27. package/dist/{registry-gyJqaWmp.d.ts → registry-BKQhhIO3.d.ts} +1 -1
  28. package/dist/runtime.d.ts +6 -6
  29. package/dist/runtime.js +12 -2
  30. package/dist/runtime.js.map +1 -1
  31. package/dist/state.d.ts +3 -3
  32. package/dist/state.js.map +1 -1
  33. package/dist/telemetry.d.ts +3 -3
  34. package/dist/telemetry.js +4 -1
  35. package/dist/telemetry.js.map +1 -1
  36. package/dist/testing.d.ts +6 -6
  37. package/dist/testing.js +52 -6
  38. package/dist/testing.js.map +1 -1
  39. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/config/schema.ts","../src/model/primitives.ts","../src/privacy/policy.ts","../src/config/destinations.ts","../src/config/header-value.ts","../src/config/otlp-headers.ts","../src/config/resource-attributes.ts","../src/diagnostics/health.ts","../src/errors/index.ts","../src/errors/taxonomy.ts","../src/lifecycle/dedup.ts","../src/state/async-lock.ts","../src/state/store.ts","../src/lifecycle/keys.ts","../src/lifecycle/metric-series.ts","../src/telemetry/export-identity.ts","../src/model/events.ts","../src/model/content.ts","../src/model/extensions.ts","../src/model/identity.ts","../src/model/target.ts","../src/model/usage.ts","../src/model/version.ts","../src/telemetry/metric-model.ts","../src/lifecycle/janitor.ts","../src/telemetry/semconv.ts","../src/version.ts","../src/lifecycle/span-correlator.ts","../src/lifecycle/usage-accumulator.ts","../src/privacy/service.ts","../src/providers/claude/transcript.ts","../src/providers/adapter.ts","../src/providers/claude/schema.ts","../src/providers/claude/usage.ts","../src/providers/claude/payload-normalize.ts","../src/providers/claude/detect.ts","../src/runtime/clock.ts","../src/runtime/hook.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/session-context.ts","../src/runtime/git-worktree.ts","../src/state/filesystem-store.ts","../src/state/keys.ts","../src/config/otlp-endpoint.ts","../src/telemetry/spool-queue.ts","../src/telemetry/durable-log-spool.ts","../src/telemetry/durable-metric-spool.ts","../src/telemetry/durable-spool.ts","../src/telemetry/otlp-log-sink.ts","../src/telemetry/export-failure.ts","../src/telemetry/exporter-resource.ts","../src/telemetry/log-records.ts","../src/telemetry/otlp-metric-sink.ts","../src/telemetry/otlp-sink.ts","../src/telemetry/signal-fanout.ts","../src/telemetry/export-destinations.ts","../src/integration/hook-runtime.ts"],"sourcesContent":["import { isAbsolute } from \"node:path\";\n\nimport { z } from \"zod\";\n\nimport { detectionConfidenceSchema, nonEmptyStringSchema } from \"../model/primitives.js\";\nimport {\n contentModeSchema,\n DEFAULT_PRIVACY_POLICY,\n privacyPolicySchema,\n} from \"../privacy/policy.js\";\nimport { exportDestinationsSchema, spoolPolicySchema } from \"./destinations.js\";\nimport { EMPTY_RESOURCE_ATTRIBUTES, resourceAttributesSchema } from \"./resource-attributes.js\";\n\n/**\n * Policy for the OTLP logs signal.\n *\n * Two switches rather than one, because they answer different questions and an\n * operator needs to be able to answer them differently:\n *\n * - `enabled` — whether a second signal leaves this host at all. Off by default:\n * an installation that upgrades must not silently start sending a new stream to a\n * collector whose receivers, quotas, and retention were sized for traces.\n * - `includeContent` — whether *disclosed* text may appear in a log body. Also off\n * by default, and deliberately not the same knob as `privacy.contentMode`: spans\n * carry no content in any content mode, so an installation that set\n * `contentMode` to get a hash and a length has never had content on the wire.\n * Reusing that setting to also mean \"publish prompts\" would change what an\n * existing configuration discloses without anybody editing it.\n *\n * `raw` content additionally requires the pre-existing `privacy.allowRawContent`\n * opt-in, which the privacy service enforces before a fact is ever built and the\n * log mapping re-checks at the wire.\n */\nexport const logsPolicySchema = z.strictObject({\n enabled: z.boolean(),\n /**\n * Full URL for the logs signal.\n *\n * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes\n * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.\n */\n endpoint: z.string().url().max(2048).optional(),\n includeContent: z.boolean(),\n maxBatchSize: z.number().int().min(1).max(4096),\n});\nexport type LogsPolicy = z.infer<typeof logsPolicySchema>;\n\nexport const DEFAULT_LOGS_POLICY: LogsPolicy = Object.freeze({\n enabled: false,\n includeContent: false,\n maxBatchSize: 128,\n});\n\n/**\n * Policy for hook-derived metrics (issue #69).\n *\n * Off by default, like logs: an upgrade must not start a new stream to a\n * collector nobody sized for it. `enabled` governs the `default` destination\n * (the single-endpoint settings); an `exporter.destinations[]` entry receives\n * metrics when its `signals` list names `metrics`. Metrics carry no content, so\n * listing the signal is the whole opt-in.\n *\n * - `temporality`: `cumulative` (default) exports running totals per series,\n * kept in the state store across hook processes, so a receiver that merges\n * counters by keeping the largest value stays correct. `delta` exports what one\n * callback observed and keeps no state.\n * - `includeSessionId`: put `session.id` on every data point (default true). Turn\n * it off where per-session series are too many for the backend.\n */\nexport const metricsPolicySchema = z.strictObject({\n enabled: z.boolean(),\n /** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */\n endpoint: z.string().url().max(2048).optional(),\n temporality: z.enum([\"cumulative\", \"delta\"]),\n includeSessionId: z.boolean(),\n});\nexport type MetricsPolicy = z.infer<typeof metricsPolicySchema>;\n\nexport const DEFAULT_METRICS_POLICY: MetricsPolicy = Object.freeze({\n enabled: false,\n temporality: \"cumulative\",\n includeSessionId: true,\n});\n\n/**\n * Runtime exporter policy.\n *\n * This describes *where and how* telemetry goes. It deliberately contains no\n * session, invocation, or workspace field: see ADR 0001. Mixing the two would\n * make identity globally reachable through configuration.\n */\nexport const exporterPolicySchema = z.strictObject({\n enabled: z.boolean(),\n protocol: z.enum([\"http/protobuf\", \"http/json\", \"none\"]),\n endpoint: z.string().url().max(2048).optional(),\n /**\n * Header names only. Values are supplied separately at construction time and\n * are never part of a resolved-config snapshot, which is logged and exported.\n */\n headerNames: z.array(nonEmptyStringSchema).max(32).readonly(),\n timeoutMillis: z.number().int().min(1).max(600_000),\n maxBatchSize: z.number().int().min(1).max(4096),\n maxQueueSize: z.number().int().min(1).max(65_536),\n maxRetryAttempts: z.number().int().min(0).max(10),\n serviceName: nonEmptyStringSchema,\n serviceNamespace: nonEmptyStringSchema.optional(),\n /**\n * Custom attributes merged into the exported OTLP Resource.\n *\n * Bounded and validated, and refusing `service.name`/`service.namespace`,\n * which are the two fields above. Distinct from an invocation's\n * `consumerAttributes`: this describes the emitting deployment, carries no\n * identity, and is the same for every span this process exports.\n */\n resourceAttributes: resourceAttributesSchema,\n /**\n * The logs signal. Nested under the exporter because it shares the endpoint,\n * headers, timeout, protocol, service identity, and resource attributes above —\n * a second top-level section would invite two of each to drift apart.\n */\n logs: logsPolicySchema,\n /**\n * Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before\n * metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.\n */\n metrics: metricsPolicySchema.optional(),\n /**\n * Additional OTLP destinations, each sent every batch in parallel.\n *\n * Absent (the default), the exporter has exactly one destination — the\n * single-endpoint settings above, named `default` — and behaves exactly as it\n * did before this list existed. See `destinations.ts`.\n *\n * Merged as one leaf: a higher layer that sets the list replaces it whole,\n * because \"the union of two partial lists\" has no answer an operator could\n * predict.\n */\n destinations: exportDestinationsSchema.optional(),\n /**\n * Per-destination retry spool bounds, each optional and merged per leaf; any\n * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.\n */\n spool: spoolPolicySchema.partial().optional(),\n});\nexport type ExporterPolicy = z.infer<typeof exporterPolicySchema>;\n\nexport const detectionPolicySchema = z.strictObject({\n /** Detections below this confidence resolve to the unknown provider. */\n minimumConfidence: detectionConfidenceSchema,\n /** When false, an ambiguous detection is an error rather than unknown. */\n allowAmbiguousFallback: z.boolean(),\n /** Optional allow-list of provider ids; empty means \"any registered\". */\n allowedProviderIds: z.array(nonEmptyStringSchema).max(32).readonly(),\n});\nexport type DetectionPolicy = z.infer<typeof detectionPolicySchema>;\n\nexport const diagnosticsPolicySchema = z.strictObject({\n logLevel: z.enum([\"silent\", \"error\", \"warn\", \"info\", \"debug\"]),\n /** Emit `error.raised` events for contained failures. */\n emitErrorEvents: z.boolean(),\n});\nexport type DiagnosticsPolicy = z.infer<typeof diagnosticsPolicySchema>;\n\n/**\n * Per-provider behaviour that is not part of an adapter's parse.\n *\n * `claudeCode.readTranscriptUsage` is the one sanctioned exception to \"no\n * transcript reads in the hook\" (docs/claude-code-usage-contract.md, finding 8).\n * When true, the hook runtime — never the adapter — reads the session transcript\n * named by a Claude Code `Stop` / `StopFailure` payload, bounded, and attaches the\n * turn's model and summed token usage before the adapter parses it. Off by\n * default: without it, otel-hook reads no file a hook payload names.\n */\nexport const providersPolicySchema = z.strictObject({\n claudeCode: z\n .strictObject({\n readTranscriptUsage: z.boolean(),\n })\n .optional(),\n});\nexport type ProvidersPolicy = z.infer<typeof providersPolicySchema>;\n\n/**\n * Session context (`docs/session-context.md`): a directory a harness writes one\n * JSON file per agent session into, laid out `<dir>/<agent-tool>/<session-id>.json`.\n * With `dir` set, the hook reads that one file on every event and stamps the\n * attributes of the segment in force on every span, log record and metric point.\n * Absent (the default), nothing is read.\n *\n * Set in the configuration file or with `--session-context-dir`, never through\n * the environment: some agents (Claude Code) strip `OTEL_*` variables from the\n * hook processes they start.\n */\nexport const sessionContextPolicySchema = z.strictObject({\n /** Absolute path of the context directory. */\n dir: z\n .string()\n .min(1)\n .max(4096)\n .refine((value) => isAbsolute(value), { message: \"must be an absolute path\" }),\n});\nexport type SessionContextPolicy = z.infer<typeof sessionContextPolicySchema>;\n\nexport const otelHookConfigSchema = z.strictObject({\n exporter: exporterPolicySchema,\n privacy: privacyPolicySchema,\n detection: detectionPolicySchema,\n diagnostics: diagnosticsPolicySchema,\n /** Optional so a hand-built configuration from before it existed stays valid. */\n providers: providersPolicySchema.optional(),\n /** Optional: absent means no session context is read. */\n sessionContext: sessionContextPolicySchema.optional(),\n});\nexport type OtelHookConfig = z.infer<typeof otelHookConfigSchema>;\n\n/** Partial overlay accepted from a configuration layer. */\nexport const otelHookConfigPatchSchema = z.strictObject({\n // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:\n // merging happens per leaf, so a layer must be able to set `logs.enabled` alone\n // without also restating the endpoint and the batch size.\n exporter: exporterPolicySchema\n .omit({ logs: true, metrics: true, spool: true })\n .partial()\n .extend({\n logs: logsPolicySchema.partial().optional(),\n metrics: metricsPolicySchema.partial().optional(),\n spool: spoolPolicySchema.partial().optional(),\n })\n .optional(),\n privacy: privacyPolicySchema\n .omit({ limits: true })\n .partial()\n .extend({ limits: privacyPolicySchema.shape.limits.partial().optional() })\n .optional(),\n detection: detectionPolicySchema.partial().optional(),\n diagnostics: diagnosticsPolicySchema.partial().optional(),\n providers: z\n .strictObject({\n claudeCode: z.strictObject({ readTranscriptUsage: z.boolean() }).partial().optional(),\n })\n .partial()\n .optional(),\n sessionContext: sessionContextPolicySchema.partial().optional(),\n});\nexport type OtelHookConfigPatch = z.infer<typeof otelHookConfigPatchSchema>;\n\nexport const DEFAULT_EXPORTER_POLICY: ExporterPolicy = Object.freeze({\n enabled: true,\n protocol: \"http/protobuf\",\n headerNames: Object.freeze([]),\n timeoutMillis: 10_000,\n maxBatchSize: 128,\n maxQueueSize: 2048,\n maxRetryAttempts: 2,\n serviceName: \"coding-agent\",\n resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,\n logs: DEFAULT_LOGS_POLICY,\n metrics: DEFAULT_METRICS_POLICY,\n});\n\nexport const DEFAULT_DETECTION_POLICY: DetectionPolicy = Object.freeze({\n minimumConfidence: \"strong\",\n allowAmbiguousFallback: true,\n allowedProviderIds: Object.freeze([]),\n});\n\nexport const DEFAULT_DIAGNOSTICS_POLICY: DiagnosticsPolicy = Object.freeze({\n logLevel: \"warn\",\n emitErrorEvents: true,\n});\n\nexport const DEFAULT_PROVIDERS_POLICY: ProvidersPolicy = Object.freeze({\n claudeCode: Object.freeze({ readTranscriptUsage: false }),\n});\n\nexport const DEFAULT_CONFIG: OtelHookConfig = Object.freeze({\n exporter: DEFAULT_EXPORTER_POLICY,\n privacy: DEFAULT_PRIVACY_POLICY,\n detection: DEFAULT_DETECTION_POLICY,\n diagnostics: DEFAULT_DIAGNOSTICS_POLICY,\n providers: DEFAULT_PROVIDERS_POLICY,\n});\n\n/** Whether the runtime may read Claude Code transcripts at `Stop` (default false). */\nexport const readsClaudeTranscriptUsage = (config: OtelHookConfig): boolean =>\n config.providers?.claudeCode?.readTranscriptUsage === true;\n\n/** The session context directory in force, or `undefined` when none is configured. */\nexport const sessionContextDir = (config: OtelHookConfig): string | undefined => config.sessionContext?.dir;\n\n/** Content mode is re-exported for callers building patches. */\nexport { contentModeSchema };\n\n/** The metrics policy in force, defaults filled in. */\nexport const effectiveMetricsPolicy = (exporter: ExporterPolicy): MetricsPolicy => ({\n ...DEFAULT_METRICS_POLICY,\n ...(exporter.metrics ?? {}),\n});\n","import { z } from \"zod\";\n\n/** Maximum length accepted for short identifier-like strings. */\nexport const MAX_IDENTIFIER_LENGTH = 256;\n\n/** Maximum length accepted for a single string attribute value. */\nexport const MAX_ATTRIBUTE_STRING_LENGTH = 4096;\n\n/** Maximum number of entries accepted in an attribute array value. */\nexport const MAX_ATTRIBUTE_ARRAY_LENGTH = 128;\n\nexport const nonEmptyStringSchema = z.string().min(1).max(MAX_IDENTIFIER_LENGTH);\n\n/** Wall-clock time as whole milliseconds since the Unix epoch. */\nexport const epochMillisSchema = z.number().int().min(0).max(8_640_000_000_000_000);\nexport type EpochMillis = z.infer<typeof epochMillisSchema>;\n\n/** Non-negative duration in milliseconds; may be fractional. */\nexport const durationMillisSchema = z.number().min(0).finite();\n\n/** Token counts are always non-negative integers. */\nexport const tokenCountSchema = z.number().int().min(0);\n\n/** Monotonically increasing per-invocation ordering key. */\nexport const sequenceNumberSchema = z.number().int().min(0);\n\nconst brandedIdSchema = (): z.ZodString => z.string().min(1).max(MAX_IDENTIFIER_LENGTH);\n\nexport const invocationIdSchema = brandedIdSchema().brand<\"InvocationId\">();\nexport type InvocationId = z.infer<typeof invocationIdSchema>;\n\nexport const sessionIdSchema = brandedIdSchema().brand<\"SessionId\">();\nexport type SessionId = z.infer<typeof sessionIdSchema>;\n\nexport const eventIdSchema = brandedIdSchema().brand<\"EventId\">();\nexport type EventId = z.infer<typeof eventIdSchema>;\n\n/**\n * Workspace identifiers are opaque, privacy-safe handles of the form\n * `<scheme>:<token>`. Filesystem paths cannot satisfy this pattern, which keeps\n * home directories and repository paths out of telemetry by construction.\n */\nexport const WORKSPACE_ID_PATTERN = /^[a-z][a-z0-9]{0,15}:[A-Za-z0-9_-]{8,128}$/;\nexport const workspaceIdSchema = z\n .string()\n .regex(WORKSPACE_ID_PATTERN, \"workspace id must be an opaque `<scheme>:<token>` handle\")\n .brand<\"WorkspaceId\">();\nexport type WorkspaceId = z.infer<typeof workspaceIdSchema>;\n\n/** Provider ids are lowercase, hyphenated, and stable across releases. */\nexport const PROVIDER_ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\nexport const providerIdSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(PROVIDER_ID_PATTERN, \"provider id must be lowercase and hyphenated\")\n .brand<\"ProviderId\">();\nexport type ProviderId = z.infer<typeof providerIdSchema>;\n\n/** Sentinel used whenever the source provider could not be established. */\nexport const UNKNOWN_PROVIDER_ID = \"unknown\" as const;\nexport type UnknownProviderId = typeof UNKNOWN_PROVIDER_ID;\n\nexport const resolvedProviderIdSchema = z.union([\n providerIdSchema,\n z.literal(UNKNOWN_PROVIDER_ID),\n]);\nexport type ResolvedProviderId = z.infer<typeof resolvedProviderIdSchema>;\n\nexport const isUnknownProvider = (value: ResolvedProviderId): value is UnknownProviderId =>\n value === UNKNOWN_PROVIDER_ID;\n\n/**\n * Attribute values are restricted to OpenTelemetry-compatible primitives.\n *\n * This restriction is a containment boundary, not a convenience: because no\n * nested object can be represented, a raw provider payload cannot be smuggled\n * out of an adapter through attributes or extensions.\n */\nexport const attributePrimitiveSchema = z.union([\n z.string().max(MAX_ATTRIBUTE_STRING_LENGTH),\n z.number().finite(),\n z.boolean(),\n]);\nexport type AttributePrimitive = z.infer<typeof attributePrimitiveSchema>;\n\nexport const attributeValueSchema = z.union([\n attributePrimitiveSchema,\n z.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH),\n]);\nexport type AttributeValue = z.infer<typeof attributeValueSchema>;\n\nexport const attributesSchema = z.record(z.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);\nexport type Attributes = z.infer<typeof attributesSchema>;\n\n/** Ordered confidence ladder for provider detection. */\nexport const detectionConfidenceSchema = z.enum([\"none\", \"weak\", \"strong\", \"exact\"]);\nexport type DetectionConfidence = z.infer<typeof detectionConfidenceSchema>;\n\nexport const DETECTION_CONFIDENCE_RANK: Readonly<Record<DetectionConfidence, number>> =\n Object.freeze({\n none: 0,\n weak: 1,\n strong: 2,\n exact: 3,\n });\n\nexport const compareDetectionConfidence = (a: DetectionConfidence, b: DetectionConfidence): number =>\n DETECTION_CONFIDENCE_RANK[a] - DETECTION_CONFIDENCE_RANK[b];\n\n/** How the observed data reached this process. */\nexport const sourceTransportSchema = z.enum([\n \"hook-stdin\",\n \"cli-argument\",\n \"library-call\",\n \"test-fixture\",\n]);\nexport type SourceTransport = z.infer<typeof sourceTransportSchema>;\n","import { z } from \"zod\";\n\nimport type { ContentDisclosure } from \"../model/content.js\";\n\n/**\n * How much content the library is permitted to disclose.\n *\n * `omit` is the default and the only mode that requires no trust in the\n * downstream collector.\n */\nexport const contentModeSchema = z.enum([\"omit\", \"mask\", \"redact\", \"raw\"]);\nexport type ContentMode = z.infer<typeof contentModeSchema>;\n\nexport const CONTENT_MODE_DISCLOSURE: Readonly<Record<ContentMode, ContentDisclosure>> =\n Object.freeze({\n omit: \"omitted\",\n mask: \"masked\",\n redact: \"redacted\",\n raw: \"raw\",\n });\n\n/**\n * Default secret-key patterns, matched case-insensitively against object keys at\n * every depth. A key matching any of these has its value replaced before the\n * value itself is ever inspected.\n */\nexport const DEFAULT_SECRET_KEY_PATTERNS: readonly string[] = Object.freeze([\n \"(^|[._-])(secret|secrets)([._-]|$)\",\n \"(^|[._-])(token|tokens)([._-]|$)\",\n \"(^|[._-])(password|passwd|pwd)([._-]|$)\",\n \"(^|[._-])(credential|credentials)([._-]|$)\",\n \"(^|[._-])(api[._-]?key|apikey|access[._-]?key|secret[._-]?key|private[._-]?key)([._-]|$)\",\n \"(^|[._-])(authorization|auth[._-]?header|bearer)([._-]|$)\",\n \"(^|[._-])(cookie|set[._-]?cookie)([._-]|$)\",\n \"(^|[._-])(signature|sig)([._-]|$)\",\n]);\n\n/**\n * Default secret-value patterns applied to disclosed text in `redact` mode.\n * These are heuristics; they reduce accidental disclosure but are not a\n * substitute for `omit`.\n */\nexport const DEFAULT_SECRET_VALUE_PATTERNS: readonly string[] = Object.freeze([\n \"AKIA[0-9A-Z]{16}\",\n \"sk-[A-Za-z0-9_-]{16,}\",\n \"gh[pousr]_[A-Za-z0-9]{16,}\",\n \"xox[abprs]-[A-Za-z0-9-]{10,}\",\n \"-----BEGIN[A-Z ]*PRIVATE KEY-----\",\n \"eyJ[A-Za-z0-9_-]{10,}\\\\.[A-Za-z0-9_-]{10,}\\\\.[A-Za-z0-9_-]{10,}\",\n \"(?:Bearer|Basic)\\\\s+[A-Za-z0-9._~+/=-]{12,}\",\n]);\n\nexport const privacyLimitsSchema = z.strictObject({\n /** Maximum characters of disclosed text per content fact or string value. */\n maxStringLength: z.number().int().min(0).max(65_536),\n /** Maximum nesting depth walked when sanitizing structured values. */\n maxDepth: z.number().int().min(1).max(32),\n /** Maximum array entries retained when sanitizing structured values. */\n maxArrayLength: z.number().int().min(1).max(4096),\n /** Maximum canonical events emitted per invocation. */\n maxEventsPerInvocation: z.number().int().min(1).max(10_000),\n /** Maximum object keys retained per level when sanitizing. */\n maxObjectKeys: z.number().int().min(1).max(1024),\n});\nexport type PrivacyLimits = z.infer<typeof privacyLimitsSchema>;\n\nexport const privacyPolicySchema = z.strictObject({\n contentMode: contentModeSchema,\n /**\n * `raw` mode is refused unless this is also true, so a single mistyped\n * environment variable cannot start exporting prompts.\n */\n allowRawContent: z.boolean(),\n /**\n * Salt mixed into every hash. A per-deployment salt makes hashes\n * non-correlatable across deployments; an empty salt makes them globally\n * comparable. Both are legitimate; the choice is explicit.\n */\n hashSalt: z.string().max(256),\n maskCharacter: z.string().length(1),\n redactionPlaceholder: z.string().min(1).max(64),\n secretKeyPatterns: z.array(z.string().min(1)).max(128).readonly(),\n secretValuePatterns: z.array(z.string().min(1)).max(128).readonly(),\n limits: privacyLimitsSchema,\n});\nexport type PrivacyPolicy = z.infer<typeof privacyPolicySchema>;\n\nexport const DEFAULT_PRIVACY_LIMITS: PrivacyLimits = Object.freeze({\n maxStringLength: 1024,\n maxDepth: 6,\n maxArrayLength: 64,\n maxEventsPerInvocation: 512,\n maxObjectKeys: 128,\n});\n\nexport const DEFAULT_PRIVACY_POLICY: PrivacyPolicy = Object.freeze({\n contentMode: \"omit\",\n allowRawContent: false,\n hashSalt: \"\",\n maskCharacter: \"*\",\n redactionPlaceholder: \"[redacted]\",\n secretKeyPatterns: DEFAULT_SECRET_KEY_PATTERNS,\n secretValuePatterns: DEFAULT_SECRET_VALUE_PATTERNS,\n limits: DEFAULT_PRIVACY_LIMITS,\n});\n\nexport type PolicyResolution = {\n readonly policy: PrivacyPolicy;\n /** Non-sensitive notes about deterministic downgrades that were applied. */\n readonly notes: readonly string[];\n};\n\n/**\n * Validate a policy and apply the one deterministic downgrade the library\n * enforces: `raw` without `allowRawContent` becomes `omit`.\n */\nexport const resolvePrivacyPolicy = (policy: PrivacyPolicy): PolicyResolution => {\n const parsed = privacyPolicySchema.parse(policy);\n if (parsed.contentMode === \"raw\" && !parsed.allowRawContent) {\n return {\n policy: { ...parsed, contentMode: \"omit\" },\n notes: [\"contentMode=raw downgraded to omit because allowRawContent is false\"],\n };\n }\n return { policy: parsed, notes: [] };\n};\n","import { z } from \"zod\";\n\nimport { isUnsafeHeaderValue } from \"./header-value.js\";\nimport { MAX_OTLP_HEADERS } from \"./otlp-headers.js\";\nimport type { ExporterPolicy } from \"./schema.js\";\n\n/**\n * Export destinations: one batch, several OTLP endpoints.\n *\n * otel-hook is not a long-running process, so it cannot sit behind a proxy that\n * fans out for it. Instead every enabled destination is sent the same batch by the\n * same short-lived process, and what a destination could not take is kept in that\n * destination's own spool for the next invocation.\n *\n * ## The `default` destination\n *\n * The single-endpoint settings that predate this list — `exporter.endpoint`,\n * `exporter.logs.endpoint`, `exporter.protocol`, `--header`, and the standard\n * `OTEL_EXPORTER_OTLP_*` variables that feed them — describe one destination\n * named `default`. The name is therefore reserved: a `destinations[]` entry may\n * not take it, so there is exactly one place that destination is configured.\n *\n * A configuration with no `destinations` resolves to that one destination and\n * nothing else, exactly as before the list existed.\n */\n\nexport const DEFAULT_DESTINATION_NAME = \"default\";\n\n/**\n * Destination names become directory names (each destination spools on its own),\n * so they are held to a lowercase, filesystem-safe vocabulary rather than being\n * sanitized into something an operator would not recognize.\n */\nexport const DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;\n\nexport const MAX_EXPORT_DESTINATIONS = 16;\n/** The same bound `OTEL_EXPORTER_OTLP_*HEADERS` and `exporter.headerNames` have. */\nexport const MAX_DESTINATION_HEADERS = MAX_OTLP_HEADERS;\n\n/** Prefix of a header value that names an environment variable instead of holding a value. */\nexport const HEADER_ENV_REFERENCE_PREFIX = \"env:\";\n\n/** RFC 9110 `token`: the characters a header field name may use. */\nconst HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;\nconst ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;\nconst MAX_HEADER_VALUE_LENGTH = 8_192;\n\nexport const exportSignalSchema = z.enum([\"traces\", \"logs\", \"metrics\"]);\nexport type ExportSignal = z.infer<typeof exportSignalSchema>;\n\nconst headerValueSchema = z\n .string()\n .min(1)\n .max(MAX_HEADER_VALUE_LENGTH)\n // The rule `OTEL_EXPORTER_OTLP_*HEADERS` values are held to: a line break is a\n // request-splitting vector, and other controls or non-Latin-1 characters would\n // only make Node's HTTP client throw at send time.\n .refine(\n (value) => !isUnsafeHeaderValue(value),\n \"header values may not contain line breaks, control characters, or characters beyond Latin-1\",\n )\n .refine(\n (value) =>\n !value.startsWith(HEADER_ENV_REFERENCE_PREFIX) ||\n ENV_VARIABLE_NAME_PATTERN.test(value.slice(HEADER_ENV_REFERENCE_PREFIX.length)),\n \"an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN\",\n );\n\nconst endpointSchema = z.string().url().max(2048);\n\nexport const exportDestinationSchema = z\n .strictObject({\n /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */\n name: z\n .string()\n .regex(DESTINATION_NAME_PATTERN, \"destination names are lowercase letters, digits, _ and -\"),\n /** Default true. A disabled destination is neither sent to nor drained. */\n enabled: z.boolean().optional(),\n /**\n * Traces URL, with the same meaning as `exporter.endpoint`: the logs URL is\n * derived from it (`/v1/traces` becomes `/v1/logs`) unless `logsEndpoint` is set.\n */\n endpoint: endpointSchema.optional(),\n /** Per-signal override of `endpoint` for traces. */\n tracesEndpoint: endpointSchema.optional(),\n /** Per-signal override of the derived logs URL. */\n logsEndpoint: endpointSchema.optional(),\n /** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */\n metricsEndpoint: endpointSchema.optional(),\n /** Defaults to `exporter.protocol`. */\n protocol: z.enum([\"http/protobuf\", \"http/json\", \"none\"]).optional(),\n /**\n * Header name to value. A value of the form `env:NAME` is read from that\n * environment variable at send time, so a credential never has to be written\n * into the file. Values never appear in a snapshot, a diagnostic, or `doctor`.\n */\n headers: z\n .record(z.string().regex(HEADER_NAME_PATTERN, \"not a valid header name\"), headerValueSchema)\n .refine(\n (headers) => Object.keys(headers).length <= MAX_DESTINATION_HEADERS,\n `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`,\n )\n .optional(),\n /**\n * Which signals this destination receives. Default: traces and logs. The logs\n * signal is still governed by `exporter.logs.enabled`, which stays the one\n * opt-in for content-bearing records leaving the host. `metrics` is never on by\n * default: a destination receives hook-derived metrics only when it lists them.\n */\n signals: z.array(exportSignalSchema).min(1).max(3).readonly().optional(),\n })\n .refine(\n (destination) =>\n destination.endpoint !== undefined ||\n destination.tracesEndpoint !== undefined ||\n destination.logsEndpoint !== undefined ||\n destination.metricsEndpoint !== undefined,\n \"a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint\",\n );\nexport type ExportDestinationConfig = z.infer<typeof exportDestinationSchema>;\n\n/** Signals a destination receives when it does not list any: never metrics. */\nexport const DEFAULT_DESTINATION_SIGNALS: readonly ExportSignal[] = Object.freeze([\"traces\", \"logs\"]);\n\nexport const exportDestinationsSchema = z\n .array(exportDestinationSchema)\n .max(MAX_EXPORT_DESTINATIONS)\n .readonly()\n .superRefine((destinations, context) => {\n const seen = new Set<string>();\n destinations.forEach((destination, index) => {\n if (destination.name === DEFAULT_DESTINATION_NAME) {\n context.addIssue({\n code: \"custom\",\n path: [index, \"name\"],\n message:\n 'the name \"default\" is reserved for exporter.endpoint and the OTEL_EXPORTER_OTLP_* variables',\n });\n }\n if (seen.has(destination.name)) {\n context.addIssue({\n code: \"custom\",\n path: [index, \"name\"],\n message: `duplicate destination name \"${destination.name}\"`,\n });\n }\n seen.add(destination.name);\n });\n });\n\n/**\n * Bounds on each destination's retry spool, per signal.\n *\n * Every destination spools independently, so one long outage can only ever cost\n * its own budget. When a bound is reached the *oldest* batches are dropped first —\n * a recent batch is the one a reader is still likely to look for — and every drop\n * is counted on disk so `doctor` can report it.\n */\nexport const spoolPolicySchema = z.strictObject({\n /** Total bytes of queued batches. Default 16 MiB. */\n maxBytes: z.number().int().min(1_024).max(1_073_741_824),\n /** A batch older than this is dropped instead of sent. Default 72 hours. */\n maxAgeMillis: z.number().int().min(1_000).max(30 * 24 * 60 * 60 * 1000),\n /** Number of queued batches. Default 500. */\n maxBatches: z.number().int().min(1).max(65_536),\n});\nexport type SpoolPolicy = z.infer<typeof spoolPolicySchema>;\n\nexport const DEFAULT_SPOOL_POLICY: SpoolPolicy = Object.freeze({\n maxBytes: 16 * 1024 * 1024,\n maxAgeMillis: 72 * 60 * 60 * 1000,\n maxBatches: 500,\n});\n\n/** The spool policy in force, with defaults filled in for any bound left unset. */\nexport const effectiveSpoolPolicy = (exporter: ExporterPolicy): SpoolPolicy => ({\n maxBytes: exporter.spool?.maxBytes ?? DEFAULT_SPOOL_POLICY.maxBytes,\n maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,\n maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches,\n});\n\n/**\n * One destination as the runtime sends to it.\n *\n * `headers` holds what the configuration holds — literal values and `env:`\n * references, unresolved. Resolution against an environment happens only at the\n * point of sending ({@link resolveDestinationHeaders}), and the `default`\n * destination's header values never pass through configuration at all: they are\n * handed to the runtime separately, as they always have been.\n */\nexport type ExportDestination = {\n readonly name: string;\n /** `exporter` for the `default` destination, `destinations` for a list entry. */\n readonly source: \"exporter\" | \"destinations\";\n readonly protocol: ExporterPolicy[\"protocol\"];\n /** Traces URL as configured; for `default` this is `exporter.endpoint`. */\n readonly endpoint?: string;\n readonly tracesEndpoint?: string;\n readonly logsEndpoint?: string;\n readonly metricsEndpoint?: string;\n readonly signals: { readonly traces: boolean; readonly logs: boolean; readonly metrics: boolean };\n readonly headers: Readonly<Record<string, string>>;\n};\n\nconst legacyDestination = (exporter: ExporterPolicy): ExportDestination => ({\n name: DEFAULT_DESTINATION_NAME,\n source: \"exporter\",\n protocol: exporter.protocol,\n ...(exporter.endpoint === undefined ? {} : { endpoint: exporter.endpoint }),\n ...(exporter.logs.endpoint === undefined ? {} : { logsEndpoint: exporter.logs.endpoint }),\n ...(exporter.metrics?.endpoint === undefined ? {} : { metricsEndpoint: exporter.metrics.endpoint }),\n signals: { traces: true, logs: exporter.logs.enabled, metrics: exporter.metrics?.enabled === true },\n headers: {},\n});\n\n/** Whether a configuration uses the destination list at all. */\nexport const hasConfiguredDestinations = (exporter: ExporterPolicy): boolean =>\n exporter.destinations !== undefined && exporter.destinations.length > 0;\n\n/**\n * The destinations an exporter policy sends to, in a stable order: `default`\n * first when present, then the list in file order.\n *\n * - No `destinations`: exactly one `default` destination, even when it has no\n * endpoint — the sink then reports itself unconfigured, as it always has.\n * - With `destinations`: `default` is included only when a single-endpoint setting\n * actually names an endpoint, and disabled entries are left out.\n */\nexport const resolveExportDestinations = (\n exporter: ExporterPolicy,\n): readonly ExportDestination[] => {\n if (!hasConfiguredDestinations(exporter)) {\n return [legacyDestination(exporter)];\n }\n const resolved: ExportDestination[] = [];\n if (\n exporter.endpoint !== undefined ||\n exporter.logs.endpoint !== undefined ||\n exporter.metrics?.endpoint !== undefined\n ) {\n resolved.push(legacyDestination(exporter));\n }\n for (const destination of exporter.destinations ?? []) {\n if (destination.enabled === false) {\n continue;\n }\n const signals: readonly ExportSignal[] = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;\n resolved.push({\n name: destination.name,\n source: \"destinations\",\n protocol: destination.protocol ?? exporter.protocol,\n ...(destination.endpoint === undefined ? {} : { endpoint: destination.endpoint }),\n ...(destination.tracesEndpoint === undefined\n ? {}\n : { tracesEndpoint: destination.tracesEndpoint }),\n ...(destination.logsEndpoint === undefined ? {} : { logsEndpoint: destination.logsEndpoint }),\n ...(destination.metricsEndpoint === undefined\n ? {}\n : { metricsEndpoint: destination.metricsEndpoint }),\n signals: {\n traces: signals.includes(\"traces\"),\n logs: exporter.logs.enabled && signals.includes(\"logs\"),\n metrics: signals.includes(\"metrics\"),\n },\n headers: { ...(destination.headers ?? {}) },\n });\n }\n return resolved;\n};\n\n/** A header value's meaning, without its content. */\nexport type HeaderValueReference =\n | { readonly kind: \"literal\" }\n | { readonly kind: \"env\"; readonly variable: string };\n\nexport const parseHeaderValueReference = (value: string): HeaderValueReference =>\n value.startsWith(HEADER_ENV_REFERENCE_PREFIX)\n ? { kind: \"env\", variable: value.slice(HEADER_ENV_REFERENCE_PREFIX.length) }\n : { kind: \"literal\" };\n\nexport type ResolvedDestinationHeaders = {\n /** Header values ready to send. Never logged, never reported. */\n readonly values: Readonly<Record<string, string>>;\n /** Names of referenced environment variables that are unset or empty. */\n readonly missingVariables: readonly string[];\n};\n\n/**\n * Resolve `env:` references against an explicitly supplied environment.\n *\n * Pure: the process environment is never read implicitly. An unset or empty\n * variable is reported by *name* — the only part of a reference that is safe to\n * say out loud — and its header is left out of `values`.\n */\nexport const resolveDestinationHeaders = (\n headers: Readonly<Record<string, string>>,\n environment: Readonly<Record<string, string | undefined>> | undefined,\n): ResolvedDestinationHeaders => {\n const values: Record<string, string> = {};\n const missing: string[] = [];\n for (const [name, value] of Object.entries(headers)) {\n const reference = parseHeaderValueReference(value);\n if (reference.kind === \"literal\") {\n values[name] = value;\n continue;\n }\n const resolved = environment?.[reference.variable];\n if (resolved === undefined || resolved === \"\") {\n missing.push(reference.variable);\n continue;\n }\n values[name] = resolved;\n }\n return { values, missingVariables: [...new Set(missing)].sort() };\n};\n\n/**\n * Attribute-safe description of one destination: names, origins, and variable\n * names. Never a header value, and never an endpoint beyond its origin.\n */\nexport type DestinationDescription = {\n readonly name: string;\n readonly enabled: boolean;\n readonly protocol: ExporterPolicy[\"protocol\"];\n readonly signals: readonly ExportSignal[];\n readonly tracesEndpointOrigin?: string;\n readonly logsEndpointOrigin?: string;\n readonly metricsEndpointOrigin?: string;\n readonly headerNames: readonly string[];\n /** Environment variables this destination's headers reference. */\n readonly headerVariables: readonly string[];\n};\n\nexport const endpointOrigin = (endpoint: string | undefined): string | undefined => {\n if (endpoint === undefined) {\n return undefined;\n }\n try {\n return new URL(endpoint).origin;\n } catch {\n return \"<unparsable>\";\n }\n};\n\n/** Every configured destination, disabled ones included, for `doctor` and snapshots. */\nexport const describeExportDestinations = (\n exporter: ExporterPolicy,\n): readonly DestinationDescription[] => {\n const describe = (\n destination: ExportDestination,\n enabled: boolean,\n ): DestinationDescription => {\n const tracesOrigin = endpointOrigin(destination.tracesEndpoint ?? destination.endpoint);\n const logsOrigin = endpointOrigin(\n destination.logsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint,\n );\n const metricsOrigin = endpointOrigin(\n destination.metricsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint,\n );\n const variables = Object.values(destination.headers)\n .map(parseHeaderValueReference)\n .flatMap((reference) => (reference.kind === \"env\" ? [reference.variable] : []));\n return {\n name: destination.name,\n enabled,\n protocol: destination.protocol,\n signals: exportSignalSchema.options.filter((signal) => destination.signals[signal]),\n ...(tracesOrigin === undefined || !destination.signals.traces\n ? {}\n : { tracesEndpointOrigin: tracesOrigin }),\n ...(logsOrigin === undefined || !destination.signals.logs\n ? {}\n : { logsEndpointOrigin: logsOrigin }),\n ...(metricsOrigin === undefined || !destination.signals.metrics\n ? {}\n : { metricsEndpointOrigin: metricsOrigin }),\n headerNames:\n destination.source === \"exporter\"\n ? [...exporter.headerNames].sort()\n : Object.keys(destination.headers).sort(),\n headerVariables: [...new Set(variables)].sort(),\n };\n };\n const enabled = resolveExportDestinations(exporter).map((destination) =>\n describe(destination, true),\n );\n const disabled = (exporter.destinations ?? [])\n .filter((destination) => destination.enabled === false)\n .map((destination) =>\n describe(\n {\n name: destination.name,\n source: \"destinations\",\n protocol: destination.protocol ?? exporter.protocol,\n ...(destination.endpoint === undefined ? {} : { endpoint: destination.endpoint }),\n signals: { traces: false, logs: false, metrics: false },\n headers: { ...(destination.headers ?? {}) },\n },\n false,\n ),\n );\n return [...enabled, ...disabled];\n};\n","/**\n * Internal: shared by `OTEL_EXPORTER_OTLP_*HEADERS` parsing and the\n * `exporter.destinations[].headers` schema. Not re-exported from the package.\n */\n\n/**\n * Characters an HTTP field value must not contain once decoded. CR and LF would\n * split the request; the other controls and anything beyond Latin-1 are refused\n * by Node's HTTP client anyway, and refusing them here turns a failed export into\n * a reported, skipped entry.\n */\nexport const isUnsafeHeaderValue = (value: string): boolean =>\n [...value].some((char) => {\n const code = char.codePointAt(0) ?? 0;\n return (code < 0x20 && code !== 0x09) || code === 0x7f || code > 0xff;\n });\n","/**\n * The standard OTLP exporter header variables.\n *\n * `OTEL_EXPORTER_OTLP_HEADERS` applies to every signal;\n * `OTEL_EXPORTER_OTLP_TRACES_HEADERS` and `OTEL_EXPORTER_OTLP_LOGS_HEADERS`\n * apply to one signal each. They exist so a credential (`authorization=Basic …`)\n * can reach the exporter without being written on a command line, where `ps` and\n * `/proc/<pid>/cmdline` would show it to every local user.\n *\n * Header *values* never enter configuration. Parsing returns them to the caller,\n * which hands them straight to the sink at construction; configuration carries\n * header *names* only (`exporter.headerNames`), because a resolved-config\n * snapshot is logged and exported. Every diagnostic here names an entry by its\n * position and the variable by its name — never a key, never a value — because a\n * malformed entry may be the secret itself (`Basic abc` with no `=`).\n */\n\nimport { isUnsafeHeaderValue } from \"./header-value.js\";\n\n/** Upper bound on headers per variable, matching `exporter.headerNames`. */\nexport const MAX_OTLP_HEADERS = 32;\n\nexport const OTLP_HEADER_VARIABLES = Object.freeze({\n generic: \"OTEL_EXPORTER_OTLP_HEADERS\",\n traces: \"OTEL_EXPORTER_OTLP_TRACES_HEADERS\",\n logs: \"OTEL_EXPORTER_OTLP_LOGS_HEADERS\",\n});\n\n/** RFC 9110 `token`: the characters an HTTP field name may contain. */\nconst HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n\nexport type ParsedOtlpHeaders = {\n readonly headers: Readonly<Record<string, string>>;\n /** Position-only explanations; never a key or a value. */\n readonly warnings: readonly string[];\n};\n\nconst decode = (raw: string): string | undefined => {\n try {\n return decodeURIComponent(raw);\n } catch {\n return undefined;\n }\n};\n\n/**\n * Parse one `OTEL_EXPORTER_OTLP_*HEADERS` value.\n *\n * The OpenTelemetry exporter specification defines the format as W3C\n * Baggage-like: comma-separated `key=value` pairs, surrounding whitespace\n * trimmed, keys and values percent-decoded. So `authorization=Basic%20abc` is\n * the header `authorization: Basic abc`, and a `,` inside a value must be\n * written `%2C`. A malformed entry is skipped and reported; the rest of the\n * variable still applies. A repeated key takes its last value.\n */\nexport const parseOtlpHeadersValue = (raw: string): ParsedOtlpHeaders => {\n const headers: Record<string, string> = {};\n const warnings: string[] = [];\n let overflowed = false;\n\n for (const [index, rawEntry] of raw.split(\",\").entries()) {\n const position = String(index + 1);\n const entry = rawEntry.trim();\n if (entry === \"\") {\n continue;\n }\n const equals = entry.indexOf(\"=\");\n if (equals <= 0) {\n warnings.push(`entry ${position} is not a key=value pair; ignored`);\n continue;\n }\n const key = decode(entry.slice(0, equals).trim());\n // Split on the first `=` only: a base64 credential ends in `=` padding.\n const value = decode(entry.slice(equals + 1).trim());\n if (key === undefined || value === undefined) {\n warnings.push(`entry ${position} has malformed percent-encoding; ignored`);\n continue;\n }\n const name = key.trim();\n const trimmedValue = value.trim();\n if (!HEADER_NAME_PATTERN.test(name)) {\n warnings.push(`entry ${position} does not name a valid HTTP header; ignored`);\n continue;\n }\n if (trimmedValue === \"\") {\n warnings.push(`entry ${position} has an empty value; ignored`);\n continue;\n }\n if (isUnsafeHeaderValue(trimmedValue)) {\n warnings.push(`entry ${position} has a character not allowed in an HTTP header value; ignored`);\n continue;\n }\n const existing = findHeaderName(headers, name);\n if (existing === undefined && Object.keys(headers).length >= MAX_OTLP_HEADERS) {\n overflowed = true;\n continue;\n }\n if (existing !== undefined) {\n delete headers[existing];\n }\n headers[name] = trimmedValue;\n }\n\n if (overflowed) {\n warnings.push(`more than ${String(MAX_OTLP_HEADERS)} headers were supplied; the excess was ignored`);\n }\n return { headers, warnings };\n};\n\n/** HTTP field names are case-insensitive: `Authorization` and `authorization` are one header. */\nconst findHeaderName = (headers: Readonly<Record<string, string>>, name: string): string | undefined => {\n const lower = name.toLowerCase();\n return Object.keys(headers).find((candidate) => candidate.toLowerCase() === lower);\n};\n\n/**\n * Overlay header maps, lowest precedence first, per header name.\n *\n * A higher source replaces only the names it sets (case-insensitively), so a\n * signal-specific variable can override `authorization` while a generic tenant\n * header still applies — the same per-key merge the OpenTelemetry SDKs apply.\n */\nexport const mergeOtlpHeaders = (\n ...sources: readonly Readonly<Record<string, string>>[]\n): Readonly<Record<string, string>> => {\n const merged: Record<string, string> = {};\n for (const source of sources) {\n for (const [name, value] of Object.entries(source)) {\n const existing = findHeaderName(merged, name);\n if (existing !== undefined) {\n delete merged[existing];\n }\n merged[name] = value;\n }\n }\n return merged;\n};\n\nexport type ResolvedOtlpHeaders = {\n /** Headers for the traces exporter. */\n readonly traces: Readonly<Record<string, string>>;\n /** Headers for the logs exporter. */\n readonly logs: Readonly<Record<string, string>>;\n /** Variable-qualified, value-free explanations of skipped entries. */\n readonly warnings: readonly { readonly variable: string; readonly detail: string }[];\n};\n\n/**\n * Resolve exporter headers per signal.\n *\n * Precedence, per header name, highest first:\n *\n * ```\n * explicit headers (--header) > OTEL_EXPORTER_OTLP_{TRACES,LOGS}_HEADERS > OTEL_EXPORTER_OTLP_HEADERS\n * ```\n *\n * Pure: the environment is passed in, never read from `process.env`.\n */\nexport const resolveOtlpHeaders = (\n env: Readonly<Record<string, string | undefined>>,\n explicit: Readonly<Record<string, string>> = {},\n): ResolvedOtlpHeaders => {\n const warnings: { variable: string; detail: string }[] = [];\n const read = (variable: string): Readonly<Record<string, string>> => {\n const raw = env[variable];\n if (raw === undefined || raw.trim() === \"\") {\n return {};\n }\n const parsed = parseOtlpHeadersValue(raw);\n for (const detail of parsed.warnings) {\n warnings.push({ variable, detail });\n }\n return parsed.headers;\n };\n const generic = read(OTLP_HEADER_VARIABLES.generic);\n const traces = read(OTLP_HEADER_VARIABLES.traces);\n const logs = read(OTLP_HEADER_VARIABLES.logs);\n return {\n traces: mergeOtlpHeaders(generic, traces, explicit),\n logs: mergeOtlpHeaders(generic, logs, explicit),\n warnings,\n };\n};\n\n/**\n * Header names, deduplicated case-insensitively (first spelling kept), sorted\n * and bounded — the only part of a header that may enter configuration or a\n * diagnostic.\n */\nexport const unionOtlpHeaderNames = (...lists: readonly (readonly string[])[]): readonly string[] => {\n const names: string[] = [];\n const seen = new Set<string>();\n for (const name of lists.flat()) {\n if (!seen.has(name.toLowerCase())) {\n seen.add(name.toLowerCase());\n names.push(name);\n }\n }\n return names.sort().slice(0, MAX_OTLP_HEADERS);\n};\n\n/** {@link unionOtlpHeaderNames} over the names of header maps. */\nexport const describeOtlpHeaderNames = (\n ...sources: readonly Readonly<Record<string, string>>[]\n): readonly string[] => unionOtlpHeaderNames(...sources.map((source) => Object.keys(source)));\n","import { z } from \"zod\";\n\nimport { 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 type { OtelHookErrorCode } from \"../errors/index.js\";\nimport type { EpochMillis } from \"../model/primitives.js\";\n\n/**\n * One tracked delivery path.\n *\n * The two telemetry signals are separate subsystems because they fail\n * independently — a collector with no logs receiver leaves traces perfectly\n * healthy — and a single combined verdict would make an operator bisect which one\n * is broken. `telemetry-sink` remains the traces signal, unrenamed, so an existing\n * `doctor --json` consumer keeps reading the same field.\n */\nexport type DeliverySubsystem =\n | \"state-store\"\n | \"telemetry-sink\"\n | \"telemetry-log-sink\"\n | \"telemetry-metric-sink\"\n | \"lifecycle\";\n\n/**\n * Sanitized delivery health.\n *\n * Every field is a count, a timestamp, a boolean, or a closed-vocabulary error\n * code — the same restriction the privacy service applies to everything else\n * that might reach a sink, so a health snapshot is itself safe to export or log\n * without a second review.\n */\nexport type DeliveryHealthSnapshot = {\n readonly subsystem: DeliverySubsystem;\n readonly healthy: boolean;\n readonly totalAccepted: number;\n readonly totalRejected: number;\n readonly consecutiveFailures: number;\n readonly lastSuccessAt?: EpochMillis;\n readonly lastFailureAt?: EpochMillis;\n readonly lastErrorCode?: OtelHookErrorCode;\n /**\n * Export destination this snapshot describes. Present only when\n * `exporter.destinations` is in use, so a single-destination snapshot is\n * unchanged.\n */\n readonly destination?: string;\n};\n\nexport type HealthTrackerOptions = {\n /** Consecutive failures at or beyond this count flip `healthy` to false. Default 3. */\n readonly unhealthyAfterConsecutiveFailures?: number;\n /** Labels every snapshot with an export destination name. */\n readonly destination?: string;\n};\n\n/**\n * Accumulates success/failure counts for one subsystem instance.\n *\n * Deliberately per-instance rather than a module-level registry: a store or\n * sink constructs its own tracker and exposes a `health()` accessor, so two\n * instances in one process never share counters (see ADR 0001 on module-level\n * identity).\n */\nexport interface HealthTracker {\n recordSuccess(count?: number, at?: number): void;\n recordFailure(code: OtelHookErrorCode, count?: number, at?: number): void;\n snapshot(): DeliveryHealthSnapshot;\n}\n\nexport const createHealthTracker = (\n subsystem: DeliverySubsystem,\n options: HealthTrackerOptions = {},\n): HealthTracker => {\n const unhealthyThreshold = options.unhealthyAfterConsecutiveFailures ?? 3;\n let totalAccepted = 0;\n let totalRejected = 0;\n let consecutiveFailures = 0;\n let lastSuccessAt: number | undefined;\n let lastFailureAt: number | undefined;\n let lastErrorCode: OtelHookErrorCode | undefined;\n\n return {\n recordSuccess: (count = 1, at?: number): void => {\n totalAccepted += count;\n consecutiveFailures = 0;\n if (at !== undefined) {\n lastSuccessAt = at;\n }\n },\n recordFailure: (code: OtelHookErrorCode, count = 1, at?: number): void => {\n totalRejected += count;\n consecutiveFailures += 1;\n lastErrorCode = code;\n if (at !== undefined) {\n lastFailureAt = at;\n }\n },\n snapshot: (): DeliveryHealthSnapshot => ({\n subsystem,\n healthy: consecutiveFailures < unhealthyThreshold,\n totalAccepted,\n totalRejected,\n consecutiveFailures,\n ...(lastSuccessAt === undefined ? {} : { lastSuccessAt }),\n ...(lastFailureAt === undefined ? {} : { lastFailureAt }),\n ...(lastErrorCode === undefined ? {} : { lastErrorCode }),\n ...(options.destination === undefined ? {} : { destination: options.destination }),\n }),\n };\n};\n\nexport type OverallHealth = {\n readonly healthy: boolean;\n readonly subsystems: readonly DeliveryHealthSnapshot[];\n};\n\n/** Combines snapshots from every configured subsystem into one overall verdict. */\nexport const summarizeHealth = (snapshots: readonly DeliveryHealthSnapshot[]): OverallHealth => ({\n healthy: snapshots.every((snapshot) => snapshot.healthy),\n subsystems: [...snapshots],\n});\n","import { z } from \"zod\";\n\nimport { attributesSchema, epochMillisSchema, type Attributes } from \"../model/primitives.js\";\nimport {\n describeErrorCode,\n errorPhaseSchema,\n errorSeveritySchema,\n failurePostureSchema,\n otelHookErrorCodeSchema,\n type ErrorPhase,\n type OtelHookErrorCode,\n} from \"./taxonomy.js\";\n\nexport * from \"./taxonomy.js\";\n\n/**\n * Serializable, privacy-safe description of a failure.\n *\n * `message` is a fixed-vocabulary summary derived from the code and phase, never\n * a provider or exception string, because exception messages routinely contain\n * prompt text, file paths, and credentials. `details` is restricted to attribute\n * primitives for the same reason.\n */\nexport const otelHookErrorInfoSchema = z.strictObject({\n code: otelHookErrorCodeSchema,\n severity: errorSeveritySchema,\n phase: errorPhaseSchema,\n posture: failurePostureSchema,\n retryable: z.boolean(),\n message: z.string().min(1).max(512),\n details: attributesSchema.optional(),\n occurredAt: epochMillisSchema.optional(),\n});\nexport type OtelHookErrorInfo = z.infer<typeof otelHookErrorInfoSchema>;\n\nexport type CreateErrorInfoInput = {\n readonly code: OtelHookErrorCode;\n readonly phase: ErrorPhase;\n /** Short, non-sensitive detail, e.g. `\"2 adapters matched\"`. */\n readonly detail?: string;\n readonly details?: Attributes;\n readonly occurredAt?: number;\n};\n\nexport const createErrorInfo = (input: CreateErrorInfoInput): OtelHookErrorInfo => {\n const descriptor = describeErrorCode(input.code);\n const message =\n input.detail === undefined\n ? `${input.code} during ${input.phase}: ${descriptor.summary}`\n : `${input.code} during ${input.phase}: ${input.detail}`;\n return otelHookErrorInfoSchema.parse({\n code: descriptor.code,\n severity: descriptor.severity,\n phase: input.phase,\n posture: descriptor.posture,\n retryable: descriptor.retryable,\n message: message.slice(0, 512),\n ...(input.details === undefined ? {} : { details: input.details }),\n ...(input.occurredAt === undefined ? {} : { occurredAt: input.occurredAt }),\n });\n};\n\nexport class OtelHookError extends Error {\n public readonly info: OtelHookErrorInfo;\n\n public constructor(info: OtelHookErrorInfo) {\n super(info.message);\n this.name = \"OtelHookError\";\n this.info = info;\n }\n\n public static of(input: CreateErrorInfoInput): OtelHookError {\n return new OtelHookError(createErrorInfo(input));\n }\n}\n\nexport const isOtelHookError = (value: unknown): value is OtelHookError =>\n value instanceof OtelHookError;\n\n/**\n * Describe an arbitrary thrown value without disclosing its message.\n *\n * Only the constructor name crosses the boundary; the presence of a message is\n * reported as a boolean so operators can tell \"threw nothing useful\" from\n * \"threw something we deliberately did not log\".\n */\nexport const describeThrown = (\n thrown: unknown,\n): { readonly errorName: string; readonly hasMessage: boolean } => {\n if (thrown instanceof Error) {\n return {\n errorName: thrown.name.slice(0, 64) || \"Error\",\n hasMessage: typeof thrown.message === \"string\" && thrown.message.length > 0,\n };\n }\n return { errorName: typeof thrown, hasMessage: false };\n};\n\n/** Convert an unexpected throw into privacy-safe error info. */\nexport const errorInfoFromThrown = (\n thrown: unknown,\n input: { readonly code?: OtelHookErrorCode; readonly phase: ErrorPhase; readonly occurredAt?: number },\n): OtelHookErrorInfo => {\n if (isOtelHookError(thrown)) {\n return thrown.info;\n }\n const described = describeThrown(thrown);\n return createErrorInfo({\n code: input.code ?? \"internal-error\",\n phase: input.phase,\n detail: `contained ${described.errorName}`,\n details: { \"error.name\": described.errorName, \"error.has_message\": described.hasMessage },\n ...(input.occurredAt === undefined ? {} : { occurredAt: input.occurredAt }),\n });\n};\n","import { z } from \"zod\";\n\n/**\n * Closed set of error codes. Adding a code is a minor change; changing what a\n * code means is a breaking change.\n */\nexport const otelHookErrorCodeSchema = z.enum([\n /** Input was not usable at all (empty stdin, unparsable JSON). */\n \"invalid-input\",\n /** Input parsed but failed canonical schema validation. */\n \"schema-validation-failed\",\n /** No adapter claimed the input with sufficient confidence. */\n \"provider-unknown\",\n /** Several adapters claimed the input at the same confidence. */\n \"provider-detection-ambiguous\",\n /** An adapter threw or returned a malformed result. */\n \"provider-adapter-failure\",\n /** Two identity claims disagreed at equal confidence. */\n \"identity-conflict\",\n /** Required identity fields were absent. */\n \"identity-incomplete\",\n /** A usage report violated the canonical usage invariants. */\n \"usage-invalid\",\n /** The state store could not be read or written. */\n \"state-store-failure\",\n /** The telemetry sink rejected or could not deliver a batch. */\n \"telemetry-export-failure\",\n /** Content reached the sink boundary in a state the policy forbids. */\n \"privacy-policy-violation\",\n /** Configuration could not be resolved. */\n \"configuration-invalid\",\n /** A configured bound (events, batch size) dropped data. */\n \"limit-exceeded\",\n /**\n * No replay-stable delivery identifier was available for a callback while\n * deduplication was required.\n */\n \"delivery-identifier-unavailable\",\n \"delivery-claim-superseded\",\n /** Anything unanticipated. Always reported, never fatal to the host. */\n \"internal-error\",\n]);\nexport type OtelHookErrorCode = z.infer<typeof otelHookErrorCodeSchema>;\n\nexport const errorSeveritySchema = z.enum([\"warning\", \"error\"]);\nexport type ErrorSeverity = z.infer<typeof errorSeveritySchema>;\n\n/** Pipeline stage where a failure occurred. */\nexport const errorPhaseSchema = z.enum([\n \"configuration\",\n \"detection\",\n \"identity\",\n \"parsing\",\n \"normalization\",\n \"privacy\",\n \"state\",\n \"export\",\n \"shutdown\",\n]);\nexport type ErrorPhase = z.infer<typeof errorPhaseSchema>;\n\n/**\n * Which of the two safety postures a code participates in.\n *\n * - `fail-open`: the hook still reports success to the host agent. Telemetry may\n * be incomplete; the coding agent is never blocked.\n * - `fail-closed-attribution`: the observation is not attributed to a session or\n * provider. Data is dropped rather than labelled with a guess.\n */\nexport const failurePostureSchema = z.enum([\"fail-open\", \"fail-closed-attribution\"]);\nexport type FailurePosture = z.infer<typeof failurePostureSchema>;\n\nexport type ErrorCodeDescriptor = {\n readonly code: OtelHookErrorCode;\n readonly severity: ErrorSeverity;\n readonly posture: FailurePosture;\n /** Whether retrying the same input could succeed. */\n readonly retryable: boolean;\n readonly summary: string;\n};\n\nexport const ERROR_TAXONOMY: Readonly<Record<OtelHookErrorCode, ErrorCodeDescriptor>> =\n Object.freeze({\n \"invalid-input\": {\n code: \"invalid-input\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Input could not be read or decoded.\",\n },\n \"schema-validation-failed\": {\n code: \"schema-validation-failed\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"A canonical event failed schema validation and was dropped.\",\n },\n \"provider-unknown\": {\n code: \"provider-unknown\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"No adapter recognized the source provider; the input stays unattributed.\",\n },\n \"provider-detection-ambiguous\": {\n code: \"provider-detection-ambiguous\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Multiple adapters claimed the input at equal confidence.\",\n },\n \"provider-adapter-failure\": {\n code: \"provider-adapter-failure\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A provider adapter failed while parsing.\",\n },\n \"identity-conflict\": {\n code: \"identity-conflict\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Identity claims disagreed; attribution was declined.\",\n },\n \"identity-incomplete\": {\n code: \"identity-incomplete\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Required identity fields were missing; attribution was declined.\",\n },\n \"usage-invalid\": {\n code: \"usage-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A usage report violated the canonical usage invariants.\",\n },\n \"state-store-failure\": {\n code: \"state-store-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"State could not be read or written; derived values may be incomplete.\",\n },\n \"telemetry-export-failure\": {\n code: \"telemetry-export-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"The telemetry sink could not accept a batch.\",\n },\n \"privacy-policy-violation\": {\n code: \"privacy-policy-violation\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Content violated the resolved privacy policy and was dropped.\",\n },\n \"configuration-invalid\": {\n code: \"configuration-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Configuration could not be resolved; defaults apply.\",\n },\n \"limit-exceeded\": {\n code: \"limit-exceeded\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A configured bound was reached and data was dropped.\",\n },\n \"delivery-identifier-unavailable\": {\n code: \"delivery-identifier-unavailable\",\n severity: \"warning\",\n // Fail-open: the observation is still attributed and exported. Only the\n // at-most-once guarantee is missing, and refusing the telemetry to protect\n // a duplicate count would trade a certain loss for a possible one.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"No replay-stable delivery identifier was available; this callback was exported without deduplication.\",\n },\n \"delivery-claim-superseded\": {\n code: \"delivery-claim-superseded\",\n severity: \"warning\",\n // Fail-open, and specifically *not* silent. A peer reclaimed this callback's\n // claim while this process was still working on it, which means the\n // configured stale window is shorter than this installation's real worst\n // case. Both processes may now have exported the callback, so the\n // at-most-once guarantee did not hold for it — the only honest response is\n // to say so and let the operator raise the window.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"A delivery claim was reclaimed by another process before this one committed; the callback may have been exported twice.\",\n },\n \"internal-error\": {\n code: \"internal-error\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"An unexpected failure was contained.\",\n },\n });\n\nexport const describeErrorCode = (code: OtelHookErrorCode): ErrorCodeDescriptor =>\n ERROR_TAXONOMY[code];\n\n/** Outcome of attributing an observation to a provider and session. */\nexport const attributionOutcomeSchema = z.enum([\n /** Identity resolved; events carry provider and session identity. */\n \"attributed\",\n /** Identity could not be established safely; nothing was attributed. */\n \"declined\",\n /** Attribution was attempted and failed unexpectedly. */\n \"failed\",\n /** Input was recognized but intentionally carried no telemetry. */\n \"not-applicable\",\n]);\nexport type AttributionOutcome = z.infer<typeof attributionOutcomeSchema>;\n\nexport const attributionReasonSchema = z.enum([\n \"provider-unknown\",\n \"provider-detection-ambiguous\",\n \"identity-conflict\",\n \"identity-incomplete\",\n \"adapter-ignored-input\",\n \"adapter-failure\",\n \"invalid-input\",\n \"internal-error\",\n]);\nexport type AttributionReason = z.infer<typeof attributionReasonSchema>;\n","import { 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\n/**\n * Metric series state (issue #69): one record per series, under the provider\n * session it belongs to so the janitor can sweep a session's series with the rest\n * of its state. The scope segment is `s=<sessionId>` for a per-session series and\n * `all` for one that spans sessions (`session.id` switched off); the `s=` prefix\n * keeps the two from ever colliding, whatever a provider names its sessions.\n *\n * `seriesDigest` is a digest of the instrument and its attributes, never the\n * attributes themselves.\n */\nexport const metricSeriesKey = (sessionScope: string, seriesDigest: string): string =>\n `${metricSeriesScanPrefix(sessionScope)}${encodeSegment(seriesDigest)}`;\n\nexport const metricSeriesScanPrefix = (sessionScope?: string): string =>\n sessionScope === undefined\n ? `${LIFECYCLE_PREFIX}:metric:v1:`\n : `${LIFECYCLE_PREFIX}:metric:v1:${encodeSegment(sessionScope)}:`;\n","import { createHash } from \"node:crypto\";\n\nimport type { Clock, StateStore } from \"../runtime/ports.js\";\nimport { withOptionalSessionLock } from \"../state/store.js\";\nimport {\n emptyHistogram,\n METRIC_INSTRUMENTS,\n recordIntoHistogram,\n seriesIdentity,\n type HistogramState,\n type MetricObservation,\n type MetricPoint,\n} from \"../telemetry/metric-model.js\";\nimport { metricSeriesKey, metricSeriesScanPrefix } from \"./keys.js\";\n\n/**\n * Cumulative metric series kept across hook processes (issue #69).\n *\n * A hook process lives for one callback, so an in-process `MeterProvider` would\n * only ever see one observation and restart every series at zero. Cumulative\n * temporality — what receivers that merge counters by keeping the largest value\n * need — therefore requires the running total to outlive the process. Each series\n * is one state record: read, fold the batch's observations in, write back, and\n * export the new total as a point whose interval starts at the series' first\n * observation.\n *\n * Folding is idempotent per delivery: the record names the last delivery folded\n * into it, so a callback replayed after a crash between \"recorded\" and \"committed\"\n * restates the total instead of adding to it.\n *\n * Concurrency: the read-fold-write runs under the session lock of the series'\n * scope (the provider session, or one shared lock for series that span sessions),\n * the same lock usage accounting uses, so two concurrent processes cannot both add\n * to the same stale total.\n */\n\nexport type MetricSeriesStoreDependencies = {\n readonly stateStore: StateStore;\n readonly clock: Clock;\n};\n\nexport type RecordCumulativeOptions = {\n /** Opaque digest of the delivery these observations came from. */\n readonly deliveryToken?: string;\n /** Whether series are per session (`session.id` on the points). Default true. */\n readonly perSession?: boolean;\n};\n\nexport type MetricSeriesCleanupResult = { readonly removed: number; readonly scanned: number };\n\nexport interface MetricSeriesStore {\n /** Fold observations into their series; returns one cumulative point per touched series. */\n recordCumulative(\n observations: readonly MetricObservation[],\n options?: RecordCumulativeOptions,\n ): Promise<readonly MetricPoint[]>;\n /** Remember when the session's current turn began (its last prompt). */\n recordTurnStart(sessionId: string, startMillis: number): Promise<void>;\n /** When the session's current turn began, if a prompt was recorded. */\n readTurnStart(sessionId: string): Promise<number | undefined>;\n cleanup(\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<MetricSeriesCleanupResult>;\n}\n\n/** Not a base64url digest (43 chars), so it can never collide with a series key. */\nconst TURN_START_SEGMENT = \"turn-start\";\n\n/** Lock and key scope for series that are not per session. */\nconst SHARED_SCOPE = \"all\";\nconst SHARED_LOCK = \"otelhook.metrics.shared\";\n\nconst sessionScope = (sessionId: string): string => `s=${sessionId}`;\n\nconst digest = (identity: string): string =>\n createHash(\"sha256\").update(identity).digest(\"base64url\").slice(0, 43);\n\ntype SeriesRecord = {\n readonly startTimeMillis: number;\n readonly value?: number | undefined;\n readonly histogram?: HistogramState | undefined;\n readonly appliedDelivery?: string | undefined;\n};\n\nconst toStoredHistogram = (\n histogram: HistogramState,\n): { count: number; sum: number; min: number; max: number; bucketCounts: number[] } => ({\n count: histogram.count,\n sum: histogram.sum,\n // An empty histogram has infinite min/max, which JSON cannot hold. A stored\n // histogram always has at least one value, so these are finite in practice.\n min: Number.isFinite(histogram.min) ? histogram.min : 0,\n max: Number.isFinite(histogram.max) ? histogram.max : 0,\n bucketCounts: [...histogram.bucketCounts],\n});\n\nexport const createMetricSeriesStore = (deps: MetricSeriesStoreDependencies): MetricSeriesStore => {\n const { stateStore, clock } = deps;\n\n const readSeries = async (key: string): Promise<SeriesRecord | undefined> => {\n const record = await stateStore.read(key);\n if (record?.value.kind !== \"metric-series\") {\n return undefined;\n }\n return record.value;\n };\n\n const recordGroup = async (\n scope: string,\n observations: readonly MetricObservation[],\n deliveryToken: string | undefined,\n ): Promise<MetricPoint[]> => {\n const bySeries = new Map<string, MetricObservation[]>();\n for (const observation of observations) {\n const identity = seriesIdentity(observation.instrument, observation.attributes);\n const group = bySeries.get(identity) ?? [];\n group.push(observation);\n bySeries.set(identity, group);\n }\n\n const now = clock.now();\n const points: MetricPoint[] = [];\n for (const [identity, group] of bySeries) {\n const first = group[0];\n if (first === undefined) {\n continue;\n }\n const instrument = METRIC_INSTRUMENTS[first.instrument];\n const key = metricSeriesKey(scope, digest(identity));\n const existing = await readSeries(key);\n const boundaries = instrument.boundaries;\n // A stored histogram whose bucket layout no longer matches the instrument\n // cannot be continued; it restarts, with a new start time, which a receiver\n // reads as a reset rather than as a decrease.\n const compatible =\n existing !== undefined &&\n (boundaries === undefined\n ? existing.value !== undefined\n : existing.histogram?.bucketCounts.length === boundaries.length + 1);\n const base = compatible ? existing : undefined;\n const replay = deliveryToken !== undefined && base?.appliedDelivery === deliveryToken;\n\n const earliest = Math.min(...group.map((observation) => observation.timeMillis));\n const startTimeMillis = base?.startTimeMillis ?? Math.min(earliest, now);\n let value = base?.value ?? 0;\n let histogram: HistogramState | undefined =\n boundaries === undefined\n ? undefined\n : base?.histogram === undefined\n ? emptyHistogram(boundaries)\n : base.histogram;\n\n if (!replay) {\n for (const observation of group) {\n if (histogram !== undefined && boundaries !== undefined) {\n histogram = recordIntoHistogram(histogram, boundaries, observation.value);\n } else {\n value += observation.value;\n }\n }\n await stateStore.write(key, {\n kind: \"metric-series\",\n startTimeMillis,\n ...(histogram === undefined ? { value } : { histogram: toStoredHistogram(histogram) }),\n ...(deliveryToken === undefined ? {} : { appliedDelivery: deliveryToken }),\n });\n }\n\n points.push({\n instrument: first.instrument,\n temporality: \"cumulative\",\n attributes: first.attributes,\n startTimeMillis,\n timeMillis: Math.max(now, startTimeMillis),\n ...(histogram === undefined ? { value } : { histogram }),\n });\n }\n return points;\n };\n\n const recordCumulative = async (\n observations: readonly MetricObservation[],\n options?: RecordCumulativeOptions,\n ): Promise<readonly MetricPoint[]> => {\n if (observations.length === 0) {\n return [];\n }\n if (options?.perSession === false) {\n return withOptionalSessionLock(stateStore, SHARED_LOCK, () =>\n recordGroup(SHARED_SCOPE, observations, options.deliveryToken),\n );\n }\n const bySession = new Map<string, MetricObservation[]>();\n for (const observation of observations) {\n const group = bySession.get(observation.sessionId) ?? [];\n group.push(observation);\n bySession.set(observation.sessionId, group);\n }\n const points: MetricPoint[] = [];\n for (const [sessionId, group] of bySession) {\n points.push(\n ...(await withOptionalSessionLock(stateStore, sessionId, () =>\n recordGroup(sessionScope(sessionId), group, options?.deliveryToken),\n )),\n );\n }\n return points;\n };\n\n const cleanup = async (\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<MetricSeriesCleanupResult> => {\n const cap = options?.maxEntries ?? 1_000;\n const now = clock.now();\n let removed = 0;\n let scanned = 0;\n const prefix = metricSeriesScanPrefix(\n options?.sessionId === undefined ? undefined : sessionScope(options.sessionId),\n );\n for (const key of await stateStore.keys(prefix)) {\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 await stateStore.delete(key);\n removed += 1;\n }\n }\n return { removed, scanned };\n };\n\n const turnKey = (sessionId: string): string => metricSeriesKey(sessionScope(sessionId), TURN_START_SEGMENT);\n\n const recordTurnStart = (sessionId: string, startMillis: number): Promise<void> =>\n withOptionalSessionLock(stateStore, sessionId, async () => {\n const existing = await stateStore.read(turnKey(sessionId));\n const previous =\n existing?.value.kind === \"attributes\" && typeof existing.value.attributes.startMillis === \"number\"\n ? existing.value.attributes.startMillis\n : undefined;\n // Never move backwards: a late, redelivered prompt must not reopen an older turn.\n if (previous !== undefined && previous >= startMillis) {\n return;\n }\n await stateStore.write(turnKey(sessionId), { kind: \"attributes\", attributes: { startMillis } });\n });\n\n const readTurnStart = async (sessionId: string): Promise<number | undefined> => {\n const record = await stateStore.read(turnKey(sessionId));\n const value = record?.value.kind === \"attributes\" ? record.value.attributes.startMillis : undefined;\n return typeof value === \"number\" ? value : undefined;\n };\n\n return { recordCumulative, recordTurnStart, readTurnStart, cleanup };\n};\n","import type { Attributes } from \"@opentelemetry/api\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport { ATTR_SESSION_ID } from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport { isTargetedEvent, type CanonicalEvent } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\n\n/**\n * W3C hex identity attributes on every log and span.\n *\n * Mission Control (and any consumer that decodes OTLP protobuf with a JSON\n * `toObject` that stringifies bytes as UTF-8) cannot recover a usable id from\n * the protobuf `trace_id` / `span_id` fields. These attributes are already hex\n * in the OpenTelemetry JS API; they are copied onto the attribute map so a\n * consumer never has to stringify binary ids.\n */\nexport const ATTR_TRACE_ID = \"trace_id\";\nexport const ATTR_SPAN_ID = \"span_id\";\nexport const ATTR_PARENT_SPAN_ID = \"parent_span_id\";\n\n/** Provider session id, kept when `session.id` is an externally supplied key. */\nexport const ATTR_OTELHOOK_SESSION_ID = \"otelhook.session.id\";\n/** Same provider session id under the gen_ai conversation attribute. */\nexport const ATTR_GEN_AI_CONVERSATION_ID = \"gen_ai.conversation.id\";\n\nexport const TRACE_ID_HEX_PATTERN = /^[0-9a-f]{32}$/;\nexport const SPAN_ID_HEX_PATTERN = /^[0-9a-f]{16}$/;\n\nconst ATTR_OTELHOOK_INVOCATION_ID = \"otelhook.invocation.id\";\nconst ATTR_OTELHOOK_PROVIDER_ID = \"otelhook.provider.id\";\nconst ATTR_OTELHOOK_PROVIDER_VERSION = \"otelhook.provider.version\";\nconst ATTR_OTELHOOK_WORKSPACE_ID = \"otelhook.workspace.id\";\n\n/**\n * Resource attributes a launcher may set to supply the session key, in\n * preference order: the OpenTelemetry semantic-convention `session.id`, then the\n * legacy `har.session_key` that earlier launchers still send.\n */\nexport const EXTERNAL_SESSION_KEY_ATTRIBUTES: readonly string[] = Object.freeze([\n ATTR_SESSION_ID,\n \"har.session_key\",\n]);\n\n/**\n * The provider's own subagent id (Claude Code `agent_id`), on every record of an\n * event emitted inside a subagent. Same class as `session.id`: a provider-minted\n * opaque identifier, exported verbatim so a consumer can join it to the\n * provider's own per-subagent records.\n */\nexport const ATTR_OTELHOOK_SUBAGENT_ID = \"otelhook.subagent.id\";\n\n/**\n * Worktree an event targeted (ADR 0008): the one a tool call touched, or the one\n * a session runs in on its start and prompts. Branch under the OTel VCS\n * attribute; the worktree root, and its repository's main worktree root, only\n * as salted `git-root` handles.\n */\nexport const ATTR_VCS_REF_HEAD_NAME = \"vcs.ref.head.name\";\nexport const ATTR_OTELHOOK_TARGET_WORKSPACE_ID = \"otelhook.target.workspace.id\";\nexport const ATTR_OTELHOOK_TARGET_SOURCE = \"otelhook.target.source\";\nexport const ATTR_OTELHOOK_TARGET_REPOSITORY_ID = \"otelhook.target.repository.id\";\nexport const ATTR_OTELHOOK_TARGET_WORKTREE_KIND = \"otelhook.target.worktree.kind\";\n\n/** Whether `gen_ai.usage.*` on this record is a delta or a running total. */\nexport const ATTR_OTELHOOK_USAGE_TEMPORALITY = \"otelhook.usage.temporality\";\n\n/** Target attributes for a targeted event; empty when the core resolved none. */\nexport const targetAttributes = (event: CanonicalEvent): Attributes => {\n if (!isTargetedEvent(event) || event.target === undefined) {\n return {};\n }\n const { target } = event;\n return {\n [ATTR_OTELHOOK_TARGET_WORKSPACE_ID]: target.workspaceId,\n [ATTR_OTELHOOK_TARGET_SOURCE]: target.source,\n ...(target.vcsBranchName === undefined ? {} : { [ATTR_VCS_REF_HEAD_NAME]: target.vcsBranchName }),\n ...(target.repositoryId === undefined\n ? {}\n : { [ATTR_OTELHOOK_TARGET_REPOSITORY_ID]: target.repositoryId }),\n ...(target.worktreeKind === undefined\n ? {}\n : { [ATTR_OTELHOOK_TARGET_WORKTREE_KIND]: target.worktreeKind }),\n };\n};\n\n/** Temporality of reported usage, so a consumer never sums running totals. */\nexport const usageTemporalityAttributes = (usage: CanonicalUsage | undefined): Attributes =>\n usage === undefined ? {} : { [ATTR_OTELHOOK_USAGE_TEMPORALITY]: usage.temporality };\n\nconst isPrimitiveAttribute = (value: unknown): value is string | number | boolean =>\n typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\";\n\n/**\n * Resource attribute namespaces a launcher puts on the process that are also\n * copied onto every span and log record.\n *\n * Many backends index only record attributes (filters, search, dashboards), so a\n * value that exists only on the Resource is invisible there. Copied:\n *\n * - `har.*` — attributes earlier launchers send;\n * - `factory.*` — the Factory Commits telemetry profile (work unit, slot, …),\n * **except** `factory.local.*`, which the profile defines as local-only: it\n * stays on the Resource and never reaches a record;\n * - `vcs.*` — OpenTelemetry VCS attributes. An event's own resolved target\n * (ADR 0008) still wins for the keys it sets, such as `vcs.ref.head.name`.\n *\n * `session.id` is not copied: it is resolved separately (see\n * `resolveExportedSessionId`), so a resource value cannot overwrite the\n * trimmed, resolved one.\n */\nexport const PASSTHROUGH_RESOURCE_PREFIXES: readonly string[] = Object.freeze([\"har.\", \"factory.\", \"vcs.\"]);\n/** Local-only profile namespace: never copied from the Resource onto records. */\nexport const LOCAL_ONLY_RESOURCE_PREFIX = \"factory.local.\";\n\nconst isPassthroughKey = (key: string): boolean =>\n PASSTHROUGH_RESOURCE_PREFIXES.some((prefix) => key.startsWith(prefix)) &&\n !key.startsWith(LOCAL_ONLY_RESOURCE_PREFIX) &&\n key !== \"factory.local\";\n\n/**\n * Primitive resource attributes to copy onto every log and span record.\n *\n * Only the namespaces in `PASSTHROUGH_RESOURCE_PREFIXES` are forwarded, minus\n * `factory.local.*`; nothing is invented when they are absent.\n */\nexport const passthroughResourceAttributes = (resource: Resource): Attributes => {\n const attributes: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(resource.attributes)) {\n if (isPassthroughKey(key) && isPrimitiveAttribute(value)) {\n attributes[key] = value;\n }\n }\n return attributes;\n};\n\n/**\n * Session context attributes the core stamped on this event\n * (`docs/session-context.md`); empty when none applies.\n */\nexport const contextAttributesOf = (event: CanonicalEvent): Attributes =>\n event.contextAttributes === undefined ? {} : { ...event.contextAttributes };\n\n/**\n * The profile layer of a record: the Resource's passthrough namespaces,\n * overridden key by key by the event's session context.\n *\n * Context wins because it is the more specific and more recent statement: a\n * session that moved from one attempt to another still has the first one in its\n * process environment (and so on the Resource), but its context names the\n * second. Everything otel-hook derives for the event itself — `session.id`,\n * `otelhook.*`, `gen_ai.*`, trace ids, and a resolved worktree target — is\n * layered above this and is never overridden by it.\n */\nexport const profileAttributes = (event: CanonicalEvent, resource: Resource): Attributes => ({\n ...passthroughResourceAttributes(resource),\n ...contextAttributesOf(event),\n});\n\n/**\n * Session id to put on `session.id`, preferring an externally supplied key.\n *\n * A launcher supplies the key as a resource attribute (usually through\n * `OTEL_RESOURCE_ATTRIBUTES`): `session.id` first, then the legacy\n * `har.session_key`, then the provider's own session id. The provider's id is\n * never discarded: it is returned separately so callers can emit it as\n * `otelhook.session.id` / `gen_ai.conversation.id`.\n */\nexport const resolveExportedSessionId = (\n eventSessionId: string,\n resource: Resource,\n): { readonly sessionId: string; readonly providerSessionId: string } => {\n for (const key of EXTERNAL_SESSION_KEY_ATTRIBUTES) {\n const supplied = resource.attributes[key];\n if (typeof supplied === \"string\") {\n const trimmed = supplied.trim();\n if (trimmed.length > 0) {\n return { sessionId: trimmed, providerSessionId: eventSessionId };\n }\n }\n }\n return { sessionId: eventSessionId, providerSessionId: eventSessionId };\n};\n\nexport type ExportedTraceIds = {\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n};\n\n/**\n * Hex-only trace/span attributes. A value that is not W3C hex is omitted\n * rather than stringified — binary blobs must never appear in id fields.\n */\nexport const hexTraceAttributes = (ids: ExportedTraceIds): Attributes => ({\n ...(TRACE_ID_HEX_PATTERN.test(ids.traceId) ? { [ATTR_TRACE_ID]: ids.traceId } : {}),\n ...(SPAN_ID_HEX_PATTERN.test(ids.spanId) ? { [ATTR_SPAN_ID]: ids.spanId } : {}),\n ...(ids.parentSpanId !== undefined && SPAN_ID_HEX_PATTERN.test(ids.parentSpanId)\n ? { [ATTR_PARENT_SPAN_ID]: ids.parentSpanId }\n : {}),\n});\n\n/**\n * Identity attributes shared by the log and span mappings.\n *\n * `session.id` is the externally supplied session key when the resource carries\n * one (`session.id`, then `har.session_key`), otherwise the provider session id.\n * The provider id is always also emitted under `otelhook.session.id` and\n * `gen_ai.conversation.id`. Profile resource attributes and the event's session\n * context are copied on too, beneath them (see `profileAttributes`).\n */\nexport const exportIdentityAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n ids: ExportedTraceIds,\n): Attributes => {\n const { sessionId, providerSessionId } = resolveExportedSessionId(event.sessionId, resource);\n return {\n // First, so nothing in the profile layer can replace an identity attribute.\n ...profileAttributes(event, resource),\n [ATTR_SESSION_ID]: sessionId,\n [ATTR_OTELHOOK_SESSION_ID]: providerSessionId,\n [ATTR_GEN_AI_CONVERSATION_ID]: providerSessionId,\n [ATTR_OTELHOOK_INVOCATION_ID]: event.invocationId,\n [ATTR_OTELHOOK_PROVIDER_ID]: event.provenance.providerId,\n ...(event.provenance.providerVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event.provenance.providerVersion }),\n [ATTR_OTELHOOK_WORKSPACE_ID]: event.workspace.workspaceId,\n ...(event.subagentId === undefined ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event.subagentId }),\n ...hexTraceAttributes(ids),\n };\n};\n","import { z } from \"zod\";\n\nimport {\n errorPhaseSchema,\n errorSeveritySchema,\n otelHookErrorCodeSchema,\n} from \"../errors/taxonomy.js\";\nimport { contentFactSchema, contentFactsSchema } from \"./content.js\";\nimport { extensionsSchema, emptyExtensions } from \"./extensions.js\";\nimport { sourceProvenanceSchema, workspaceIdentitySchema } from \"./identity.js\";\nimport { subagentIdSchema, workspaceTargetSchema } from \"./target.js\";\nimport {\n durationMillisSchema,\n epochMillisSchema,\n eventIdSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n sequenceNumberSchema,\n sessionIdSchema,\n tokenCountSchema,\n} from \"./primitives.js\";\nimport { canonicalUsageSchema, type CanonicalUsage } from \"./usage.js\";\nimport { canonicalSchemaVersionSchema } from \"./version.js\";\n\n/** Model being invoked. Model identifiers are not treated as sensitive. */\nexport const modelDescriptorSchema = z.strictObject({\n modelId: nonEmptyStringSchema,\n /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */\n vendor: nonEmptyStringSchema.optional(),\n family: nonEmptyStringSchema.optional(),\n});\nexport type ModelDescriptor = z.infer<typeof modelDescriptorSchema>;\n\nexport const costFactsSchema = z.strictObject({\n /** ISO 4217 code. */\n currency: z.string().length(3),\n amount: z.number().min(0).finite(),\n source: z.enum([\"provider-reported\", \"computed\"]),\n});\nexport type CostFacts = z.infer<typeof costFactsSchema>;\n\nexport const canonicalEventTypeSchema = z.enum([\n \"session.start\",\n \"session.end\",\n \"prompt.submitted\",\n \"generation.start\",\n \"generation.end\",\n \"tool.start\",\n \"tool.end\",\n \"subagent.start\",\n \"subagent.end\",\n \"compaction.performed\",\n \"error.raised\",\n]);\nexport type CanonicalEventType = z.infer<typeof canonicalEventTypeSchema>;\n\nexport const CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;\n\nconst outcomeSchema = z.enum([\"ok\", \"error\", \"cancelled\", \"timeout\", \"denied\", \"unknown\"]);\nexport type EventOutcome = z.infer<typeof outcomeSchema>;\n\n/**\n * Fields present on every canonical event.\n *\n * Identity fields are duplicated onto each event rather than referenced through\n * shared state, so an event is self-describing once it leaves the process.\n */\nconst baseEventFields = {\n schemaVersion: canonicalSchemaVersionSchema,\n eventId: eventIdSchema,\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Per-invocation ordering key. Stable across replays of the same input. */\n sequence: sequenceNumberSchema,\n occurredAt: epochMillisSchema,\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n /**\n * The provider's own id for the subagent this event was emitted inside (e.g.\n * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event\n * factory, never by hand.\n */\n subagentId: subagentIdSchema.optional(),\n extensions: extensionsSchema.default(emptyExtensions),\n /**\n * Attributes of the session context segment in force when the event\n * occurred (`docs/session-context.md`), stamped by the core from a file a\n * harness wrote. Exported on every record of the event, over the same keys\n * from the Resource. Absent when no context applies. Set by the core only,\n * never by an adapter.\n */\n contextAttributes: z.record(z.string().min(1).max(255), z.union([z.string(), z.number(), z.boolean()])).optional(),\n} as const;\n\nconst event = <TShape extends z.ZodRawShape>(shape: TShape) =>\n z.strictObject({ ...baseEventFields, ...shape });\n\nexport const sessionStartEventSchema = event({\n type: z.literal(\"session.start\"),\n sessionKind: z.enum([\"interactive\", \"non-interactive\", \"unknown\"]),\n agentName: nonEmptyStringSchema.optional(),\n agentVersion: nonEmptyStringSchema.optional(),\n model: modelDescriptorSchema.optional(),\n /** The git worktree the session runs in, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const sessionEndEventSchema = event({\n type: z.literal(\"session.end\"),\n reason: z.enum([\"completed\", \"aborted\", \"error\", \"timeout\", \"unknown\"]),\n durationMillis: durationMillisSchema.optional(),\n /** Session totals, typically cumulative. */\n usage: canonicalUsageSchema.optional(),\n cost: costFactsSchema.optional(),\n});\n\nexport const promptSubmittedEventSchema = event({\n type: z.literal(\"prompt.submitted\"),\n promptSource: z.enum([\"user\", \"automation\", \"resumed\", \"unknown\"]),\n content: contentFactSchema.optional(),\n turnIndex: z.number().int().min(0).optional(),\n /** The git worktree the session runs in, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const generationStartEventSchema = event({\n type: z.literal(\"generation.start\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n requestedMaxOutputTokens: tokenCountSchema.optional(),\n inputContent: contentFactsSchema.optional(),\n});\n\nexport const generationEndEventSchema = event({\n type: z.literal(\"generation.end\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n outcome: outcomeSchema,\n stopReason: nonEmptyStringSchema.optional(),\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n /**\n * True when `usage` is known to cover only part of the generation (for\n * example the last model request of a multi-request turn); false when the\n * provider or harness said it is the whole. Absent: not stated. Meaningless\n * without `usage`.\n */\n usagePartial: z.boolean().optional(),\n cost: costFactsSchema.optional(),\n outputContent: contentFactsSchema.optional(),\n});\n\nexport const toolKindSchema = z.enum([\n \"read\",\n \"write\",\n \"execute\",\n \"search\",\n \"network\",\n \"delegate\",\n \"other\",\n \"unknown\",\n]);\nexport type ToolKind = z.infer<typeof toolKindSchema>;\n\nexport const toolStartEventSchema = event({\n type: z.literal(\"tool.start\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n toolKind: toolKindSchema,\n generationId: nonEmptyStringSchema.optional(),\n input: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const toolEndEventSchema = event({\n type: z.literal(\"tool.end\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n /** Present when the host asked for or recorded a permission decision. */\n permissionDecision: z.enum([\"allowed\", \"denied\", \"deferred\", \"not-required\"]).optional(),\n output: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const subagentStartEventSchema = event({\n type: z.literal(\"subagent.start\"),\n subagentInvocationId: invocationIdSchema,\n subagentType: nonEmptyStringSchema.optional(),\n /** 0 for the top-level agent; 1 for its direct children. */\n delegationDepth: z.number().int().min(0).max(64),\n model: modelDescriptorSchema.optional(),\n});\n\nexport const subagentEndEventSchema = event({\n type: z.literal(\"subagent.end\"),\n subagentInvocationId: invocationIdSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const compactionPerformedEventSchema = event({\n type: z.literal(\"compaction.performed\"),\n trigger: z.enum([\"automatic\", \"manual\", \"unknown\"]),\n /** Provider-reported context size before and after compaction, if known. */\n contextTokensBefore: tokenCountSchema.optional(),\n contextTokensAfter: tokenCountSchema.optional(),\n droppedMessageCount: z.number().int().min(0).optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const errorRaisedEventSchema = event({\n type: z.literal(\"error.raised\"),\n errorCode: otelHookErrorCodeSchema,\n severity: errorSeveritySchema,\n phase: errorPhaseSchema,\n retryable: z.boolean(),\n /** Error text is content: it is described, never embedded verbatim by default. */\n message: contentFactSchema.optional(),\n /** Non-sensitive, provider-agnostic short label. */\n detail: nonEmptyStringSchema.optional(),\n});\n\nexport const canonicalEventSchema = z.discriminatedUnion(\"type\", [\n sessionStartEventSchema,\n sessionEndEventSchema,\n promptSubmittedEventSchema,\n generationStartEventSchema,\n generationEndEventSchema,\n toolStartEventSchema,\n toolEndEventSchema,\n subagentStartEventSchema,\n subagentEndEventSchema,\n compactionPerformedEventSchema,\n errorRaisedEventSchema,\n]);\n\nexport type CanonicalEvent = z.infer<typeof canonicalEventSchema>;\nexport type CanonicalEventInput = z.input<typeof canonicalEventSchema>;\n\nexport type SessionStartEvent = z.infer<typeof sessionStartEventSchema>;\nexport type SessionEndEvent = z.infer<typeof sessionEndEventSchema>;\nexport type PromptSubmittedEvent = z.infer<typeof promptSubmittedEventSchema>;\nexport type GenerationStartEvent = z.infer<typeof generationStartEventSchema>;\nexport type GenerationEndEvent = z.infer<typeof generationEndEventSchema>;\nexport type ToolStartEvent = z.infer<typeof toolStartEventSchema>;\nexport type ToolEndEvent = z.infer<typeof toolEndEventSchema>;\nexport type SubagentStartEvent = z.infer<typeof subagentStartEventSchema>;\nexport type SubagentEndEvent = z.infer<typeof subagentEndEventSchema>;\nexport type CompactionPerformedEvent = z.infer<typeof compactionPerformedEventSchema>;\nexport type ErrorRaisedEvent = z.infer<typeof errorRaisedEventSchema>;\n\nexport type CanonicalEventOfType<TType extends CanonicalEventType> = Extract<\n CanonicalEvent,\n { type: TType }\n>;\n\n/**\n * The event types that may carry a resolved `target` (ADR 0008): a tool call\n * names the worktree it touched; a session start and a prompt name the one the\n * session runs in, so a consumer knows the session's place before its first\n * tool call.\n */\nexport const TARGETED_EVENT_TYPES = [\"session.start\", \"prompt.submitted\", \"tool.start\", \"tool.end\"] as const;\nexport type TargetedEventType = (typeof TARGETED_EVENT_TYPES)[number];\nexport type TargetedEvent = CanonicalEventOfType<TargetedEventType>;\n\nconst TARGETED: ReadonlySet<string> = new Set(TARGETED_EVENT_TYPES);\nexport const isTargetedEvent = (event: CanonicalEvent): event is TargetedEvent => TARGETED.has(event.type);\n\nexport type EventValidationResult =\n | { readonly status: \"ok\"; readonly event: CanonicalEvent }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nexport const validateCanonicalEvent = (value: unknown): EventValidationResult => {\n const parsed = canonicalEventSchema.safeParse(value);\n if (parsed.success) {\n return { status: \"ok\", event: parsed.data };\n }\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n};\n\n/** Parse or throw. Intended for fixtures and tests, not the hook path. */\nexport const parseCanonicalEvent = (value: unknown): CanonicalEvent =>\n canonicalEventSchema.parse(value);\n\n/** Usage carried by an event, if the event type can carry any. */\nexport const eventUsage = (event: CanonicalEvent): CanonicalUsage | undefined =>\n \"usage\" in event ? event.usage : undefined;\n\n/** Stable ordering: by sequence, then by timestamp, then by event id. */\nexport const compareEvents = (a: CanonicalEvent, b: CanonicalEvent): number =>\n a.sequence - b.sequence || a.occurredAt - b.occurredAt || a.eventId.localeCompare(b.eventId);\n","import { z } from \"zod\";\n\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 { attributeValueSchema, type AttributeValue } from \"./primitives.js\";\n\n/**\n * Extension keys must be namespaced: at least one dot-separated segment before\n * the leaf, e.g. `acme.deployment-tier`. Namespacing keeps provider- and\n * consumer-specific fields from colliding with core fields or each other.\n */\nexport const EXTENSION_KEY_PATTERN =\n /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;\n\n/** Namespaces owned by the core model; extensions may not use them. */\nexport const RESERVED_EXTENSION_NAMESPACES: readonly string[] = Object.freeze([\n \"otelhook\",\n \"otel\",\n \"telemetry\",\n]);\n\nexport const MAX_EXTENSION_ENTRIES = 64;\n\nexport const extensionKeyNamespace = (key: string): string => key.slice(0, key.indexOf(\".\"));\n\nexport const isReservedExtensionNamespace = (key: string): boolean =>\n RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));\n\nexport const isValidExtensionKey = (key: string): boolean =>\n EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);\n\n/**\n * Namespaced extension bag.\n *\n * Values are restricted to attribute primitives, so extensions cannot carry\n * nested provider payloads.\n */\nexport const extensionsSchema = z\n .record(z.string(), attributeValueSchema)\n .check((ctx) => {\n const keys = Object.keys(ctx.value);\n if (keys.length > MAX_EXTENSION_ENTRIES) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`,\n });\n }\n for (const key of keys) {\n if (!EXTENSION_KEY_PATTERN.test(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. \"acme.tier\"`,\n });\n continue;\n }\n if (isReservedExtensionNamespace(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`,\n });\n }\n }\n });\n\nexport type Extensions = Record<string, AttributeValue>;\n\nexport const EMPTY_EXTENSIONS: Extensions = Object.freeze({});\n\nexport const emptyExtensions = (): Extensions => ({});\n","import { z } from \"zod\";\n\nimport {\n attributesSchema,\n detectionConfidenceSchema,\n DETECTION_CONFIDENCE_RANK,\n epochMillisSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n resolvedProviderIdSchema,\n sessionIdSchema,\n sourceTransportSchema,\n workspaceIdSchema,\n type DetectionConfidence,\n type InvocationId,\n type SessionId,\n type WorkspaceId,\n} from \"./primitives.js\";\n\n/**\n * Where a workspace identifier came from.\n *\n * Ordered from most to least stable. The source is recorded so consumers can\n * tell a repository-scoped identity from a directory-scoped one instead of\n * assuming they are comparable.\n */\nexport const workspaceKeySourceSchema = z.enum([\n \"git-remote\",\n \"git-root\",\n \"working-directory\",\n \"explicit\",\n \"unknown\",\n]);\nexport type WorkspaceKeySource = z.infer<typeof workspaceKeySourceSchema>;\n\n/**\n * Privacy-safe workspace identity.\n *\n * Only opaque handles and explicitly allowed labels are modelled. There is no\n * field for a filesystem path, so paths cannot be exported through this type.\n */\nexport const workspaceIdentitySchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n keySource: workspaceKeySourceSchema,\n /** Repository name only; never an owner path or URL with credentials. */\n repositoryName: nonEmptyStringSchema.optional(),\n vcsBranchName: nonEmptyStringSchema.optional(),\n /** Opaque handle for the checked-out revision. */\n vcsRevisionId: nonEmptyStringSchema.optional(),\n })\n .readonly();\nexport type WorkspaceIdentity = z.infer<typeof workspaceIdentitySchema>;\n\nexport const UNKNOWN_WORKSPACE_ID = \"unknown:0000000000000000\" as WorkspaceId;\n\nexport const unknownWorkspaceIdentity = (): WorkspaceIdentity =>\n workspaceIdentitySchema.parse({\n workspaceId: UNKNOWN_WORKSPACE_ID,\n keySource: \"unknown\",\n });\n\n/**\n * Provenance of an observation: which provider produced it and which adapter\n * interpreted it, with the confidence of that attribution.\n */\nexport const sourceProvenanceSchema = z\n .strictObject({\n providerId: resolvedProviderIdSchema,\n providerVersion: nonEmptyStringSchema.optional(),\n adapterId: nonEmptyStringSchema,\n adapterVersion: nonEmptyStringSchema,\n detectionConfidence: detectionConfidenceSchema,\n /** The provider's own name for the source event, e.g. a hook event name. */\n sourceEventName: nonEmptyStringSchema.optional(),\n transport: sourceTransportSchema,\n })\n .readonly();\nexport type SourceProvenance = z.infer<typeof sourceProvenanceSchema>;\n\n/**\n * Opaque, immutable metadata supplied by the embedding consumer.\n *\n * The library never interprets these values; it only carries and exports them.\n */\nexport const consumerAttributesSchema = attributesSchema.readonly();\nexport type ConsumerAttributes = z.infer<typeof consumerAttributesSchema>;\n\n/**\n * Immutable identity of a single hook invocation.\n *\n * Frozen on parse. There is deliberately no setter, no builder that mutates in\n * place, and no module-level instance: identity is passed explicitly so two\n * concurrent invocations can never observe each other's fields.\n */\nexport const invocationIdentitySchema = z\n .strictObject({\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Set when this invocation runs beneath another agent invocation. */\n parentInvocationId: invocationIdSchema.optional(),\n /** Root of the session tree when the provider exposes one. */\n rootSessionId: sessionIdSchema.optional(),\n /** Stable handle for the agent process/instance, when available. */\n agentInstanceId: nonEmptyStringSchema.optional(),\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n startedAt: epochMillisSchema,\n consumerAttributes: consumerAttributesSchema,\n })\n .readonly();\nexport type InvocationIdentity = z.infer<typeof invocationIdentitySchema>;\n\n/** Fields an identity claim may contribute. */\nexport const identityClaimFieldsSchema = z.strictObject({\n invocationId: invocationIdSchema.optional(),\n sessionId: sessionIdSchema.optional(),\n parentInvocationId: invocationIdSchema.optional(),\n rootSessionId: sessionIdSchema.optional(),\n agentInstanceId: nonEmptyStringSchema.optional(),\n workspace: workspaceIdentitySchema.optional(),\n startedAt: epochMillisSchema.optional(),\n});\nexport type IdentityClaimFields = z.infer<typeof identityClaimFieldsSchema>;\n\n/**\n * A claim about invocation identity from one source.\n *\n * Claims are evidence, not truth. Resolution keeps the highest-confidence claim\n * per field and refuses to merge disagreeing peers.\n */\nexport const identityClaimSchema = z.strictObject({\n /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */\n source: nonEmptyStringSchema,\n confidence: detectionConfidenceSchema,\n fields: identityClaimFieldsSchema,\n});\nexport type IdentityClaim = z.infer<typeof identityClaimSchema>;\n\nexport type IdentityConflict = {\n readonly field: keyof IdentityClaimFields;\n readonly confidence: DetectionConfidence;\n /** Rendered, non-sensitive representations of the disagreeing values. */\n readonly values: readonly string[];\n readonly sources: readonly string[];\n};\n\nexport type IdentityResolution =\n | { readonly status: \"resolved\"; readonly identity: InvocationIdentity }\n | {\n readonly status: \"conflict\";\n readonly conflicts: readonly IdentityConflict[];\n }\n | {\n readonly status: \"incomplete\";\n readonly missing: readonly (keyof IdentityClaimFields)[];\n }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nconst CLAIM_FIELDS = [\n \"invocationId\",\n \"sessionId\",\n \"parentInvocationId\",\n \"rootSessionId\",\n \"agentInstanceId\",\n \"workspace\",\n \"startedAt\",\n] as const satisfies readonly (keyof IdentityClaimFields)[];\n\nconst renderClaimValue = (value: unknown): string => {\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (value !== null && typeof value === \"object\" && \"workspaceId\" in value) {\n const { workspaceId } = value;\n return typeof workspaceId === \"string\" ? workspaceId : \"<workspace>\";\n }\n return \"<opaque>\";\n};\n\nexport type ResolveIdentityInput = {\n readonly claims: readonly IdentityClaim[];\n readonly provenance: SourceProvenance;\n /** Used only for fields no claim provides and that have a safe default. */\n readonly fallback?: {\n readonly startedAt?: number;\n readonly workspace?: WorkspaceIdentity;\n };\n readonly consumerAttributes?: Readonly<Record<string, unknown>>;\n};\n\n/**\n * Resolve identity from claims, failing closed.\n *\n * Rules:\n * 1. For each field, only claims at the highest confidence that provided it are\n * considered. Lower-confidence claims never fill in or override.\n * 2. Two distinct values at that highest confidence produce a `conflict`. The\n * invocation is then not attributed at all — a mislabelled session is worse\n * than a missing one.\n * 3. `invocationId` and `sessionId` are mandatory. Missing either yields\n * `incomplete`; neither is invented here.\n * 4. `startedAt` and `workspace` may come from an explicit fallback, because a\n * clock reading and an `unknown` workspace handle assert nothing false.\n */\nexport const resolveInvocationIdentity = (input: ResolveIdentityInput): IdentityResolution => {\n const parsedClaims: IdentityClaim[] = [];\n const issues: string[] = [];\n for (const [index, claim] of input.claims.entries()) {\n const parsed = identityClaimSchema.safeParse(claim);\n if (parsed.success) {\n parsedClaims.push(parsed.data);\n } else {\n issues.push(\n `claim[${index}]: ${parsed.error.issues.map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`).join(\", \")}`,\n );\n }\n }\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const conflicts: IdentityConflict[] = [];\n const selected: Record<string, unknown> = {};\n\n for (const field of CLAIM_FIELDS) {\n const contributors = parsedClaims.filter((claim) => claim.fields[field] !== undefined);\n if (contributors.length === 0) {\n continue;\n }\n const bestRank = Math.max(\n ...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence]),\n );\n const best = contributors.filter(\n (claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank,\n );\n const rendered = new Map<string, string[]>();\n for (const claim of best) {\n const key = JSON.stringify(claim.fields[field]);\n const sources = rendered.get(key) ?? [];\n sources.push(claim.source);\n rendered.set(key, sources);\n }\n if (rendered.size > 1) {\n const [firstBest] = best;\n conflicts.push({\n field,\n confidence: firstBest?.confidence ?? \"none\",\n values: best.map((claim) => renderClaimValue(claim.fields[field])),\n sources: best.map((claim) => claim.source),\n });\n continue;\n }\n const [winner] = best;\n if (winner !== undefined) {\n selected[field] = winner.fields[field];\n }\n }\n\n if (conflicts.length > 0) {\n return { status: \"conflict\", conflicts };\n }\n\n const missing: (keyof IdentityClaimFields)[] = [];\n if (selected.invocationId === undefined) {\n missing.push(\"invocationId\");\n }\n if (selected.sessionId === undefined) {\n missing.push(\"sessionId\");\n }\n if (missing.length > 0) {\n return { status: \"incomplete\", missing };\n }\n\n const startedAt = (selected.startedAt as number | undefined) ?? input.fallback?.startedAt;\n if (startedAt === undefined) {\n return { status: \"incomplete\", missing: [\"startedAt\"] };\n }\n const workspace =\n (selected.workspace as WorkspaceIdentity | undefined) ??\n input.fallback?.workspace ??\n unknownWorkspaceIdentity();\n\n const candidate = {\n invocationId: selected.invocationId as InvocationId,\n sessionId: selected.sessionId as SessionId,\n ...(selected.parentInvocationId === undefined\n ? {}\n : { parentInvocationId: selected.parentInvocationId as InvocationId }),\n ...(selected.rootSessionId === undefined\n ? {}\n : { rootSessionId: selected.rootSessionId as SessionId }),\n ...(selected.agentInstanceId === undefined\n ? {}\n : { agentInstanceId: selected.agentInstanceId as string }),\n provenance: input.provenance,\n workspace,\n startedAt,\n consumerAttributes: input.consumerAttributes ?? {},\n };\n\n const parsed = invocationIdentitySchema.safeParse(candidate);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n }\n return { status: \"resolved\", identity: parsed.data };\n};\n","import { z } from \"zod\";\n\nimport { nonEmptyStringSchema, workspaceIdSchema } from \"./primitives.js\";\n\n/**\n * Per-event workspace targeting (ADR 0008).\n *\n * A session's `workspace` is where the agent was *started*. An agent routinely\n * works somewhere else — in a linked git worktree beside the checkout it was\n * launched from — and the session-level identity cannot show that. A tool event\n * can: the file it edited, or the directory its shell command ran in, names the\n * worktree it actually touched.\n *\n * Two values model that, and the split between them is the privacy boundary:\n *\n * - {@link TargetHint} is what an adapter observed — local paths. It is an\n * in-process value only: it is never part of a {@link CanonicalEvent}, never\n * persisted, never exported. The core resolves it and drops it.\n * - {@link WorkspaceTarget} is what the core resolved — salted handles of the\n * worktree and its repository, the worktree's kind, the checked-out branch, and\n * what the evidence was. It travels on the event.\n */\n\n/**\n * What a target was derived from, strongest evidence first.\n *\n * - `tool-path` — a path the tool call itself named (an edited or read file, a\n * patch header).\n * - `shell-cwd` — the working directory the provider reports a shell command ran in.\n * - `session-cwd` — only the session's own directory was known; the event may\n * have reached elsewhere (e.g. a shell `cd`) without the provider saying so.\n */\nexport const targetSourceSchema = z.enum([\"tool-path\", \"shell-cwd\", \"session-cwd\"]);\nexport type TargetSource = z.infer<typeof targetSourceSchema>;\n\n/** Most paths one hint may name; a bound, not a sampling rule (all must agree). */\nexport const MAX_TARGET_HINT_PATHS = 8;\n\n/** Longest local path a hint may carry. Longer input is dropped, never truncated. */\nexport const MAX_TARGET_PATH_LENGTH = 4096;\n\nconst localPathSchema = z\n .string()\n .min(1)\n .max(MAX_TARGET_PATH_LENGTH)\n .refine((value) => !value.includes(\"\\u0000\"), \"path must not contain NUL\");\n\n/**\n * An adapter's observation of where a tool event pointed. **Carries local paths**\n * — in-process only, see the module note.\n *\n * Every path in one hint must resolve to the same worktree, or the event gets no\n * target at all: a patch touching two worktrees did not target either of them.\n */\nexport const targetHintSchema = z\n .strictObject({\n source: targetSourceSchema,\n paths: z.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),\n /** Absolute directory that relative `paths` resolve against. */\n baseDirectory: localPathSchema.optional(),\n })\n .readonly();\nexport type TargetHint = z.infer<typeof targetHintSchema>;\n\n/**\n * The weakest hint: the session's own directory. Every adapter gives it to a\n * session start and a prompt, and to a tool call that names no path.\n */\nexport const sessionCwdHint = (cwd: string | undefined): TargetHint | undefined =>\n cwd === undefined || cwd.length === 0 ? undefined : { source: \"session-cwd\", paths: [cwd] };\n\n/**\n * Whether a worktree is its repository's main checkout (`main`) or one added\n * beside it with `git worktree add` (`linked`).\n */\nexport const worktreeKindSchema = z.enum([\"main\", \"linked\"]);\nexport type WorktreeKind = z.infer<typeof worktreeKindSchema>;\n\n/**\n * The git worktree a tool event targeted. Exported; carries no path.\n *\n * `workspaceId` is derived exactly like a `git-root` workspace identity, so a\n * consumer holding the same salt can match it against one it derived itself.\n * `repositoryId` is the same derivation applied to the repository's main\n * worktree, so every worktree of one repository shares it — and for a main\n * worktree it equals `workspaceId`.\n */\nexport const workspaceTargetSchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n /** Branch checked out in that worktree; absent on a detached HEAD. */\n vcsBranchName: nonEmptyStringSchema.optional(),\n source: targetSourceSchema,\n /** `git-root` handle of the repository's main worktree; absent when there is none to name. */\n repositoryId: workspaceIdSchema.optional(),\n worktreeKind: worktreeKindSchema.optional(),\n })\n .readonly();\nexport type WorkspaceTarget = z.infer<typeof workspaceTargetSchema>;\n\n/**\n * Shape a provider's own subagent identifier must have to be exported.\n *\n * Identifier-shaped on purpose — no whitespace, no path separators — so a\n * malformed payload field cannot carry prose or a path onto the wire under an id\n * attribute. A value that does not fit is dropped, not repaired.\n */\nexport const SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;\nexport const subagentIdSchema = z.string().regex(SUBAGENT_ID_PATTERN);\nexport type SubagentId = z.infer<typeof subagentIdSchema>;\n","import { z } from \"zod\";\n\nimport { tokenCountSchema } from \"./primitives.js\";\n\n/**\n * Whether an observation reports the change since the previous observation\n * (`delta`) or the running total for the session/generation (`cumulative`).\n *\n * The canonical model keeps temporality explicit rather than assuming one:\n * summing cumulative observations double-counts, and diffing delta observations\n * silently loses tokens.\n */\nexport const usageTemporalitySchema = z.enum([\"delta\", \"cumulative\"]);\nexport type UsageTemporality = z.infer<typeof usageTemporalitySchema>;\n\n/**\n * Whether the provider counts cache-creation tokens inside its input total or\n * reports them as a disjoint bucket.\n *\n * - `included-in-input`: `cacheCreationInputTokens` is a subset of `inputTokens`.\n * - `disjoint-from-input`: cache-creation tokens are billed in addition to\n * `inputTokens` and must be added when computing a total.\n * - `not-reported`: the provider exposes no cache-creation counter; the field is\n * pinned to zero.\n */\nexport const cacheCreationAccountingSchema = z.enum([\n \"included-in-input\",\n \"disjoint-from-input\",\n \"not-reported\",\n]);\nexport type CacheCreationAccounting = z.infer<typeof cacheCreationAccountingSchema>;\n\n/** Whether a provider-reported total agrees with the canonical computation. */\nexport const providerTotalAgreementSchema = z.enum([\"unreported\", \"agrees\", \"disagrees\"]);\nexport type ProviderTotalAgreement = z.infer<typeof providerTotalAgreementSchema>;\n\n/**\n * What an adapter reports, before normalization.\n *\n * `inputTokens` is *inclusive*: it counts every input token the provider\n * attributes to the call, including cache reads (and cache creation when the\n * provider folds it in). `outputTokens` is likewise inclusive of reasoning\n * output. Subset fields describe portions of those totals, never additions.\n */\nexport const usageReportSchema = z.strictObject({\n temporality: usageTemporalitySchema,\n /** Inclusive input tokens. */\n inputTokens: tokenCountSchema.optional(),\n /** Subset of `inputTokens` served from a prompt cache. */\n cachedInputTokens: tokenCountSchema.optional(),\n /** Tokens written to a prompt cache. */\n cacheCreationInputTokens: tokenCountSchema.optional(),\n /** Required when `cacheCreationInputTokens` is present and non-zero. */\n cacheCreationAccounting: cacheCreationAccountingSchema.optional(),\n /** Inclusive output tokens. */\n outputTokens: tokenCountSchema.optional(),\n /** Subset of `outputTokens` spent on reasoning. */\n reasoningOutputTokens: tokenCountSchema.optional(),\n /** Total exactly as the provider reported it, if it reported one. */\n providerTotalTokens: tokenCountSchema.optional(),\n});\nexport type UsageReport = z.infer<typeof usageReportSchema>;\n\n/**\n * Fully normalized usage.\n *\n * Derived fields (`uncachedInputTokens`, `totalTokens`,\n * `providerTotalAgreement`) are part of the schema and are re-checked on parse,\n * so an inconsistent object cannot exist. Construct values with\n * {@link normalizeUsage} rather than by hand.\n */\nexport const canonicalUsageSchema = z\n .strictObject({\n temporality: usageTemporalitySchema,\n inputTokens: tokenCountSchema,\n cachedInputTokens: tokenCountSchema,\n cacheCreationInputTokens: tokenCountSchema,\n cacheCreationAccounting: cacheCreationAccountingSchema,\n outputTokens: tokenCountSchema,\n reasoningOutputTokens: tokenCountSchema,\n /** Derived: input tokens that were neither cache reads nor cache writes. */\n uncachedInputTokens: tokenCountSchema,\n /** Derived: canonical billable total. */\n totalTokens: tokenCountSchema,\n providerTotalTokens: tokenCountSchema.optional(),\n providerTotalAgreement: providerTotalAgreementSchema,\n })\n .check((ctx) => {\n const usage = ctx.value;\n const push = (message: string): void => {\n ctx.issues.push({ code: \"custom\", input: usage, message });\n };\n\n if (usage.cachedInputTokens > usage.inputTokens) {\n push(\"cachedInputTokens must not exceed inputTokens (it is a subset)\");\n }\n if (usage.reasoningOutputTokens > usage.outputTokens) {\n push(\"reasoningOutputTokens must not exceed outputTokens (it is a subset)\");\n }\n if (usage.cacheCreationAccounting === \"not-reported\" && usage.cacheCreationInputTokens !== 0) {\n push(\"cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported\");\n }\n const creationInsideInput =\n usage.cacheCreationAccounting === \"included-in-input\" ? usage.cacheCreationInputTokens : 0;\n if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {\n push(\n \"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input\",\n );\n }\n const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;\n if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {\n push(`uncachedInputTokens must equal ${expectedUncached}`);\n }\n const creationOutsideInput =\n usage.cacheCreationAccounting === \"disjoint-from-input\" ? usage.cacheCreationInputTokens : 0;\n const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;\n if (usage.totalTokens !== expectedTotal) {\n push(`totalTokens must equal ${expectedTotal}`);\n }\n const expectedAgreement: ProviderTotalAgreement =\n usage.providerTotalTokens === undefined\n ? \"unreported\"\n : usage.providerTotalTokens === expectedTotal\n ? \"agrees\"\n : \"disagrees\";\n if (usage.providerTotalAgreement !== expectedAgreement) {\n push(`providerTotalAgreement must be ${expectedAgreement}`);\n }\n });\nexport type CanonicalUsage = z.infer<typeof canonicalUsageSchema>;\n\nexport type UsageNormalizationIssue = {\n readonly code:\n | \"invalid-report\"\n | \"cached-exceeds-input\"\n | \"reasoning-exceeds-output\"\n | \"cache-creation-exceeds-input\"\n | \"cache-creation-accounting-missing\";\n readonly message: string;\n};\n\nexport type UsageNormalizationResult =\n | { readonly status: \"ok\"; readonly usage: CanonicalUsage; readonly notes: readonly string[] }\n | { readonly status: \"invalid\"; readonly issues: readonly UsageNormalizationIssue[] };\n\n/**\n * Normalize a provider usage report into canonical usage.\n *\n * Deterministic rules:\n * 1. Absent counters default to `0`; `providerTotalTokens` stays absent.\n * 2. Non-integer, negative, or non-finite counters are rejected.\n * 3. A subset exceeding its total is rejected — never clamped — because\n * clamping would silently invent a billing story.\n * 4. `cacheCreationAccounting` defaults to `not-reported` when no cache-creation\n * tokens are reported, and is *required* when they are: guessing whether the\n * bucket is disjoint would mis-total every downstream cost calculation.\n * 5. A provider total that disagrees with the canonical total is preserved as\n * reported and flagged `disagrees`. Both numbers survive; neither is edited.\n */\nexport const normalizeUsage = (report: unknown): UsageNormalizationResult => {\n const parsed = usageReportSchema.safeParse(report);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map((issue) => ({\n code: \"invalid-report\" as const,\n message: `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n })),\n };\n }\n\n const input = parsed.data;\n const issues: UsageNormalizationIssue[] = [];\n const notes: string[] = [];\n\n const inputTokens = input.inputTokens ?? 0;\n const cachedInputTokens = input.cachedInputTokens ?? 0;\n const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;\n const outputTokens = input.outputTokens ?? 0;\n const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;\n\n let accounting: CacheCreationAccounting;\n if (cacheCreationInputTokens === 0) {\n accounting = input.cacheCreationAccounting ?? \"not-reported\";\n if (accounting !== \"not-reported\") {\n notes.push(\n `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`,\n );\n }\n } else if (input.cacheCreationAccounting === undefined) {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message:\n \"cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred\",\n });\n accounting = \"not-reported\";\n } else if (input.cacheCreationAccounting === \"not-reported\") {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message: \"cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens\",\n });\n accounting = \"not-reported\";\n } else {\n accounting = input.cacheCreationAccounting;\n }\n\n if (cachedInputTokens > inputTokens) {\n issues.push({\n code: \"cached-exceeds-input\",\n message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n if (reasoningOutputTokens > outputTokens) {\n issues.push({\n code: \"reasoning-exceeds-output\",\n message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`,\n });\n }\n\n const creationInsideInput = accounting === \"included-in-input\" ? cacheCreationInputTokens : 0;\n if (cachedInputTokens + creationInsideInput > inputTokens) {\n issues.push({\n code: \"cache-creation-exceeds-input\",\n message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const creationOutsideInput = accounting === \"disjoint-from-input\" ? cacheCreationInputTokens : 0;\n const totalTokens = inputTokens + creationOutsideInput + outputTokens;\n const providerTotalAgreement: ProviderTotalAgreement =\n input.providerTotalTokens === undefined\n ? \"unreported\"\n : input.providerTotalTokens === totalTokens\n ? \"agrees\"\n : \"disagrees\";\n\n if (providerTotalAgreement === \"disagrees\") {\n notes.push(\n `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`,\n );\n }\n\n const usage: CanonicalUsage = {\n temporality: input.temporality,\n inputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens,\n reasoningOutputTokens,\n uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,\n totalTokens,\n ...(input.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: input.providerTotalTokens }),\n providerTotalAgreement,\n };\n\n return { status: \"ok\", usage, notes };\n};\n\nexport class UsageNormalizationError extends Error {\n public readonly issues: readonly UsageNormalizationIssue[];\n\n public constructor(issues: readonly UsageNormalizationIssue[]) {\n super(`invalid usage report: ${issues.map((issue) => issue.message).join(\"; \")}`);\n this.name = \"UsageNormalizationError\";\n this.issues = issues;\n }\n}\n\n/** Convenience wrapper for call sites that treat invalid usage as a bug. */\nexport const normalizeUsageOrThrow = (report: unknown): CanonicalUsage => {\n const result = normalizeUsage(report);\n if (result.status === \"invalid\") {\n throw new UsageNormalizationError(result.issues);\n }\n return result.usage;\n};\n\nexport const EMPTY_DELTA_USAGE: CanonicalUsage = Object.freeze(\n normalizeUsageOrThrow({ temporality: \"delta\" }),\n);\n\nexport type UsageDeltaResult = {\n readonly usage: CanonicalUsage;\n /**\n * True when the current snapshot is smaller than the previous one on any\n * counter. That means the cumulative series restarted (new session, replayed\n * transcript, provider reset), so the current snapshot is emitted as the delta\n * instead of a negative difference.\n */\n readonly resetDetected: boolean;\n};\n\nconst requireCumulative = (usage: CanonicalUsage, label: string): void => {\n if (usage.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: `${label} must have cumulative temporality` },\n ]);\n }\n};\n\n/**\n * Convert two cumulative snapshots into a delta observation.\n *\n * Replay safety: re-processing the same snapshot yields an all-zero delta, and a\n * decreasing series is reported as a reset rather than a negative delta.\n * Accounting mode must match; mixing modes would make the subtraction meaningless.\n */\nexport const cumulativeToDelta = (\n previous: CanonicalUsage,\n current: CanonicalUsage,\n): UsageDeltaResult => {\n requireCumulative(previous, \"previous usage\");\n requireCumulative(current, \"current usage\");\n\n if (\n previous.cacheCreationAccounting !== current.cacheCreationAccounting &&\n previous.cacheCreationInputTokens !== 0 &&\n current.cacheCreationInputTokens !== 0\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot diff cumulative usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const resetDetected =\n current.inputTokens < previous.inputTokens ||\n current.cachedInputTokens < previous.cachedInputTokens ||\n current.cacheCreationInputTokens < previous.cacheCreationInputTokens ||\n current.outputTokens < previous.outputTokens ||\n current.reasoningOutputTokens < previous.reasoningOutputTokens;\n\n if (resetDetected) {\n return {\n usage: normalizeUsageOrThrow({ ...toReport(current), temporality: \"delta\" }),\n resetDetected: true,\n };\n }\n\n const usage = normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: current.inputTokens - previous.inputTokens,\n cachedInputTokens: current.cachedInputTokens - previous.cachedInputTokens,\n cacheCreationInputTokens:\n current.cacheCreationInputTokens - previous.cacheCreationInputTokens,\n cacheCreationAccounting: current.cacheCreationAccounting,\n outputTokens: current.outputTokens - previous.outputTokens,\n reasoningOutputTokens: current.reasoningOutputTokens - previous.reasoningOutputTokens,\n });\n\n return { usage, resetDetected: false };\n};\n\n/** Project canonical usage back onto the reported shape. */\nexport const toReport = (usage: CanonicalUsage): UsageReport => ({\n temporality: usage.temporality,\n inputTokens: usage.inputTokens,\n cachedInputTokens: usage.cachedInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n cacheCreationAccounting: usage.cacheCreationAccounting,\n outputTokens: usage.outputTokens,\n reasoningOutputTokens: usage.reasoningOutputTokens,\n ...(usage.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: usage.providerTotalTokens }),\n});\n\n/**\n * Add two delta observations. Cumulative usage is never summed, because two\n * running totals do not compose.\n */\nexport const addUsage = (a: CanonicalUsage, b: CanonicalUsage): CanonicalUsage => {\n if (a.temporality !== \"delta\" || b.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"only delta usage may be summed\" },\n ]);\n }\n const accounting =\n a.cacheCreationInputTokens === 0 && a.cacheCreationAccounting === \"not-reported\"\n ? b.cacheCreationAccounting\n : b.cacheCreationInputTokens === 0 && b.cacheCreationAccounting === \"not-reported\"\n ? a.cacheCreationAccounting\n : a.cacheCreationAccounting;\n\n if (\n a.cacheCreationInputTokens !== 0 &&\n b.cacheCreationInputTokens !== 0 &&\n a.cacheCreationAccounting !== b.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot sum usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n a.providerTotalTokens === undefined && b.providerTotalTokens === undefined\n ? undefined\n : (a.providerTotalTokens ?? 0) + (b.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: a.inputTokens + b.inputTokens,\n cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,\n cacheCreationInputTokens: a.cacheCreationInputTokens + b.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: a.outputTokens + b.outputTokens,\n reasoningOutputTokens: a.reasoningOutputTokens + b.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n","import { z } from \"zod\";\n\n/**\n * Version of the canonical event model.\n *\n * Every emitted event carries this value. Consumers must treat an unknown\n * version as unreadable rather than guessing field semantics.\n *\n * Compatibility rules:\n * - Additive optional fields do not change the version.\n * - Renaming, removing, or re-interpreting a field increments the version.\n */\nexport const CANONICAL_SCHEMA_VERSION = 1 as const;\n\nexport type CanonicalSchemaVersion = typeof CANONICAL_SCHEMA_VERSION;\n\nexport const canonicalSchemaVersionSchema = z.literal(CANONICAL_SCHEMA_VERSION);\n","import type { Attributes } from \"@opentelemetry/api\";\nimport type { Resource } from \"@opentelemetry/resources\";\n\nimport type { CanonicalEvent, GenerationEndEvent } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\nimport { resolveExportedSessionId } from \"./export-identity.js\";\n\n/**\n * Metrics derived from hook events (issue #69).\n *\n * otel-hook already normalizes every provider's hook callbacks into canonical\n * events; this module turns one batch of those events into *observations* — a\n * value recorded against an instrument, with attributes. It is pure: it reads no\n * state and sends nothing. Aggregating observations into OTLP data points\n * (cumulative across processes, or delta per batch) and exporting them are the\n * jobs of `lifecycle/metric-series.ts` and `otlp-metric-sink.ts`.\n *\n * ## Why observations come from the runtime's accounting, not from the events alone\n *\n * Token usage is taken from the orchestrator's `UsageObservation` deltas rather than\n * from `generation.end.usage` directly. A provider that reports a session-wide\n * running total (Codex) stamps the *cumulative* figure on every turn; summing those\n * into a histogram would bill a three-turn session several times over. The\n * orchestrator already diffs them against a persisted baseline, exactly once per\n * delivery, so the metric reuses that answer.\n *\n * ## What is never on a metric\n *\n * Session context attributes (`docs/session-context.md`) are on every data point\n * of an event that has them, so a new context starts a new series.\n *\n * No account identity (`user.*`, `enduser.*`, `organization.id`), no content, no\n * paths, and no per-event ids (`otelhook.event.id`, tool-call ids, generation ids):\n * an id per data point is a new series per data point. `session.id` is the one\n * high-cardinality attribute, and it can be switched off.\n */\n\n/** Recommended bucket boundaries from the GenAI semantic conventions. */\nexport const TOKEN_USAGE_BUCKETS: readonly number[] = Object.freeze([\n 1, 4, 16, 64, 256, 1_024, 4_096, 16_384, 65_536, 262_144, 1_048_576, 4_194_304, 16_777_216,\n 67_108_864,\n]);\nexport const OPERATION_DURATION_BUCKETS: readonly number[] = Object.freeze([\n 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24, 20.48, 40.96, 81.92,\n]);\n\nexport const METRIC_TOKEN_USAGE = \"gen_ai.client.token.usage\";\nexport const METRIC_OPERATION_DURATION = \"gen_ai.client.operation.duration\";\nexport const METRIC_SESSIONS = \"otelhook.sessions\";\nexport const METRIC_TOOL_CALLS = \"otelhook.tool.calls\";\nexport const METRIC_COST_USAGE = \"otelhook.cost.usage\";\n\nexport type MetricInstrumentName =\n | typeof METRIC_TOKEN_USAGE\n | typeof METRIC_OPERATION_DURATION\n | typeof METRIC_SESSIONS\n | typeof METRIC_TOOL_CALLS\n | typeof METRIC_COST_USAGE;\n\nexport type MetricInstrument = {\n readonly name: MetricInstrumentName;\n readonly kind: \"histogram\" | \"counter\";\n readonly unit: string;\n readonly description: string;\n /** Integer values (`asInt`) or doubles. Histograms always carry a double sum. */\n readonly valueType: \"int\" | \"double\";\n /** Histograms only. */\n readonly boundaries?: readonly number[];\n};\n\nexport const METRIC_INSTRUMENTS: Readonly<Record<MetricInstrumentName, MetricInstrument>> = Object.freeze({\n [METRIC_TOKEN_USAGE]: {\n name: METRIC_TOKEN_USAGE,\n kind: \"histogram\",\n unit: \"{token}\",\n description: \"Tokens used per generation, by token type (hook-derived)\",\n valueType: \"int\",\n boundaries: TOKEN_USAGE_BUCKETS,\n },\n [METRIC_OPERATION_DURATION]: {\n name: METRIC_OPERATION_DURATION,\n kind: \"histogram\",\n unit: \"s\",\n description: \"Generation duration, from its start hook to its end hook (hook-derived)\",\n valueType: \"double\",\n boundaries: OPERATION_DURATION_BUCKETS,\n },\n [METRIC_SESSIONS]: {\n name: METRIC_SESSIONS,\n kind: \"counter\",\n unit: \"{session}\",\n description: \"Agent sessions started\",\n valueType: \"int\",\n },\n [METRIC_TOOL_CALLS]: {\n name: METRIC_TOOL_CALLS,\n kind: \"counter\",\n unit: \"{call}\",\n description: \"Completed tool calls, by tool name and outcome\",\n valueType: \"int\",\n },\n [METRIC_COST_USAGE]: {\n name: METRIC_COST_USAGE,\n kind: \"counter\",\n unit: \"USD\",\n description: \"Cost reported by the provider; never estimated\",\n valueType: \"double\",\n },\n});\n\nexport const isMetricInstrumentName = (value: unknown): value is MetricInstrumentName =>\n typeof value === \"string\" && Object.hasOwn(METRIC_INSTRUMENTS, value);\n\nexport const ATTR_GEN_AI_TOKEN_TYPE = \"gen_ai.token.type\";\nexport const ATTR_GEN_AI_PROVIDER_NAME = \"gen_ai.provider.name\";\nconst ATTR_GEN_AI_OPERATION_NAME = \"gen_ai.operation.name\";\nconst ATTR_GEN_AI_REQUEST_MODEL = \"gen_ai.request.model\";\nconst ATTR_GEN_AI_RESPONSE_MODEL = \"gen_ai.response.model\";\nconst ATTR_GEN_AI_TOOL_NAME = \"gen_ai.tool.name\";\nconst ATTR_ERROR_TYPE = \"error.type\";\nconst ATTR_SESSION_ID = \"session.id\";\nconst ATTR_OTELHOOK_PROVIDER_ID = \"otelhook.provider.id\";\nconst ATTR_OTELHOOK_OUTCOME = \"otelhook.outcome\";\nconst ATTR_OTELHOOK_SESSION_KIND = \"otelhook.session.kind\";\n\n/**\n * Token types on `gen_ai.client.token.usage`.\n *\n * `input` is inclusive of cache reads, as the GenAI conventions define\n * `gen_ai.usage.input_tokens`. `cache_read` and `cache_creation` are extra series\n * describing parts of the input; summing every token type double-counts.\n */\nexport type TokenType = \"input\" | \"output\" | \"cache_read\" | \"cache_creation\";\n\nexport type MetricsTemporality = \"cumulative\" | \"delta\";\n\n/** One recorded value. */\nexport type MetricObservation = {\n readonly instrument: MetricInstrumentName;\n readonly value: number;\n /** Data-point attributes. Primitives only. */\n readonly attributes: Readonly<Record<string, string | number | boolean>>;\n /** When the observed thing happened, in epoch milliseconds. */\n readonly timeMillis: number;\n /** Provider session the observation belongs to; scopes cumulative state. */\n readonly sessionId: string;\n};\n\n/** A start time recovered for a generation, by generation id. */\nexport type GenerationStart = {\n readonly startMillis: number;\n readonly requestModel?: string;\n};\n\n/** The usage delta the orchestrator derived for one usage-bearing event. */\nexport type MetricUsageInput = {\n readonly eventId: string;\n readonly scope: string;\n readonly delta: CanonicalUsage;\n};\n\nexport type DeriveMetricObservationsInput = {\n readonly events: readonly CanonicalEvent[];\n readonly usage: readonly MetricUsageInput[];\n /** The exported resource; supplies the launcher's `session.id` when it sets one. */\n readonly resource: Resource;\n /** Put `session.id` on every data point. Default true. */\n readonly includeSessionId?: boolean;\n /**\n * Start times for generations whose start edge is not in this batch (it was\n * recorded by an earlier hook process). Looked up by generation id.\n */\n readonly generationStarts?: (generationId: string) => GenerationStart | undefined;\n /**\n * When the session's current turn began: the last `prompt.submitted` recorded,\n * by an earlier callback or this one. The fallback duration source for\n * providers whose generation is a turn (Claude Code, Codex).\n */\n readonly turnStart?: (sessionId: string) => number | undefined;\n};\n\nconst commonAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n includeSessionId: boolean,\n): Record<string, string | number | boolean> => ({\n // Session context first, so the metric's own attributes always win; and never\n // anything account-shaped, whatever the context says.\n ...(event.contextAttributes === undefined\n ? {}\n : (withoutAccountIdentity(event.contextAttributes) as Record<string, string | number | boolean>)),\n [ATTR_OTELHOOK_PROVIDER_ID]: event.provenance.providerId,\n ...(includeSessionId\n ? { [ATTR_SESSION_ID]: resolveExportedSessionId(event.sessionId, resource).sessionId }\n : {}),\n});\n\nconst generationAttributes = (\n end: GenerationEndEvent,\n requestModel: string | undefined,\n): Record<string, string> => ({\n [ATTR_GEN_AI_OPERATION_NAME]: \"chat\",\n ...(end.model.vendor === undefined ? {} : { [ATTR_GEN_AI_PROVIDER_NAME]: end.model.vendor }),\n [ATTR_GEN_AI_REQUEST_MODEL]: requestModel ?? end.model.modelId,\n [ATTR_GEN_AI_RESPONSE_MODEL]: end.model.modelId,\n});\n\nconst TOKEN_FIELDS: readonly (readonly [TokenType, (usage: CanonicalUsage) => number])[] = [\n [\"input\", (usage) => usage.inputTokens],\n [\"output\", (usage) => usage.outputTokens],\n [\"cache_read\", (usage) => usage.cachedInputTokens],\n [\"cache_creation\", (usage) => usage.cacheCreationInputTokens],\n];\n\nconst isFailedOutcome = (outcome: string): boolean =>\n outcome !== \"ok\" && outcome !== \"unknown\" && outcome !== \"cancelled\";\n\n/**\n * Observations for one batch.\n *\n * - `otelhook.sessions`: one per `session.start`.\n * - `otelhook.tool.calls`: one per `tool.end`.\n * - `gen_ai.client.operation.duration`: one per `generation.end` whose duration is\n * known, from the first source that has it:\n * 1. the duration the provider stated (`durationMillis`);\n * 2. a `generation.start` recorded by an *earlier* callback;\n * 3. the turn's start: the last `prompt.submitted` of the session, no later than\n * the end. For Claude Code and Codex a generation is a turn, so this is the\n * turn's wall-clock time, tool calls included.\n * A `generation.start` in the *same* batch as its end is not a start: an\n * adapter that emits both from one callback (Claude Code's `Stop`) synthesized\n * it, and measuring from it would record a zero.\n * - `gen_ai.client.token.usage`: per generation-scoped usage delta, one per token\n * type. A zero `cache_read` / `cache_creation` is not recorded: a provider that\n * never reports cache tokens would otherwise fill the low bucket with zeros.\n * `input` and `output` are always recorded, zero included, so the count of a\n * token histogram is the number of generations with usage.\n * - `otelhook.cost.usage`: per `generation.end` with a provider-reported USD cost.\n */\nexport const deriveMetricObservations = (\n input: DeriveMetricObservationsInput,\n): readonly MetricObservation[] => {\n const includeSessionId = input.includeSessionId ?? true;\n const observations: MetricObservation[] = [];\n const byId = new Map<string, CanonicalEvent>();\n const startsInBatch = new Map<string, GenerationStart>();\n for (const event of input.events) {\n byId.set(event.eventId, event);\n if (event.type === \"generation.start\") {\n startsInBatch.set(event.generationId, {\n startMillis: event.occurredAt,\n requestModel: event.model.modelId,\n });\n }\n }\n // Request model only: a start in this batch says what was asked for, but not when.\n const requestModelOf = (generationId: string): string | undefined =>\n startsInBatch.get(generationId)?.requestModel ?? input.generationStarts?.(generationId)?.requestModel;\n let lastPromptInBatch: Map<string, number> | undefined;\n for (const event of input.events) {\n if (event.type === \"prompt.submitted\") {\n lastPromptInBatch ??= new Map();\n lastPromptInBatch.set(event.sessionId, Math.max(lastPromptInBatch.get(event.sessionId) ?? 0, event.occurredAt));\n }\n }\n const measuredDurationOf = (end: GenerationEndEvent): number | undefined => {\n if (end.durationMillis !== undefined) {\n return end.durationMillis;\n }\n const recovered = startsInBatch.has(end.generationId) ? undefined : input.generationStarts?.(end.generationId);\n if (recovered !== undefined) {\n return end.occurredAt - recovered.startMillis;\n }\n const turn = lastPromptInBatch?.get(end.sessionId) ?? input.turnStart?.(end.sessionId);\n return turn === undefined || turn > end.occurredAt ? undefined : end.occurredAt - turn;\n };\n\n const push = (\n event: CanonicalEvent,\n instrument: MetricInstrumentName,\n value: number,\n attributes: Record<string, string | number | boolean>,\n ): void => {\n if (!Number.isFinite(value) || value < 0) {\n return;\n }\n observations.push({\n instrument,\n value,\n attributes: { ...commonAttributes(event, input.resource, includeSessionId), ...attributes },\n timeMillis: event.occurredAt,\n sessionId: event.sessionId,\n });\n };\n\n for (const event of input.events) {\n switch (event.type) {\n case \"session.start\":\n push(event, METRIC_SESSIONS, 1, { [ATTR_OTELHOOK_SESSION_KIND]: event.sessionKind });\n break;\n case \"tool.end\":\n push(event, METRIC_TOOL_CALLS, 1, {\n [ATTR_GEN_AI_TOOL_NAME]: event.toolName,\n [ATTR_OTELHOOK_OUTCOME]: event.outcome,\n });\n break;\n case \"generation.end\": {\n const attributes = generationAttributes(event, requestModelOf(event.generationId));\n const durationMillis = measuredDurationOf(event);\n if (durationMillis !== undefined && durationMillis >= 0) {\n push(event, METRIC_OPERATION_DURATION, durationMillis / 1000, {\n ...attributes,\n ...(isFailedOutcome(event.outcome) ? { [ATTR_ERROR_TYPE]: event.outcome } : {}),\n });\n }\n if (\n event.cost !== undefined &&\n event.cost.source === \"provider-reported\" &&\n event.cost.currency === \"USD\"\n ) {\n push(event, METRIC_COST_USAGE, event.cost.amount, attributes);\n }\n break;\n }\n default:\n break;\n }\n }\n\n for (const observation of input.usage) {\n if (observation.scope !== \"generation\") {\n // Session totals and subagent rollups restate generation spend; counting them\n // too would double it.\n continue;\n }\n const event = byId.get(observation.eventId);\n if (event?.type !== \"generation.end\") {\n continue;\n }\n const attributes = generationAttributes(event, requestModelOf(event.generationId));\n for (const [tokenType, read] of TOKEN_FIELDS) {\n const value = read(observation.delta);\n if (value === 0 && (tokenType === \"cache_read\" || tokenType === \"cache_creation\")) {\n continue;\n }\n push(event, METRIC_TOKEN_USAGE, value, { ...attributes, [ATTR_GEN_AI_TOKEN_TYPE]: tokenType });\n }\n }\n return observations;\n};\n\n/** Accumulated histogram state for one series. */\nexport type HistogramState = {\n readonly count: number;\n readonly sum: number;\n readonly min: number;\n readonly max: number;\n /** One more entry than the instrument's boundaries. */\n readonly bucketCounts: readonly number[];\n};\n\n/**\n * One OTLP data point, as plain JSON so it can be spooled.\n *\n * A point is self-describing: the instrument, its temporality, and its interval.\n * A cumulative point is a snapshot of a running total, so resending one (from a\n * spool) restates a value rather than adding to it.\n */\nexport type MetricPoint = {\n readonly instrument: MetricInstrumentName;\n readonly temporality: MetricsTemporality;\n readonly attributes: Readonly<Record<string, string | number | boolean>>;\n readonly startTimeMillis: number;\n readonly timeMillis: number;\n /** Counters. */\n readonly value?: number;\n /** Histograms. */\n readonly histogram?: HistogramState;\n};\n\nexport const emptyHistogram = (boundaries: readonly number[]): HistogramState => ({\n count: 0,\n sum: 0,\n min: Number.POSITIVE_INFINITY,\n max: Number.NEGATIVE_INFINITY,\n bucketCounts: new Array<number>(boundaries.length + 1).fill(0),\n});\n\n/** OTLP explicit buckets: bucket `i` holds values in `(boundaries[i-1], boundaries[i]]`. */\nexport const bucketIndex = (boundaries: readonly number[], value: number): number => {\n for (let index = 0; index < boundaries.length; index += 1) {\n const bound = boundaries[index];\n if (bound !== undefined && value <= bound) {\n return index;\n }\n }\n return boundaries.length;\n};\n\nexport const recordIntoHistogram = (\n state: HistogramState,\n boundaries: readonly number[],\n value: number,\n): HistogramState => {\n const bucketCounts = [...state.bucketCounts];\n const index = bucketIndex(boundaries, value);\n bucketCounts[index] = (bucketCounts[index] ?? 0) + 1;\n return {\n count: state.count + 1,\n sum: state.sum + value,\n min: Math.min(state.min, value),\n max: Math.max(state.max, value),\n bucketCounts,\n };\n};\n\n/**\n * Stable identity of a series: instrument plus sorted attributes.\n *\n * Used as a map key and, digested, as a state key. JSON of sorted entries is\n * unambiguous where a joined string would not be.\n */\nexport const seriesIdentity = (\n instrument: MetricInstrumentName,\n attributes: Readonly<Record<string, string | number | boolean>>,\n): string =>\n JSON.stringify([\n instrument,\n Object.entries(attributes).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),\n ]);\n\n/**\n * Delta points for one batch: observations of the same series folded together,\n * over the interval from the earliest observation to `nowMillis`.\n */\nexport const aggregateDeltaPoints = (\n observations: readonly MetricObservation[],\n nowMillis: number,\n): readonly MetricPoint[] => {\n const series = new Map<\n string,\n { observation: MetricObservation; start: number; value: number; histogram?: HistogramState }\n >();\n for (const observation of observations) {\n const instrument = METRIC_INSTRUMENTS[observation.instrument];\n const key = seriesIdentity(observation.instrument, observation.attributes);\n const existing =\n series.get(key) ??\n ({\n observation,\n start: observation.timeMillis,\n value: 0,\n ...(instrument.boundaries === undefined ? {} : { histogram: emptyHistogram(instrument.boundaries) }),\n });\n existing.start = Math.min(existing.start, observation.timeMillis);\n if (existing.histogram !== undefined && instrument.boundaries !== undefined) {\n existing.histogram = recordIntoHistogram(existing.histogram, instrument.boundaries, observation.value);\n } else {\n existing.value += observation.value;\n }\n series.set(key, existing);\n }\n return [...series.values()].map((entry) => ({\n instrument: entry.observation.instrument,\n temporality: \"delta\",\n attributes: entry.observation.attributes,\n startTimeMillis: Math.min(entry.start, nowMillis),\n timeMillis: Math.max(nowMillis, entry.start),\n ...(entry.histogram === undefined ? { value: entry.value } : { histogram: entry.histogram }),\n }));\n};\n\n/** Data-point attribute keys that must never appear on a metric. */\nexport const FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES: readonly string[] = Object.freeze([\n \"user.\",\n \"enduser.\",\n \"organization.\",\n]);\n\n/** Strip anything account-shaped from attributes, as a last line of defence. */\nexport const withoutAccountIdentity = (attributes: Attributes): Attributes =>\n Object.fromEntries(\n Object.entries(attributes).filter(\n ([key]) => !FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES.some((prefix) => key.startsWith(prefix)),\n ),\n );\n","import type { CallbackDeduplicator } from \"./dedup.js\";\nimport type { SpanCorrelator } from \"./span-correlator.js\";\nimport type { MetricSeriesStore } from \"./metric-series.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 /** Cumulative metric series state; swept by age, like usage rollups. */\n readonly metricSeries?: MetricSeriesStore;\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 readonly metrics?: 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, metrics] = 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 options.metricSeries?.cleanup(usageMaxAge, scope),\n ]);\n return {\n ...(span === undefined ? {} : { span }),\n ...(dedup === undefined ? {} : { dedup }),\n ...(usage === undefined ? {} : { usage }),\n ...(metrics === undefined ? {} : { metrics }),\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_REPOSITORY_ID,\n ATTR_OTELHOOK_TARGET_SOURCE,\n ATTR_OTELHOOK_TARGET_WORKSPACE_ID,\n ATTR_OTELHOOK_TARGET_WORKTREE_KIND,\n ATTR_VCS_REF_HEAD_NAME,\n exportIdentityAttributes,\n profileAttributes,\n targetAttributes,\n usageTemporalityAttributes,\n} from \"./export-identity.js\";\n\nconst SCOPE_NAME = \"@osfactory/otel-hook\";\n\nexport const DEFAULT_INSTRUMENTATION_SCOPE: InstrumentationScope = Object.freeze({\n name: SCOPE_NAME,\n version: VERSION,\n});\n\nconst ATTR_OTELHOOK_SPAN_PAIRED = \"otelhook.span.paired\";\nconst ATTR_OTELHOOK_SPAN_PAIRING = \"otelhook.span.pairing\";\nconst ATTR_OTELHOOK_SPAN_ORPHAN = \"otelhook.span.orphan\";\nconst ATTR_OTELHOOK_OUTCOME = \"otelhook.outcome\";\nconst ATTR_OTELHOOK_RESET_DETECTED = \"otelhook.usage.reset_detected\";\n/** True when a generation's usage covers only part of it; see `generation.end.usagePartial`. */\nexport const ATTR_OTELHOOK_USAGE_PARTIAL = \"otelhook.usage.partial\";\nconst ATTR_OTELHOOK_TOOL_KIND = \"otelhook.tool.kind\";\nconst ATTR_OTELHOOK_DELEGATION_DEPTH = \"otelhook.delegation_depth\";\nconst ATTR_OTELHOOK_COMPACTION_TRIGGER = \"otelhook.compaction.trigger\";\nconst ATTR_OTELHOOK_AGENT_NAME = \"otelhook.agent.name\";\nconst ATTR_OTELHOOK_AGENT_VERSION = \"otelhook.agent.version\";\nconst ATTR_OTELHOOK_GENERATION_ID = \"otelhook.generation.id\";\n\n/**\n * Pure, stateless canonical-event-to-span mapping.\n *\n * Isolated in one module so every other piece of the telemetry pipeline\n * — batching, retry, spooling — can change without touching what an attribute\n * means. Two edges of the same lifecycle scope are merged into one span when\n * they appear in the same batch; when they arrive in *different* short-lived\n * hook processes they are merged through a {@link SpanCorrelation} the caller\n * resolved from persisted state. Either way the mapping itself stays a pure\n * function: state is read by the correlator, never by this module.\n *\n * ## Identity of a span\n *\n * Trace and span ids are derived, never random, so two processes that never\n * meet still agree on them:\n *\n * - `traceId = H(providerId, sessionId)` — one trace per session per provider.\n * Deriving it from the session rather than the invocation is what lets a\n * `tool.end` emitted minutes later land in the same trace as its `tool.start`;\n * including the provider is what stops two providers that happen to reuse a\n * session id from being stitched into one trace.\n * - `spanId = H(providerId, sessionId, family, scopeKey)` — stable across\n * processes and idempotent under redelivery, so a collector that sees a\n * start-only span and later the completed span treats them as one span\n * rather than two.\n */\n// NUL, so joined parts cannot collide across a different split: no identifier\n// this library accepts can contain one, which a printable separator cannot\n// promise. Never emitted — only hashed, or used as an in-memory map key.\nconst FIELD_SEPARATOR = \"\\u0000\";\n\nconst digestHex = (parts: readonly string[], length: number): string =>\n createHash(\"sha256\").update(parts.join(FIELD_SEPARATOR)).digest(\"hex\").slice(0, length);\n\n/** Lifecycle scopes that pair a `*.start` edge with a later `*.end` edge. */\nexport type SpanFamily = \"session\" | \"generation\" | \"tool\" | \"subagent\";\n\n/** Identifies one lifecycle span within a session. */\nexport type SpanScopeRef = {\n readonly family: SpanFamily;\n readonly scopeKey: string;\n};\n\n/**\n * Why a lifecycle span is, or is not, a complete pair.\n *\n * Deliberately explicit rather than a bare boolean: \"we never saw the start\",\n * \"we saw it but it aged out of state\", and \"state could not be read at all\"\n * are different operational facts, and a dashboard that cannot tell them apart\n * cannot tell a broken host from a broken exporter.\n */\nexport type SpanOrphanClassification =\n /** Both edges are known — from this batch, or from persisted state. */\n | \"none\"\n /** The start is known; its end has not arrived yet. */\n | \"missing-end\"\n /** An end arrived and no start was ever recorded for this scope. */\n | \"missing-start\"\n /** A start was recorded but aged past the retention window before the end arrived. */\n | \"expired-start\"\n /** A start exists but was recorded by a different provider; pairing it would be a guess. */\n | \"provider-mismatch\"\n /** A second, distinct end arrived for a scope that was already closed. */\n | \"already-closed\"\n /** The persisted record was written by an incompatible version and was discarded. */\n | \"state-incompatible\"\n /** The persisted record could not be understood. */\n | \"state-corrupt\"\n /** State could not be consulted at all; the mapping degraded rather than failing. */\n | \"state-unavailable\";\n\nexport type SpanPairing =\n /** Both edges were present in this batch. */\n | \"in-batch\"\n /** The other edge came from state written by an earlier process. */\n | \"cross-process\"\n | \"unpaired\";\n\n/**\n * Whether this scope should produce an OTLP record now.\n *\n * OTLP has no notion of updating a span: a span is exported once, when it ends,\n * and a second record carrying the same trace and span id is not a revision of\n * the first — it is a duplicate that backends variously drop, keep the older of,\n * or display twice. Since every lifecycle span id here is *derived* from\n * `(provider, session, family, scopeKey)`, a `*.start` edge and its later `*.end`\n * edge compute the identical id, so exporting on both is precisely that\n * duplicate.\n *\n * `defer` is therefore the answer for a start whose end has not arrived: the\n * start is durable in the state store, and the end edge exports the one complete\n * span using the times recovered from it. Nothing is lost by waiting, and what is\n * gained is that the record a collector receives has a real duration.\n */\nexport type SpanDisposition =\n /** Export a record for this scope now. */\n | \"emit\"\n /** Hold: the start is recorded, and the end edge will export the complete span. */\n | \"defer\";\n\n/**\n * One scope's correlation facts, resolved from persisted state by the caller.\n *\n * Plain data on purpose: the telemetry layer must not reach into the state\n * store itself (ADR 0006), so it declares what it needs and the lifecycle layer\n * supplies it.\n */\nexport type SpanCorrelation = {\n readonly providerId: string;\n readonly sessionId: string;\n readonly ref: SpanScopeRef;\n readonly pairing: SpanPairing;\n readonly orphan: SpanOrphanClassification;\n /**\n * Whether to export a record for this scope now. Defaults to `emit` when a\n * correlation is supplied without one.\n */\n readonly disposition?: SpanDisposition;\n /**\n * Extra component mixed into the derived span id.\n *\n * Set only when this record is a genuinely *additional* observation of a scope\n * that has already been exported once — a second, distinct end for a scope that\n * was already closed. Both records are real, so neither is dropped, and the\n * discriminator keeps them from claiming the same span id.\n */\n readonly spanIdDiscriminator?: string;\n /** Start recovered from state; authoritative over the batch's own start edge. */\n readonly startMillis?: number;\n /** End recovered from state; authoritative so a redelivered end re-exports an identical span. */\n readonly endMillis?: number;\n /** Parent recorded at start time, so an end-only process hangs the span in the same place. */\n readonly parent?: SpanScopeRef;\n /** Attributes only the start edge could supply, recovered for an end-only span. */\n readonly attributes?: Attributes;\n};\n\n/**\n * Resolves persisted correlation for one batch.\n *\n * Must never reject: a state failure is a degraded span, never a lost export.\n */\nexport type SpanCorrelationResolver = (\n events: readonly CanonicalEvent[],\n) => Promise<readonly SpanCorrelation[]>;\n\n/**\n * Upper bound on how many start-edge attributes the correlator may carry\n * forward, so persisted state cannot grow with provider-controlled input.\n */\nexport const MAX_RECOVERED_START_ATTRIBUTES = 16;\n\nconst familyOf = (type: CanonicalEventType): SpanFamily | undefined => {\n switch (type) {\n case \"session.start\":\n case \"session.end\":\n return \"session\";\n case \"generation.start\":\n case \"generation.end\":\n return \"generation\";\n case \"tool.start\":\n case \"tool.end\":\n return \"tool\";\n case \"subagent.start\":\n case \"subagent.end\":\n return \"subagent\";\n default:\n return undefined;\n }\n};\n\n/** The lifecycle span an event is an edge of, or undefined for a point-in-time event. */\nexport const spanScopeRefOf = (event: CanonicalEvent): SpanScopeRef | undefined => {\n const family = familyOf(event.type);\n if (family === undefined) {\n return undefined;\n }\n switch (event.type) {\n case \"session.start\":\n case \"session.end\":\n return { family, scopeKey: event.sessionId };\n case \"generation.start\":\n case \"generation.end\":\n return { family, scopeKey: event.generationId };\n case \"tool.start\":\n case \"tool.end\":\n return { family, scopeKey: event.toolCallId };\n case \"subagent.start\":\n case \"subagent.end\":\n return { family, scopeKey: event.subagentInvocationId };\n default:\n return undefined;\n }\n};\n\n/**\n * Where a span hangs in the trace, judged from this event alone.\n *\n * Everything in a session descends from the session span. A tool call names its\n * generation only on `tool.start`, which is exactly why the correlator persists\n * the parent: the `tool.end` process would otherwise reparent the same span to\n * the session and produce a tree whose shape depends on which edge happened to\n * be exported last.\n */\nexport const parentScopeRefOf = (event: CanonicalEvent): SpanScopeRef | undefined => {\n if (event.type === \"session.start\" || event.type === \"session.end\") {\n return undefined;\n }\n if (event.type === \"tool.start\" && event.generationId !== undefined) {\n return { family: \"generation\", scopeKey: event.generationId };\n }\n return { family: \"session\", scopeKey: event.sessionId };\n};\n\n/**\n * Span attributes that only a `*.start` edge can supply.\n *\n * The correlator persists these verbatim so an end-only span in a later process\n * still carries the tool kind, requested model, delegation depth, or agent name\n * the start process saw. An allowlist, and bounded, so persisted state can\n * never become a second route for provider payload content to escape.\n */\nexport const startOnlySpanAttributes = (event: CanonicalEvent): Attributes => {\n switch (event.type) {\n // The session's own worktree is carried forward like a tool's target, so\n // the session span a later `session.end` process exports still names it.\n case \"session.start\":\n return {\n ...(event.agentName === undefined ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: event.agentName }),\n ...(event.agentVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_AGENT_VERSION]: event.agentVersion }),\n ...targetAttributes(event),\n };\n case \"generation.start\":\n return {\n [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId,\n ...(event.model.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: event.model.vendor }),\n };\n // `toolName` and `toolCallId` are on both tool edges, so they are not\n // start-only and persisting them would just pad every record.\n // The target is carried forward too: an end-only process may see a payload\n // with less to go on (no tool input), and the start's evidence still holds.\n case \"tool.start\":\n return { [ATTR_OTELHOOK_TOOL_KIND]: event.toolKind, ...targetAttributes(event) };\n case \"subagent.start\":\n return { [ATTR_OTELHOOK_DELEGATION_DEPTH]: event.delegationDepth };\n default:\n return {};\n }\n};\n\nconst deriveTraceId = (providerId: string, sessionId: string): string =>\n digestHex([\"otelhook/trace\", providerId, sessionId], 32);\n\nconst deriveSpanId = (providerId: string, sessionId: string, ref: SpanScopeRef): string =>\n digestHex([\"otelhook/span\", providerId, sessionId, ref.family, ref.scopeKey], 16);\n\nconst deriveStandaloneSpanId = (\n providerId: string,\n sessionId: string,\n eventType: string,\n eventId: string,\n): string => digestHex([\"otelhook/span\", providerId, sessionId, \"event\", eventType, eventId], 16);\n\nconst correlationKey = (providerId: string, sessionId: string, ref: SpanScopeRef): string =>\n [providerId, sessionId, ref.family, ref.scopeKey].join(FIELD_SEPARATOR);\n\nconst outcomeStatus = (outcome: string | undefined): SpanStatus => {\n if (outcome === undefined || outcome === \"ok\" || outcome === \"unknown\") {\n return { code: SpanStatusCode.UNSET };\n }\n if (outcome === \"cancelled\") {\n return { code: SpanStatusCode.UNSET };\n }\n return { code: SpanStatusCode.ERROR, message: outcome };\n};\n\nconst identityAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n ids: { readonly traceId: string; readonly spanId: string; readonly parentSpanId?: string },\n): Attributes => exportIdentityAttributes(event, resource, ids);\n\nconst usageAttributes = (usage: CanonicalUsage | undefined, resetDetected: boolean): Attributes => {\n if (usage === undefined) {\n return {};\n }\n return {\n [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: usage.inputTokens,\n [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: usage.outputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: usage.cachedInputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: usage.cacheCreationInputTokens,\n [ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]: usage.reasoningOutputTokens,\n ...usageTemporalityAttributes(usage),\n ...(resetDetected ? { [ATTR_OTELHOOK_RESET_DETECTED]: true } : {}),\n };\n};\n\n/** Evidence strength of a target source; see `targetSourceSchema`. */\nconst TARGET_SOURCE_RANK: Readonly<Record<string, number>> = Object.freeze({\n \"tool-path\": 3,\n \"shell-cwd\": 2,\n \"session-cwd\": 1,\n});\n\nconst TARGET_KEYS = [\n ATTR_OTELHOOK_TARGET_WORKSPACE_ID,\n ATTR_OTELHOOK_TARGET_SOURCE,\n ATTR_VCS_REF_HEAD_NAME,\n ATTR_OTELHOOK_TARGET_REPOSITORY_ID,\n ATTR_OTELHOOK_TARGET_WORKTREE_KIND,\n] as const;\n\nconst pickTarget = (attributes: Attributes): Attributes => {\n const picked: Attributes = {};\n for (const key of TARGET_KEYS) {\n if (attributes[key] !== undefined) {\n picked[key] = attributes[key];\n }\n }\n return picked;\n};\n\n/**\n * Drop the target keys so they can be re-chosen as one unit, keeping only what\n * the launcher put on the Resource or the session context named (a\n * `vcs.ref.head.name` passed through by `exportIdentityAttributes`) as the\n * fallback beneath the chosen target.\n */\nconst withoutTarget = (attributes: Attributes, resource: Resource, event: CanonicalEvent): Attributes => {\n const rest: Attributes = { ...attributes };\n for (const key of TARGET_KEYS) {\n delete rest[key];\n }\n return { ...rest, ...pickTarget(profileAttributes(event, resource)) };\n};\n\nconst rankOf = (candidate: Attributes): number => {\n const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];\n return typeof source === \"string\" && Object.hasOwn(TARGET_SOURCE_RANK, source)\n ? (TARGET_SOURCE_RANK[source] ?? 0)\n : 0;\n};\n\n/**\n * One span, one target: the strongest evidence among the recovered start,\n * the live start, and the live end — later wins a tie. A Cursor shell call's\n * start knows its `cwd` and its end does not; the span must keep the former,\n * not be downgraded to the workspace root by whichever edge exported last.\n */\nconst strongestTarget = (candidates: readonly Attributes[]): Attributes => {\n let best: Attributes = {};\n let bestRank = 0;\n for (const candidate of candidates) {\n const rank = rankOf(candidate);\n if (rank > 0 && rank >= bestRank) {\n best = candidate;\n bestRank = rank;\n }\n }\n return best;\n};\n\ntype SpanGroup = {\n readonly ref: SpanScopeRef;\n start?: CanonicalEvent;\n end?: CanonicalEvent;\n};\n\nconst buildSpanContext = (traceId: string, spanId: string): SpanContext => ({\n traceId,\n spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n});\n\nexport type ReadableSpanInput = {\n readonly name: string;\n readonly kind: SpanKind;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly attributes: Attributes;\n readonly status: SpanStatus;\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n};\n\n/** Reconstructs a {@link ReadableSpan} from plain, serializable fields. Used by the durable spool to replay a span it persisted earlier. */\nexport const assembleReadableSpan = (input: ReadableSpanInput): ReadableSpan => toReadableSpan(input);\n\nconst toReadableSpan = (input: ReadableSpanInput): ReadableSpan => {\n const startTime = millisToHrTime(input.startMillis);\n const endTime = millisToHrTime(Math.max(input.startMillis, input.endMillis));\n const duration = millisToHrTime(Math.max(0, input.endMillis - input.startMillis));\n return {\n name: input.name,\n kind: input.kind,\n spanContext: (): SpanContext => buildSpanContext(input.traceId, input.spanId),\n ...(input.parentSpanId === undefined\n ? {}\n : { parentSpanContext: buildSpanContext(input.traceId, input.parentSpanId) }),\n startTime,\n endTime,\n status: input.status,\n attributes: input.attributes,\n links: [],\n events: [],\n duration,\n ended: true,\n resource: input.resource,\n instrumentationScope: input.instrumentationScope,\n droppedAttributesCount: 0,\n droppedEventsCount: 0,\n droppedLinksCount: 0,\n };\n};\n\ntype ResolvedPairing = {\n readonly pairing: SpanPairing;\n readonly orphan: SpanOrphanClassification;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly parent: SpanScopeRef | undefined;\n readonly recovered: Attributes;\n};\n\nconst resolvePairing = (\n group: SpanGroup,\n anchor: CanonicalEvent,\n correlation: SpanCorrelation | undefined,\n): ResolvedPairing => {\n const inBatch = group.start !== undefined && group.end !== undefined;\n const batchStart = group.start?.occurredAt ?? anchor.occurredAt;\n const batchEnd = group.end?.occurredAt ?? anchor.occurredAt;\n\n if (correlation === undefined) {\n return {\n pairing: inBatch ? \"in-batch\" : \"unpaired\",\n orphan: inBatch ? \"none\" : group.start === undefined ? \"missing-start\" : \"missing-end\",\n startMillis: batchStart,\n endMillis: inBatch ? batchEnd : batchStart,\n parent: parentScopeRefOf(anchor),\n recovered: {},\n };\n }\n\n // A correlation that reports no start (an orphaned end) must not fabricate\n // one: the span collapses onto the end instant rather than claiming a\n // duration measured from an event nobody ever saw.\n const startMillis = correlation.startMillis ?? (inBatch ? batchStart : batchEnd);\n const endMillis = correlation.endMillis ?? (group.end === undefined ? startMillis : batchEnd);\n return {\n pairing: correlation.pairing,\n orphan: correlation.orphan,\n startMillis,\n endMillis,\n parent: correlation.parent ?? parentScopeRefOf(anchor),\n recovered: correlation.attributes ?? {},\n };\n};\n\nconst buildLifecycleSpan = (\n plan: GroupPlan,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan => {\n const group = plan.group;\n const anchor = plan.anchor;\n const correlation = plan.correlation;\n const providerId = anchor.provenance.providerId;\n const sessionId = anchor.sessionId;\n const resolved = resolvePairing(group, anchor, correlation);\n const traceId = plan.traceId;\n const spanId = plan.spanId;\n const parentSpanId =\n resolved.parent === undefined ? undefined : deriveSpanId(providerId, sessionId, resolved.parent);\n\n let name: string = group.ref.family;\n let kind: SpanKind = SpanKind.INTERNAL;\n let status: SpanStatus = { code: SpanStatusCode.UNSET };\n // Attributes recovered from the start process sit *beneath* whatever this\n // batch observed: a live edge always wins over a remembered one.\n let attributes: Attributes = {\n ...identityAttributes(anchor, resource, {\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n }),\n ...resolved.recovered,\n [ATTR_OTELHOOK_SPAN_PAIRED]: resolved.pairing !== \"unpaired\",\n [ATTR_OTELHOOK_SPAN_PAIRING]: resolved.pairing,\n [ATTR_OTELHOOK_SPAN_ORPHAN]: resolved.orphan,\n };\n\n switch (group.ref.family) {\n case \"session\": {\n const end = group.end?.type === \"session.end\" ? group.end : undefined;\n const start = group.start?.type === \"session.start\" ? group.start : undefined;\n name = \"session\";\n kind = SpanKind.INTERNAL;\n attributes = {\n ...withoutTarget(attributes, resource, anchor),\n ...strongestTarget([pickTarget(resolved.recovered), start === undefined ? {} : targetAttributes(start)]),\n ...(start?.agentName === undefined ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName }),\n ...(start?.agentVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion }),\n ...(end === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.reason }),\n ...usageAttributes(end?.usage, false),\n };\n if (end?.reason === \"error\" || end?.reason === \"timeout\") {\n status = { code: SpanStatusCode.ERROR, message: end.reason };\n }\n break;\n }\n case \"generation\": {\n const start = group.start?.type === \"generation.start\" ? group.start : undefined;\n const end = group.end?.type === \"generation.end\" ? group.end : undefined;\n const model = end?.model ?? start?.model;\n name = model === undefined ? \"generation\" : `generation ${model.modelId}`;\n kind = SpanKind.CLIENT;\n attributes = {\n ...attributes,\n [ATTR_GEN_AI_OPERATION_NAME]: \"chat\",\n ...(model?.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: model.vendor }),\n ...(start?.model?.modelId === undefined ? {} : { [ATTR_GEN_AI_REQUEST_MODEL]: start.model.modelId }),\n ...(end?.model?.modelId === undefined ? {} : { [ATTR_GEN_AI_RESPONSE_MODEL]: end.model.modelId }),\n // The provider's own id for this unit of work (Cursor generation,\n // Codex turn): the key a consumer stores a usage observation under.\n [ATTR_OTELHOOK_GENERATION_ID]: group.ref.scopeKey,\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...usageAttributes(end?.usage, false),\n ...(end?.usage === undefined || end.usagePartial === undefined\n ? {}\n : { [ATTR_OTELHOOK_USAGE_PARTIAL]: end.usagePartial }),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n case \"tool\": {\n const start = group.start?.type === \"tool.start\" ? group.start : undefined;\n const end = group.end?.type === \"tool.end\" ? group.end : undefined;\n const toolName = start?.toolName ?? end?.toolName ?? \"unknown\";\n name = `tool ${toolName}`;\n kind = SpanKind.CLIENT;\n attributes = {\n // Target keys are re-chosen below as one unit, never mixed across edges.\n ...withoutTarget(attributes, resource, anchor),\n [ATTR_GEN_AI_TOOL_NAME]: toolName,\n [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,\n ...(start?.toolKind === undefined ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind }),\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...strongestTarget([\n pickTarget(resolved.recovered),\n start === undefined ? {} : targetAttributes(start),\n end === undefined ? {} : targetAttributes(end),\n ]),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n case \"subagent\": {\n const start = group.start?.type === \"subagent.start\" ? group.start : undefined;\n const end = group.end?.type === \"subagent.end\" ? group.end : undefined;\n name = \"subagent\";\n kind = SpanKind.INTERNAL;\n attributes = {\n ...attributes,\n ...(start?.delegationDepth === undefined\n ? {}\n : { [ATTR_OTELHOOK_DELEGATION_DEPTH]: start.delegationDepth }),\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...usageAttributes(end?.usage, false),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n }\n\n if (status.code === SpanStatusCode.ERROR) {\n attributes = { ...attributes, [ATTR_ERROR_TYPE]: status.message ?? \"error\" };\n }\n\n return toReadableSpan({\n name,\n kind,\n startMillis: resolved.startMillis,\n endMillis: resolved.endMillis,\n attributes,\n status,\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n resource,\n instrumentationScope: scope,\n });\n};\n\nconst buildStandaloneSpan = (\n event: CanonicalEvent,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan => {\n const providerId = event.provenance.providerId;\n const traceId = deriveTraceId(providerId, event.sessionId);\n const spanId = deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId);\n const parent = parentScopeRefOf(event);\n const parentSpanId =\n parent === undefined ? undefined : deriveSpanId(providerId, event.sessionId, parent);\n let attributes: Attributes = {\n ...identityAttributes(event, resource, {\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n }),\n [ATTR_OTELHOOK_SPAN_PAIRED]: true,\n };\n let status: SpanStatus = { code: SpanStatusCode.UNSET };\n let name: string = event.type;\n\n switch (event.type) {\n case \"prompt.submitted\":\n name = \"prompt\";\n attributes = { ...attributes, \"otelhook.prompt.source\": event.promptSource, ...targetAttributes(event) };\n break;\n case \"compaction.performed\":\n name = \"compaction\";\n attributes = {\n ...attributes,\n [ATTR_OTELHOOK_COMPACTION_TRIGGER]: event.trigger,\n ...usageAttributes(event.usage, false),\n };\n break;\n case \"error.raised\":\n name = \"error\";\n status = { code: SpanStatusCode.ERROR, message: event.errorCode };\n attributes = {\n ...attributes,\n [ATTR_ERROR_TYPE]: event.errorCode,\n \"otelhook.error.phase\": event.phase,\n \"otelhook.error.retryable\": event.retryable,\n };\n break;\n default:\n break;\n }\n\n return toReadableSpan({\n name,\n kind: SpanKind.INTERNAL,\n startMillis: event.occurredAt,\n endMillis: event.occurredAt,\n attributes,\n status,\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n resource,\n instrumentationScope: scope,\n });\n};\n\nexport type SemanticMappingOptions = {\n readonly resource: Resource;\n readonly instrumentationScope?: InstrumentationScope;\n /**\n * Cross-process pairing facts, at most one entry per lifecycle scope in\n * `events`. Omitted entirely, the mapping degrades to in-batch pairing only —\n * the behavior of a host that wired no state store.\n */\n readonly correlations?: readonly SpanCorrelation[];\n /**\n * Whether a correlator was consulted at all, and whether it answered.\n *\n * This is what separates \"the state store is holding this start, so the end edge\n * will publish it\" from \"nothing recorded this start\". Both look like an empty\n * `correlations` list, and only the first is safe to drop — dropping the second\n * would discard an observation that was neither persisted nor exported, while a\n * caller that saw zero rejections went on to mark the callback handled.\n *\n * - `true` — the correlator ran; an absent or non-`defer` entry means emit.\n * - `false` — the correlator failed; every unpaired start is emitted as an\n * explicitly labelled, uniquely identified fallback.\n * - omitted — no correlator is wired, so cross-process pairing was never on\n * offer and an unpaired start is deferred (the documented no-state-root\n * degradation).\n */\n readonly correlationAvailable?: boolean;\n};\n\n/**\n * Fill in a correlation for an unpaired start that nothing recorded.\n *\n * Reached when a correlator was consulted and either failed outright or reported\n * nothing for this scope. The synthesized entry says what is true — the state was\n * not consulted successfully, so this span is unpaired and no end can complete it\n * — and carries a discriminator so the record cannot claim the span id a later end\n * will publish for the same scope.\n */\nconst effectiveCorrelation = (\n group: SpanGroup,\n correlation: SpanCorrelation | undefined,\n): SpanCorrelation | undefined => {\n if (correlation !== undefined || group.end !== undefined || group.start === undefined) {\n return correlation;\n }\n return {\n providerId: group.start.provenance.providerId,\n sessionId: group.start.sessionId,\n ref: group.ref,\n pairing: \"unpaired\",\n orphan: \"state-unavailable\",\n disposition: \"emit\",\n spanIdDiscriminator: group.start.eventId,\n };\n};\n\n/** How one batch's events distribute over the lifecycle scopes they are edges of. */\ntype BatchLayout = {\n readonly groups: ReadonlyMap<string, SpanGroup>;\n readonly standalone: readonly CanonicalEvent[];\n /** Event id of each lifecycle edge, mapped to the group key it belongs to. */\n readonly groupOf: ReadonlyMap<string, string>;\n};\n\nconst layoutBatch = (events: readonly CanonicalEvent[]): BatchLayout => {\n const groups = new Map<string, SpanGroup>();\n const standalone: CanonicalEvent[] = [];\n const groupOf = new Map<string, string>();\n\n for (const event of events) {\n const ref = spanScopeRefOf(event);\n if (ref === undefined) {\n standalone.push(event);\n continue;\n }\n const groupKey = correlationKey(event.provenance.providerId, event.sessionId, ref);\n const group: SpanGroup = groups.get(groupKey) ?? { ref };\n if (event.type.endsWith(\".start\")) {\n group.start = event;\n } else {\n group.end = event;\n }\n groups.set(groupKey, group);\n groupOf.set(event.eventId, groupKey);\n }\n return { groups, standalone, groupOf };\n};\n\nconst indexCorrelations = (\n correlations: readonly SpanCorrelation[] | undefined,\n): ReadonlyMap<string, SpanCorrelation> => {\n const indexed = new Map<string, SpanCorrelation>();\n for (const correlation of correlations ?? []) {\n indexed.set(\n correlationKey(correlation.providerId, correlation.sessionId, correlation.ref),\n correlation,\n );\n }\n return indexed;\n};\n\n/**\n * What this batch does with one lifecycle scope, decided once.\n *\n * Both the span mapping and the log mapping need the *same* answer to \"which\n * span id identifies this scope, and is a record for it going out now?\" — a log\n * record whose `spanContext` names a span id the exporter never published would\n * dangle at the collector. Computing it in one place is what keeps the two\n * signals pointing at the same span rather than at two plausible derivations of\n * it.\n */\ntype GroupPlan = {\n readonly group: SpanGroup;\n /** The event the span's identity and provenance are read from. */\n readonly anchor: CanonicalEvent;\n /**\n * False when the start is deferred: the state store is holding it and the end\n * edge will publish the one complete span, so nothing is exported for it now.\n */\n readonly emits: boolean;\n readonly correlation: SpanCorrelation | undefined;\n readonly traceId: string;\n readonly spanId: string;\n};\n\nconst planGroup = (\n group: SpanGroup,\n correlation: SpanCorrelation | undefined,\n correlationAvailable: boolean | undefined,\n): GroupPlan | undefined => {\n const anchor = group.start ?? group.end;\n if (anchor === undefined) {\n // Unreachable: a group exists only because an event was filed into it.\n return undefined;\n }\n const providerId = anchor.provenance.providerId;\n const sessionId = anchor.sessionId;\n\n // A start with no end in this batch is dropped **only** when something states\n // that it is durably recorded, because its span id is a pure function of the\n // scope: emitting here and again at the end edge would put two records with one\n // id on the wire, and OTLP has no update operation.\n //\n // `defer` is that statement, and it is the correlator's to make — it just wrote\n // the record. Anything else means nothing is holding this start, so dropping it\n // would lose an observation that was neither persisted nor exported, while the\n // caller saw zero rejections and marked the callback handled. Those are exported\n // under a discriminated span id instead.\n const durablyRecorded =\n group.end === undefined &&\n (correlation?.disposition === \"defer\" ||\n // No correlator wired at all: cross-process pairing was never on offer, so\n // this is the documented no-state-root degradation rather than a failure to\n // persist something that should have been persisted.\n (correlation === undefined && correlationAvailable === undefined));\n\n // A deferred start keeps the scope's *plain* span id, because that is the id the\n // end edge will publish. Only a record actually going out now may claim a\n // discriminated one.\n const effective = durablyRecorded ? correlation : effectiveCorrelation(group, correlation);\n const discriminator = durablyRecorded ? undefined : effective?.spanIdDiscriminator;\n\n return {\n group,\n anchor,\n emits: !durablyRecorded,\n correlation: effective,\n traceId: deriveTraceId(providerId, sessionId),\n spanId:\n discriminator === undefined\n ? deriveSpanId(providerId, sessionId, group.ref)\n : digestHex(\n [\n \"otelhook/span\",\n providerId,\n sessionId,\n group.ref.family,\n group.ref.scopeKey,\n discriminator,\n ],\n 16,\n ),\n };\n};\n\n/** Trace and span a record derived from one canonical event belongs to. */\nexport type EventTraceIdentity = {\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n};\n\n/**\n * Resolve the trace and span identity of every event in one batch.\n *\n * Exposed for signals other than traces — a log record correlates by carrying\n * the *same* derived ids the span mapping would compute, including the deferred\n * and discriminated cases. Whole batch at once because a start's identity\n * depends on whether its end is in the same batch.\n *\n * Both ids come from the event's own `(providerId, sessionId)`, never from a\n * batch-level or module-level value, which is what makes cross-session\n * contamination structurally impossible: two sessions in one batch derive two\n * different trace ids.\n */\nexport const canonicalEventTraceIdentities = (\n events: readonly CanonicalEvent[],\n options: {\n readonly correlations?: readonly SpanCorrelation[];\n readonly correlationAvailable?: boolean;\n } = {},\n): ReadonlyMap<string, EventTraceIdentity> => {\n const layout = layoutBatch(events);\n const correlations = indexCorrelations(options.correlations);\n const plans = new Map<string, GroupPlan>();\n for (const [groupKey, group] of layout.groups) {\n const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);\n if (plan !== undefined) {\n plans.set(groupKey, plan);\n }\n }\n\n const identities = new Map<string, EventTraceIdentity>();\n for (const event of events) {\n const providerId = event.provenance.providerId;\n const groupKey = layout.groupOf.get(event.eventId);\n const plan = groupKey === undefined ? undefined : plans.get(groupKey);\n if (plan === undefined) {\n const parent = parentScopeRefOf(event);\n identities.set(event.eventId, {\n traceId: deriveTraceId(providerId, event.sessionId),\n spanId: deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId),\n ...(parent === undefined\n ? {}\n : { parentSpanId: deriveSpanId(providerId, event.sessionId, parent) }),\n });\n continue;\n }\n const parent = plan.correlation?.parent ?? parentScopeRefOf(event);\n identities.set(event.eventId, {\n traceId: plan.traceId,\n spanId: plan.spanId,\n ...(parent === undefined\n ? {}\n : { parentSpanId: deriveSpanId(providerId, event.sessionId, parent) }),\n });\n }\n return identities;\n};\n\n/** Maps one invocation's canonical event batch into OTLP-ready spans. */\nexport const canonicalEventsToReadableSpans = (\n events: readonly CanonicalEvent[],\n options: SemanticMappingOptions,\n): readonly ReadableSpan[] => {\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const layout = layoutBatch(events);\n const correlations = indexCorrelations(options.correlations);\n\n const spans: ReadableSpan[] = [];\n for (const [groupKey, group] of layout.groups) {\n const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);\n if (plan === undefined || !plan.emits) {\n continue;\n }\n spans.push(buildLifecycleSpan(plan, options.resource, scope));\n }\n for (const event of layout.standalone) {\n spans.push(buildStandaloneSpan(event, options.resource, scope));\n }\n return spans;\n};\n","/**\n * Package version, kept in its own module so the CLI can report it without\n * importing the whole library barrel (and every provider adapter with it).\n *\n * Updated by `scripts/release/sync-version.mjs` during semantic-release.\n */\nexport const VERSION = \"0.12.0\";\n","import type { Attributes 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 {\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 { createHash } from \"node:crypto\";\nimport { open, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport type { PayloadEnricher, PayloadEnrichment, ReadCursor } from \"../../runtime/ports.js\";\nimport { CLAUDE_CODE_PROVIDER_ID } from \"./detect.js\";\nimport type { ClaudeUsage } from \"./schema.js\";\nimport { coerceClaudeUsage } from \"./usage.js\";\n\n/**\n * Bounded readers for one Claude Code session transcript, and the enricher that\n * uses them to attach a turn's model and token usage to a `Stop` payload.\n *\n * None of this is part of the Claude Code adapter, and the adapter never calls\n * it: `ProviderContext` gives adapters no filesystem handle (ADR 0003). Two\n * callers use it instead:\n *\n * - a wrapping harness, through {@link attachClaudeTranscriptTurn}, which reads\n * the last assistant message only;\n * - the hook runtime, through {@link createClaudeTranscriptUsageEnricher}, when\n * the host turns on `providers.claudeCode.readTranscriptUsage` — the one\n * sanctioned exception to \"no transcript reads in the hook\". It sums the whole\n * turn, from a byte cursor the runtime keeps in the state store.\n *\n * Why the transcript at all: no Claude Code hook callback carries a token\n * counter, and only `SessionStart` names a model. The per-turn model\n * (`message.model`, which follows `/model`) and the Anthropic usage object\n * (`message.usage`) exist only on assistant transcript records, one record per\n * content block, each repeating its request's `message.id`.\n *\n * Every bound is hard, and nothing here throws:\n * - only regular `.jsonl` files at an absolute path are opened, so a FIFO or a\n * device cannot stall the hook, and no directory is ever listed;\n * - a read is capped in bytes and raced against a time budget;\n * - a malformed or truncated line is skipped, never fatal.\n *\n * Nothing but model ids and numeric counters leaves this module: a record's\n * content (prompt, response, thinking, tool input) is parsed only to be dropped.\n */\n\nexport type ClaudeTranscriptUnavailableReason =\n | \"invalid-path\"\n | \"not-a-file\"\n | \"unreadable\"\n | \"timeout\"\n | \"no-assistant-message\";\n\nexport type ClaudeTranscriptTurn =\n | {\n readonly status: \"found\";\n /** `message.model`; absent when the record named none. */\n readonly model?: string;\n /** `message.usage`, coerced onto the shape the `Stop` schema accepts. */\n readonly usage?: ClaudeUsage;\n }\n | { readonly status: \"unavailable\"; readonly reason: ClaudeTranscriptUnavailableReason };\n\nexport type ReadClaudeTranscriptTurnOptions = {\n /** Bytes read from the end of the file. Default 1 MiB, clamped to 64 KiB..16 MiB. */\n readonly maxTailBytes?: number;\n /** Budget for the whole read. Default 250 ms, clamped to 10 ms..5 s. */\n readonly timeoutMillis?: number;\n};\n\nexport const DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES = 1_048_576;\nexport const DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS = 250;\nexport const DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES = 8_388_608;\nexport const DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS = 500;\n\nconst MIN_TAIL_BYTES = 65_536;\nconst MAX_TAIL_BYTES = 16_777_216;\nconst MAX_RANGE_BYTES = 67_108_864;\nconst MIN_TIMEOUT_MILLIS = 10;\nconst MAX_TIMEOUT_MILLIS = 5_000;\n/** Longer than any real model id; a longer value is not one. */\nconst MAX_MODEL_ID_LENGTH = 256;\n/** Bounds the request ids held while summing one range. */\nconst MAX_REQUESTS_PER_RANGE = 10_000;\n/**\n * Claude Code writes `<synthetic>` as the model of assistant records it made up\n * itself (an API error, an interrupted turn). Those name no real model and carry\n * zeroed usage, so they are skipped.\n */\nconst SYNTHETIC_MODEL = \"<synthetic>\";\n\nconst TIMED_OUT = Symbol(\"timed-out\");\n\nconst clamp = (value: number | undefined, fallback: number, min: number, max: number): number => {\n if (value === undefined || !Number.isFinite(value)) {\n return fallback;\n }\n return Math.min(max, Math.max(min, Math.floor(value)));\n};\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\nconst isTranscriptPath = (transcriptPath: unknown): transcriptPath is string =>\n typeof transcriptPath === \"string\" &&\n transcriptPath.length > 0 &&\n !transcriptPath.includes(\"\\0\") &&\n path.isAbsolute(transcriptPath) &&\n path.extname(transcriptPath) === \".jsonl\";\n\ntype AssistantRecord = { readonly id?: string; readonly model?: string; readonly usage?: ClaudeUsage };\n\n/**\n * The request id, model and usage of one transcript line, or `undefined` when\n * it is not a usable main-thread assistant record.\n *\n * Sidechain records are a subagent's conversation; the parent's `Stop` is not\n * about them.\n */\nconst assistantRecordOf = (line: string): AssistantRecord | undefined => {\n // Cheap pre-filter: most lines are user, tool-result, or summary records, and\n // parsing every one of them would spend the budget on records never used.\n if (!line.includes('\"assistant\"')) {\n return undefined;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n return undefined;\n }\n const record = asRecord(parsed);\n if (record === undefined || record.type !== \"assistant\" || record.isSidechain === true) {\n return undefined;\n }\n const message = asRecord(record.message);\n if (message === undefined || message.model === SYNTHETIC_MODEL) {\n return undefined;\n }\n const model =\n typeof message.model === \"string\" && message.model.length > 0 && message.model.length <= MAX_MODEL_ID_LENGTH\n ? message.model\n : undefined;\n const usage = coerceClaudeUsage(message.usage);\n if (model === undefined && usage === undefined) {\n return undefined;\n }\n const id =\n typeof message.id === \"string\" && message.id.length > 0 && message.id.length <= 256 ? message.id : undefined;\n return {\n ...(id === undefined ? {} : { id }),\n ...(model === undefined ? {} : { model }),\n ...(usage === undefined ? {} : { usage }),\n };\n};\n\nconst cacheCreationOf = (usage: ClaudeUsage): number =>\n usage.cache_creation_input_tokens ??\n (usage.cache_creation === undefined\n ? 0\n : (usage.cache_creation.ephemeral_5m_input_tokens ?? 0) + (usage.cache_creation.ephemeral_1h_input_tokens ?? 0));\n\n/**\n * Sum per-request usage into one turn total.\n *\n * Only the four counters are summed. The TTL split and `iterations[]` are\n * breakdowns of one request's counters (docs/claude-code-usage-contract.md,\n * findings 3 and 4); carrying them across requests would add nothing a consumer\n * reads, and the adapter would only audit them against the sums.\n */\nconst sumUsage = (usages: readonly ClaudeUsage[]): ClaudeUsage => {\n let input = 0;\n let output = 0;\n let cacheRead = 0;\n let cacheCreation = 0;\n for (const usage of usages) {\n input += usage.input_tokens;\n output += usage.output_tokens;\n cacheRead += usage.cache_read_input_tokens ?? 0;\n cacheCreation += cacheCreationOf(usage);\n }\n return {\n input_tokens: input,\n output_tokens: output,\n cache_read_input_tokens: cacheRead,\n cache_creation_input_tokens: cacheCreation,\n };\n};\n\n/** Race `work` against a budget; a rejection becomes `onError`. */\nconst withTimeout = async <T>(\n work: Promise<T>,\n timeoutMillis: number,\n onError: T,\n): Promise<T | typeof TIMED_OUT> => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(() => {\n resolve(TIMED_OUT);\n }, timeoutMillis);\n // A hook process must be free to exit the moment its real work is done.\n timer.unref();\n });\n try {\n return await Promise.race([work.catch(() => onError), timeout]);\n } finally {\n clearTimeout(timer);\n }\n};\n\ntype FileUnavailable = { readonly status: \"unavailable\"; readonly reason: \"not-a-file\" | \"unreadable\" };\n\ntype FileHandle = Awaited<ReturnType<typeof open>>;\n\n/** Open a regular file and run `body` with its handle and size; always closes. */\nconst withRegularFile = async <T>(\n transcriptPath: string,\n body: (handle: FileHandle, size: number) => Promise<T>,\n): Promise<T | FileUnavailable> => {\n let info;\n try {\n info = await stat(transcriptPath);\n } catch {\n return { status: \"unavailable\", reason: \"unreadable\" };\n }\n if (!info.isFile()) {\n return { status: \"unavailable\", reason: \"not-a-file\" };\n }\n let handle;\n try {\n handle = await open(transcriptPath, \"r\");\n } catch {\n return { status: \"unavailable\", reason: \"unreadable\" };\n }\n try {\n const { size } = await handle.stat();\n return await body(handle, size);\n } catch {\n return { status: \"unavailable\", reason: \"unreadable\" };\n } finally {\n await handle.close().catch(() => undefined);\n }\n};\n\nconst readBytes = async (handle: FileHandle, start: number, length: number): Promise<Buffer> => {\n const buffer = Buffer.alloc(length);\n let filled = 0;\n while (filled < length) {\n const { bytesRead } = await handle.read(buffer, filled, length - filled, start + filled);\n if (bytesRead === 0) {\n break;\n }\n filled += bytesRead;\n }\n return buffer.subarray(0, filled);\n};\n\n/** Offset just past the last complete line of `bytes`, read from `start`. */\nconst completeLinesEnd = (bytes: Buffer, start: number): number => {\n const lastNewline = bytes.lastIndexOf(0x0a);\n return lastNewline < 0 ? start : start + lastNewline + 1;\n};\n\ntype TailRead = { readonly turn: ClaudeTranscriptTurn; readonly endOffset: number };\n\nconst readTail = (transcriptPath: string, maxTailBytes: number): Promise<TailRead | FileUnavailable> =>\n withRegularFile(transcriptPath, async (handle, size): Promise<TailRead> => {\n const length = Math.min(size, maxTailBytes);\n const start = size - length;\n const bytes = await readBytes(handle, start, length);\n const endOffset = completeLinesEnd(bytes, start);\n const lines = bytes.toString(\"utf8\").split(\"\\n\");\n // A tail that starts mid-file starts mid-line: that first fragment is not a\n // record, and parsing it could only fail or, worse, half-succeed.\n if (start > 0) {\n lines.shift();\n }\n for (let index = lines.length - 1; index >= 0; index -= 1) {\n const record = assistantRecordOf((lines[index] ?? \"\").trim());\n if (record !== undefined) {\n return {\n turn: {\n status: \"found\",\n ...(record.model === undefined ? {} : { model: record.model }),\n ...(record.usage === undefined ? {} : { usage: record.usage }),\n },\n endOffset,\n };\n }\n }\n return { turn: { status: \"unavailable\", reason: \"no-assistant-message\" }, endOffset };\n });\n\nconst boundedTail = async (\n transcriptPath: string,\n options: ReadClaudeTranscriptTurnOptions,\n): Promise<TailRead | FileUnavailable | typeof TIMED_OUT> =>\n withTimeout<TailRead | FileUnavailable>(\n readTail(\n transcriptPath,\n clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES),\n ),\n clamp(options.timeoutMillis, DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS, MIN_TIMEOUT_MILLIS, MAX_TIMEOUT_MILLIS),\n { status: \"unavailable\", reason: \"unreadable\" },\n );\n\n/**\n * Read the model and usage of the last main-thread assistant message in a\n * Claude Code transcript. Never throws, never rejects.\n *\n * The usage is that **one message's** — the final model request of the turn. A\n * turn that called tools made several requests, and the earlier ones are not\n * summed in; {@link readClaudeTranscriptRange} sums a whole turn.\n */\nexport const readClaudeTranscriptTurn = async (\n transcriptPath: string,\n options: ReadClaudeTranscriptTurnOptions = {},\n): Promise<ClaudeTranscriptTurn> => {\n if (!isTranscriptPath(transcriptPath)) {\n return { status: \"unavailable\", reason: \"invalid-path\" };\n }\n const read = await boundedTail(transcriptPath, options);\n if (read === TIMED_OUT) {\n return { status: \"unavailable\", reason: \"timeout\" };\n }\n return \"turn\" in read ? read.turn : read;\n};\n\nexport type ClaudeTranscriptRange =\n | {\n readonly status: \"found\";\n /** Model of the last main-thread assistant record in the range. */\n readonly model?: string;\n /** Summed usage of every distinct request; absent when none reported usage. */\n readonly usage?: ClaudeUsage;\n /** Distinct main-thread requests (by `message.id`) in the range. */\n readonly requestCount: number;\n /** Offset just past the last complete line read: the next range starts here. */\n readonly endOffset: number;\n }\n | {\n readonly status: \"unavailable\";\n readonly reason:\n | \"invalid-path\"\n | \"not-a-file\"\n | \"unreadable\"\n | \"timeout\"\n /** The file is shorter than the offset: it was replaced or truncated. */\n | \"truncated\"\n /** More than the range cap was written since the offset. */\n | \"over-cap\";\n };\n\nexport type ReadClaudeTranscriptRangeOptions = {\n /** Most bytes a range may span. Default 8 MiB, clamped to 64 KiB..64 MiB. */\n readonly maxRangeBytes?: number;\n /** Budget for the whole range read. Default 500 ms, clamped to 10 ms..5 s. */\n readonly rangeTimeoutMillis?: number;\n};\n\n/**\n * Sum every main-thread model request written between `fromOffset` and the end\n * of the transcript. Never throws, never rejects.\n *\n * Records of one request share a `message.id` and each repeats its usage, so the\n * last record per id is the one counted; a record without an id counts alone.\n * A trailing partial line is left for the next range.\n */\nexport const readClaudeTranscriptRange = async (\n transcriptPath: string,\n fromOffset: number,\n options: ReadClaudeTranscriptRangeOptions = {},\n): Promise<ClaudeTranscriptRange> => {\n if (!isTranscriptPath(transcriptPath) || !Number.isSafeInteger(fromOffset) || fromOffset < 0) {\n return { status: \"unavailable\", reason: \"invalid-path\" };\n }\n const maxRangeBytes = clamp(options.maxRangeBytes, DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES, MIN_TAIL_BYTES, MAX_RANGE_BYTES);\n const timeoutMillis = clamp(\n options.rangeTimeoutMillis,\n DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS,\n MIN_TIMEOUT_MILLIS,\n MAX_TIMEOUT_MILLIS,\n );\n const work = withRegularFile(transcriptPath, async (handle, size): Promise<ClaudeTranscriptRange> => {\n if (size < fromOffset) {\n return { status: \"unavailable\", reason: \"truncated\" };\n }\n if (size - fromOffset > maxRangeBytes) {\n return { status: \"unavailable\", reason: \"over-cap\" };\n }\n const bytes = await readBytes(handle, fromOffset, size - fromOffset);\n const endOffset = completeLinesEnd(bytes, fromOffset);\n const complete = bytes.subarray(0, endOffset - fromOffset).toString(\"utf8\");\n const requests = new Map<string, AssistantRecord>();\n let anonymous = 0;\n let model: string | undefined;\n for (const line of complete.split(\"\\n\")) {\n const record = assistantRecordOf(line.trim());\n if (record === undefined) {\n continue;\n }\n if (record.model !== undefined) {\n model = record.model;\n }\n anonymous += record.id === undefined ? 1 : 0;\n // The last record of a request carries its final usage, so it replaces the earlier ones.\n requests.set(record.id ?? `#${String(anonymous)}`, record);\n if (requests.size > MAX_REQUESTS_PER_RANGE) {\n return { status: \"unavailable\", reason: \"over-cap\" };\n }\n }\n const usages = [...requests.values()].flatMap((record) => (record.usage === undefined ? [] : [record.usage]));\n return {\n status: \"found\",\n ...(model === undefined ? {} : { model }),\n ...(usages.length === 0 ? {} : { usage: sumUsage(usages) }),\n requestCount: requests.size,\n endOffset,\n };\n });\n const result = await withTimeout<ClaudeTranscriptRange | FileUnavailable>(work, timeoutMillis, {\n status: \"unavailable\",\n reason: \"unreadable\",\n });\n return result === TIMED_OUT ? { status: \"unavailable\", reason: \"timeout\" } : result;\n};\n\nconst STOP_EVENTS: ReadonlySet<string> = new Set([\"Stop\", \"StopFailure\"]);\n\nconst hasUsage = (record: Record<string, unknown>): boolean =>\n record.usage !== undefined || record.token_usage !== undefined || record.tokenUsage !== undefined;\n\nconst eventNameOf = (record: Record<string, unknown>): unknown => record.hook_event_name ?? record.hookEventName;\nconst transcriptPathOf = (record: Record<string, unknown>): unknown =>\n record.transcript_path ?? record.transcriptPath;\n\n/**\n * Attach the last assistant message's `{ model, usage }` to a Claude Code\n * `Stop` / `StopFailure` payload, for a wrapper to hand to otel-hook.\n *\n * The usage is one request's, so it is attached with `usage_partial: true`,\n * which the exported generation reports as `otelhook.usage.partial`. For whole\n * turn totals, turn on `providers.claudeCode.readTranscriptUsage` instead.\n *\n * Returns the payload unchanged when it is not a stop, names no\n * `transcript_path`, already carries both fields, or the transcript yields\n * nothing — so a wrapper can call it unconditionally. A field the payload\n * already carries is never overwritten. Never throws, never rejects.\n */\nexport const attachClaudeTranscriptTurn = async (\n payload: unknown,\n options: ReadClaudeTranscriptTurnOptions = {},\n): Promise<unknown> => {\n const record = asRecord(payload);\n if (record === undefined) {\n return payload;\n }\n const eventName = eventNameOf(record);\n if (typeof eventName !== \"string\" || !STOP_EVENTS.has(eventName)) {\n return payload;\n }\n const transcriptPath = transcriptPathOf(record);\n if (typeof transcriptPath !== \"string\") {\n return payload;\n }\n const needsModel = record.model === undefined;\n const needsUsage = !hasUsage(record);\n if (!needsModel && !needsUsage) {\n return payload;\n }\n const turn = await readClaudeTranscriptTurn(transcriptPath, options);\n if (turn.status !== \"found\") {\n return payload;\n }\n return {\n ...record,\n ...(needsModel && turn.model !== undefined ? { model: turn.model } : {}),\n ...(needsUsage && turn.usage !== undefined ? { usage: turn.usage, usage_partial: true } : {}),\n };\n};\n\nexport type ClaudeTranscriptUsageEnricherOptions = ReadClaudeTranscriptTurnOptions &\n ReadClaudeTranscriptRangeOptions;\n\nexport const CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = \"claude-transcript-usage\";\n\n/** Opaque, path-free name for a transcript, stored beside its cursor. */\nconst sourceDigest = (transcriptPath: string): string =>\n createHash(\"sha256\").update(transcriptPath, \"utf8\").digest(\"hex\").slice(0, 32);\n\n/**\n * The hook-runtime side of `providers.claudeCode.readTranscriptUsage`: attach\n * each turn's model and **summed** usage to its `Stop` / `StopFailure`.\n *\n * The runtime keeps a byte cursor per session (state value `read-cursor`):\n *\n * - `SessionStart` records where the transcript ends now (0 when it does not\n * exist yet), unless a cursor for the same transcript is already stored — a\n * compaction restart must not skip the turn it interrupted.\n * - `Stop` sums every main-thread request from the cursor to the end, and moves\n * the cursor there. That is the exact turn total: `usage_partial: false`.\n * - With no usable cursor (enabled mid-session, an expired or lost store, a\n * different transcript), a range over the cap, or a transcript that shrank, it\n * falls back to the last request in the bounded tail, attaches it with\n * `usage_partial: true`, and moves the cursor to the end so the next turn is\n * exact again.\n * - A timeout or an unreadable file attaches nothing and keeps the cursor, so\n * the next turn's range includes this one: tokens are counted late, never\n * twice and never lost.\n *\n * A payload that already carries `usage` (a wrapper attached it) is left as it\n * is, and the cursor moves past it so those tokens are not counted again.\n */\nexport const createClaudeTranscriptUsageEnricher = (\n options: ClaudeTranscriptUsageEnricherOptions = {},\n): PayloadEnricher => {\n const fileSize = async (transcriptPath: string): Promise<number | \"absent\" | undefined> => {\n try {\n const info = await stat(transcriptPath);\n return info.isFile() ? info.size : undefined;\n } catch (thrown) {\n return (thrown as { code?: unknown } | undefined)?.code === \"ENOENT\" ? \"absent\" : undefined;\n }\n };\n\n const enrich = async (input: {\n readonly payload: unknown;\n readonly cursor?: ReadCursor;\n }): Promise<PayloadEnrichment> => {\n const unchanged: PayloadEnrichment = { payload: input.payload };\n const record = asRecord(input.payload);\n if (record === undefined) {\n return unchanged;\n }\n const eventName = eventNameOf(record);\n const transcriptPath = transcriptPathOf(record);\n if (typeof eventName !== \"string\" || !isTranscriptPath(transcriptPath)) {\n return unchanged;\n }\n const source = sourceDigest(transcriptPath);\n const cursor = input.cursor?.source === source ? input.cursor : undefined;\n\n if (eventName === \"SessionStart\") {\n if (cursor !== undefined) {\n return unchanged;\n }\n const size = await fileSize(transcriptPath);\n if (size === undefined) {\n return { ...unchanged, notes: [\"transcript is not a readable regular file; no cursor recorded\"] };\n }\n return { payload: input.payload, cursor: { source, offset: size === \"absent\" ? 0 : size } };\n }\n\n if (!STOP_EVENTS.has(eventName)) {\n return unchanged;\n }\n\n if (hasUsage(record)) {\n const size = await fileSize(transcriptPath);\n return typeof size === \"number\" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;\n }\n\n const attach = (\n model: string | undefined,\n usage: ClaudeUsage | undefined,\n partial: boolean,\n ): Record<string, unknown> => ({\n ...record,\n ...(record.model === undefined && model !== undefined ? { model } : {}),\n ...(usage === undefined ? {} : { usage, usage_partial: partial }),\n });\n\n if (cursor !== undefined) {\n const range = await readClaudeTranscriptRange(transcriptPath, cursor.offset, options);\n if (range.status === \"found\") {\n return {\n payload: attach(range.model, range.usage, false),\n cursor: { source, offset: range.endOffset },\n notes: [`summed ${String(range.requestCount)} request(s) since the last stop`],\n };\n }\n if (range.reason !== \"truncated\" && range.reason !== \"over-cap\") {\n return { ...unchanged, notes: [`transcript range not read (${range.reason}); cursor kept`] };\n }\n }\n\n // No usable cursor, or a range that cannot be summed within bounds.\n const tail = await boundedTail(transcriptPath, options);\n if (tail === TIMED_OUT || !(\"turn\" in tail)) {\n return { ...unchanged, notes: [`transcript tail not read (${tail === TIMED_OUT ? \"timeout\" : tail.reason})`] };\n }\n const why = cursor === undefined ? \"no cursor for this transcript\" : \"range not summable within bounds\";\n return {\n payload: tail.turn.status === \"found\" ? attach(tail.turn.model, tail.turn.usage, true) : input.payload,\n cursor: { source, offset: tail.endOffset },\n notes: [`${why}; attached the last request only (usage_partial)`],\n };\n };\n\n return Object.freeze({\n id: CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,\n providerId: CLAUDE_CODE_PROVIDER_ID,\n enrich,\n });\n};\n","import { z } from \"zod\";\n\nimport type { AttributionOutcome, AttributionReason, OtelHookErrorInfo } from \"../errors/index.js\";\nimport {\n canonicalEventTypeSchema,\n type CanonicalEvent,\n type CanonicalEventType,\n type ModelDescriptor,\n} 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 * The model this session last reported, as the core remembers it across\n * invocations (`session.start` or a `generation.*` edge with a known model).\n *\n * Read from the state store by the core and handed in, because an adapter must\n * not hold cross-invocation state itself (ADR 0006). Absent when no earlier\n * invocation of this session named a model, or when the store is unreadable.\n * An adapter whose generation callbacks carry no model id (Claude Code's\n * `Stop`) uses it instead of the `unknown` sentinel; one whose callbacks carry\n * their own model can ignore it.\n */\n readonly sessionModel?: ModelDescriptor;\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\n/**\n * Raw Claude Code hook payload shapes.\n *\n * Field names and event names are taken from Claude Code's published hooks\n * reference (`code.claude.com/docs/en/hooks`). Objects are intentionally\n * non-strict: an unrecognized field is ignored rather than rejected, so a\n * protocol addition does not break detection or parsing. Discriminants\n * (`hook_event_name`, and the enum-shaped fields we do constrain) are strict.\n */\n\n/** Fields Claude Code includes on effectively every hook invocation. */\nconst commonFields = {\n session_id: z.string().min(1),\n transcript_path: z.string().min(1).optional(),\n cwd: z.string().min(1).optional(),\n permission_mode: z.string().min(1).optional(),\n /** Correlates a hook firing with the user prompt that triggered it (Claude Code v2.1.196+). */\n prompt_id: z.string().min(1).optional(),\n /** Present when the hook fired while running inside a subagent. */\n agent_id: z.string().min(1).optional(),\n agent_type: z.string().min(1).optional(),\n};\n\n/**\n * Cache-creation tokens split by cache TTL.\n *\n * A *breakdown* of `cache_creation_input_tokens`, not tokens beside it: the two\n * sub-buckets summed to that counter in 4,999 of 4,999 real usage objects. See\n * `usage.ts` for why they are verified and never added, and\n * docs/claude-code-usage-contract.md (finding 3) for the capture.\n */\nexport const claudeCacheCreationSchema = z.object({\n ephemeral_5m_input_tokens: z.number().int().min(0).optional(),\n ephemeral_1h_input_tokens: z.number().int().min(0).optional(),\n});\n\n/**\n * One model request inside a turn that took more than one.\n *\n * Also a breakdown: the per-iteration counters summed to the outer counters\n * exactly, for all four fields, in every capture (finding 4).\n */\nexport const claudeUsageIterationSchema = z.object({\n input_tokens: z.number().int().min(0).optional(),\n output_tokens: z.number().int().min(0).optional(),\n cache_creation_input_tokens: z.number().int().min(0).optional(),\n cache_read_input_tokens: z.number().int().min(0).optional(),\n});\n\n/**\n * Anthropic Messages API usage shape, as a wrapping harness may attach it\n * after correlating a hook firing with the transcript.\n *\n * **No Claude Code hook callback carries this object.** Confirmed against the\n * CLI's own hook-input schemas at 2.1.220: not `Stop`, not `SubagentStop`, not\n * `PostCompact` — no hook event in the protocol reports a token counter at all\n * (docs/claude-code-usage-contract.md, finding 1). The tokens exist only at\n * `message.usage` in the transcript, and this adapter never reads the transcript\n * itself (AGENTS.md and ADR 0003: an adapter has no filesystem handle). So the\n * field is accepted only when a caller has already placed it on the payload, and\n * the shape mirrors `message.usage` exactly so a harness can attach what it read\n * without reshaping it — `readClaudeTranscriptTurn` / `attachClaudeTranscriptTurn`\n * (`transcript.ts`) are the bounded helper a wrapper can call to do that.\n *\n * `input_tokens` is the **fresh** portion of the prompt only; cache reads and\n * cache writes are separate, additive buckets (finding 2). `usage.ts` documents\n * the fold that turns those three into the canonical inclusive total.\n */\nexport const claudeUsageSchema = z.object({\n input_tokens: z.number().int().min(0),\n output_tokens: z.number().int().min(0),\n cache_creation_input_tokens: z.number().int().min(0).optional(),\n cache_read_input_tokens: z.number().int().min(0).optional(),\n cache_creation: claudeCacheCreationSchema.optional(),\n iterations: z.array(claudeUsageIterationSchema).optional(),\n /**\n * Counters the canonical model has a home for but Claude Code never reports:\n * 0 of 4,999 real usage objects carried either (finding 5).\n *\n * Named here rather than left to the object's forward-compatible looseness so\n * that a harness attaching one gets told it was excluded, instead of watching\n * it vanish. See `CLAUDE_EXCLUDED_USAGE_COUNTERS`.\n */\n total_tokens: z.number().int().min(0).optional(),\n reasoning_output_tokens: z.number().int().min(0).optional(),\n});\nexport type ClaudeUsage = z.infer<typeof claudeUsageSchema>;\n\nexport const sessionStartPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"SessionStart\"),\n /** Matcher values: startup | resume | clear | compact | fork. Forward-compatible: any string. */\n source: z.string().min(1).optional(),\n model: z.string().min(1).optional(),\n session_title: z.string().min(1).optional(),\n});\nexport type SessionStartPayload = z.infer<typeof sessionStartPayloadSchema>;\n\nexport const sessionEndPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"SessionEnd\"),\n /** Current Claude Code field; values include clear, logout, prompt_input_exit, and other. */\n reason: z.string().min(1).optional(),\n /** Compatibility alias emitted by older wrappers and hook integrations. */\n end_reason: z.string().min(1).optional(),\n});\nexport type SessionEndPayload = z.infer<typeof sessionEndPayloadSchema>;\n\nexport const userPromptSubmitPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"UserPromptSubmit\"),\n prompt: z.string(),\n});\nexport type UserPromptSubmitPayload = z.infer<typeof userPromptSubmitPayloadSchema>;\n\nexport const preToolUsePayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"PreToolUse\"),\n tool_name: z.string().min(1),\n tool_input: z.unknown(),\n tool_use_id: z.string().min(1),\n});\nexport type PreToolUsePayload = z.infer<typeof preToolUsePayloadSchema>;\n\nexport const postToolUsePayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"PostToolUse\"),\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n tool_response: z.unknown(),\n tool_use_id: z.string().min(1),\n});\nexport type PostToolUsePayload = z.infer<typeof postToolUsePayloadSchema>;\n\nexport const postToolUseFailurePayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"PostToolUseFailure\"),\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n tool_error: z.unknown(),\n tool_use_id: z.string().min(1),\n});\nexport type PostToolUseFailurePayload = z.infer<typeof postToolUseFailurePayloadSchema>;\n\nexport const permissionRequestPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"PermissionRequest\"),\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n tool_use_id: z.string().min(1),\n});\nexport type PermissionRequestPayload = z.infer<typeof permissionRequestPayloadSchema>;\n\nexport const subagentStartPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"SubagentStart\"),\n agent_type: z.string().min(1),\n agent_id: z.string().min(1),\n});\nexport type SubagentStartPayload = z.infer<typeof subagentStartPayloadSchema>;\n\nexport const subagentStopPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"SubagentStop\"),\n agent_type: z.string().min(1),\n agent_id: z.string().min(1),\n last_assistant_message: z.string().optional(),\n /** True when this stop fired because a hook continued the subagent's turn. */\n stop_hook_active: z.boolean().optional(),\n usage: claudeUsageSchema.optional(),\n});\nexport type SubagentStopPayload = z.infer<typeof subagentStopPayloadSchema>;\n\n/**\n * Compaction callbacks.\n *\n * The upstream contract at 2.1.220 is `PreCompact { trigger, custom_instructions }`\n * and `PostCompact { trigger, compact_summary }`. **Neither reports a token\n * count** — no context size before or after, no dropped-message count\n * (docs/claude-code-usage-contract.md, finding 6). The counters below are\n * accepted for a wrapping harness that computed them; they are not a claim that\n * Claude Code sends them, and `capabilities.ts` excludes `contextTokensBefore`\n * accordingly.\n *\n * `custom_instructions` and `compact_summary` are deliberately absent. The\n * summary is a model-generated précis of the conversation — content — and\n * compaction telemetry needs the trigger and the sizes, not the text. Both are\n * ignored by the object's forward-compatible looseness rather than read and\n * screened, so there is no path by which they could reach an event.\n */\nexport const preCompactPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"PreCompact\"),\n /** Upstream values: manual | auto. Forward-compatible: any string. */\n trigger: z.string().min(1).optional(),\n /** Compatibility alias emitted by older wrappers and hook integrations. */\n compact_trigger: z.string().min(1).optional(),\n /**\n * Harness-supplied, never upstream. Reported as an explicit exclusion rather\n * than carried across the process boundary: see `events.ts`.\n */\n context_tokens_before: z.number().int().min(0).optional(),\n estimated_tokens_removed: z.number().int().min(0).optional(),\n});\nexport type PreCompactPayload = z.infer<typeof preCompactPayloadSchema>;\n\nexport const postCompactPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"PostCompact\"),\n trigger: z.string().min(1).optional(),\n compact_trigger: z.string().min(1).optional(),\n /** Harness-supplied, never upstream; accepted here because one callback carries both. */\n context_tokens_before: z.number().int().min(0).optional(),\n context_tokens_after: z.number().int().min(0).optional(),\n dropped_message_count: z.number().int().min(0).optional(),\n usage: claudeUsageSchema.optional(),\n});\nexport type PostCompactPayload = z.infer<typeof postCompactPayloadSchema>;\n\nexport const stopPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"Stop\"),\n /**\n * Interactive Stop field (Claude Code ≥ 2.1.47). Print / `-p` / Agent SDK\n * result messages use `result` instead; `events.ts` reads both (and camelCase\n * `lastAssistantMessage`) through `extractClaudeAssistantText`.\n */\n last_assistant_message: z.string().optional(),\n /** Print / `-p` JSON result field; accepted so a harness can attach it as-is. */\n result: z.string().optional(),\n /**\n * True when this stop fired because a hook continued the turn.\n *\n * Required upstream, optional here. It is what separates the once-per-prompt\n * stop from a continuation stop, which is what lets `delivery.ts` deduplicate\n * the former without suppressing the latter.\n */\n stop_hook_active: z.boolean().optional(),\n usage: claudeUsageSchema.optional(),\n /**\n * The model that answered this turn — harness-supplied, never upstream.\n *\n * Claude Code's `Stop` carries no model id; the per-turn model sits only at\n * `message.model` in the transcript, beside `message.usage`. A wrapping harness\n * that read it (for instance with `readClaudeTranscriptTurn`) attaches it here\n * with `usage`, and it becomes the generation's response model. An unusable\n * value (empty, over 256 characters, not a string) is dropped rather than\n * failing the whole payload: the turn is still worth reporting without it.\n */\n model: z.string().min(1).max(256).optional().catch(undefined),\n /**\n * Harness-supplied, never upstream: whether `usage` covers only part of the\n * turn. `true` when it is the last model request alone (the tail fallback),\n * `false` when it sums every request since the previous stop. Exported as\n * `otelhook.usage.partial`; absent means the attacher did not say.\n */\n usage_partial: z.boolean().optional().catch(undefined),\n});\nexport type StopPayload = z.infer<typeof stopPayloadSchema>;\n\nexport const stopFailurePayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"StopFailure\"),\n /**\n * Matcher values: rate_limit | overloaded | authentication_failed |\n * oauth_org_not_allowed | billing_error | invalid_request | model_not_found\n * | server_error | max_output_tokens | unknown.\n */\n error_type: z.string().min(1),\n error_message: z.string().optional(),\n usage: claudeUsageSchema.optional(),\n /** Harness-supplied, never upstream: see `stopPayloadSchema.model`. */\n model: z.string().min(1).max(256).optional().catch(undefined),\n /** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */\n usage_partial: z.boolean().optional().catch(undefined),\n});\nexport type StopFailurePayload = z.infer<typeof stopFailurePayloadSchema>;\n\nexport const claudeHookPayloadSchema = z.discriminatedUnion(\"hook_event_name\", [\n sessionStartPayloadSchema,\n sessionEndPayloadSchema,\n userPromptSubmitPayloadSchema,\n preToolUsePayloadSchema,\n postToolUsePayloadSchema,\n postToolUseFailurePayloadSchema,\n permissionRequestPayloadSchema,\n subagentStartPayloadSchema,\n subagentStopPayloadSchema,\n preCompactPayloadSchema,\n postCompactPayloadSchema,\n stopPayloadSchema,\n stopFailurePayloadSchema,\n]);\nexport type ClaudeHookPayload = z.infer<typeof claudeHookPayloadSchema>;\n\n/** Every `hook_event_name` this adapter recognizes. */\nexport const CLAUDE_HOOK_EVENT_NAMES = [\n \"SessionStart\",\n \"SessionEnd\",\n \"UserPromptSubmit\",\n \"PreToolUse\",\n \"PostToolUse\",\n \"PostToolUseFailure\",\n \"PermissionRequest\",\n \"SubagentStart\",\n \"SubagentStop\",\n \"PreCompact\",\n \"PostCompact\",\n \"Stop\",\n \"StopFailure\",\n] as const;\nexport type ClaudeHookEventName = (typeof CLAUDE_HOOK_EVENT_NAMES)[number];\n\n/**\n * Minimal shape identity resolution needs. Deliberately looser than\n * {@link claudeHookPayloadSchema}: a payload that is missing an\n * event-specific field (e.g. `PreToolUse` without `tool_use_id`) can still be\n * attributed to a session, so the deeper failure surfaces from `parse`\n * instead of silently declining attribution.\n */\nexport const claudeIdentityFieldsSchema = z.object({\n session_id: z.string().min(1),\n hook_event_name: z.string().min(1),\n cwd: z.string().min(1).optional(),\n prompt_id: z.string().min(1).optional(),\n agent_id: z.string().min(1).optional(),\n tool_use_id: z.string().min(1).optional(),\n /** Read by `delivery.ts` to tell a once-per-prompt stop from a continuation. */\n stop_hook_active: z.boolean().optional(),\n});\nexport type ClaudeIdentityFields = z.infer<typeof claudeIdentityFieldsSchema>;\n","import { normalizeUsage, type CanonicalUsage } from \"../../model/index.js\";\nimport { claudeUsageSchema, type ClaudeUsage } from \"./schema.js\";\n\nexport type ClaudeUsageNormalization = {\n readonly usage?: CanonicalUsage;\n readonly warnings: readonly string[];\n};\n\n/**\n * Counters this adapter deliberately does not read.\n *\n * Both are absent from Claude Code's usage shape — 0 of 4,999 real usage objects\n * carried either (docs/claude-code-usage-contract.md, finding 5) — and both have\n * a home in the canonical model, which is exactly why reading a\n * harness-supplied one would be wrong: `providerTotalAgreement` would start\n * reporting `agrees`/`disagrees` for a provider that reports no total, and\n * `reasoningOutputTokens` would carry a figure `reportsReasoningOutput: false`\n * says does not exist. A consumer's ability to tell \"not reported\" from \"zero\"\n * depends on the capability declaration staying true.\n *\n * So the field is excluded and *said out loud*, rather than silently dropped.\n */\nexport const CLAUDE_EXCLUDED_USAGE_COUNTERS = Object.freeze({\n total_tokens:\n \"usage.total_tokens is outside Claude Code's usage contract (capability reportsProviderTotal=false): \" +\n \"it is not read, so providerTotalAgreement stays \\\"unreported\\\"\",\n reasoning_output_tokens:\n \"usage.reasoning_output_tokens is outside Claude Code's usage contract (capability \" +\n \"reportsReasoningOutput=false): Anthropic bills thinking tokens inside output_tokens with no separate \" +\n \"counter, so it is not read and reasoningOutputTokens stays 0\",\n});\n\n/** The four counters `usage.iterations[]` itemizes, and the outer fields they must match. */\nconst ITERATION_COUNTERS = [\n \"input_tokens\",\n \"output_tokens\",\n \"cache_read_input_tokens\",\n \"cache_creation_input_tokens\",\n] as const;\n\n/**\n * Cache-creation tokens split by TTL, or `undefined` when the split is absent.\n *\n * The two sub-buckets summed to `cache_creation_input_tokens` in every capture,\n * so this is a *breakdown* to reconcile against, never an addend.\n */\nconst ttlSplitTotal = (raw: ClaudeUsage): number | undefined => {\n const split = raw.cache_creation;\n if (split === undefined) {\n return undefined;\n }\n return (split.ephemeral_5m_input_tokens ?? 0) + (split.ephemeral_1h_input_tokens ?? 0);\n};\n\n/**\n * Settle on one cache-creation figure from the two places it can be stated.\n *\n * The explicit counter wins when both are present: it is the billed total, and\n * preferring a sum of parts over a stated whole would let a future third TTL\n * bucket silently deflate it. A disagreement is reported rather than resolved\n * quietly, because only one of the two numbers can be the billing story.\n */\nconst resolveCacheCreationTokens = (raw: ClaudeUsage, warnings: string[]): number => {\n const declared = raw.cache_creation_input_tokens;\n const split = ttlSplitTotal(raw);\n if (declared === undefined) {\n // Only the TTL split was attached. Deriving the total is the whole point of\n // accepting the sub-object: the tokens were reported, just itemized.\n return split ?? 0;\n }\n if (split !== undefined && split !== declared) {\n warnings.push(\n `usage.cache_creation TTL buckets sum to ${String(split)} but ` +\n `usage.cache_creation_input_tokens reports ${String(declared)}; the explicit counter is used and the ` +\n `buckets are never added to it`,\n );\n }\n return declared;\n};\n\n/**\n * Reconcile `usage.iterations[]` against the outer counters without adding it.\n *\n * A multi-request turn itemizes the same tokens per model request, and the\n * per-iteration figures summed to the outer ones exactly in every capture. Adding\n * a breakdown to its own total is the archetypal double-count — it would double\n * every counter of every turn — so the sums are *checked* and a disagreement is\n * reported, which is the only reading under which either number could be wrong.\n */\nconst auditIterations = (\n raw: ClaudeUsage,\n cacheCreationInputTokens: number,\n warnings: string[],\n): void => {\n const iterations = raw.iterations;\n if (iterations === undefined || iterations.length === 0) {\n return;\n }\n const outer: Readonly<Record<(typeof ITERATION_COUNTERS)[number], number>> = {\n input_tokens: raw.input_tokens,\n output_tokens: raw.output_tokens,\n cache_read_input_tokens: raw.cache_read_input_tokens ?? 0,\n cache_creation_input_tokens: cacheCreationInputTokens,\n };\n for (const counter of ITERATION_COUNTERS) {\n const summed = iterations.reduce((total, iteration) => total + (iteration[counter] ?? 0), 0);\n if (summed !== outer[counter]) {\n warnings.push(\n `usage.iterations[].${counter} sums to ${String(summed)} but usage.${counter} reports ` +\n `${String(outer[counter])}; the outer counter is used and per-iteration figures are never added to it`,\n );\n }\n }\n};\n\nconst auditExcludedCounters = (raw: ClaudeUsage, warnings: string[]): void => {\n if (raw.total_tokens !== undefined) {\n warnings.push(CLAUDE_EXCLUDED_USAGE_COUNTERS.total_tokens);\n }\n if (raw.reasoning_output_tokens !== undefined) {\n warnings.push(CLAUDE_EXCLUDED_USAGE_COUNTERS.reasoning_output_tokens);\n }\n};\n\n/**\n * `normalizeUsage` notes when a caller declared a cache-creation accounting mode\n * on a snapshot with zero cache-creation tokens. That note is aimed at a caller\n * choosing the mode per observation; this adapter's mode is a fixed property of\n * the provider, so on any turn that wrote nothing to cache the note restates the\n * design rather than reporting anything. It would fire on most turns and bury the\n * warnings that do mean something, so it is dropped here — by prefix, so a note\n * this adapter has not considered still reaches the caller.\n */\nconst ACCOUNTING_RETAINED_NOTE_PREFIX = \"cacheCreationAccounting=\";\n\nconst forwardableNotes = (notes: readonly string[]): readonly string[] =>\n notes.filter((note) => !note.startsWith(ACCOUNTING_RETAINED_NOTE_PREFIX));\n\n/**\n * Normalize Anthropic's on-wire usage shape into canonical usage.\n *\n * `input_tokens` is the *fresh* portion of the prompt only: cache reads and cache\n * writes are separate, additive buckets. Confirmed against real captures rather\n * than assumed — across 4,999 usage objects `input_tokens` stayed within\n * 1..5,656 while `cache_read_input_tokens` reached 713,543\n * (docs/claude-code-usage-contract.md, finding 2). The canonical model instead\n * wants an inclusive `inputTokens`, so this folds all three into one total and\n * marks cache creation `included-in-input` — `uncachedInputTokens` then falls out\n * to exactly Anthropic's own `input_tokens`.\n *\n * The fold is what makes the canonical buckets **non-overlapping by\n * construction**: each subset is one of the addends of the total it is a subset\n * of, so no subset can exceed its total and no bucket is counted twice. That\n * holds structurally, not by a range check a provider change could invalidate.\n * The two places tokens are *itemized* rather than reported — the cache-creation\n * TTL split and `iterations[]` — are reconciled against the totals and never\n * added, which is where a double-count would otherwise come from within a single\n * callback. Double-counting *across* callbacks is the delivery layer's job; see\n * `delivery.ts`.\n *\n * Each usage snapshot corresponds to a single turn, subagent invocation, or\n * compaction — never a running session total — so it is always reported as a\n * `delta` observation.\n */\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\nconst asNonNegativeInt = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isInteger(value) && value >= 0 ? value : undefined;\n\n/**\n * Coerce one usage-shaped object onto {@link claudeUsageSchema}.\n *\n * Accepts the Anthropic Messages API snake_case counters and the camelCase\n * aliases a print/`-p` result or wrapping harness may use. Both `input_tokens`\n * and `output_tokens` must be present — a lone counter is not a usage object,\n * and inventing the missing side as zero would report tokens the provider\n * never sent.\n */\nexport const coerceClaudeUsage = (value: unknown): ClaudeUsage | undefined => {\n const record = asRecord(value);\n if (record === undefined) {\n return undefined;\n }\n const inputTokens = asNonNegativeInt(record.input_tokens ?? record.inputTokens);\n const outputTokens = asNonNegativeInt(record.output_tokens ?? record.outputTokens);\n if (inputTokens === undefined || outputTokens === undefined) {\n return undefined;\n }\n const cacheCreation = asRecord(record.cache_creation ?? record.cacheCreation);\n const parsed = claudeUsageSchema.safeParse({\n input_tokens: inputTokens,\n output_tokens: outputTokens,\n ...(asNonNegativeInt(record.cache_creation_input_tokens ?? record.cacheCreationInputTokens) ===\n undefined\n ? {}\n : {\n cache_creation_input_tokens: asNonNegativeInt(\n record.cache_creation_input_tokens ?? record.cacheCreationInputTokens,\n ),\n }),\n ...(asNonNegativeInt(record.cache_read_input_tokens ?? record.cacheReadInputTokens) === undefined\n ? {}\n : {\n cache_read_input_tokens: asNonNegativeInt(\n record.cache_read_input_tokens ?? record.cacheReadInputTokens,\n ),\n }),\n ...(cacheCreation === undefined\n ? {}\n : {\n cache_creation: {\n ...(asNonNegativeInt(\n cacheCreation.ephemeral_5m_input_tokens ?? cacheCreation.ephemeral5mInputTokens,\n ) === undefined\n ? {}\n : {\n ephemeral_5m_input_tokens: asNonNegativeInt(\n cacheCreation.ephemeral_5m_input_tokens ?? cacheCreation.ephemeral5mInputTokens,\n ),\n }),\n ...(asNonNegativeInt(\n cacheCreation.ephemeral_1h_input_tokens ?? cacheCreation.ephemeral1hInputTokens,\n ) === undefined\n ? {}\n : {\n ephemeral_1h_input_tokens: asNonNegativeInt(\n cacheCreation.ephemeral_1h_input_tokens ?? cacheCreation.ephemeral1hInputTokens,\n ),\n }),\n },\n }),\n ...(Array.isArray(record.iterations) ? { iterations: record.iterations } : {}),\n ...(asNonNegativeInt(record.total_tokens ?? record.totalTokens) === undefined\n ? {}\n : { total_tokens: asNonNegativeInt(record.total_tokens ?? record.totalTokens) }),\n ...(asNonNegativeInt(record.reasoning_output_tokens ?? record.reasoningOutputTokens) ===\n undefined\n ? {}\n : {\n reasoning_output_tokens: asNonNegativeInt(\n record.reasoning_output_tokens ?? record.reasoningOutputTokens,\n ),\n }),\n });\n return parsed.success ? parsed.data : undefined;\n};\n\n/**\n * Find a usage object on a Stop / print-result / SessionEnd payload.\n *\n * Looks at `usage`, `token_usage`, `message.usage`, and top-level token\n * counters. The first object that coerces to {@link ClaudeUsage} wins. Absence\n * is reported as `undefined` — never as a zeroed snapshot.\n */\nexport const extractClaudeUsage = (payload: unknown): ClaudeUsage | undefined => {\n const record = asRecord(payload);\n if (record === undefined) {\n return undefined;\n }\n const message = asRecord(record.message);\n const candidates: readonly unknown[] = [\n record.usage,\n record.token_usage,\n record.tokenUsage,\n message?.usage,\n record,\n ];\n for (const candidate of candidates) {\n const usage = coerceClaudeUsage(candidate);\n if (usage !== undefined) {\n return usage;\n }\n }\n return undefined;\n};\n\nexport const normalizeClaudeUsage = (raw: ClaudeUsage | undefined): ClaudeUsageNormalization => {\n if (raw === undefined) {\n return { warnings: [] };\n }\n\n const warnings: string[] = [];\n const cachedInputTokens = raw.cache_read_input_tokens ?? 0;\n const cacheCreationInputTokens = resolveCacheCreationTokens(raw, warnings);\n auditIterations(raw, cacheCreationInputTokens, warnings);\n auditExcludedCounters(raw, warnings);\n\n const result = normalizeUsage({\n temporality: \"delta\",\n inputTokens: raw.input_tokens + cachedInputTokens + cacheCreationInputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: \"included-in-input\",\n outputTokens: raw.output_tokens,\n });\n\n if (result.status === \"invalid\") {\n return { warnings: [...warnings, ...result.issues.map((issue) => issue.message)] };\n }\n return { usage: result.usage, warnings: [...warnings, ...forwardableNotes(result.notes)] };\n};\n","import { coerceClaudeUsage } from \"./usage.js\";\n\n/**\n * Fold Claude Code hook and print/`-p` payload aliases onto the snake_case\n * shapes {@link claudeHookPayloadSchema} already accepts.\n *\n * Interactive Stop payloads document `last_assistant_message`. Print / `-p` /\n * Agent SDK result messages use `type: \"result\"` and `result` instead, and some\n * wrappers emit camelCase field names. None of these are invented: each alias\n * is a name Claude Code or its published result JSON has actually used. An\n * unrecognized shape is returned unchanged so detection can decline it.\n */\n\nconst FIELD_ALIASES = Object.freeze({\n hookEventName: \"hook_event_name\",\n sessionId: \"session_id\",\n lastAssistantMessage: \"last_assistant_message\",\n transcriptPath: \"transcript_path\",\n promptId: \"prompt_id\",\n toolUseId: \"tool_use_id\",\n toolName: \"tool_name\",\n toolInput: \"tool_input\",\n toolResponse: \"tool_response\",\n toolError: \"tool_error\",\n stopHookActive: \"stop_hook_active\",\n agentId: \"agent_id\",\n agentType: \"agent_type\",\n errorType: \"error_type\",\n errorMessage: \"error_message\",\n tokenUsage: \"token_usage\",\n} as const);\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\n/**\n * Copy documented camelCase aliases onto their snake_case names when the\n * snake_case field is absent. Existing snake_case values win, so a payload that\n * carries both is not rewritten.\n */\nconst applyFieldAliases = (record: Record<string, unknown>): Record<string, unknown> => {\n const normalized: Record<string, unknown> = { ...record };\n for (const [alias, canonical] of Object.entries(FIELD_ALIASES)) {\n if (normalized[canonical] === undefined && normalized[alias] !== undefined) {\n normalized[canonical] = normalized[alias];\n }\n }\n return normalized;\n};\n\n/**\n * Claude Code print / `-p` / Agent SDK result messages are not hook events, but\n * they are the stop/result payload a non-interactive session actually produces.\n * When one arrives with a session id and no `hook_event_name`, treat it as the\n * Stop (or StopFailure) the interactive protocol would have fired.\n */\nconst applyPrintResultShape = (record: Record<string, unknown>): Record<string, unknown> => {\n if (record.hook_event_name !== undefined || record.type !== \"result\") {\n return record;\n }\n if (typeof record.session_id !== \"string\" || record.session_id.length === 0) {\n return record;\n }\n\n const isError = record.subtype === \"error\" || record.is_error === true;\n const normalized: Record<string, unknown> = {\n ...record,\n hook_event_name: isError ? \"StopFailure\" : \"Stop\",\n };\n if (\n normalized.last_assistant_message === undefined &&\n typeof record.result === \"string\" &&\n record.result.length > 0\n ) {\n normalized.last_assistant_message = record.result;\n }\n if (isError && (typeof normalized.error_type !== \"string\" || normalized.error_type.length === 0)) {\n normalized.error_type = \"unknown\";\n }\n return normalized;\n};\n\n/**\n * Return a Claude-shaped payload with documented aliases folded onto canonical\n * field names, or the original value when it is not an object.\n */\nexport const normalizeClaudeHookPayload = (payload: unknown): unknown => {\n const record = asRecord(payload);\n if (record === undefined) {\n return payload;\n }\n return applyUsageShape(applyPrintResultShape(applyFieldAliases(record)));\n};\n\n/**\n * Coerce `usage` / `token_usage` onto the Anthropic snake_case object the\n * Stop schema accepts, so a camelCase print-result usage object is not\n * rejected as an invalid `usage` field.\n */\nconst applyUsageShape = (record: Record<string, unknown>): Record<string, unknown> => {\n const usage =\n coerceClaudeUsage(record.usage) ??\n coerceClaudeUsage(record.token_usage) ??\n coerceClaudeUsage(record.tokenUsage);\n if (usage === undefined) {\n return record;\n }\n return { ...record, usage };\n};\n","import {\n asProviderId,\n providerDetectionSchema,\n type ProviderDetection,\n type ProviderDetectionInput,\n} from \"../adapter.js\";\nimport { normalizeClaudeHookPayload } from \"./payload-normalize.js\";\nimport { CLAUDE_HOOK_EVENT_NAMES } from \"./schema.js\";\n\n/** Stable, hyphenated provider id for Claude Code. */\nexport const CLAUDE_CODE_PROVIDER_ID = asProviderId(\"claude-code\");\n\nconst KNOWN_EVENT_NAMES: ReadonlySet<string> = new Set(CLAUDE_HOOK_EVENT_NAMES);\n\nconst none = (reason: string): ProviderDetection =>\n providerDetectionSchema.parse({\n providerId: \"unknown\",\n confidence: \"none\",\n reasons: [reason],\n });\n\n/**\n * Recognize a Claude Code hook payload.\n *\n * Confidence is never `exact` from shape alone: Claude Code hook JSON has no\n * self-identifying `provider` field, so `hook_event_name` plus `session_id`\n * is the strongest evidence a shape check can offer. A caller-supplied\n * `providerHint` naming this adapter is treated as the stronger claim.\n */\nexport const detectClaudeCode = (input: ProviderDetectionInput): ProviderDetection => {\n const payload = normalizeClaudeHookPayload(input.payload);\n if (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) {\n return none(\"payload is not a JSON object\");\n }\n\n const record = payload as Record<string, unknown>;\n const hookEventName = record.hook_event_name;\n if (typeof hookEventName !== \"string\" || !KNOWN_EVENT_NAMES.has(hookEventName)) {\n return none(\"hook_event_name is missing or not a recognized Claude Code hook event\");\n }\n\n const sessionId = record.session_id;\n if (typeof sessionId !== \"string\" || sessionId.length === 0) {\n return none(\"session_id is missing\");\n }\n\n const hasTranscriptPath =\n typeof record.transcript_path === \"string\" && record.transcript_path.length > 0;\n const isPrintResult = record.type === \"result\";\n const hinted = input.providerHint === CLAUDE_CODE_PROVIDER_ID;\n\n return providerDetectionSchema.parse({\n providerId: CLAUDE_CODE_PROVIDER_ID,\n confidence: hinted ? \"exact\" : hasTranscriptPath || isPrintResult ? \"strong\" : \"weak\",\n reasons: [\n `hook_event_name=${hookEventName} matches the Claude Code hooks protocol`,\n \"session_id present\",\n ...(hasTranscriptPath ? [\"transcript_path present\"] : []),\n ...(isPrintResult ? [\"type=result print/SDK result message\"] : []),\n ...(hinted ? [\"caller asserted providerHint=claude-code\"] : []),\n ],\n sourceEventName: hookEventName,\n });\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, ModelDescriptor } 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 PayloadEnricher,\n ReadCursor,\n SessionContextReader,\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\";\nimport { stampSessionContext } from \"./session-context.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 * Host-configured payload enrichers (see {@link PayloadEnricher}). Empty by\n * default: nothing reads beyond the payload unless a host asks for it.\n */\n readonly payloadEnrichers?: readonly PayloadEnricher[];\n /**\n * Reads the session context a harness wrote (`docs/session-context.md`). Absent\n * means none: no event carries `contextAttributes`. The filesystem\n * implementation is `createDirectorySessionContextReader`.\n */\n readonly sessionContext?: SessionContextReader;\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 sessionModelKey = (sessionId: string): string => `model:${sessionId}`;\nconst readCursorKey = (enricherId: string, sessionId: string): string =>\n `cursor:${enricherId}:${sessionId}`;\n\n/**\n * The placeholder an adapter uses when its payload names no model. Never\n * remembered: storing it would overwrite a real model the session reported.\n */\nconst UNKNOWN_MODEL_ID = \"unknown\";\n\n/**\n * The last model a batch reports for the top-level agent, if any.\n *\n * `session.start` and `generation.*` edges count; a subagent's events do not,\n * because a subagent can run on a different model than the session it serves and\n * must not rename the session's own generations. The last such event wins, so a\n * turn that reports a model switch updates what the session remembers.\n */\nconst latestSessionModel = (events: readonly CanonicalEvent[]): ModelDescriptor | undefined => {\n let latest: ModelDescriptor | undefined;\n for (const event of events) {\n if (event.subagentId !== undefined) {\n continue;\n }\n if (\n (event.type === \"session.start\" || event.type === \"generation.start\" || event.type === \"generation.end\") &&\n event.model !== undefined &&\n event.model.modelId !== UNKNOWN_MODEL_ID\n ) {\n latest = event.model;\n }\n }\n return latest;\n};\n\nconst sameModel = (left: ModelDescriptor | undefined, right: ModelDescriptor): boolean =>\n left !== undefined &&\n left.modelId === right.modelId &&\n left.vendor === right.vendor &&\n left.family === right.family;\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 * Run the configured enrichers for this provider over the payload.\n *\n * Inside the session lock, so a cursor is read, advanced, and written by one\n * process at a time. Every failure is contained: a throwing enricher or an\n * unusable store leaves the payload as it was, and a cursor write that fails\n * is a diagnostic — the next read then starts from the old cursor, which can\n * count a turn into the next one but never twice.\n */\n const enrichPayload = async (\n payload: unknown,\n providerId: string,\n sessionId: string,\n diagnostics: OtelHookErrorInfo[],\n ): Promise<unknown> => {\n let current = payload;\n for (const enricher of deps.payloadEnrichers ?? []) {\n if (enricher.providerId !== providerId) {\n continue;\n }\n const key = readCursorKey(enricher.id, sessionId);\n let cursor: ReadCursor | undefined;\n try {\n const record = await deps.stateStore.read(key);\n if (record?.value.kind === \"read-cursor\") {\n cursor = { source: record.value.source, offset: record.value.offset };\n }\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, { code: \"state-store-failure\", phase: \"state\", occurredAt: clock.now() }),\n );\n // Without the stored cursor a read would start from the wrong place.\n continue;\n }\n let result;\n try {\n result = await enricher.enrich({ payload: current, sessionId, ...(cursor === undefined ? {} : { cursor }) });\n } catch (thrown) {\n logger.warn(\"payload enricher failed; parsing the payload as delivered\", {\n \"enricher.id\": enricher.id,\n \"error.name\": thrown instanceof Error ? thrown.name : typeof thrown,\n });\n continue;\n }\n current = result.payload;\n if (result.notes !== undefined && result.notes.length > 0) {\n logger.debug(\"payload enricher notes\", {\n \"enricher.id\": enricher.id,\n \"enricher.notes\": result.notes.slice(0, 8).map((note) => note.slice(0, 200)),\n });\n }\n const next = result.cursor;\n if (next !== undefined && (next.source !== cursor?.source || next.offset !== cursor.offset)) {\n try {\n await deps.stateStore.write(key, { kind: \"read-cursor\", source: next.source, offset: next.offset });\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, { code: \"state-store-failure\", phase: \"state\", occurredAt: clock.now() }),\n );\n }\n }\n }\n return current;\n };\n\n /**\n * The model this session last reported, or `undefined`.\n *\n * Fails open: an unreadable store costs the model name, never the observation,\n * so a read failure is a diagnostic and the adapter falls back to `unknown`.\n */\n const readSessionModel = async (\n sessionId: string,\n diagnostics: OtelHookErrorInfo[],\n ): Promise<ModelDescriptor | undefined> => {\n try {\n const record = await deps.stateStore.read(sessionModelKey(sessionId));\n return record?.value.kind === \"session-model\" ? record.value.model : undefined;\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, { code: \"state-store-failure\", phase: \"state\", occurredAt: clock.now() }),\n );\n return undefined;\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 const sessionModel = await readSessionModel(identity.sessionId, diagnostics);\n const payload = suppress\n ? detectionInput.payload\n : await enrichPayload(detectionInput.payload, detection.providerId, identity.sessionId, diagnostics);\n\n let parsed;\n try {\n parsed = adapter.parse(\n {\n ...detectionInput,\n payload,\n detection,\n identity,\n sequenceBase,\n ...(sessionModel === undefined ? {} : { sessionModel }),\n },\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 // Remember the session's model for the invocations whose payload names\n // none. Written only when it changed, so a session costs one record and\n // a steady session no extra writes; never written for a redelivery,\n // which is not a new observation.\n const reportedModel = latestSessionModel(screened.kept);\n if (reportedModel !== undefined && !sameModel(sessionModel, reportedModel)) {\n try {\n await deps.stateStore.write(sessionModelKey(identity.sessionId), {\n kind: \"session-model\",\n model: reportedModel,\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\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 // Session context: a core step, never adapter code (ADR 0003), outside the\n // session lock like target resolution. One bounded read of the file for this\n // invocation's session — for a subagent event that is its parent's session,\n // because events carry the invocation's session id, never the subagent's.\n // Always run, so an event can only ever carry the core's stamp.\n batch = stampSessionContext(\n batch,\n !suppress && batch.length > 0 && deps.sessionContext !== undefined\n ? await readSessionContext(deps.sessionContext, detection.providerId, identity.sessionId)\n : undefined,\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\n/** Fail-open wrapper: a reader that throws despite its contract stamps nothing. */\nconst readSessionContext = async (\n reader: SessionContextReader,\n providerId: string,\n sessionId: string,\n): Promise<Awaited<ReturnType<SessionContextReader[\"read\"]>>> => {\n try {\n return await reader.read({ providerId, sessionId });\n } catch {\n return undefined;\n }\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 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 { modelDescriptorSchema, 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 type { WorktreeKind } from \"../model/target.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 /**\n * The model a session last reported, so a later invocation whose payload names\n * none (Claude Code's `Stop`) can still say which model it was. A model id is\n * not sensitive (`modelDescriptorSchema`), and the descriptor is the strict,\n * bounded canonical shape, never a payload fragment.\n */\n z.strictObject({\n kind: z.literal(\"session-model\"),\n model: modelDescriptorSchema,\n }),\n /**\n * How far a {@link PayloadEnricher} has read a session's append-only source\n * (Claude Code's transcript), so the next read starts where the last ended.\n * `source` is an opaque digest of what was read, never a path.\n */\n /**\n * Running state of one metric series (issue #69), so a cumulative data point\n * exported by a later hook process continues the same total. Holds numbers and\n * a series digest only; the series' attributes are re-supplied by the caller\n * and never read back from disk.\n */\n z.strictObject({\n kind: z.literal(\"metric-series\"),\n /** Start of the cumulative interval. */\n startTimeMillis: epochMillisSchema,\n /** Counters: the running total. */\n value: z.number().finite().min(0).optional(),\n /** Histograms: the running aggregation. */\n histogram: z\n .strictObject({\n count: z.number().int().min(0),\n sum: z.number().finite().min(0),\n min: z.number().finite(),\n max: z.number().finite(),\n bucketCounts: z.array(z.number().int().min(0)).max(64),\n })\n .optional(),\n /** Opaque digest of the last delivery folded in; makes a replay a no-op. */\n appliedDelivery: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional(),\n }),\n z.strictObject({\n kind: z.literal(\"read-cursor\"),\n source: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/),\n offset: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),\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 /** Main checkout or linked worktree; absent when the locator does not tell. */\n readonly kind?: WorktreeKind;\n /**\n * Absolute path of the repository's main worktree — `root` itself for a main\n * worktree. Absent when there is none to name: a bare repository, a main\n * checkout that is gone, or a layout the locator cannot read.\n */\n readonly mainRoot?: 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\n/** Where an enricher stopped reading a session's source; see the `read-cursor` state value. */\nexport type ReadCursor = {\n /** Opaque digest naming the source, so a cursor never applies to another file. */\n readonly source: string;\n /** Byte offset the next read starts at. */\n readonly offset: number;\n};\n\nexport type PayloadEnrichmentInput = {\n readonly payload: unknown;\n readonly sessionId: string;\n /** The cursor this enricher stored for this session last time, if any. */\n readonly cursor?: ReadCursor;\n};\n\nexport type PayloadEnrichment = {\n /** The payload the adapter parses: the input, or a copy with fields attached. */\n readonly payload: unknown;\n /** A cursor to store for this session; absent leaves the stored one as it is. */\n readonly cursor?: ReadCursor;\n /** Short, non-sensitive notes for the debug log (why a read fell back, ...). */\n readonly notes?: readonly string[];\n};\n\n/**\n * Host-side step that attaches facts to a provider payload before its adapter\n * parses it — for facts the provider writes somewhere other than the hook\n * payload, such as Claude Code's transcript.\n *\n * Not an adapter capability, on purpose: adapters get no filesystem handle (ADR\n * 0003). An enricher is configured by the host, runs inside the session lock so\n * its cursor is read and written atomically, and must be bounded and never throw\n * (a throw is contained and the original payload is parsed). It never runs for a\n * redelivered callback, which is not a new observation.\n */\nexport interface PayloadEnricher {\n /** Stable id; namespaces the enricher's cursor in the state store. */\n readonly id: string;\n /** The provider whose payloads it enriches. Others are never passed to it. */\n readonly providerId: string;\n enrich(input: PayloadEnrichmentInput): Promise<PayloadEnrichment>;\n}\n\n/**\n * One window of a session's context: the attributes in force from `from`\n * (inclusive) until `to` (exclusive), or open-ended when `to` is `null`.\n * Attributes are already screened (see `sanitizeSessionContextAttributes`).\n */\nexport type SessionContextSegment = {\n readonly from: EpochMillis;\n readonly to: EpochMillis | null;\n readonly attributes: Readonly<Record<string, string | number | boolean>>;\n};\n\nexport type SessionContextRequest = {\n /** The detected provider, e.g. `claude-code`. The reader maps it to its directory name. */\n readonly providerId: string;\n /**\n * The session whose context applies: always the invocation's session, which\n * for a subagent event is its parent's — never the subagent's own id.\n */\n readonly sessionId: string;\n};\n\n/**\n * Reads the session context a harness wrote for one agent session.\n *\n * A port for the same reason {@link WorktreeLocator} is one: the core decides\n * when to ask and what of the answer reaches a record; the implementation only\n * reads. Adapters never see it (ADR 0003). Implementations must never throw or\n * reject: no file, an unreadable file, an invalid one, or one of an unknown\n * version are all `undefined`, and the core then stamps nothing.\n */\nexport interface SessionContextReader {\n read(request: SessionContextRequest): Promise<readonly SessionContextSegment[] | 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 { isTargetedEvent, 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, branch, and repository through the injected {@link WorktreeLocator};\n * only salted `git-root` handles of the root and of its repository's main\n * worktree, the worktree's kind, 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 // The repository is named by its main worktree, as that worktree would name\n // itself — so a main worktree's repository id is its own workspace id.\n const repository =\n first.mainRoot === undefined\n ? undefined\n : deriveWorkspaceIdentity(privacy, { kind: \"git-root\", absolutePath: first.mainRoot });\n const parsed = workspaceTargetSchema.safeParse({\n workspaceId: identity.workspaceId,\n ...(identity.vcsBranchName === undefined ? {} : { vcsBranchName: identity.vcsBranchName }),\n source: hint.source,\n ...(repository?.keySource === \"git-root\" ? { repositoryId: repository.workspaceId } : {}),\n ...(first.kind === undefined ? {} : { worktreeKind: first.kind }),\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 targeted event (`TARGETED_EVENT_TYPES`) 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((event) => isTargetedEvent(event) && input.hints.has(event.eventId));\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 || !isTargetedEvent(event)) {\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 } from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport { z } from \"zod\";\n\nimport {\n checkResourceAttributeKey,\n MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH,\n MAX_RESOURCE_ATTRIBUTES,\n} from \"../config/resource-attributes.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { SessionContextReader, SessionContextSegment } from \"./ports.js\";\n\n/**\n * Session context: attributes a harness wants on every record of one agent\n * session, for a window of time.\n *\n * A harness (HAR, or anything else) writes one JSON file per agent session:\n *\n * ```text\n * <dir>/<agent-tool>/<session-id>.json\n * { \"version\": 1, \"agentTool\": \"claude_code\", \"sessionId\": \"…\",\n * \"segments\": [ { \"from\": \"<ISO-8601>\", \"to\": \"<ISO-8601>\" | null,\n * \"reason\": \"launch\", \"attributes\": { \"k\": \"v\" } } ] }\n * ```\n *\n * On every hook event the core reads the one file for the event's session,\n * picks the segment in force at each event's time, and stamps its attributes on\n * every record the event produces. otel-hook knows nothing about what the\n * attributes mean: it applies an attribute map. See `docs/session-context.md`.\n *\n * Fail-open throughout: a missing, unreadable, oversized, invalid, or\n * wrong-version file — or no segment in force — stamps nothing and never fails\n * the hook.\n */\n\n/** The only file format version this build reads. Any other is ignored whole. */\nexport const SESSION_CONTEXT_FILE_VERSION = 1 as const;\n\n/** Largest file read; anything bigger is ignored rather than truncated. */\nexport const DEFAULT_SESSION_CONTEXT_MAX_BYTES = 256 * 1024;\n\n/** Ceiling on one read; a slow filesystem costs the stamp, never the hook. */\nexport const DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS = 100;\n\n/** Upper bound on segments considered in one file. */\nexport const MAX_SESSION_CONTEXT_SEGMENTS = 1024;\n\n/**\n * otel-hook provider id → the agent-tool directory a harness writes under.\n *\n * The names are the ones HAR derives from the agent process it finds\n * (`claude_code`, `codex`, `cursor`). A provider absent from this table has no\n * session context: nothing is read for it.\n */\nexport const SESSION_CONTEXT_AGENT_TOOLS: Readonly<Record<string, string>> = Object.freeze({\n \"claude-code\": \"claude_code\",\n codex: \"codex\",\n cursor: \"cursor\",\n \"gemini-cli\": \"gemini_cli\",\n antigravity: \"antigravity\",\n});\n\nexport const sessionContextAgentTool = (providerId: string): string | undefined =>\n Object.hasOwn(SESSION_CONTEXT_AGENT_TOOLS, providerId) ? SESSION_CONTEXT_AGENT_TOOLS[providerId] : undefined;\n\n/**\n * A session id is used as a file name, so it must be one: no separators, no\n * `.`/`..`, nothing a path could be steered with. Real session ids (UUIDs) pass.\n */\nconst SESSION_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;\n\nexport const isSessionContextFileName = (sessionId: string): boolean =>\n SESSION_FILE_NAME_PATTERN.test(sessionId) && !sessionId.includes(\"..\");\n\n/**\n * Where the context of one session lives, or `undefined` when the provider has\n * no agent-tool directory or the session id cannot be a file name.\n */\nexport const sessionContextFilePath = (\n dir: string,\n providerId: string,\n sessionId: string,\n): string | undefined => {\n const tool = sessionContextAgentTool(providerId);\n if (tool === undefined || !isSessionContextFileName(sessionId) || !path.isAbsolute(dir)) {\n return undefined;\n }\n return path.join(dir, tool, `${sessionId}.json`);\n};\n\n/**\n * Keys a context may never set, whatever it says.\n *\n * - `factory.local.*`: the Factory Commits telemetry profile defines it as\n * local-only (paths and the like); it must never reach a record.\n * - otel-hook's own record identity (`session.id`, `otelhook.*`, the hex trace\n * ids, `gen_ai.conversation.id`): a context file describes the work a session\n * does, it does not get to rename the session or forge its trace.\n * - Everything `checkResourceAttributeKey` refuses: malformed keys, the\n * `service.*` exporter policy keys, and secret-like names.\n */\nconst RESERVED_CONTEXT_KEYS: ReadonlySet<string> = new Set([\n \"session.id\",\n \"trace_id\",\n \"span_id\",\n \"parent_span_id\",\n \"gen_ai.conversation.id\",\n \"factory.local\",\n]);\nconst RESERVED_CONTEXT_PREFIXES: readonly string[] = Object.freeze([\"factory.local.\", \"otelhook.\"]);\n\nexport const isReservedSessionContextKey = (key: string): boolean =>\n RESERVED_CONTEXT_KEYS.has(key) || RESERVED_CONTEXT_PREFIXES.some((prefix) => key.startsWith(prefix));\n\n/**\n * Screen one segment's attribute map: primitive values only, bounded, and no\n * reserved or unsafe key. Dropped entries are dropped silently, one by one; the\n * rest of the map still applies.\n */\nexport const sanitizeSessionContextAttributes = (\n attributes: Readonly<Record<string, unknown>>,\n): Readonly<Record<string, string | number | boolean>> => {\n const kept: Record<string, string | number | boolean> = {};\n let count = 0;\n for (const [key, value] of Object.entries(attributes)) {\n if (count >= MAX_RESOURCE_ATTRIBUTES) {\n break;\n }\n if (checkResourceAttributeKey(key) !== undefined || isReservedSessionContextKey(key)) {\n continue;\n }\n if (typeof value === \"string\") {\n if (value.length > MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) {\n continue;\n }\n } else if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n continue;\n }\n } else if (typeof value !== \"boolean\") {\n continue;\n }\n kept[key] = value;\n count += 1;\n }\n return kept;\n};\n\nconst ISO_INSTANT_PATTERN =\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?(?:Z|[+-]\\d{2}:\\d{2})$/;\n\nconst isoInstantSchema = z\n .string()\n .max(64)\n .regex(ISO_INSTANT_PATTERN)\n .transform((value, ctx) => {\n const millis = Date.parse(value);\n if (!Number.isFinite(millis)) {\n ctx.issues.push({ code: \"custom\", input: value, message: \"not a valid instant\" });\n return z.NEVER;\n }\n return millis;\n });\n\nconst segmentSchema = z.object({\n from: isoInstantSchema,\n to: isoInstantSchema.nullable(),\n reason: z.string().max(256).optional(),\n attributes: z.record(z.string(), z.unknown()),\n});\n\n/**\n * The file format. Unknown extra fields are tolerated (a later minor revision\n * may add some); a different `version` is not, because its fields may mean\n * something else.\n */\nconst sessionContextFileSchema = z.object({\n version: z.literal(SESSION_CONTEXT_FILE_VERSION),\n agentTool: z.string().max(64).optional(),\n sessionId: z.string().max(256).optional(),\n segments: z.array(segmentSchema).max(MAX_SESSION_CONTEXT_SEGMENTS),\n});\n\n/**\n * Parse a decoded context file into screened segments.\n *\n * `expected` guards against a file that names another session or tool than the\n * one it was read for (a copy, a misplaced write): such a file applies to\n * nobody. Returns `undefined` for anything invalid; never throws.\n */\nexport const parseSessionContextFile = (\n value: unknown,\n expected?: { readonly agentTool?: string; readonly sessionId?: string },\n): readonly SessionContextSegment[] | undefined => {\n const parsed = sessionContextFileSchema.safeParse(value);\n if (!parsed.success) {\n return undefined;\n }\n const file = parsed.data;\n if (\n (expected?.agentTool !== undefined && file.agentTool !== undefined && file.agentTool !== expected.agentTool) ||\n (expected?.sessionId !== undefined && file.sessionId !== undefined && file.sessionId !== expected.sessionId)\n ) {\n return undefined;\n }\n return file.segments.map((segment) => ({\n from: segment.from,\n to: segment.to,\n attributes: sanitizeSessionContextAttributes(segment.attributes),\n }));\n};\n\n/**\n * The segment in force at `at`: `from <= at` and (`to` is null or `at < to`).\n * Should a writer ever leave two overlapping, the one that started last wins,\n * because it is the more recent statement.\n */\nexport const segmentInForce = (\n segments: readonly SessionContextSegment[],\n at: number,\n): SessionContextSegment | undefined => {\n let best: SessionContextSegment | undefined;\n for (const segment of segments) {\n if (segment.from <= at && (segment.to === null || at < segment.to)) {\n if (best === undefined || segment.from >= best.from) {\n best = segment;\n }\n }\n }\n return best;\n};\n\n/**\n * Stamp each event with the attributes of the segment in force at its own\n * `occurredAt`, and strip any `contextAttributes` an event already carried: only\n * this core step may set them. An event with no segment in force, or one whose\n * segment has no usable attribute, carries none.\n */\nexport const stampSessionContext = (\n events: readonly CanonicalEvent[],\n segments: readonly SessionContextSegment[] | undefined,\n): readonly CanonicalEvent[] =>\n events.map((event) => {\n const { contextAttributes: _discarded, ...rest } = event;\n const segment = segments === undefined ? undefined : segmentInForce(segments, event.occurredAt);\n if (segment === undefined || Object.keys(segment.attributes).length === 0) {\n return _discarded === undefined ? event : (rest);\n }\n return { ...rest, contextAttributes: { ...segment.attributes } };\n });\n\nexport type DirectorySessionContextReaderOptions = {\n /** Absolute directory holding `<agent-tool>/<session-id>.json`. */\n readonly dir: string;\n readonly maxBytes?: number;\n readonly budgetMillis?: number;\n};\n\nconst readBounded = async (file: string, maxBytes: number): Promise<string | undefined> => {\n let handle;\n try {\n handle = await open(file, \"r\");\n } catch {\n return undefined;\n }\n try {\n const stats = await handle.stat();\n if (!stats.isFile() || stats.size > maxBytes) {\n return undefined;\n }\n const buffer = Buffer.alloc(maxBytes + 1);\n let length = 0;\n while (length < buffer.length) {\n const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);\n if (bytesRead === 0) {\n break;\n }\n length += bytesRead;\n }\n if (length > maxBytes) {\n return undefined;\n }\n return buffer.subarray(0, length).toString(\"utf8\");\n } catch {\n return undefined;\n } finally {\n await handle.close().catch(() => undefined);\n }\n};\n\n/**\n * The filesystem {@link SessionContextReader}: one bounded read of one file per\n * call, never a directory scan. Never throws.\n */\nexport const createDirectorySessionContextReader = (\n options: DirectorySessionContextReaderOptions,\n): SessionContextReader => {\n const maxBytes = options.maxBytes ?? DEFAULT_SESSION_CONTEXT_MAX_BYTES;\n const budgetMillis = options.budgetMillis ?? DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS;\n\n const readOnce = async (\n providerId: string,\n sessionId: string,\n ): Promise<readonly SessionContextSegment[] | undefined> => {\n const file = sessionContextFilePath(options.dir, providerId, sessionId);\n if (file === undefined) {\n return undefined;\n }\n const text = await readBounded(file, maxBytes);\n if (text === undefined) {\n return undefined;\n }\n let decoded: unknown;\n try {\n decoded = JSON.parse(text);\n } catch {\n return undefined;\n }\n const agentTool = sessionContextAgentTool(providerId);\n return parseSessionContextFile(decoded, {\n ...(agentTool === undefined ? {} : { agentTool }),\n sessionId,\n });\n };\n\n return {\n read: async (request) => {\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<undefined>((resolve) => {\n timer = setTimeout(() => resolve(undefined), budgetMillis);\n timer.unref?.();\n });\n try {\n return await Promise.race([\n readOnce(request.providerId, request.sessionId).catch(() => undefined),\n timeout,\n ]);\n } finally {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n }\n },\n };\n};\n","import { lstat, 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.\n *\n * Which repository the worktree belongs to is read the same way git reads it:\n *\n * - A git dir holding a `commondir` file is a **linked** worktree's; that file\n * names the repository's common git dir, relative to the git dir. When the\n * common dir is a directory named `.git`, its parent is the main worktree —\n * the path `git worktree list` prints first. Any other common dir (a bare\n * repository, a `--separate-git-dir` repository, a submodule's\n * `.git/modules/<name>`) or one that no longer exists names no main worktree.\n * - A git dir without one is a **main** worktree's, including a submodule's\n * (`gitdir: <super>/.git/modules/<name>`): a submodule is its own repository,\n * not a linked worktree of the superproject.\n *\n * A `.git` entry that cannot be read, points nowhere, or has no readable `HEAD`\n * makes the answer `undefined` — a broken worktree is not evidence, and the walk\n * does not skip past it to an enclosing repository that the event did not\n * target. A repository that cannot be named costs only `mainRoot`.\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\nconst firstLine = (content: string): string => content.split(/\\r?\\n/, 1)[0]?.trim() ?? \"\";\n\nconst resolveGitPath = (target: string | undefined, base: string): string | undefined =>\n target === undefined || target.length === 0 || target.includes(\"\\u0000\")\n ? undefined\n : path.resolve(base, target);\n\n/** `gitdir: <path>` → the path, resolved against the worktree root. */\nexport const parseGitDirFile = (content: string, worktreeRoot: string): string | undefined => {\n const line = firstLine(content);\n // A prefix check, not a regex: `gitdir:` followed by long runs of spaces made\n // the former `/^gitdir:\\s*(.+)$/` backtrack polynomially (CodeQL).\n return resolveGitPath(\n line.startsWith(\"gitdir:\") ? line.slice(\"gitdir:\".length).trim() : undefined,\n worktreeRoot,\n );\n};\n\n/** A `commondir` file → the common git dir it names, resolved against the git dir. */\nexport const parseCommonDirFile = (content: string, gitDir: string): string | undefined =>\n resolveGitPath(firstLine(content), gitDir);\n\nconst isMissing = async (filePath: string): Promise<boolean> => {\n try {\n await lstat(filePath);\n return false;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n return code === \"ENOENT\" || code === \"ENOTDIR\";\n }\n};\n\nconst isDirectory = async (directory: string): Promise<boolean> => {\n try {\n return (await stat(directory)).isDirectory();\n } catch {\n return false;\n }\n};\n\ntype Repository = Pick<LocatedWorktree, \"kind\" | \"mainRoot\">;\n\n/** Kind and main worktree for a `.git` file's git dir; see the module note. */\nconst repositoryOf = async (worktreeRoot: string, gitDir: string): Promise<Repository> => {\n const commonDirFile = path.join(gitDir, \"commondir\");\n const content = await readBounded(commonDirFile);\n if (content === undefined) {\n // Only a missing file makes this a main worktree. An unreadable one is still\n // a linked worktree's, of a repository it cannot name.\n return (await isMissing(commonDirFile)) ? { kind: \"main\", mainRoot: worktreeRoot } : { kind: \"linked\" };\n }\n const commonDir = parseCommonDirFile(content, gitDir);\n const mainRoot =\n commonDir !== undefined && path.basename(commonDir) === \".git\" && (await isDirectory(commonDir))\n ? path.dirname(commonDir)\n : undefined;\n return { kind: \"linked\", ...(mainRoot === undefined ? {} : { mainRoot }) };\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 // A `.git` directory is always a main worktree's git dir: nothing more to read.\n const repository: Repository = info.isDirectory()\n ? { kind: \"main\", mainRoot: directory }\n : await repositoryOf(directory, gitDir);\n return {\n kind: \"worktree\",\n located: { root: directory, ...(branch === undefined ? {} : { branch }), ...repository },\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","/**\n * OTLP/HTTP endpoint URLs per signal, as the OpenTelemetry exporter\n * specification defines them.\n *\n * - `OTEL_EXPORTER_OTLP_ENDPOINT` is a **base** URL: the signal path\n * (`/v1/traces`, `/v1/logs`) is appended to it.\n * - `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` / `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`\n * are full URLs, used as they are.\n *\n * One compatibility rule: earlier releases read `OTEL_EXPORTER_OTLP_ENDPOINT`\n * as the full traces URL. A base URL that already ends in `/v1/traces` is\n * therefore taken to be that full URL, not a base to append to, so an existing\n * `…/v1/traces` value keeps posting where it did.\n */\n\n/**\n * The standard endpoint variables. `generic` and `logs` also appear in\n * `ENVIRONMENT_VARIABLES`; `traces` does not, because that list is guarded\n * against identity-looking (`TRACE`) names.\n */\nexport const OTLP_ENDPOINT_VARIABLES = Object.freeze({\n generic: \"OTEL_EXPORTER_OTLP_ENDPOINT\",\n traces: \"OTEL_EXPORTER_OTLP_TRACES_ENDPOINT\",\n logs: \"OTEL_EXPORTER_OTLP_LOGS_ENDPOINT\",\n metrics: \"OTEL_EXPORTER_OTLP_METRICS_ENDPOINT\",\n});\n\nexport const OTLP_TRACES_PATH = \"/v1/traces\";\nexport const OTLP_LOGS_PATH = \"/v1/logs\";\nexport const OTLP_METRICS_PATH = \"/v1/metrics\";\n\nexport type OtlpSignal = \"traces\" | \"logs\" | \"metrics\";\n\nconst SIGNAL_PATHS: Readonly<Record<OtlpSignal, string>> = Object.freeze({\n traces: OTLP_TRACES_PATH,\n logs: OTLP_LOGS_PATH,\n metrics: OTLP_METRICS_PATH,\n});\n\n/**\n * Strip trailing slashes, by scan rather than by regex.\n *\n * `/\\/+$/` is a polynomial-ReDoS on this input: an endpoint of many `/` followed by\n * anything else makes the engine retry the `+` from every position. The endpoint is\n * operator-supplied configuration bounded to 2048 characters, so the practical cost\n * is small — but a linear scan is just as short, and the bound is not the guarantee.\n */\nexport const withoutTrailingSlashes = (value: string): string => {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === 0x2f) {\n end -= 1;\n }\n return value.slice(0, end);\n};\n\n/**\n * The URL a signal posts to, given an `OTEL_EXPORTER_OTLP_ENDPOINT` base.\n *\n * Trailing slashes on the base are dropped before the signal path is appended,\n * so `https://host/otlp` and `https://host/otlp/` both give\n * `https://host/otlp/v1/traces`. A base ending in `/v1/traces` (the legacy\n * full-URL form) is used as-is for traces and has that suffix swapped for\n * `/v1/logs` for logs.\n */\nexport const otlpSignalEndpointFromBase = (base: string, signal: OtlpSignal): string => {\n const trimmed = withoutTrailingSlashes(base);\n if (trimmed.endsWith(OTLP_TRACES_PATH)) {\n return signal === \"traces\"\n ? trimmed\n : `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${SIGNAL_PATHS[signal]}`;\n }\n return `${trimmed}${SIGNAL_PATHS[signal]}`;\n};\n\n/**\n * A sibling signal's URL derived from a traces URL: a trailing `/v1/traces` (or\n * the target signal's own path) is swapped for the target path, and any other URL\n * is treated as a base and has the path appended. The rule logs have always used.\n */\nexport const siblingSignalEndpoint = (tracesEndpoint: string, signal: OtlpSignal): string => {\n const trimmed = withoutTrailingSlashes(tracesEndpoint);\n const target = SIGNAL_PATHS[signal];\n if (trimmed.endsWith(target)) {\n return trimmed;\n }\n if (trimmed.endsWith(OTLP_TRACES_PATH)) {\n return `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${target}`;\n }\n return `${trimmed}${target}`;\n};\n","import { randomBytes } from \"node:crypto\";\nimport { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport type { Clock, Logger } from \"../runtime/ports.js\";\nimport { namespaceSegments, type StoreNamespace } from \"../state/keys.js\";\n\nexport type SpoolEnqueueResult =\n | { readonly spooled: true }\n | { readonly spooled: false; readonly reason: \"capacity-exceeded\" };\n\nexport type SpoolDrainResult = {\n readonly drained: number;\n readonly remaining: number;\n readonly failed: number;\n /**\n * Batches removed from the queue because they were unusable rather than\n * undeliverable.\n *\n * Distinct from `failed`, which means \"the collector would not take it, try\n * later\". A quarantined batch will never become deliverable, so counting it\n * separately is what stops a permanent problem from reading as transient.\n */\n readonly quarantined: number;\n};\n\n/**\n * Why a queued batch was dropped rather than delivered.\n *\n * - `age` — older than the queue's `maxAgeMillis`.\n * - `size` — evicted (or refused) to stay within `maxBytes`.\n * - `count` — evicted (or refused) to stay within the batch-count bound.\n * - `rejected` — the destination answered with a non-retryable status on replay,\n * so sending it again could never succeed.\n */\nexport type SpoolDropReason = \"age\" | \"size\" | \"count\" | \"rejected\";\n\n/** Drop counts, persisted beside the queue so they outlive the process that dropped. */\nexport type SpoolDropCounts = {\n readonly total: number;\n readonly age: number;\n readonly size: number;\n readonly count: number;\n readonly rejected: number;\n readonly lastDroppedAt?: number;\n};\n\nexport type SpoolStats = {\n readonly batches: number;\n readonly bytes: number;\n /** Enqueue time of the oldest queued batch. Absent when the queue is empty. */\n readonly oldestEnqueuedAt?: number;\n readonly dropped: SpoolDropCounts;\n};\n\n/**\n * What a queue does when a new batch would exceed a bound.\n *\n * `refuse-new` keeps what is queued and reports the new batch as lost — the\n * original behavior, still the default for a queue built directly. `drop-oldest`\n * evicts from the head until the new batch fits, which is what the runtime's\n * per-destination spools use.\n */\nexport type SpoolOverflowPolicy = \"refuse-new\" | \"drop-oldest\";\n\n/**\n * What a drain's sender reports for one batch: delivered (`true`), still\n * undeliverable and worth retrying (`false`), or permanently undeliverable\n * (`\"discard\"`), which removes it and counts it as a `rejected` drop instead of\n * stopping the drain behind it.\n */\nexport type SpoolSendOutcome = boolean | \"discard\";\n\nexport const EMPTY_SPOOL_DROP_COUNTS: SpoolDropCounts = Object.freeze({\n total: 0,\n age: 0,\n size: 0,\n count: 0,\n rejected: 0,\n});\n\n/** Outcome of validating one batch read back from a queue file. */\nexport type SpoolValidation<TBatch> =\n | { readonly batch: TBatch }\n | { readonly rejection: string };\n\nexport type SpoolQueueOptions<TBatch> = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Bound on the number of queued batches. */\n readonly maxFiles: number;\n /** Bound on the total bytes of queued batches. Unbounded when absent. */\n readonly maxBytes?: number;\n /** A batch older than this is dropped, at enqueue and at drain. No age bound when absent. */\n readonly maxAgeMillis?: number;\n /** Default `refuse-new`. */\n readonly overflow?: SpoolOverflowPolicy;\n /**\n * Directory holding the queue, under the identity namespace. One name per\n * signal, so a batch of one signal can never be drained by the other's sender —\n * the two encode different payloads and a mixed queue would quarantine\n * perfectly good batches.\n */\n readonly queueName: string;\n /** Re-validates a batch read back from disk, before any of it reaches a sender. */\n readonly validate: (value: unknown, identity: StoreNamespace) => SpoolValidation<TBatch>;\n};\n\n/**\n * Durable filesystem queue for export batches a collector could not accept.\n *\n * A hook process is short-lived, so \"retry later\" means \"persist and let a later\n * invocation retry\" rather than an in-process backoff loop. Each instance is\n * rooted at `<rootDir>/<providerId>/<installationId>/<queueName>`; two queues for\n * different providers, installations, or signals never share a directory, so a\n * batch from one identity cannot physically land in another's drain — batches\n * cannot mix identities by construction, not by a runtime check alone (the check\n * inside {@link SpoolQueue.drain} is defense in depth for a hand-edited or\n * misplaced file).\n *\n * Shared by the trace and log spools rather than written twice: the drain's\n * quarantine-and-continue behavior is the subtle part, and a second copy of it is\n * a second place for the head-of-queue-blocking bug to come back.\n */\nexport interface SpoolQueue<TBatch> {\n enqueue(batch: TBatch): Promise<SpoolEnqueueResult>;\n /** Sequential, bounded drain: stops after the first failed send, or after `maxBatches`. */\n drain(\n send: (batch: TBatch) => Promise<SpoolSendOutcome>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\n /** Depth, bytes, and persisted drop counts. Read-only: creates no directory. */\n stats(): Promise<SpoolStats>;\n}\n\n/** Name of the drop-count file, inside the queue directory and outside its `*.json` listing. */\nexport const SPOOL_DROPS_FILE = \".drops\";\n\n/** Enqueue time encoded in a queue file name, or undefined for a foreign name. */\nconst enqueuedAtOf = (fileName: string): number | undefined => {\n const match = /^(\\d{16})-/.exec(fileName);\n return match?.[1] === undefined ? undefined : Number(match[1]);\n};\n\nconst isCount = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isInteger(value) && value >= 0;\n\n/** Read a queue directory's drop counts. Missing or unreadable reads as zero. */\nexport const readSpoolDropCounts = async (queueDir: string): Promise<SpoolDropCounts> => {\n try {\n const parsed = JSON.parse(await readFile(path.join(queueDir, SPOOL_DROPS_FILE), \"utf8\")) as unknown;\n if (typeof parsed !== \"object\" || parsed === null) {\n return EMPTY_SPOOL_DROP_COUNTS;\n }\n const record = parsed as Record<string, unknown>;\n const field = (name: string): number => (isCount(record[name]) ? record[name] : 0);\n return {\n total: field(\"total\"),\n age: field(\"age\"),\n size: field(\"size\"),\n count: field(\"count\"),\n rejected: field(\"rejected\"),\n ...(isCount(record.lastDroppedAt) ? { lastDroppedAt: record.lastDroppedAt } : {}),\n };\n } catch {\n return EMPTY_SPOOL_DROP_COUNTS;\n }\n};\n\n/**\n * Depth, bytes, and drop counts of one queue directory, without creating it.\n *\n * Exported for `doctor`, which inspects queues on disk without constructing the\n * sinks that own them.\n */\nexport const readSpoolQueueStats = async (queueDir: string): Promise<SpoolStats> => {\n let entries: string[];\n try {\n entries = await readdir(queueDir);\n } catch {\n return { batches: 0, bytes: 0, dropped: await readSpoolDropCounts(queueDir) };\n }\n const files = entries.filter((entry) => entry.endsWith(\".json\") && !entry.startsWith(\".tmp-\")).sort();\n let bytes = 0;\n for (const file of files) {\n try {\n bytes += (await stat(path.join(queueDir, file))).size;\n } catch {\n // Drained by a peer between the listing and the stat.\n }\n }\n const oldest = files[0] === undefined ? undefined : enqueuedAtOf(files[0]);\n return {\n batches: files.length,\n bytes,\n ...(oldest === undefined ? {} : { oldestEnqueuedAt: oldest }),\n dropped: await readSpoolDropCounts(queueDir),\n };\n};\n\n/** Default bound on a single drain pass, so one invocation's flush stays short. */\nexport const DEFAULT_DRAIN_MAX_BATCHES = 20;\n\nconst isErrnoException = (thrown: unknown, code: string): boolean =>\n thrown instanceof Error && (thrown as NodeJS.ErrnoException).code === code;\n\nexport const createSpoolQueue = <TBatch>(\n options: SpoolQueueOptions<TBatch>,\n): SpoolQueue<TBatch> => {\n const [providerSegment, installationSegment] = namespaceSegments(options);\n const queueDir = path.join(options.rootDir, providerSegment, installationSegment, options.queueName);\n const corruptDir = path.join(\n options.rootDir,\n providerSegment,\n installationSegment,\n `${options.queueName}-corrupt`,\n );\n\n let dirsReady: Promise<void> | undefined;\n const ensureDirs = async (): Promise<void> => {\n if (dirsReady !== undefined) {\n return dirsReady;\n }\n const promise = (async (): Promise<void> => {\n await mkdir(queueDir, { recursive: true });\n await mkdir(corruptDir, { recursive: true });\n })();\n dirsReady = promise;\n try {\n await promise;\n } catch (thrown) {\n dirsReady = undefined;\n throw thrown;\n }\n };\n\n const listSorted = async (): Promise<readonly string[]> => {\n let entries: string[];\n try {\n entries = await readdir(queueDir);\n } catch (thrown) {\n if (isErrnoException(thrown, \"ENOENT\")) {\n return [];\n }\n throw thrown;\n }\n return entries.filter((entry) => entry.endsWith(\".json\") && !entry.startsWith(\".tmp-\")).sort();\n };\n\n /**\n * Add drops to the persisted counts.\n *\n * A read-modify-write without a lock: two processes dropping at the same moment\n * can lose one increment. The counts are a diagnostic, not an invoice, and a\n * lock here would put a second contention point on the failure path.\n */\n const recordDrops = async (reason: SpoolDropReason, dropped: number): Promise<void> => {\n if (dropped <= 0) {\n return;\n }\n try {\n const current = await readSpoolDropCounts(queueDir);\n const next: SpoolDropCounts = {\n ...current,\n total: current.total + dropped,\n [reason]: current[reason] + dropped,\n lastDroppedAt: options.clock.now(),\n };\n const tmp = path.join(queueDir, `.tmp-${randomBytes(6).toString(\"hex\")}.drops`);\n await writeFile(tmp, JSON.stringify(next), \"utf8\");\n await rename(tmp, path.join(queueDir, SPOOL_DROPS_FILE));\n } catch {\n // Counting is best-effort; the drop itself already happened.\n }\n options.logger?.warn(\"durable spool dropped batches\", {\n \"spool.queue\": options.queueName,\n \"spool.drop_reason\": reason,\n \"spool.dropped\": dropped,\n });\n };\n\n type QueuedFile = { readonly name: string; readonly enqueuedAt?: number; readonly bytes: number };\n\n const listWithSizes = async (): Promise<QueuedFile[]> => {\n const names = await listSorted();\n const files: QueuedFile[] = [];\n for (const name of names) {\n let bytes = 0;\n if (options.maxBytes !== undefined) {\n try {\n bytes = (await stat(path.join(queueDir, name))).size;\n } catch {\n continue;\n }\n }\n const enqueuedAt = enqueuedAtOf(name);\n files.push({ name, bytes, ...(enqueuedAt === undefined ? {} : { enqueuedAt }) });\n }\n return files;\n };\n\n /** Remove queued files; the count is what actually left the queue. */\n const evict = async (files: readonly QueuedFile[]): Promise<number> => {\n let removed = 0;\n for (const file of files) {\n try {\n await unlink(path.join(queueDir, file.name));\n removed += 1;\n } catch {\n // Already drained or evicted by a peer: it left the queue either way, but\n // not because of this process, so it is not counted here.\n }\n }\n return removed;\n };\n\n const isExpired = (file: QueuedFile, now: number): boolean =>\n options.maxAgeMillis !== undefined &&\n file.enqueuedAt !== undefined &&\n now - file.enqueuedAt > options.maxAgeMillis;\n\n const enqueue = async (batch: TBatch): Promise<SpoolEnqueueResult> => {\n await ensureDirs();\n const serialized = JSON.stringify(batch);\n const bytes = Buffer.byteLength(serialized, \"utf8\");\n const refuse = async (reason: \"size\" | \"count\"): Promise<SpoolEnqueueResult> => {\n options.logger?.warn(\"durable spool at capacity; batch dropped\", {\n \"spool.max_files\": options.maxFiles,\n ...(options.maxBytes === undefined ? {} : { \"spool.max_bytes\": options.maxBytes }),\n \"spool.queue\": options.queueName,\n });\n await recordDrops(reason, 1);\n return { spooled: false, reason: \"capacity-exceeded\" };\n };\n\n if (options.maxBytes !== undefined && bytes > options.maxBytes) {\n // Larger than the whole budget: evicting everything else still would not\n // make room, so it is the one batch that is refused under either policy.\n return refuse(\"size\");\n }\n\n let queued = await listWithSizes();\n const now = options.clock.now();\n const expired = queued.filter((file) => isExpired(file, now));\n if (expired.length > 0) {\n await recordDrops(\"age\", await evict(expired));\n queued = queued.filter((file) => !isExpired(file, now));\n }\n\n const overflow = options.overflow ?? \"refuse-new\";\n const totalBytes = (): number => queued.reduce((sum, file) => sum + file.bytes, 0);\n if (overflow === \"refuse-new\") {\n if (queued.length >= options.maxFiles) {\n return refuse(\"count\");\n }\n if (options.maxBytes !== undefined && totalBytes() + bytes > options.maxBytes) {\n return refuse(\"size\");\n }\n } else {\n // Oldest first: the listing is sorted by enqueue time.\n const overCount = Math.max(0, queued.length + 1 - options.maxFiles);\n if (overCount > 0) {\n await recordDrops(\"count\", await evict(queued.slice(0, overCount)));\n queued = queued.slice(overCount);\n }\n if (options.maxBytes !== undefined) {\n let excess = totalBytes() + bytes - options.maxBytes;\n let cut = 0;\n while (excess > 0 && cut < queued.length) {\n excess -= queued[cut]?.bytes ?? 0;\n cut += 1;\n }\n if (cut > 0) {\n await recordDrops(\"size\", await evict(queued.slice(0, cut)));\n queued = queued.slice(cut);\n }\n }\n }\n\n const fileName = `${String(now).padStart(16, \"0\")}-${randomBytes(6).toString(\"hex\")}.json`;\n const target = path.join(queueDir, fileName);\n const tmp = path.join(queueDir, `.tmp-${randomBytes(6).toString(\"hex\")}.json`);\n await writeFile(tmp, serialized, \"utf8\");\n await rename(tmp, target);\n return { spooled: true };\n };\n\n const drain = async (\n send: (batch: TBatch) => Promise<SpoolSendOutcome>,\n drainOptions?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult> => {\n await ensureDirs();\n const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;\n let files = await listSorted();\n if (options.maxAgeMillis !== undefined) {\n // Expired batches are dropped, not sent: a collector would place them far in\n // the past, and they would spend this invocation's short flush window.\n const now = options.clock.now();\n const expired = files\n .map((name): QueuedFile => {\n const enqueuedAt = enqueuedAtOf(name);\n return { name, bytes: 0, ...(enqueuedAt === undefined ? {} : { enqueuedAt }) };\n })\n .filter((file) => isExpired(file, now));\n if (expired.length > 0) {\n await recordDrops(\"age\", await evict(expired));\n const gone = new Set(expired.map((file) => file.name));\n files = files.filter((name) => !gone.has(name));\n }\n }\n let drained = 0;\n let failed = 0;\n let quarantined = 0;\n let index = 0;\n\n for (; index < files.length && index < cap; index += 1) {\n const fileName = files[index];\n if (fileName === undefined) {\n break;\n }\n const filePath = path.join(queueDir, fileName);\n\n /**\n * Move a file out of the queue, or delete it if quarantine is unavailable.\n *\n * Getting it *out of the queue* is the part that matters. A file the drain\n * cannot use and cannot move would be re-read on every pass, and because the\n * head is processed first it would block every healthy batch behind it — the\n * one failure mode a retry queue must not have. So a failed quarantine falls\n * back to deleting: losing one unusable batch beats losing all the usable\n * ones queued behind it.\n */\n const quarantine = async (rejection: string): Promise<void> => {\n quarantined += 1;\n options.logger?.error(\"durable spool quarantined an unusable batch\", {\n \"spool.rejection\": rejection,\n \"spool.file\": fileName,\n \"spool.queue\": options.queueName,\n });\n try {\n await rename(filePath, path.join(corruptDir, fileName));\n } catch {\n await unlink(filePath).catch(() => undefined);\n }\n };\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(await readFile(filePath, \"utf8\")) as unknown;\n } catch {\n await quarantine(\"unparseable-json\");\n continue;\n }\n\n const validation = options.validate(parsed, {\n providerId: options.providerId,\n installationId: options.installationId,\n });\n if (\"rejection\" in validation) {\n await quarantine(validation.rejection);\n continue;\n }\n\n let delivered: SpoolSendOutcome;\n try {\n delivered = await send(validation.batch);\n } catch {\n delivered = false;\n }\n if (delivered === \"discard\") {\n // Permanently refused: retrying can never succeed, and stopping here would\n // wedge every batch queued behind it.\n if (await unlink(filePath).then(() => true, () => false)) {\n await recordDrops(\"rejected\", 1);\n }\n continue;\n }\n if (delivered) {\n await unlink(filePath).catch(() => undefined);\n drained += 1;\n } else {\n failed += 1;\n break;\n }\n }\n\n const remaining = (await listSorted()).length;\n return { drained, remaining, failed, quarantined };\n };\n\n return {\n enqueue,\n drain,\n size: async (): Promise<number> => {\n await ensureDirs();\n return (await listSorted()).length;\n },\n stats: (): Promise<SpoolStats> => readSpoolQueueStats(queueDir),\n };\n};\n","import type { Attributes } from \"@opentelemetry/api\";\n\nimport type { Clock, Logger } from \"../runtime/ports.js\";\nimport type { StoreNamespace } from \"../state/keys.js\";\nimport {\n createSpoolQueue,\n type SpoolDrainResult,\n type SpoolEnqueueResult,\n type SpoolValidation,\n type SpoolOverflowPolicy,\n type SpoolSendOutcome,\n type SpoolStats,\n} from \"./spool-queue.js\";\n\n/**\n * One log record, flattened to plain JSON so it survives a process exit.\n *\n * `body` is a string or absent, never a nested value: the mapping only ever\n * produces a disclosed text body, and admitting anything richer here would make a\n * spool file a route for a structure the live path would have refused.\n */\nexport type SerializedLogRecord = {\n readonly eventName: string;\n readonly severityNumber: number;\n readonly severityText?: string;\n readonly body?: string;\n readonly timeMillis: number;\n readonly observedTimeMillis: number;\n /** Absent only on a record that was mapped without trace correlation. */\n readonly traceId?: string;\n readonly spanId?: string;\n readonly attributes: Attributes;\n};\n\nexport type LogSpoolBatch = {\n readonly providerId: string;\n readonly installationId: string;\n readonly resourceAttributes: Attributes;\n readonly instrumentationScope: { readonly name: string; readonly version?: string };\n readonly records: readonly SerializedLogRecord[];\n readonly enqueuedAt: number;\n};\n\n/** Upper bounds on a replayed batch. A spool file is untrusted input. */\nexport const MAX_SPOOLED_LOG_RECORDS_PER_BATCH = 4_096;\nexport const MAX_SPOOLED_LOG_STRING_LENGTH = 8_192;\n/**\n * Longest replayed body.\n *\n * Matches the live mapping's `MAX_LOG_BODY_CHARACTERS`, because \"what the mapping\n * would have put on the wire\" and \"what is accepted back off disk\" diverging is\n * the whole vulnerability — a hand-edited spool file must not be able to export a\n * body the live path would have cut.\n */\nexport const MAX_SPOOLED_LOG_BODY_LENGTH = 8_192;\nconst MAX_SPOOLED_ATTRIBUTES_PER_RECORD = 256;\nconst TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;\nconst SPAN_ID_PATTERN = /^[0-9a-f]{16}$/;\n\nconst isFiniteNonNegative = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n\nconst isBoundedString = (value: unknown, maxLength = MAX_SPOOLED_LOG_STRING_LENGTH): value is string =>\n typeof value === \"string\" && value.length > 0 && value.length <= maxLength;\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isReplayableAttributeValue = (value: unknown): boolean => {\n if (Array.isArray(value)) {\n // OTLP permits homogeneous primitive arrays; anything nested is not an\n // attribute and would fail encoding.\n return value.every(\n (item) =>\n (typeof item === \"string\" && item.length <= MAX_SPOOLED_LOG_STRING_LENGTH) ||\n (typeof item === \"number\" && Number.isFinite(item)) ||\n typeof item === \"boolean\" ||\n item === null,\n );\n }\n return (\n (typeof value === \"string\" && value.length <= MAX_SPOOLED_LOG_STRING_LENGTH) ||\n (typeof value === \"number\" && Number.isFinite(value)) ||\n typeof value === \"boolean\" ||\n value === undefined\n );\n};\n\n/**\n * Whether one recorded log record can be replayed.\n *\n * Every field is checked, not just the ones a happy path reads. The rebuilt record\n * goes straight to the OTLP encoder, which assumes the shapes the type declares —\n * so a `severityNumber` of `null`, a nested object in `attributes`, or a trace id\n * of the wrong width becomes an encoder error deep inside the exporter rather than\n * a rejected file here. Trace and span ids are held to their hex forms because a\n * malformed id is not a correlation a collector can resolve.\n */\nconst isReplayableLogRecord = (value: unknown): value is SerializedLogRecord => {\n if (!isPlainObject(value)) {\n return false;\n }\n if (!isBoundedString(value.eventName)) {\n return false;\n }\n if (!isFiniteNonNegative(value.severityNumber)) {\n return false;\n }\n if (value.severityText !== undefined && typeof value.severityText !== \"string\") {\n return false;\n }\n if (\n value.body !== undefined &&\n (typeof value.body !== \"string\" || value.body.length > MAX_SPOOLED_LOG_BODY_LENGTH)\n ) {\n return false;\n }\n if (!isFiniteNonNegative(value.timeMillis) || !isFiniteNonNegative(value.observedTimeMillis)) {\n return false;\n }\n // Correlation is all-or-nothing: a trace id without a span id (or the reverse)\n // is not a span reference, and half of one would export as a record pointing at\n // span `0000000000000000`.\n const hasTrace = value.traceId !== undefined;\n const hasSpan = value.spanId !== undefined;\n if (hasTrace !== hasSpan) {\n return false;\n }\n if (hasTrace && (typeof value.traceId !== \"string\" || !TRACE_ID_PATTERN.test(value.traceId))) {\n return false;\n }\n if (hasSpan && (typeof value.spanId !== \"string\" || !SPAN_ID_PATTERN.test(value.spanId))) {\n return false;\n }\n if (!isPlainObject(value.attributes)) {\n return false;\n }\n const entries = Object.entries(value.attributes);\n if (entries.length > MAX_SPOOLED_ATTRIBUTES_PER_RECORD) {\n return false;\n }\n return entries.every(([, attribute]) => isReplayableAttributeValue(attribute));\n};\n\nexport type LogSpoolBatchRejection =\n | \"not-an-object\"\n | \"identity-mismatch\"\n | \"resource-attributes-invalid\"\n | \"instrumentation-scope-invalid\"\n | \"records-invalid\"\n | \"record-field-invalid\";\n\n/**\n * Validate a whole batch read back from disk, before any of it reaches an exporter.\n *\n * The identity check alone is not enough. `records` being anything other than an\n * array makes the sender's `records.map(...)` throw, and a throwing send is\n * indistinguishable from an unreachable collector — so the drain would treat a\n * permanently poisoned file as a transient failure and stop at it on every pass,\n * wedging the queue head and every batch behind it forever. Validation is what\n * turns that into a single quarantined file.\n */\nexport const validateLogSpoolBatch = (\n value: unknown,\n identity: StoreNamespace,\n): SpoolValidation<LogSpoolBatch> => {\n if (!isPlainObject(value)) {\n return { rejection: \"not-an-object\" satisfies LogSpoolBatchRejection };\n }\n if (\n value.providerId !== identity.providerId ||\n value.installationId !== identity.installationId\n ) {\n return { rejection: \"identity-mismatch\" satisfies LogSpoolBatchRejection };\n }\n if (!isPlainObject(value.resourceAttributes)) {\n // Not merely absent: the resource is rebuilt by iterating it, and a string or\n // an array would silently produce a resource built from its indices.\n return { rejection: \"resource-attributes-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (\n !isPlainObject(value.instrumentationScope) ||\n !isBoundedString(value.instrumentationScope.name)\n ) {\n return { rejection: \"instrumentation-scope-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (\n value.instrumentationScope.version !== undefined &&\n typeof value.instrumentationScope.version !== \"string\"\n ) {\n return { rejection: \"instrumentation-scope-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (!Array.isArray(value.records) || value.records.length === 0) {\n return { rejection: \"records-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (value.records.length > MAX_SPOOLED_LOG_RECORDS_PER_BATCH) {\n return { rejection: \"records-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (!value.records.every(isReplayableLogRecord)) {\n return { rejection: \"record-field-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (!isFiniteNonNegative(value.enqueuedAt)) {\n return { rejection: \"not-an-object\" satisfies LogSpoolBatchRejection };\n }\n return { batch: value as unknown as LogSpoolBatch };\n};\n\nexport type DurableLogSpoolOptions = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Refuses new entries once this many are queued. Default 500. */\n readonly maxSpoolFiles?: number;\n /**\n * Queue directory below the identity namespace. Default `spool-logs`; each\n * export destination other than `default` gets its own.\n */\n readonly queueName?: string;\n /** Bound on total queued bytes. Unbounded when absent. */\n readonly maxBytes?: number;\n /** Batches older than this are dropped rather than sent. No age bound when absent. */\n readonly maxAgeMillis?: number;\n /** Default `refuse-new`, the original behavior. */\n readonly overflow?: SpoolOverflowPolicy;\n};\n\n/**\n * Durable filesystem queue for log batches a collector could not accept.\n *\n * Rooted at `<rootDir>/<providerId>/<installationId>/spool-logs`, deliberately a\n * different directory from the trace spool: the two hold different encodings, so a\n * single mixed queue would have each signal's sender quarantining the other's\n * perfectly deliverable batches. Separate directories also mean a logs outage\n * cannot consume the trace spool's capacity, which is what keeps the primary\n * signal unaffected by a misconfigured logs endpoint.\n */\nexport interface DurableLogSpool {\n enqueue(batch: LogSpoolBatch): Promise<SpoolEnqueueResult>;\n /** Sequential, bounded drain: stops after the first failed send, or after `maxBatches`. */\n drain(\n send: (batch: LogSpoolBatch) => Promise<SpoolSendOutcome>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\n /**\n * Depth, bytes, and persisted drop counts. Optional so a host's own\n * implementation of this interface keeps compiling; the file-backed one has it.\n */\n stats?(): Promise<SpoolStats>;\n}\n\nexport const DEFAULT_MAX_LOG_SPOOL_FILES = 500;\n\nexport const createFileDurableLogSpool = (options: DurableLogSpoolOptions): DurableLogSpool =>\n createSpoolQueue<LogSpoolBatch>({\n rootDir: options.rootDir,\n providerId: options.providerId,\n installationId: options.installationId,\n clock: options.clock,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_LOG_SPOOL_FILES,\n queueName: options.queueName ?? \"spool-logs\",\n ...(options.maxBytes === undefined ? {} : { maxBytes: options.maxBytes }),\n ...(options.maxAgeMillis === undefined ? {} : { maxAgeMillis: options.maxAgeMillis }),\n ...(options.overflow === undefined ? {} : { overflow: options.overflow }),\n validate: validateLogSpoolBatch,\n });\n","import type { Attributes } from \"@opentelemetry/api\";\n\nimport type { Clock, Logger } from \"../runtime/ports.js\";\nimport type { StoreNamespace } from \"../state/keys.js\";\nimport { isMetricInstrumentName, METRIC_INSTRUMENTS, type MetricPoint } from \"./metric-model.js\";\nimport {\n createSpoolQueue,\n type SpoolDrainResult,\n type SpoolEnqueueResult,\n type SpoolOverflowPolicy,\n type SpoolSendOutcome,\n type SpoolStats,\n type SpoolValidation,\n} from \"./spool-queue.js\";\n\n/**\n * A batch of metric points a destination could not take, kept for the next\n * invocation.\n *\n * Points are plain JSON (`MetricPoint`), so a batch replays without the process\n * that recorded it. A cumulative point is a snapshot of a running total: replaying\n * an old one after a newer one was delivered restates an earlier value with an\n * earlier timestamp, which a receiver orders by time rather than adding.\n */\nexport type MetricSpoolBatch = {\n readonly providerId: string;\n readonly installationId: string;\n readonly resourceAttributes: Attributes;\n readonly instrumentationScope: { readonly name: string; readonly version?: string };\n readonly points: readonly MetricPoint[];\n readonly enqueuedAt: number;\n};\n\nexport const MAX_SPOOLED_METRIC_POINTS_PER_BATCH = 4_096;\nconst MAX_STRING_LENGTH = 8_192;\nconst MAX_ATTRIBUTES_PER_POINT = 64;\nconst MAX_BUCKETS = 64;\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isFiniteNonNegative = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n\nconst isBoundedString = (value: unknown): value is string =>\n typeof value === \"string\" && value.length > 0 && value.length <= MAX_STRING_LENGTH;\n\nconst isPrimitiveAttribute = (value: unknown): boolean =>\n (typeof value === \"string\" && value.length <= MAX_STRING_LENGTH) ||\n (typeof value === \"number\" && Number.isFinite(value)) ||\n typeof value === \"boolean\";\n\n/**\n * Whether one spooled point can be replayed. A spool file is untrusted input, and\n * a malformed point would otherwise fail inside the OTLP encoder, where it reads\n * as an unreachable collector and wedges the queue head.\n */\nconst isReplayablePoint = (value: unknown): value is MetricPoint => {\n if (!isPlainObject(value) || !isMetricInstrumentName(value.instrument)) {\n return false;\n }\n if (value.temporality !== \"cumulative\" && value.temporality !== \"delta\") {\n return false;\n }\n if (!isFiniteNonNegative(value.startTimeMillis) || !isFiniteNonNegative(value.timeMillis)) {\n return false;\n }\n if (!isPlainObject(value.attributes)) {\n return false;\n }\n const entries = Object.entries(value.attributes);\n if (entries.length > MAX_ATTRIBUTES_PER_POINT || !entries.every(([, item]) => isPrimitiveAttribute(item))) {\n return false;\n }\n const instrument = METRIC_INSTRUMENTS[value.instrument];\n if (instrument.kind === \"counter\") {\n return isFiniteNonNegative(value.value) && value.histogram === undefined;\n }\n const histogram = value.histogram;\n if (!isPlainObject(histogram) || value.value !== undefined) {\n return false;\n }\n const buckets = histogram.bucketCounts;\n return (\n isFiniteNonNegative(histogram.count) &&\n Number.isInteger(histogram.count) &&\n isFiniteNonNegative(histogram.sum) &&\n typeof histogram.min === \"number\" &&\n typeof histogram.max === \"number\" &&\n Array.isArray(buckets) &&\n buckets.length <= MAX_BUCKETS &&\n buckets.length === (instrument.boundaries?.length ?? 0) + 1 &&\n buckets.every((count) => isFiniteNonNegative(count) && Number.isInteger(count))\n );\n};\n\nexport const validateMetricSpoolBatch = (\n value: unknown,\n identity: StoreNamespace,\n): SpoolValidation<MetricSpoolBatch> => {\n if (!isPlainObject(value)) {\n return { rejection: \"not-an-object\" };\n }\n if (value.providerId !== identity.providerId || value.installationId !== identity.installationId) {\n return { rejection: \"identity-mismatch\" };\n }\n if (!isPlainObject(value.resourceAttributes)) {\n return { rejection: \"resource-attributes-invalid\" };\n }\n if (!isPlainObject(value.instrumentationScope) || !isBoundedString(value.instrumentationScope.name)) {\n return { rejection: \"instrumentation-scope-invalid\" };\n }\n if (\n value.instrumentationScope.version !== undefined &&\n typeof value.instrumentationScope.version !== \"string\"\n ) {\n return { rejection: \"instrumentation-scope-invalid\" };\n }\n if (\n !Array.isArray(value.points) ||\n value.points.length === 0 ||\n value.points.length > MAX_SPOOLED_METRIC_POINTS_PER_BATCH\n ) {\n return { rejection: \"points-invalid\" };\n }\n if (!value.points.every(isReplayablePoint)) {\n return { rejection: \"point-field-invalid\" };\n }\n if (!isFiniteNonNegative(value.enqueuedAt)) {\n return { rejection: \"not-an-object\" };\n }\n return { batch: value as unknown as MetricSpoolBatch };\n};\n\nexport interface DurableMetricSpool {\n enqueue(batch: MetricSpoolBatch): Promise<SpoolEnqueueResult>;\n drain(\n send: (batch: MetricSpoolBatch) => Promise<SpoolSendOutcome>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\n stats?(): Promise<SpoolStats>;\n}\n\nexport type DurableMetricSpoolOptions = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n readonly maxSpoolFiles?: number;\n /** Queue directory below the identity namespace. Default `spool-metrics`. */\n readonly queueName?: string;\n readonly maxBytes?: number;\n readonly maxAgeMillis?: number;\n readonly overflow?: SpoolOverflowPolicy;\n};\n\nexport const DEFAULT_MAX_METRIC_SPOOL_FILES = 500;\n\n/** Durable queue for metric batches, in its own directory beside the trace and log spools. */\nexport const createFileDurableMetricSpool = (options: DurableMetricSpoolOptions): DurableMetricSpool =>\n createSpoolQueue<MetricSpoolBatch>({\n rootDir: options.rootDir,\n providerId: options.providerId,\n installationId: options.installationId,\n clock: options.clock,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_METRIC_SPOOL_FILES,\n queueName: options.queueName ?? \"spool-metrics\",\n ...(options.maxBytes === undefined ? {} : { maxBytes: options.maxBytes }),\n ...(options.maxAgeMillis === undefined ? {} : { maxAgeMillis: options.maxAgeMillis }),\n ...(options.overflow === undefined ? {} : { overflow: options.overflow }),\n validate: validateMetricSpoolBatch,\n });\n","import type { Attributes } from \"@opentelemetry/api\";\n\nimport type { Clock, Logger } from \"../runtime/ports.js\";\nimport type { StoreNamespace } from \"../state/keys.js\";\n// Deliberately not re-exported: `spool-queue.js` is their one home, and a second\n// `export *` path to the same names makes them ambiguous in the barrel below.\nimport {\n createSpoolQueue,\n type SpoolDrainResult,\n type SpoolEnqueueResult,\n type SpoolOverflowPolicy,\n type SpoolSendOutcome,\n type SpoolStats,\n} from \"./spool-queue.js\";\n\nexport type SerializedSpan = {\n readonly name: string;\n readonly kind: number;\n readonly traceId: string;\n readonly spanId: string;\n /** Absent on batches spooled before cross-process parenting existed, and on root spans. */\n readonly parentSpanId?: string;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly attributes: Attributes;\n readonly statusCode: number;\n readonly statusMessage?: string;\n};\n\nexport type SpoolBatch = {\n readonly providerId: string;\n readonly installationId: string;\n readonly resourceAttributes: Attributes;\n readonly instrumentationScope: { readonly name: string; readonly version?: string };\n readonly spans: readonly SerializedSpan[];\n readonly enqueuedAt: number;\n};\n\n/** Upper bounds on a replayed batch. A spool file is untrusted input. */\nexport const MAX_SPOOLED_SPANS_PER_BATCH = 4_096;\nexport const MAX_SPOOLED_STRING_LENGTH = 8_192;\nconst MAX_SPOOLED_ATTRIBUTES_PER_SPAN = 256;\nconst TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;\nconst SPAN_ID_PATTERN = /^[0-9a-f]{16}$/;\n\nconst isFiniteNonNegative = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n\nconst isBoundedString = (value: unknown, maxLength = MAX_SPOOLED_STRING_LENGTH): value is string =>\n typeof value === \"string\" && value.length > 0 && value.length <= maxLength;\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * Whether one recorded span can be replayed.\n *\n * Every field is checked, not just the ones a happy path reads. `assembleReadableSpan`\n * hands its output straight to the OTLP encoder, which assumes the shapes the type\n * declares — so a `spanId` of the wrong length, a `startMillis` of `null`, or an\n * `attributes` value holding a nested object becomes an encoder error deep inside\n * the exporter rather than a rejected file here. Trace and span ids are further held\n * to their hex forms, because a malformed id is not a span a collector can place.\n */\nconst isReplayableSpan = (value: unknown): value is SerializedSpan => {\n if (!isPlainObject(value)) {\n return false;\n }\n if (!isBoundedString(value.name) || !isFiniteNonNegative(value.kind)) {\n return false;\n }\n if (typeof value.traceId !== \"string\" || !TRACE_ID_PATTERN.test(value.traceId)) {\n return false;\n }\n if (typeof value.spanId !== \"string\" || !SPAN_ID_PATTERN.test(value.spanId)) {\n return false;\n }\n if (\n value.parentSpanId !== undefined &&\n (typeof value.parentSpanId !== \"string\" || !SPAN_ID_PATTERN.test(value.parentSpanId))\n ) {\n return false;\n }\n if (!isFiniteNonNegative(value.startMillis) || !isFiniteNonNegative(value.endMillis)) {\n return false;\n }\n if (!isFiniteNonNegative(value.statusCode)) {\n return false;\n }\n if (\n value.statusMessage !== undefined &&\n typeof value.statusMessage !== \"string\"\n ) {\n return false;\n }\n if (!isPlainObject(value.attributes)) {\n return false;\n }\n const entries = Object.entries(value.attributes);\n if (entries.length > MAX_SPOOLED_ATTRIBUTES_PER_SPAN) {\n return false;\n }\n return entries.every(([, attribute]) => {\n if (Array.isArray(attribute)) {\n // OTLP permits homogeneous primitive arrays; anything nested is not a span\n // attribute and would fail encoding.\n return attribute.every(\n (item) =>\n (typeof item === \"string\" && item.length <= MAX_SPOOLED_STRING_LENGTH) ||\n (typeof item === \"number\" && Number.isFinite(item)) ||\n typeof item === \"boolean\" ||\n item === null,\n );\n }\n return (\n (typeof attribute === \"string\" && attribute.length <= MAX_SPOOLED_STRING_LENGTH) ||\n (typeof attribute === \"number\" && Number.isFinite(attribute)) ||\n typeof attribute === \"boolean\" ||\n attribute === undefined\n );\n });\n};\n\nexport type SpoolBatchRejection =\n | \"not-an-object\"\n | \"identity-mismatch\"\n | \"resource-attributes-invalid\"\n | \"instrumentation-scope-invalid\"\n | \"spans-invalid\"\n | \"span-field-invalid\";\n\n/**\n * Validate a whole batch read back from disk, before any of it reaches an exporter.\n *\n * The identity check alone is not enough. `spans` being anything other than an array\n * makes the sink's `spans.map(...)` throw, and a throwing send is indistinguishable\n * from an unreachable collector — so the drain would treat a permanently poisoned\n * file as a transient failure and stop at it on every pass, wedging the queue head\n * and every batch behind it forever. Validation is what turns that into a single\n * quarantined file.\n */\nexport const validateSpoolBatch = (\n value: unknown,\n identity: StoreNamespace,\n): { readonly batch: SpoolBatch } | { readonly rejection: SpoolBatchRejection } => {\n if (!isPlainObject(value)) {\n return { rejection: \"not-an-object\" };\n }\n if (\n value.providerId !== identity.providerId ||\n value.installationId !== identity.installationId\n ) {\n return { rejection: \"identity-mismatch\" };\n }\n if (!isPlainObject(value.resourceAttributes)) {\n // Not merely absent: `replayResource` iterates it, and a string or an array\n // would silently produce a resource built from its indices.\n return { rejection: \"resource-attributes-invalid\" };\n }\n if (!isPlainObject(value.instrumentationScope) || !isBoundedString(value.instrumentationScope.name)) {\n return { rejection: \"instrumentation-scope-invalid\" };\n }\n if (\n value.instrumentationScope.version !== undefined &&\n typeof value.instrumentationScope.version !== \"string\"\n ) {\n return { rejection: \"instrumentation-scope-invalid\" };\n }\n if (!Array.isArray(value.spans) || value.spans.length === 0) {\n return { rejection: \"spans-invalid\" };\n }\n if (value.spans.length > MAX_SPOOLED_SPANS_PER_BATCH) {\n return { rejection: \"spans-invalid\" };\n }\n if (!value.spans.every(isReplayableSpan)) {\n return { rejection: \"span-field-invalid\" };\n }\n if (!isFiniteNonNegative(value.enqueuedAt)) {\n return { rejection: \"not-an-object\" };\n }\n return { batch: value as unknown as SpoolBatch };\n};\n\nexport type DurableSpoolOptions = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Refuses new entries once this many are queued, rather than growing without bound. Default 500. */\n readonly maxSpoolFiles?: number;\n /**\n * Queue directory below the identity namespace. Default `spool`; each\n * export destination other than `default` gets its own.\n */\n readonly queueName?: string;\n /** Bound on total queued bytes. Unbounded when absent. */\n readonly maxBytes?: number;\n /** Batches older than this are dropped rather than sent. No age bound when absent. */\n readonly maxAgeMillis?: number;\n /** Default `refuse-new`, the original behavior. */\n readonly overflow?: SpoolOverflowPolicy;\n};\n\n/**\n * Durable filesystem queue for export batches a collector could not accept.\n *\n * A hook process is short-lived, so \"retry later\" means \"persist and let a\n * later invocation retry\" rather than an in-process backoff loop. Each\n * instance is rooted at `<rootDir>/<providerId>/<installationId>/spool`; two\n * spools for different providers or installations never share a directory,\n * so a batch from one identity cannot physically land in another's drain —\n * batches cannot mix identities by construction, not by a runtime check\n * alone (the check in {@link DurableSpool.drain} is defense in depth for a\n * hand-edited or misplaced file).\n */\nexport interface DurableSpool {\n enqueue(batch: SpoolBatch): Promise<SpoolEnqueueResult>;\n /** Sequential, bounded drain: stops after the first failed send, or after `maxBatches`. */\n drain(\n send: (batch: SpoolBatch) => Promise<SpoolSendOutcome>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\n /**\n * Depth, bytes, and persisted drop counts. Optional so a host's own\n * implementation of this interface keeps compiling; the file-backed one has it.\n */\n stats?(): Promise<SpoolStats>;\n}\n\n/** Default bound on queued trace batches, so the spool cannot grow without limit. */\nexport const DEFAULT_MAX_SPOOL_FILES = 500;\n\nexport const createFileDurableSpool = (options: DurableSpoolOptions): DurableSpool =>\n createSpoolQueue<SpoolBatch>({\n rootDir: options.rootDir,\n providerId: options.providerId,\n installationId: options.installationId,\n clock: options.clock,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_SPOOL_FILES,\n queueName: options.queueName ?? \"spool\",\n ...(options.maxBytes === undefined ? {} : { maxBytes: options.maxBytes }),\n ...(options.maxAgeMillis === undefined ? {} : { maxAgeMillis: options.maxAgeMillis }),\n ...(options.overflow === undefined ? {} : { overflow: options.overflow }),\n validate: validateSpoolBatch,\n });\n","import { TraceFlags, type AttributeValue, type Attributes, type SpanContext } from \"@opentelemetry/api\";\nimport { ExportResultCode, type ExportResult } from \"@opentelemetry/core\";\nimport { millisToHrTime, type InstrumentationScope } from \"@opentelemetry/core\";\nimport { OTLPLogExporter } from \"@opentelemetry/exporter-logs-otlp-proto\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport type { ReadableLogRecord } from \"@opentelemetry/sdk-logs\";\n\nimport { OTLP_LOGS_PATH, OTLP_TRACES_PATH, withoutTrailingSlashes } from \"../config/otlp-endpoint.js\";\nimport type { ExporterPolicy } from \"../config/schema.js\";\nimport { createHealthTracker, type DeliveryHealthSnapshot } from \"../diagnostics/health.js\";\nimport { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { Clock, Logger, TelemetryEmitResult, TelemetrySink } from \"../runtime/ports.js\";\nimport type { DurableLogSpool, LogSpoolBatch, SerializedLogRecord } from \"./durable-log-spool.js\";\nimport { isPermanentExportFailure } from \"./export-failure.js\";\nimport type { SpoolSendOutcome } from \"./spool-queue.js\";\nimport {\n agreedContextAttributes,\n replayResource,\n resourceFromExporterPolicy,\n resourceWithContext,\n} from \"./exporter-resource.js\";\nimport {\n canonicalEventsToLogRecords,\n NO_LOG_CONTENT,\n type LogContentPolicy,\n} from \"./log-records.js\";\nimport {\n DEFAULT_INSTRUMENTATION_SCOPE,\n type SpanCorrelation,\n type SpanCorrelationResolver,\n} from \"./semconv.js\";\n\n/**\n * OTLP HTTP/protobuf log sink.\n *\n * The logs counterpart of `otlp-sink.ts`, and deliberately its mirror image:\n * semantic mapping lives entirely in `log-records.ts`, and this module owns only\n * batching, delivery, bounded flush/shutdown, health tracking, and — when a spool\n * is configured — persisting what a down collector rejected. Every failure mode\n * (disabled config, missing or underivable endpoint, export failure, timeout,\n * spool write failure) degrades to a reported diagnostic rather than a thrown\n * error, preserving the hook's fail-open contract.\n *\n * The two sinks are separate objects rather than one exporter with two encoders\n * because they fail independently: a collector that has no logs receiver, or an\n * operator who pointed logs at the wrong port, must cost the logs signal and\n * nothing else. The trace pipeline is the one an installation already depends on.\n */\n\n/**\n * Where log records are posted.\n *\n * Resolution order, highest first:\n *\n * 1. `logs.endpoint` — stated outright, used verbatim.\n * 2. the trace endpoint with a trailing `/v1/traces` swapped for `/v1/logs`, which\n * is the shape a collector configured for both signals actually has.\n * 3. the trace endpoint treated as a base URL, with `/v1/logs` appended — the\n * convention the OTLP specification defines for a signal-less endpoint.\n *\n * Returned as a discriminated result rather than a bare string because \"no logs\n * endpoint could be derived\" has to be reportable: silently posting an\n * `ExportLogsServiceRequest` to a traces receiver produces a rejection whose cause\n * is a configuration mistake, and an operator reading \"collector rejected a batch\"\n * would go looking at the collector.\n */\nexport const resolveLogsEndpoint = (\n exporter: ExporterPolicy,\n): { readonly endpoint: string; readonly derived: boolean } | { readonly unresolvable: \"no-endpoint\" } => {\n if (exporter.logs.endpoint !== undefined) {\n return { endpoint: exporter.logs.endpoint, derived: false };\n }\n if (exporter.endpoint === undefined) {\n return { unresolvable: \"no-endpoint\" };\n }\n const trimmed = withoutTrailingSlashes(exporter.endpoint);\n if (trimmed.endsWith(OTLP_LOGS_PATH)) {\n return { endpoint: trimmed, derived: true };\n }\n if (trimmed.endsWith(OTLP_TRACES_PATH)) {\n return {\n endpoint: `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${OTLP_LOGS_PATH}`,\n derived: true,\n };\n }\n return { endpoint: `${trimmed}${OTLP_LOGS_PATH}`, derived: true };\n};\n\n/**\n * Narrow a log record's attributes to what a spool file can hold.\n *\n * Log attributes admit any value (`AnyValue` is `unknown` since api 1.10); the spool's own validator\n * does not, and neither does `assembleReadableSpan`'s sibling contract for traces.\n * This mapping only ever produces primitives, so the filter is unreachable in\n * practice — it is here so that \"what the live path emits\" and \"what survives a\n * spool round-trip\" cannot silently diverge if a future attribute is richer than\n * the queue's schema.\n */\nconst toSpoolAttributes = (attributes: Attributes): Attributes => {\n const safe: Record<string, AttributeValue> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n safe[key] = value;\n continue;\n }\n if (Array.isArray(value) && value.every((item) => typeof item === \"string\")) {\n safe[key] = value;\n }\n }\n return safe;\n};\n\nconst serializeRecord = (record: ReadableLogRecord): SerializedLogRecord => {\n const context = record.spanContext;\n return {\n eventName: record.eventName ?? \"otelhook.record\",\n severityNumber: record.severityNumber ?? 0,\n ...(record.severityText === undefined ? {} : { severityText: record.severityText }),\n ...(typeof record.body === \"string\" ? { body: record.body } : {}),\n timeMillis: record.hrTime[0] * 1000 + Math.round(record.hrTime[1] / 1e6),\n observedTimeMillis:\n record.hrTimeObserved[0] * 1000 + Math.round(record.hrTimeObserved[1] / 1e6),\n ...(context === undefined ? {} : { traceId: context.traceId, spanId: context.spanId }),\n attributes: toSpoolAttributes(record.attributes),\n };\n};\n\nconst deserializeRecord = (\n serialized: SerializedLogRecord,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableLogRecord => {\n const spanContext: SpanContext | undefined =\n serialized.traceId === undefined || serialized.spanId === undefined\n ? undefined\n : {\n traceId: serialized.traceId,\n spanId: serialized.spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n };\n return {\n hrTime: millisToHrTime(serialized.timeMillis),\n hrTimeObserved: millisToHrTime(serialized.observedTimeMillis),\n ...(spanContext === undefined ? {} : { spanContext }),\n severityNumber: serialized.severityNumber,\n ...(serialized.severityText === undefined ? {} : { severityText: serialized.severityText }),\n ...(serialized.body === undefined ? {} : { body: serialized.body }),\n eventName: serialized.eventName,\n resource,\n instrumentationScope: scope,\n attributes: serialized.attributes,\n droppedAttributesCount: 0,\n };\n};\n\nconst chunk = <T,>(items: readonly T[], size: number): readonly (readonly T[])[] => {\n if (size <= 0 || items.length <= size) {\n return [items];\n }\n const chunks: T[][] = [];\n for (let index = 0; index < items.length; index += size) {\n chunks.push(items.slice(index, index + size));\n }\n return chunks;\n};\n\nexport type OtlpLogSinkOptions = {\n readonly exporter: ExporterPolicy;\n /** Header values, kept out of the resolved-config snapshot (ADR: config carries only header *names*). */\n readonly headers?: Readonly<Record<string, string>>;\n readonly providerId: string;\n readonly installationId: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Persists batches an unreachable collector rejected, for a later retry. */\n readonly spool?: DurableLogSpool;\n readonly instrumentationScope?: InstrumentationScope;\n /**\n * Whether disclosed content text may reach a log body. Defaults to\n * {@link NO_LOG_CONTENT}, which is what an unconfigured installation gets.\n */\n readonly content?: LogContentPolicy;\n /**\n * Supplies cross-process pairing so a record correlates to the span id the trace\n * pipeline actually exported. Omitted, records still carry a derived trace and\n * span id, computed from the batch alone.\n *\n * Injected as a plain function rather than as a correlator so the telemetry layer\n * keeps no dependency on lifecycle or on the state store (ADR 0006). When both\n * sinks are wired, the fanout resolves correlation *once* and hands the same\n * answer to each — `correlateBatch` writes state, so calling it twice per batch\n * would record a start edge twice.\n */\n readonly correlate?: SpanCorrelationResolver;\n /** Export destination this sink delivers to; see `OtlpTraceSinkOptions.destination`. */\n readonly destination?: string;\n};\n\nexport interface OtlpLogTelemetrySink extends TelemetrySink {\n health(): DeliveryHealthSnapshot;\n /** Attempts to resend previously spooled batches, bounded by `maxBatches`. */\n drainSpool(\n maxBatches?: number,\n ): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }>;\n}\n\n/**\n * Sink that swallows every batch: logs disabled, or configured but unroutable.\n *\n * Reports **zero accepted and zero rejected**, which is the one place this differs\n * from the trace sink's disabled path — and it has to. The counts a sink returns are\n * what `classifyDurability` decides commit-or-retry from, and they are summed across\n * signals. A disabled signal that claimed to have accepted the batch would make a\n * *total* trace loss look like a partial delivery: `accepted > 0` from a sink that\n * sent nothing, `rejected > 0` from the sink that failed, so the callback would\n * commit as terminally-partial instead of releasing its claim for retry. Contributing\n * nothing is the truthful answer, and it leaves durability decided entirely by the\n * signals that actually tried — so an installation with logs off behaves exactly as\n * it did before logs existed.\n *\n * Health still records the batch as accepted: nothing failed, and a disabled signal\n * must not read as unhealthy.\n */\nconst createDisabledSink = (destination?: string): OtlpLogTelemetrySink => {\n const health = createHealthTracker(\n \"telemetry-log-sink\",\n destination === undefined ? {} : { destination },\n );\n return {\n emit: (events): Promise<TelemetryEmitResult> => {\n health.recordSuccess(events.length);\n return Promise.resolve({ accepted: 0, rejected: 0, errors: [] });\n },\n flush: (): Promise<void> => Promise.resolve(),\n shutdown: (): Promise<void> => Promise.resolve(),\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool: (): Promise<{\n readonly drained: number;\n readonly remaining: number;\n readonly failed: number;\n }> => Promise.resolve({ drained: 0, remaining: 0, failed: 0 }),\n };\n};\n\n/**\n * Whether this configuration can deliver logs at all.\n *\n * Separated from the constructor so `doctor` can report the same verdict without\n * building an exporter, and so each refusal names itself rather than collapsing\n * into one \"disabled\" state an operator then has to bisect.\n */\nexport type LogsDeliverability =\n | { readonly status: \"configured\"; readonly endpoint: string; readonly derivedEndpoint: boolean }\n | {\n readonly status: \"disabled\";\n readonly reason:\n | \"logs-disabled\"\n | \"exporter-disabled\"\n | \"protocol-none\"\n | \"protocol-unsupported\"\n | \"no-endpoint\";\n };\n\nexport const describeLogsDeliverability = (exporter: ExporterPolicy): LogsDeliverability => {\n if (!exporter.logs.enabled) {\n return { status: \"disabled\", reason: \"logs-disabled\" };\n }\n if (!exporter.enabled) {\n return { status: \"disabled\", reason: \"exporter-disabled\" };\n }\n if (exporter.protocol === \"none\") {\n return { status: \"disabled\", reason: \"protocol-none\" };\n }\n if (exporter.protocol !== \"http/protobuf\") {\n return { status: \"disabled\", reason: \"protocol-unsupported\" };\n }\n const resolved = resolveLogsEndpoint(exporter);\n if (\"unresolvable\" in resolved) {\n return { status: \"disabled\", reason: \"no-endpoint\" };\n }\n return { status: \"configured\", endpoint: resolved.endpoint, derivedEndpoint: resolved.derived };\n};\n\nconst DISABLED_DETAIL: Readonly<Record<Extract<LogsDeliverability, { status: \"disabled\" }>[\"reason\"], string>> =\n Object.freeze({\n \"logs-disabled\": \"otlp log sink disabled: exporter.logs.enabled is false\",\n \"exporter-disabled\": \"otlp log sink disabled: the exporter is disabled\",\n \"protocol-none\": \"otlp log sink disabled: protocol is none\",\n \"protocol-unsupported\":\n \"otlp log sink disabled: protocol not supported by this build, falling back to disabled\",\n \"no-endpoint\": \"otlp log sink disabled: no logs endpoint configured and none could be derived\",\n });\n\n/**\n * OTLP HTTP/protobuf {@link TelemetrySink} for the logs signal.\n *\n * A disabled sink never calls `correlate`: with nothing being exported there is no\n * span to correlate to, and writing correlation state anyway would leave a disabled\n * installation quietly accumulating files.\n */\nexport const createOtlpLogSink = (options: OtlpLogSinkOptions): OtlpLogTelemetrySink => {\n const destinationFields =\n options.destination === undefined ? {} : { \"export.destination\": options.destination };\n const deliverability = describeLogsDeliverability(options.exporter);\n if (deliverability.status === \"disabled\") {\n if (deliverability.reason !== \"logs-disabled\") {\n // `logs-disabled` is the default posture, not a misconfiguration, so it is\n // not worth a warning on every invocation. The rest are: somebody asked for\n // logs and will not get them.\n options.logger?.warn(DISABLED_DETAIL[deliverability.reason], {\n \"exporter.protocol\": options.exporter.protocol,\n ...destinationFields,\n });\n }\n return createDisabledSink(options.destination);\n }\n\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const resource = resourceFromExporterPolicy(options.exporter);\n const content = options.content ?? NO_LOG_CONTENT;\n const health = createHealthTracker(\n \"telemetry-log-sink\",\n options.destination === undefined ? {} : { destination: options.destination },\n );\n const exporter = new OTLPLogExporter({\n url: deliverability.endpoint,\n headers: { ...options.headers },\n timeoutMillis: options.exporter.timeoutMillis,\n });\n let shutdownCompleted = false;\n\n const exportRecords = (records: readonly ReadableLogRecord[]): Promise<ExportResult> =>\n new Promise((resolve) => {\n exporter.export([...records], (result: ExportResult) => resolve(result));\n });\n\n const toSpoolBatch = (records: readonly ReadableLogRecord[], batchResource: Resource): LogSpoolBatch => ({\n providerId: options.providerId,\n installationId: options.installationId,\n resourceAttributes: { ...batchResource.attributes },\n instrumentationScope: {\n name: scope.name,\n ...(scope.version === undefined ? {} : { version: scope.version }),\n },\n records: records.map(serializeRecord),\n enqueuedAt: options.clock.now(),\n });\n\n const sendSerializedBatch = async (batch: LogSpoolBatch): Promise<SpoolSendOutcome> => {\n const batchResource = replayResource(batch.resourceAttributes, options.exporter);\n const records = batch.records.map((record) =>\n deserializeRecord(record, batchResource, batch.instrumentationScope),\n );\n const result = await exportRecords(records);\n if (result.code === ExportResultCode.SUCCESS) {\n return true;\n }\n return isPermanentExportFailure(result) ? \"discard\" : false;\n };\n\n /**\n * Cross-process pairing is an enrichment, never a precondition: if state is\n * unreadable the batch still exports, with each record correlated from the batch\n * alone rather than dropped.\n */\n const resolveCorrelations = async (\n events: readonly CanonicalEvent[],\n ): Promise<{\n readonly correlations: readonly SpanCorrelation[];\n readonly available: boolean | undefined;\n }> => {\n if (options.correlate === undefined) {\n return { correlations: [], available: undefined };\n }\n try {\n return { correlations: await options.correlate(events), available: true };\n } catch {\n options.logger?.warn(\"span correlation unavailable; exporting uncorrelated log records\", {});\n return { correlations: [], available: false };\n }\n };\n\n const emit = async (events: Parameters<TelemetrySink[\"emit\"]>[0]): Promise<TelemetryEmitResult> => {\n if (events.length === 0) {\n return { accepted: 0, rejected: 0, errors: [] };\n }\n const resolved = await resolveCorrelations(events);\n // Session context overrides the same keys on the Resource for this batch.\n const batchResource = resourceWithContext(resource, agreedContextAttributes(events));\n const mapped = canonicalEventsToLogRecords(events, {\n resource: batchResource,\n instrumentationScope: scope,\n content,\n correlations: resolved.correlations,\n ...(resolved.available === undefined ? {} : { correlationAvailable: resolved.available }),\n });\n if (mapped.droppedFacts > 0) {\n // Said out loud rather than truncated silently: a caller that saw only\n // \"accepted\" would read a clipped batch as a complete one.\n options.logger?.warn(\"log records dropped: batch or per-event bound reached\", {\n \"logs.dropped_facts\": mapped.droppedFacts,\n });\n }\n const errors: OtelHookErrorInfo[] = [];\n let accepted = 0;\n let rejected = 0;\n\n for (const batch of chunk(mapped.records, options.exporter.logs.maxBatchSize)) {\n if (batch.length === 0) {\n continue;\n }\n let result: ExportResult;\n try {\n result = await exportRecords(batch);\n } catch (thrown) {\n result = {\n code: ExportResultCode.FAILED,\n error: thrown instanceof Error ? thrown : new Error(\"export threw\"),\n };\n }\n if (result.code === ExportResultCode.SUCCESS) {\n accepted += batch.length;\n health.recordSuccess(batch.length, options.clock.now());\n continue;\n }\n\n health.recordFailure(\"telemetry-export-failure\", batch.length, options.clock.now());\n const permanent = isPermanentExportFailure(result);\n if (options.spool !== undefined && !permanent) {\n const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({\n spooled: false as const,\n reason: \"capacity-exceeded\" as const,\n }));\n if (spoolResult.spooled) {\n accepted += batch.length;\n options.logger?.warn(\"log record batch not delivered; spooled for the next invocation\", {\n \"export.batch_size\": batch.length,\n ...destinationFields,\n });\n continue;\n }\n }\n rejected += batch.length;\n errors.push(\n createErrorInfo({\n code: \"telemetry-export-failure\",\n phase: \"export\",\n detail: permanent\n ? \"collector refused a log record batch with a non-retryable status\"\n : \"collector rejected or was unreachable for a log record batch\",\n details: {\n \"export.batch_size\": batch.length,\n \"export.signal\": \"logs\",\n ...destinationFields,\n },\n }),\n );\n }\n\n return { accepted, rejected, errors };\n };\n\n const drainSpool = async (\n maxBatches?: number,\n ): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }> => {\n if (options.spool === undefined) {\n return { drained: 0, remaining: 0, failed: 0 };\n }\n const result = await options.spool.drain(sendSerializedBatch, {\n ...(maxBatches === undefined ? {} : { maxBatches }),\n });\n if (result.drained > 0) {\n health.recordSuccess(result.drained, options.clock.now());\n }\n return result;\n };\n\n const flush = async (): Promise<void> => {\n try {\n await exporter.forceFlush();\n } catch {\n // Best-effort: flush failures are reported through health, never thrown.\n }\n await drainSpool().catch(() => undefined);\n };\n\n const shutdown = async (): Promise<void> => {\n if (shutdownCompleted) {\n return;\n }\n shutdownCompleted = true;\n await flush();\n try {\n await exporter.shutdown();\n } catch {\n // Idempotent, non-throwing per the TelemetrySink contract.\n }\n };\n\n return {\n emit,\n flush,\n shutdown,\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool,\n };\n};\n","import type { ExportResult } from \"@opentelemetry/core\";\n\n/**\n * HTTP statuses that mean \"try again later\" rather than \"never send this\".\n *\n * The OTLP specification's retryable set (429, 502, 503, 504), plus:\n *\n * - 408, which is a timeout by another name;\n * - 500, by decision for this project: a backend that is restarting, overloaded,\n * or briefly broken commonly answers 500, and losing those batches costs more\n * than retrying them. A backend that answers 500 *forever* cannot pin a batch\n * in the spool: every spooled batch is still subject to the spool's age,\n * size, and count bounds (`exporter.spool`), and is dropped and counted when\n * it exceeds them.\n *\n * Anything else the server answered with a status for is a refusal of *this\n * batch*: replaying it can only fail the same way, and a spool that kept it would\n * retry it on every invocation and stop behind it.\n */\nexport const RETRYABLE_HTTP_STATUSES: ReadonlySet<number> = new Set([408, 429, 500, 502, 503, 504]);\n\n/**\n * Whether a failed export was a permanent refusal.\n *\n * With `@opentelemetry/otlp-exporter-base` (OpenTelemetry JS 3.x), the HTTP\n * transport reports a status outside its own retryable set (429, 502, 503, 504)\n * as an `OTLPExporterError` whose numeric `code` is the HTTP status — so 400,\n * 401, 408, 413, and 500 all arrive with a `code`, and 408 and 500 are then held\n * retryable here. Its retryable statuses are retried inside the exporter and,\n * once retries or the timeout run out, arrive without a `code`, as do a refused\n * connection, a timeout, and an oversized response. Those are exactly the \"never\n * reached it, or asked us to come back\" failures a spool is for.\n */\nexport const isPermanentExportFailure = (result: ExportResult): boolean => {\n const code = (result.error as { readonly code?: unknown } | undefined)?.code;\n return (\n typeof code === \"number\" &&\n Number.isInteger(code) &&\n code >= 400 &&\n code < 600 &&\n !RETRYABLE_HTTP_STATUSES.has(code)\n );\n};\n","import { resourceFromAttributes, type Resource } from \"@opentelemetry/resources\";\nimport type { Attributes } from \"@opentelemetry/api\";\n\nimport {\n checkResourceAttributeKey,\n isReservedResourceAttributeKey,\n MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH,\n MAX_RESOURCE_ATTRIBUTES,\n sanitizeResourceAttributes,\n} from \"../config/resource-attributes.js\";\nimport type { ExporterPolicy } from \"../config/schema.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport { MAX_IDENTIFIER_LENGTH } from \"../model/primitives.js\";\n\n/**\n * The OTLP `Resource` every record of a signal is exported under.\n *\n * Shared by the trace and log sinks rather than written twice: a resource carries\n * the service identity, so two sinks disagreeing about how it is built or\n * re-validated would attribute the same installation's two signals to two\n * services — and the divergence would only be visible in a backend, long after.\n */\n\n/**\n * Resource for the live path, from exporter policy.\n *\n * Custom attributes first, then service identity: spread order makes the policy\n * fields structurally unoverridable. `sanitizeResourceAttributes` already drops\n * the reserved keys, so this is belt-and-braces for a caller who hand-built an\n * `ExporterPolicy` without running it through the schema — but between them,\n * `service.name` can only ever come from policy.\n */\nexport const resourceFromExporterPolicy = (policy: ExporterPolicy): Resource =>\n resourceFromAttributes({\n ...sanitizeResourceAttributes(policy.resourceAttributes),\n \"service.name\": policy.serviceName,\n ...(policy.serviceNamespace === undefined\n ? {}\n : { \"service.namespace\": policy.serviceNamespace }),\n });\n\n/**\n * A spool file is a plain JSON file in a state directory, so everything read back\n * out of one is untrusted input — it can be hand-edited, truncated, or written by\n * an older release with a different schema. These bounds mirror the live path's,\n * because \"what the exporter would have refused from a flag\" and \"what it accepts\n * from disk\" diverging is the whole vulnerability.\n */\nconst isReplayableValue = (value: unknown): value is string | number | boolean =>\n (typeof value === \"string\" && value.length <= MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) ||\n (typeof value === \"number\" && Number.isFinite(value)) ||\n typeof value === \"boolean\";\n\n/**\n * Validate a service identity read back from a spool file.\n *\n * `service.name` decides which service every replayed record is attributed to, so\n * a spool that could set it freely could attribute this installation's telemetry\n * to somebody else's service — the one resource field where a forged value is a\n * reporting-integrity problem rather than a cosmetic one. It is therefore held to\n * the same contract as the typed policy field: a non-empty string within\n * {@link MAX_IDENTIFIER_LENGTH}. Anything else is not \"replayed as recorded\", it is\n * discarded in favour of the draining process's own policy.\n */\nconst replayableServiceIdentity = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 && value.length <= MAX_IDENTIFIER_LENGTH\n ? value\n : undefined;\n\n/**\n * Rebuild the resource a spooled batch was recorded with.\n *\n * A recorded `service.name` is a fact about the process that made the observation,\n * not about the one draining the spool, so a *valid* one is replayed as recorded.\n * But every field is re-validated on the way out, at the same bounds the live path\n * enforces: custom keys must pass {@link checkResourceAttributeKey} (which refuses\n * reserved and secret-looking names), values must be primitives within the length\n * bound, the custom count is capped, and the two reserved service fields must look\n * like the identifiers they are. A batch that fails the service check falls back to\n * the live policy rather than exporting with no service identity, because a resource\n * without `service.name` is rejected or bucketed as \"unknown_service\" by most\n * collectors — losing the batch to a tampered byte would make the validation itself\n * the outage.\n */\nexport const replayResource = (attributes: Attributes, policy: ExporterPolicy): Resource => {\n const safe: Record<string, string | number | boolean> = {};\n let customCount = 0;\n for (const [key, value] of Object.entries(attributes)) {\n if (isReservedResourceAttributeKey(key)) {\n // Handled below against the policy fallback, never copied verbatim.\n continue;\n }\n if (!isReplayableValue(value)) {\n continue;\n }\n if (checkResourceAttributeKey(key) !== undefined || customCount >= MAX_RESOURCE_ATTRIBUTES) {\n continue;\n }\n customCount += 1;\n safe[key] = value;\n }\n\n // Reserved keys last and unconditionally, so a spooled custom attribute can\n // never occupy the slot a service field is about to be written into.\n const recordedName = replayableServiceIdentity(attributes[\"service.name\"]);\n const recordedNamespace = replayableServiceIdentity(attributes[\"service.namespace\"]);\n safe[\"service.name\"] = recordedName ?? policy.serviceName;\n const namespace = recordedNamespace ?? policy.serviceNamespace;\n if (namespace !== undefined) {\n safe[\"service.namespace\"] = namespace;\n }\n\n return resourceFromAttributes(safe);\n};\n\n/**\n * The session context attributes every event of a batch agrees on.\n *\n * The core stamps one invocation's events from one context file, so a batch\n * normally agrees on everything. Should two events disagree on a key (a segment\n * boundary inside one callback), or one event lack it, the key is left out: the\n * Resource is shared by the whole batch and must not state a value one of its\n * records contradicts. Each record still carries its own value.\n */\nexport const agreedContextAttributes = (\n events: readonly CanonicalEvent[],\n): Readonly<Record<string, string | number | boolean>> => {\n const [first, ...rest] = events;\n if (first?.contextAttributes === undefined) {\n return {};\n }\n const agreed: Record<string, string | number | boolean> = { ...first.contextAttributes };\n for (const event of rest) {\n for (const key of Object.keys(agreed)) {\n if (event.contextAttributes?.[key] !== agreed[key]) {\n delete agreed[key];\n }\n }\n }\n return agreed;\n};\n\n/**\n * The Resource a batch is exported under, with session context applied.\n *\n * Context overrides only keys the Resource already carries — a stale\n * `factory.attempt.id` from the process environment, say — so the Resource and\n * the records say the same thing to a backend that reads either. It adds no new\n * key: the Resource describes the producer, and the context's own keys are on\n * every record already. Service identity is never touched (context cannot carry\n * it). Returns the input unchanged when nothing applies.\n */\nexport const resourceWithContext = (\n resource: Resource,\n context: Readonly<Record<string, string | number | boolean>>,\n): Resource => {\n const overrides: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(context)) {\n if (\n Object.hasOwn(resource.attributes, key) &&\n !isReservedResourceAttributeKey(key) &&\n resource.attributes[key] !== value\n ) {\n overrides[key] = value;\n }\n }\n if (Object.keys(overrides).length === 0) {\n return resource;\n }\n return resourceFromAttributes({ ...resource.attributes, ...overrides });\n};\n","import { SeverityNumber, TraceFlags, type Attributes, type SpanContext } from \"@opentelemetry/api\";\nimport { millisToHrTime, type InstrumentationScope } from \"@opentelemetry/core\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport type { ReadableLogRecord } from \"@opentelemetry/sdk-logs\";\nimport {\n ATTR_ERROR_TYPE,\n ATTR_GEN_AI_OPERATION_NAME,\n ATTR_GEN_AI_REQUEST_MODEL,\n ATTR_GEN_AI_RESPONSE_MODEL,\n ATTR_GEN_AI_SYSTEM,\n ATTR_GEN_AI_TOOL_CALL_ID,\n ATTR_GEN_AI_TOOL_NAME,\n ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n} from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport type { ContentFact } from \"../model/content.js\";\nimport type { CanonicalEvent, CanonicalEventType } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\nimport {\n exportIdentityAttributes,\n targetAttributes,\n usageTemporalityAttributes,\n} from \"./export-identity.js\";\nimport {\n ATTR_OTELHOOK_USAGE_PARTIAL,\n canonicalEventTraceIdentities,\n DEFAULT_INSTRUMENTATION_SCOPE,\n type SpanCorrelation,\n} from \"./semconv.js\";\n\n/**\n * Pure, stateless canonical-event-to-OTLP-log-record mapping.\n *\n * The counterpart of `semconv.ts` for the logs signal, and deliberately the same\n * shape: no state is read here, no clock is consulted, and the only inputs are\n * the batch plus the correlations the caller already resolved. Batching, retry,\n * spooling, and delivery live in `otlp-log-sink.ts`.\n *\n * ## Why logs at all, when traces already exist\n *\n * A span reports that a tool call happened, how long it took, and whether it\n * failed. It does not report *what was in it*, and it cannot: span attributes are\n * a flat bounded map, one record per span, exported once. A conversation turn is a\n * sequence of distinct pieces of content — a prompt, a response, reasoning, a tool\n * input, a tool output — each with its own role, its own length, and its own\n * disclosure decision. That is a log stream, and OTLP has one.\n *\n * So this mapping emits **one record per content fact**, plus one record per event\n * that carries no content, and correlates every record to the span the same batch\n * produced (or will produce). Nothing here decides *whether* content is\n * disclosed — the privacy service already did that, upstream, once — but the\n * gate is re-checked here because this is the last boundary before the wire.\n *\n * ## Identity and correlation\n *\n * Every record carries the same identity attributes a span does, and a\n * `spanContext` built from {@link canonicalEventTraceIdentities}: the trace id and\n * span id are derived from the event's own `(providerId, sessionId)` and its\n * lifecycle scope, so a record lands in the same trace as its span without either\n * signal knowing about the other. Two sessions in one batch derive two trace ids;\n * there is no batch-level or module-level trace state to contaminate.\n */\n\n/**\n * Version of this mapping.\n *\n * Consumers pin it. Bumped on any change to what an existing attribute or signal\n * *means*; adding a new attribute or a new signal value does not bump it, on the\n * same additive-compatibility rule the canonical model follows\n * (`CANONICAL_SCHEMA_VERSION`). Every record carries it as\n * `otelhook.log.mapping_version`, so a consumer never has to infer which\n * vocabulary it is reading.\n */\nexport const LOG_MAPPING_VERSION = 1 as const;\n\n/**\n * Coarse routing key for one log record.\n *\n * The fact's own `otelhook.content.kind` states precisely what the content is;\n * this states which *pipeline* it belongs to, so an operator can route or drop a\n * whole class (\"no tool output off this host\") with one collector rule rather\n * than an enumeration of event types.\n */\nexport const LOG_SIGNALS = [\n \"session\",\n \"prompt\",\n \"response\",\n \"reasoning\",\n \"tool\",\n \"shell\",\n \"file-operation\",\n \"mcp\",\n \"delegation\",\n \"compaction\",\n \"error\",\n] as const;\nexport type LogSignal = (typeof LOG_SIGNALS)[number];\n\n/**\n * Naming convention that marks a tool call as MCP-mediated.\n *\n * The canonical model has no \"this went through MCP\" field, because no provider\n * contract this package has verified carries one: what they carry is a *tool\n * name*, and three of the four non-synthetic contracts (Claude Code, Codex,\n * Gemini CLI) name MCP tools `mcp__<server>__<tool>`. So the convention is the\n * evidence, matched on the canonical tool name rather than on any provider's\n * payload.\n *\n * This deliberately **under-reports**: a provider whose MCP tool names do not\n * follow the convention classifies as `tool`, which is true but less specific.\n * The alternative — per-provider branching in the canonical layer, or a canonical\n * field no adapter can populate from a verified contract — would either leak\n * provider knowledge across the boundary or invent a contract. See\n * `docs/canonical-log-mapping.md`.\n */\nexport const MCP_TOOL_NAME_PATTERN = /^mcp__/i;\n\n/**\n * Most records one event may produce.\n *\n * Matches `contentFactsSchema`'s own cap, so in practice the mapping never drops\n * a fact an adapter produced; it is the backstop for a hand-built event, not a\n * routine truncation.\n */\nexport const MAX_LOG_RECORDS_PER_EVENT = 64;\n\n/** Most records one batch may produce, whatever the batch contains. */\nexport const MAX_LOG_RECORDS_PER_BATCH = 2_048;\n\n/**\n * Longest disclosed body this mapping will put on the wire.\n *\n * Separate from, and stricter than, the privacy policy's `maxStringLength` (which\n * may be configured up to 64Ki characters): a policy bound is about *disclosure*,\n * this is about the size of one OTLP record. A body cut here is reported as\n * `otelhook.content.body_truncated` rather than as the fact's own `truncated`\n * flag, so \"the privacy policy shortened this\" and \"the log record shortened\n * this\" stay distinguishable.\n */\nexport const MAX_LOG_BODY_CHARACTERS = 8_192;\n\nconst ATTR_OTELHOOK_EVENT_TYPE = \"otelhook.event.type\";\nconst ATTR_OTELHOOK_EVENT_ID = \"otelhook.event.id\";\nconst ATTR_OTELHOOK_EVENT_SEQUENCE = \"otelhook.event.sequence\";\nconst ATTR_OTELHOOK_LOG_SIGNAL = \"otelhook.log.signal\";\nconst ATTR_OTELHOOK_LOG_MAPPING_VERSION = \"otelhook.log.mapping_version\";\nconst ATTR_OTELHOOK_OUTCOME = \"otelhook.outcome\";\nconst ATTR_OTELHOOK_TOOL_KIND = \"otelhook.tool.kind\";\nconst ATTR_OTELHOOK_TOOL_PERMISSION = \"otelhook.tool.permission_decision\";\nconst ATTR_OTELHOOK_DELEGATION_DEPTH = \"otelhook.delegation_depth\";\nconst ATTR_OTELHOOK_SUBAGENT_TYPE = \"otelhook.subagent.type\";\nconst ATTR_OTELHOOK_AGENT_NAME = \"otelhook.agent.name\";\nconst ATTR_OTELHOOK_AGENT_VERSION = \"otelhook.agent.version\";\nconst ATTR_OTELHOOK_SESSION_KIND = \"otelhook.session.kind\";\nconst ATTR_OTELHOOK_PROMPT_SOURCE = \"otelhook.prompt.source\";\nconst ATTR_OTELHOOK_PROMPT_TURN_INDEX = \"otelhook.prompt.turn_index\";\nconst ATTR_OTELHOOK_GENERATION_ID = \"otelhook.generation.id\";\nconst ATTR_OTELHOOK_STOP_REASON = \"otelhook.generation.stop_reason\";\nconst ATTR_OTELHOOK_COMPACTION_TRIGGER = \"otelhook.compaction.trigger\";\nconst ATTR_OTELHOOK_CONTEXT_TOKENS_BEFORE = \"otelhook.compaction.context_tokens_before\";\nconst ATTR_OTELHOOK_CONTEXT_TOKENS_AFTER = \"otelhook.compaction.context_tokens_after\";\nconst ATTR_OTELHOOK_DROPPED_MESSAGES = \"otelhook.compaction.dropped_message_count\";\nconst ATTR_OTELHOOK_ERROR_PHASE = \"otelhook.error.phase\";\nconst ATTR_OTELHOOK_ERROR_RETRYABLE = \"otelhook.error.retryable\";\nconst ATTR_OTELHOOK_ERROR_SEVERITY = \"otelhook.error.severity\";\n\nconst ATTR_CONTENT_KIND = \"otelhook.content.kind\";\nconst ATTR_CONTENT_ROLE = \"otelhook.content.role\";\nconst ATTR_CONTENT_DISCLOSURE = \"otelhook.content.disclosure\";\nconst ATTR_CONTENT_CHARACTER_LENGTH = \"otelhook.content.character_length\";\nconst ATTR_CONTENT_BYTE_LENGTH = \"otelhook.content.byte_length\";\nconst ATTR_CONTENT_HASH = \"otelhook.content.hash\";\nconst ATTR_CONTENT_TRUNCATED = \"otelhook.content.truncated\";\nconst ATTR_CONTENT_SECRETS_REDACTED = \"otelhook.content.secrets_redacted\";\nconst ATTR_CONTENT_LABEL = \"otelhook.content.label\";\nconst ATTR_CONTENT_WITHHELD = \"otelhook.content.withheld\";\nconst ATTR_CONTENT_BODY_TRUNCATED = \"otelhook.content.body_truncated\";\n\n/**\n * Why a content fact reached the wire without its text.\n *\n * Stated rather than left as an absence, because \"this prompt was empty\", \"this\n * deployment omits content\", and \"this deployment discloses content but not to\n * the logs pipeline\" are three different operational facts that all look like a\n * missing body.\n */\nexport type ContentWithholdingReason =\n /** The privacy policy produced no text at all — the default `omit` posture. */\n | \"privacy-policy\"\n /** Content is disclosed elsewhere, but the logs pipeline is not permitted it. */\n | \"logs-content-disabled\"\n /** The fact carries verbatim text and `allowRawContent` is not set. */\n | \"raw-not-permitted\";\n\n/**\n * Whether disclosed content text may reach a log body.\n *\n * Two gates rather than one, and both must open. `includeContent` is the logs\n * pipeline's own switch, and it exists because spans carry no content in *any*\n * content mode: without it, turning on `privacy.contentMode` to get a hash and a\n * length — which is all it ever bought before — would start putting prompts on\n * the wire. `allowRawContent` is the pre-existing verbatim-content opt-in,\n * re-checked here because the sink is the last boundary before the wire and a\n * hand-built fact could otherwise carry `disclosure: \"raw\"` past a policy that\n * never permitted it.\n */\nexport type LogContentPolicy = {\n readonly includeContent: boolean;\n readonly allowRawContent: boolean;\n};\n\n/** Content disabled, which is what an unconfigured installation gets. */\nexport const NO_LOG_CONTENT: LogContentPolicy = Object.freeze({\n includeContent: false,\n allowRawContent: false,\n});\n\nconst codePointLength = (value: string): number => [...value].length;\n\nconst sliceCodePoints = (value: string, max: number): string => {\n let result = \"\";\n let count = 0;\n for (const char of value) {\n if (count >= max) {\n break;\n }\n result += char;\n count += 1;\n }\n return result;\n};\n\n/**\n * Which pipeline an event's records belong to.\n *\n * `factKind` refines the answer where one event type carries more than one kind\n * of content: a `generation.end` holds the response *and*, on providers that\n * report it, the reasoning that produced it, and collapsing those into one signal\n * would make \"drop reasoning, keep responses\" unexpressible.\n */\nexport const logSignalOf = (event: CanonicalEvent, factKind?: ContentFact[\"kind\"]): LogSignal => {\n switch (event.type) {\n case \"session.start\":\n case \"session.end\":\n return \"session\";\n case \"prompt.submitted\":\n return \"prompt\";\n case \"generation.start\":\n return factKind === \"reasoning\" ? \"reasoning\" : \"prompt\";\n case \"generation.end\":\n return factKind === \"reasoning\" ? \"reasoning\" : \"response\";\n case \"subagent.start\":\n case \"subagent.end\":\n return \"delegation\";\n case \"compaction.performed\":\n return \"compaction\";\n case \"error.raised\":\n return \"error\";\n case \"tool.start\":\n return toolSignal(event.toolName, event.toolKind);\n case \"tool.end\":\n // A `tool.end` carries no `toolKind`: only the start edge does. Classifying\n // from the name alone is what the canonical model permits here, so a shell\n // or file operation whose name does not say so lands on `tool` — and the\n // span for the same scope, which *did* recover the kind from state, is where\n // that detail is authoritative.\n return toolSignal(event.toolName, undefined);\n }\n};\n\nconst toolSignal = (\n toolName: string,\n toolKind: Extract<CanonicalEvent, { type: \"tool.start\" }>[\"toolKind\"] | undefined,\n): LogSignal => {\n if (MCP_TOOL_NAME_PATTERN.test(toolName)) {\n return \"mcp\";\n }\n switch (toolKind) {\n case \"execute\":\n return \"shell\";\n case \"read\":\n case \"write\":\n return \"file-operation\";\n case \"delegate\":\n return \"delegation\";\n default:\n return \"tool\";\n }\n};\n\n/**\n * Log signals an adapter declaring these lifecycle events can produce.\n *\n * Derived from the adapter's existing `lifecycleEvents` declaration rather than\n * declared separately, which is the whole point: a hand-maintained second list\n * can disagree with the first, and a capability declaration that has gone stale is\n * worse than none — a consumer cannot tell \"this provider reports no tool output\"\n * from \"this declaration was never updated\".\n *\n * The tool refinements (`shell`, `file-operation`, `mcp`) are reported whenever\n * the adapter emits tool events at all, because which of them a given callback\n * produces depends on the payload, not on the adapter. So this is a statement\n * about what *may* appear, not what always will.\n */\nexport const logSignalsForLifecycleEvents = (\n lifecycleEvents: readonly CanonicalEventType[],\n): readonly LogSignal[] => {\n const signals = new Set<LogSignal>();\n const add = (...values: readonly LogSignal[]): void => {\n for (const value of values) {\n signals.add(value);\n }\n };\n for (const type of lifecycleEvents) {\n switch (type) {\n case \"session.start\":\n case \"session.end\":\n add(\"session\");\n break;\n case \"prompt.submitted\":\n add(\"prompt\");\n break;\n case \"generation.start\":\n add(\"prompt\");\n break;\n case \"generation.end\":\n add(\"response\", \"reasoning\");\n break;\n case \"tool.start\":\n case \"tool.end\":\n add(\"tool\", \"shell\", \"file-operation\", \"mcp\", \"delegation\");\n break;\n case \"subagent.start\":\n case \"subagent.end\":\n add(\"delegation\");\n break;\n case \"compaction.performed\":\n add(\"compaction\");\n break;\n case \"error.raised\":\n add(\"error\");\n break;\n }\n }\n return LOG_SIGNALS.filter((signal) => signals.has(signal));\n};\n\nconst severityFor = (event: CanonicalEvent): SeverityNumber => {\n switch (event.type) {\n case \"error.raised\":\n return event.severity === \"error\" ? SeverityNumber.ERROR : SeverityNumber.WARN;\n case \"session.end\":\n return event.reason === \"error\" || event.reason === \"timeout\"\n ? SeverityNumber.ERROR\n : event.reason === \"aborted\"\n ? SeverityNumber.WARN\n : SeverityNumber.INFO;\n case \"generation.end\":\n case \"tool.end\":\n case \"subagent.end\":\n return event.outcome === \"error\" || event.outcome === \"timeout\"\n ? SeverityNumber.ERROR\n : event.outcome === \"denied\" || event.outcome === \"cancelled\"\n ? SeverityNumber.WARN\n : SeverityNumber.INFO;\n default:\n return SeverityNumber.INFO;\n }\n};\n\nconst SEVERITY_TEXT: Readonly<Record<number, string>> = Object.freeze({\n [SeverityNumber.INFO]: \"INFO\",\n [SeverityNumber.WARN]: \"WARN\",\n [SeverityNumber.ERROR]: \"ERROR\",\n});\n\nconst identityAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n ids: { readonly traceId: string; readonly spanId: string; readonly parentSpanId?: string },\n): Attributes => exportIdentityAttributes(event, resource, ids);\n\n/**\n * Attributes describing the event itself, independent of any content it carries.\n *\n * Every attribute here is a closed vocabulary, an identifier this library\n * derived, a count, or a boolean — the same restriction the privacy service\n * applies everywhere else, so an attribute can never become a second disclosure\n * path alongside the body.\n */\nconst eventAttributes = (event: CanonicalEvent): Attributes => {\n switch (event.type) {\n case \"session.start\":\n return {\n [ATTR_OTELHOOK_SESSION_KIND]: event.sessionKind,\n ...(event.agentName === undefined ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: event.agentName }),\n ...(event.agentVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_AGENT_VERSION]: event.agentVersion }),\n ...(event.model === undefined\n ? {}\n : { [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId }),\n ...targetAttributes(event),\n };\n case \"session.end\":\n return {\n [ATTR_OTELHOOK_OUTCOME]: event.reason,\n ...usageAttributes(event.usage),\n };\n case \"prompt.submitted\":\n return {\n [ATTR_OTELHOOK_PROMPT_SOURCE]: event.promptSource,\n ...(event.turnIndex === undefined\n ? {}\n : { [ATTR_OTELHOOK_PROMPT_TURN_INDEX]: event.turnIndex }),\n ...targetAttributes(event),\n };\n case \"generation.start\":\n return {\n [ATTR_GEN_AI_OPERATION_NAME]: \"chat\",\n [ATTR_OTELHOOK_GENERATION_ID]: event.generationId,\n [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId,\n ...(event.model.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: event.model.vendor }),\n };\n case \"generation.end\":\n return {\n [ATTR_GEN_AI_OPERATION_NAME]: \"chat\",\n [ATTR_OTELHOOK_GENERATION_ID]: event.generationId,\n [ATTR_GEN_AI_RESPONSE_MODEL]: event.model.modelId,\n ...(event.model.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: event.model.vendor }),\n [ATTR_OTELHOOK_OUTCOME]: event.outcome,\n ...(event.stopReason === undefined ? {} : { [ATTR_OTELHOOK_STOP_REASON]: event.stopReason }),\n ...usageAttributes(event.usage),\n ...(event.usage === undefined || event.usagePartial === undefined\n ? {}\n : { [ATTR_OTELHOOK_USAGE_PARTIAL]: event.usagePartial }),\n };\n case \"tool.start\":\n return {\n [ATTR_GEN_AI_TOOL_NAME]: event.toolName,\n [ATTR_GEN_AI_TOOL_CALL_ID]: event.toolCallId,\n [ATTR_OTELHOOK_TOOL_KIND]: event.toolKind,\n ...(event.generationId === undefined\n ? {}\n : { [ATTR_OTELHOOK_GENERATION_ID]: event.generationId }),\n ...targetAttributes(event),\n };\n case \"tool.end\":\n return {\n [ATTR_GEN_AI_TOOL_NAME]: event.toolName,\n [ATTR_GEN_AI_TOOL_CALL_ID]: event.toolCallId,\n [ATTR_OTELHOOK_OUTCOME]: event.outcome,\n ...(event.permissionDecision === undefined\n ? {}\n : { [ATTR_OTELHOOK_TOOL_PERMISSION]: event.permissionDecision }),\n ...targetAttributes(event),\n };\n case \"subagent.start\":\n return {\n [ATTR_OTELHOOK_DELEGATION_DEPTH]: event.delegationDepth,\n ...(event.subagentType === undefined\n ? {}\n : { [ATTR_OTELHOOK_SUBAGENT_TYPE]: event.subagentType }),\n ...(event.model === undefined ? {} : { [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId }),\n };\n case \"subagent.end\":\n return {\n [ATTR_OTELHOOK_OUTCOME]: event.outcome,\n ...usageAttributes(event.usage),\n };\n case \"compaction.performed\":\n return {\n [ATTR_OTELHOOK_COMPACTION_TRIGGER]: event.trigger,\n ...(event.contextTokensBefore === undefined\n ? {}\n : { [ATTR_OTELHOOK_CONTEXT_TOKENS_BEFORE]: event.contextTokensBefore }),\n ...(event.contextTokensAfter === undefined\n ? {}\n : { [ATTR_OTELHOOK_CONTEXT_TOKENS_AFTER]: event.contextTokensAfter }),\n ...(event.droppedMessageCount === undefined\n ? {}\n : { [ATTR_OTELHOOK_DROPPED_MESSAGES]: event.droppedMessageCount }),\n ...usageAttributes(event.usage),\n };\n case \"error.raised\":\n return {\n [ATTR_ERROR_TYPE]: event.errorCode,\n [ATTR_OTELHOOK_ERROR_PHASE]: event.phase,\n [ATTR_OTELHOOK_ERROR_RETRYABLE]: event.retryable,\n [ATTR_OTELHOOK_ERROR_SEVERITY]: event.severity,\n };\n }\n};\n\nconst usageAttributes = (usage: CanonicalUsage | undefined): Attributes =>\n usage === undefined\n ? {}\n : {\n [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: usage.inputTokens,\n [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: usage.outputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: usage.cachedInputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: usage.cacheCreationInputTokens,\n ...usageTemporalityAttributes(usage),\n };\n\n/** Content facts an event carries, paired with the field they came from. */\nconst contentFactsOf = (event: CanonicalEvent): readonly ContentFact[] => {\n switch (event.type) {\n case \"prompt.submitted\":\n return event.content === undefined ? [] : [event.content];\n case \"generation.start\":\n return event.inputContent ?? [];\n case \"generation.end\":\n return event.outputContent ?? [];\n case \"tool.start\":\n return event.input === undefined ? [] : [event.input];\n case \"tool.end\":\n return event.output === undefined ? [] : [event.output];\n case \"error.raised\":\n return event.message === undefined ? [] : [event.message];\n default:\n return [];\n }\n};\n\ntype DisclosedBody =\n | { readonly text: string; readonly truncated: boolean }\n | { readonly withheld: ContentWithholdingReason }\n | { readonly metadataOnly: true };\n\nconst discloseBody = (fact: ContentFact, policy: LogContentPolicy): DisclosedBody => {\n if (fact.text === undefined && fact.characterLength === 0) {\n // The provider sent no text. Distinct from a privacy omit of real content:\n // there is nothing to withhold, and the record must say metadata_only.\n return { metadataOnly: true };\n }\n if (fact.text === undefined) {\n return { withheld: \"privacy-policy\" };\n }\n if (!policy.includeContent) {\n return { withheld: \"logs-content-disabled\" };\n }\n if (fact.disclosure === \"raw\" && !policy.allowRawContent) {\n // Belt to the privacy service's braces: `resolvePrivacyPolicy` already\n // downgrades `raw` without the opt-in, so reaching here means a fact was built\n // outside that path. Refusing rather than trusting it keeps the opt-in a\n // property of the wire, not of one code path.\n return { withheld: \"raw-not-permitted\" };\n }\n const length = codePointLength(fact.text);\n return length <= MAX_LOG_BODY_CHARACTERS\n ? { text: fact.text, truncated: false }\n : { text: sliceCodePoints(fact.text, MAX_LOG_BODY_CHARACTERS), truncated: true };\n};\n\nconst contentAttributes = (fact: ContentFact, body: DisclosedBody): Attributes => ({\n [ATTR_CONTENT_KIND]: fact.kind,\n ...(fact.role === undefined ? {} : { [ATTR_CONTENT_ROLE]: fact.role }),\n [ATTR_CONTENT_DISCLOSURE]: \"metadataOnly\" in body ? \"metadata_only\" : fact.disclosure,\n [ATTR_CONTENT_CHARACTER_LENGTH]: fact.characterLength,\n [ATTR_CONTENT_BYTE_LENGTH]: fact.byteLength,\n [ATTR_CONTENT_HASH]: fact.contentHash,\n [ATTR_CONTENT_TRUNCATED]: fact.truncated,\n [ATTR_CONTENT_SECRETS_REDACTED]: fact.secretsRedacted,\n ...(fact.label === undefined ? {} : { [ATTR_CONTENT_LABEL]: fact.label }),\n ...(\"withheld\" in body\n ? { [ATTR_CONTENT_WITHHELD]: body.withheld }\n : \"metadataOnly\" in body\n ? {}\n : { [ATTR_CONTENT_BODY_TRUNCATED]: body.truncated }),\n});\n\nexport type LogMappingOptions = {\n readonly resource: Resource;\n readonly instrumentationScope?: InstrumentationScope;\n /** Whether disclosed text may reach a body. Defaults to {@link NO_LOG_CONTENT}. */\n readonly content?: LogContentPolicy;\n /**\n * The same cross-process pairing facts the span mapping is given, so a record's\n * `spanContext` names the span id that batch actually exported.\n */\n readonly correlations?: readonly SpanCorrelation[];\n /** See `SemanticMappingOptions.correlationAvailable`. */\n readonly correlationAvailable?: boolean;\n};\n\nexport type LogMappingResult = {\n readonly records: readonly ReadableLogRecord[];\n /**\n * Content facts no record was produced for, because a bound was reached.\n *\n * Reported rather than truncated silently: a caller that logged \"N records\n * exported\" and nothing else would read a clipped batch as a complete one.\n */\n readonly droppedFacts: number;\n};\n\nconst buildRecord = (input: {\n readonly event: CanonicalEvent;\n readonly signal: LogSignal;\n readonly attributes: Attributes;\n readonly body?: string;\n readonly spanContext: SpanContext;\n readonly parentSpanId?: string;\n readonly resource: Resource;\n readonly scope: InstrumentationScope;\n}): ReadableLogRecord => {\n const severityNumber = severityFor(input.event);\n const hrTime = millisToHrTime(input.event.occurredAt);\n return {\n hrTime,\n // A hook observes an event that already happened, and this mapping is pure —\n // there is no clock here to read a real observation time from. Reporting the\n // occurrence time for both is the honest answer: it says \"this is when it\n // happened\" twice rather than inventing a second, wrong timestamp.\n hrTimeObserved: hrTime,\n spanContext: input.spanContext,\n severityNumber,\n severityText: SEVERITY_TEXT[severityNumber] ?? \"INFO\",\n ...(input.body === undefined ? {} : { body: input.body }),\n eventName: `otelhook.${input.event.type}`,\n resource: input.resource,\n instrumentationScope: input.scope,\n attributes: {\n ...identityAttributes(input.event, input.resource, {\n traceId: input.spanContext.traceId,\n spanId: input.spanContext.spanId,\n ...(input.parentSpanId === undefined ? {} : { parentSpanId: input.parentSpanId }),\n }),\n [ATTR_OTELHOOK_EVENT_TYPE]: input.event.type,\n [ATTR_OTELHOOK_EVENT_ID]: input.event.eventId,\n [ATTR_OTELHOOK_EVENT_SEQUENCE]: input.event.sequence,\n [ATTR_OTELHOOK_LOG_SIGNAL]: input.signal,\n [ATTR_OTELHOOK_LOG_MAPPING_VERSION]: LOG_MAPPING_VERSION,\n ...input.attributes,\n },\n droppedAttributesCount: 0,\n };\n};\n\n/**\n * Map one invocation's canonical event batch into OTLP-ready log records.\n *\n * One record per content fact, and one record per event that carries none, so an\n * event is never silently absent from the stream just because the provider\n * reported no text for it.\n */\nexport const canonicalEventsToLogRecords = (\n events: readonly CanonicalEvent[],\n options: LogMappingOptions,\n): LogMappingResult => {\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const content = options.content ?? NO_LOG_CONTENT;\n const identities = canonicalEventTraceIdentities(events, {\n ...(options.correlations === undefined ? {} : { correlations: options.correlations }),\n ...(options.correlationAvailable === undefined\n ? {}\n : { correlationAvailable: options.correlationAvailable }),\n });\n\n const records: ReadableLogRecord[] = [];\n let droppedFacts = 0;\n\n for (const event of events) {\n const identity = identities.get(event.eventId);\n if (identity === undefined) {\n // Unreachable: every event in the batch is given an identity above.\n continue;\n }\n const spanContext: SpanContext = {\n traceId: identity.traceId,\n spanId: identity.spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n };\n const shared = eventAttributes(event);\n const facts = contentFactsOf(event);\n\n if (facts.length === 0) {\n if (records.length >= MAX_LOG_RECORDS_PER_BATCH) {\n droppedFacts += 1;\n continue;\n }\n records.push(\n buildRecord({\n event,\n signal: logSignalOf(event),\n attributes:\n event.type === \"generation.end\"\n ? { ...shared, [ATTR_CONTENT_KIND]: \"response\", [ATTR_CONTENT_DISCLOSURE]: \"metadata_only\" }\n : shared,\n spanContext,\n ...(identity.parentSpanId === undefined ? {} : { parentSpanId: identity.parentSpanId }),\n resource: options.resource,\n scope,\n }),\n );\n continue;\n }\n\n let perEvent = 0;\n for (const fact of facts) {\n if (perEvent >= MAX_LOG_RECORDS_PER_EVENT || records.length >= MAX_LOG_RECORDS_PER_BATCH) {\n droppedFacts += 1;\n continue;\n }\n perEvent += 1;\n const body = discloseBody(fact, content);\n records.push(\n buildRecord({\n event,\n signal: logSignalOf(event, fact.kind),\n attributes: { ...shared, ...contentAttributes(fact, body) },\n ...(\"text\" in body ? { body: body.text } : {}),\n spanContext,\n ...(identity.parentSpanId === undefined ? {} : { parentSpanId: identity.parentSpanId }),\n resource: options.resource,\n scope,\n }),\n );\n }\n }\n\n return { records, droppedFacts };\n};\n","import { ValueType } from \"@opentelemetry/api\";\nimport { ExportResultCode, millisToHrTime, type ExportResult, type InstrumentationScope } from \"@opentelemetry/core\";\nimport { OTLPMetricExporter } from \"@opentelemetry/exporter-metrics-otlp-proto\";\nimport { resourceFromAttributes, type Resource } from \"@opentelemetry/resources\";\nimport {\n AggregationTemporality,\n DataPointType,\n type MetricData,\n type ResourceMetrics,\n} from \"@opentelemetry/sdk-metrics\";\n\nimport { siblingSignalEndpoint } from \"../config/otlp-endpoint.js\";\nimport type { ExporterPolicy } from \"../config/schema.js\";\nimport { createHealthTracker, type DeliveryHealthSnapshot } from \"../diagnostics/health.js\";\nimport { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { Clock, Logger } from \"../runtime/ports.js\";\nimport type { DurableMetricSpool, MetricSpoolBatch } from \"./durable-metric-spool.js\";\nimport { isPermanentExportFailure } from \"./export-failure.js\";\nimport { replayResource, resourceFromExporterPolicy, resourceWithContext } from \"./exporter-resource.js\";\nimport { METRIC_INSTRUMENTS, withoutAccountIdentity, type MetricPoint } from \"./metric-model.js\";\nimport { DEFAULT_INSTRUMENTATION_SCOPE } from \"./semconv.js\";\nimport type { SpoolSendOutcome } from \"./spool-queue.js\";\n\n/**\n * OTLP HTTP/protobuf sink for hook-derived metrics (issue #69).\n *\n * Unlike the trace and log sinks, it does not take canonical events: the points it\n * sends are already aggregated (see `metric-model.ts` and\n * `lifecycle/metric-series.ts`), because cumulative aggregation needs state the\n * telemetry layer must not own. This module only encodes, sends, spools what a\n * destination could not take, and replays the spool on flush.\n *\n * There is deliberately no `MeterProvider` and no periodic reader. A hook process\n * lives for one callback; a reader that collects on an interval would either never\n * fire or hold the process open. Points are exported once, right after the\n * callback's telemetry, inside the same bounded flush window.\n *\n * Fails open like the other sinks: every failure is a diagnostic, never a throw.\n */\n\nexport type MetricsEndpointResolution =\n | { readonly endpoint: string; readonly derived: boolean }\n | { readonly unresolvable: \"no-endpoint\" };\n\n/**\n * Where metric points are posted: `metrics.endpoint` as stated, else the traces\n * endpoint with `/v1/traces` swapped for `/v1/metrics` (or `/v1/metrics` appended\n * to a base URL).\n */\nexport const resolveMetricsEndpoint = (exporter: ExporterPolicy): MetricsEndpointResolution => {\n const stated = exporter.metrics?.endpoint;\n if (stated !== undefined) {\n return { endpoint: stated, derived: false };\n }\n if (exporter.endpoint === undefined) {\n return { unresolvable: \"no-endpoint\" };\n }\n return { endpoint: siblingSignalEndpoint(exporter.endpoint, \"metrics\"), derived: true };\n};\n\nexport type MetricsDeliverability =\n | { readonly status: \"configured\"; readonly endpoint: string; readonly derivedEndpoint: boolean }\n | {\n readonly status: \"disabled\";\n readonly reason:\n | \"metrics-disabled\"\n | \"exporter-disabled\"\n | \"protocol-none\"\n | \"protocol-unsupported\"\n | \"no-endpoint\";\n };\n\nexport const describeMetricsDeliverability = (exporter: ExporterPolicy): MetricsDeliverability => {\n if (exporter.metrics?.enabled !== true) {\n return { status: \"disabled\", reason: \"metrics-disabled\" };\n }\n if (!exporter.enabled) {\n return { status: \"disabled\", reason: \"exporter-disabled\" };\n }\n if (exporter.protocol === \"none\") {\n return { status: \"disabled\", reason: \"protocol-none\" };\n }\n if (exporter.protocol !== \"http/protobuf\") {\n return { status: \"disabled\", reason: \"protocol-unsupported\" };\n }\n const resolved = resolveMetricsEndpoint(exporter);\n if (\"unresolvable\" in resolved) {\n return { status: \"disabled\", reason: \"no-endpoint\" };\n }\n return { status: \"configured\", endpoint: resolved.endpoint, derivedEndpoint: resolved.derived };\n};\n\nconst DISABLED_DETAIL: Readonly<\n Record<Exclude<Extract<MetricsDeliverability, { status: \"disabled\" }>[\"reason\"], \"metrics-disabled\">, string>\n> = Object.freeze({\n \"exporter-disabled\": \"otlp metric sink disabled: the exporter is disabled\",\n \"protocol-none\": \"otlp metric sink disabled: protocol is none\",\n \"protocol-unsupported\": \"otlp metric sink disabled: protocol not supported by this build\",\n \"no-endpoint\": \"otlp metric sink disabled: no metrics endpoint configured and none could be derived\",\n});\n\nexport type MetricExportResult = {\n /** Points delivered or spooled. */\n readonly accepted: number;\n readonly rejected: number;\n readonly errors: readonly OtelHookErrorInfo[];\n};\n\nexport interface OtlpMetricTelemetrySink {\n /** Whether this sink sends anything. A disabled sink accepts nothing and reports nothing. */\n readonly enabled: boolean;\n /**\n * `context`: the session context the points' events agree on (see\n * `agreedContextAttributes`). It overrides the same keys on the Resource for\n * this export, as the trace and log sinks do; the points carry it already.\n */\n exportPoints(\n points: readonly MetricPoint[],\n context?: Readonly<Record<string, string | number | boolean>>,\n ): Promise<MetricExportResult>;\n /** Replays spooled batches; bounded, best-effort, never throws. */\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n health(): DeliveryHealthSnapshot;\n drainSpool(\n maxBatches?: number,\n ): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }>;\n}\n\nexport type OtlpMetricSinkOptions = {\n readonly exporter: ExporterPolicy;\n readonly headers?: Readonly<Record<string, string>>;\n readonly providerId: string;\n readonly installationId: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n readonly spool?: DurableMetricSpool;\n readonly instrumentationScope?: InstrumentationScope;\n /** Export destination this sink delivers to. */\n readonly destination?: string;\n};\n\nconst createDisabledMetricSink = (destination?: string): OtlpMetricTelemetrySink => {\n const health = createHealthTracker(\n \"telemetry-metric-sink\",\n destination === undefined ? {} : { destination },\n );\n return {\n enabled: false,\n exportPoints: (): Promise<MetricExportResult> => Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),\n flush: (): Promise<void> => Promise.resolve(),\n shutdown: (): Promise<void> => Promise.resolve(),\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool: (): Promise<{\n readonly drained: number;\n readonly remaining: number;\n readonly failed: number;\n }> => Promise.resolve({ drained: 0, remaining: 0, failed: 0 }),\n };\n};\n\n/** A sink for a destination that does not take metrics, or a build with metrics off. */\nexport const createDisabledOtlpMetricSink = createDisabledMetricSink;\n\nconst toMetricData = (points: readonly MetricPoint[]): MetricData[] => {\n const byInstrument = new Map<string, MetricPoint[]>();\n for (const point of points) {\n const key = `${point.instrument}|${point.temporality}`;\n const group = byInstrument.get(key) ?? [];\n group.push(point);\n byInstrument.set(key, group);\n }\n const metrics: MetricData[] = [];\n for (const group of byInstrument.values()) {\n const first = group[0];\n if (first === undefined) {\n continue;\n }\n const instrument = METRIC_INSTRUMENTS[first.instrument];\n const descriptor = {\n name: instrument.name,\n description: instrument.description,\n unit: instrument.unit,\n valueType: instrument.valueType === \"int\" ? ValueType.INT : ValueType.DOUBLE,\n };\n const aggregationTemporality =\n first.temporality === \"cumulative\" ? AggregationTemporality.CUMULATIVE : AggregationTemporality.DELTA;\n const times = (point: MetricPoint): { startTime: [number, number]; endTime: [number, number] } => ({\n startTime: millisToHrTime(point.startTimeMillis),\n endTime: millisToHrTime(point.timeMillis),\n });\n if (instrument.kind === \"counter\") {\n metrics.push({\n descriptor,\n aggregationTemporality,\n dataPointType: DataPointType.SUM,\n isMonotonic: true,\n dataPoints: group.map((point) => ({\n ...times(point),\n attributes: { ...point.attributes },\n value: point.value ?? 0,\n })),\n });\n continue;\n }\n metrics.push({\n descriptor,\n aggregationTemporality,\n dataPointType: DataPointType.HISTOGRAM,\n dataPoints: group.map((point) => {\n const histogram = point.histogram;\n return {\n ...times(point),\n attributes: { ...point.attributes },\n value: {\n buckets: {\n boundaries: [...(instrument.boundaries ?? [])],\n counts: [...(histogram?.bucketCounts ?? [])],\n },\n count: histogram?.count ?? 0,\n sum: histogram?.sum ?? 0,\n ...(histogram === undefined || histogram.count === 0\n ? {}\n : { min: histogram.min, max: histogram.max }),\n },\n };\n }),\n });\n }\n return metrics;\n};\n\nexport const createOtlpMetricSink = (options: OtlpMetricSinkOptions): OtlpMetricTelemetrySink => {\n const destinationFields =\n options.destination === undefined ? {} : { \"export.destination\": options.destination };\n const deliverability = describeMetricsDeliverability(options.exporter);\n if (deliverability.status === \"disabled\") {\n if (deliverability.reason !== \"metrics-disabled\") {\n options.logger?.warn(DISABLED_DETAIL[deliverability.reason], {\n \"exporter.protocol\": options.exporter.protocol,\n ...destinationFields,\n });\n }\n return createDisabledMetricSink(options.destination);\n }\n\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n // No account identity on any metric, even if an operator put it on the resource.\n const resource = resourceFromAttributes(\n withoutAccountIdentity(resourceFromExporterPolicy(options.exporter).attributes),\n );\n const health = createHealthTracker(\n \"telemetry-metric-sink\",\n options.destination === undefined ? {} : { destination: options.destination },\n );\n const exporter = new OTLPMetricExporter({\n url: deliverability.endpoint,\n headers: { ...options.headers },\n timeoutMillis: options.exporter.timeoutMillis,\n });\n let shutdownCompleted = false;\n\n const exportResourceMetrics = (\n points: readonly MetricPoint[],\n batchResource: Resource,\n batchScope: InstrumentationScope,\n ): Promise<ExportResult> =>\n new Promise((resolve) => {\n const payload: ResourceMetrics = {\n resource: batchResource,\n scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }],\n };\n try {\n exporter.export(payload, (result: ExportResult) => resolve(result));\n } catch (thrown) {\n resolve({\n code: ExportResultCode.FAILED,\n error: thrown instanceof Error ? thrown : new Error(\"export threw\"),\n });\n }\n });\n\n const toSpoolBatch = (points: readonly MetricPoint[], batchResource: Resource): MetricSpoolBatch => ({\n providerId: options.providerId,\n installationId: options.installationId,\n resourceAttributes: { ...batchResource.attributes },\n instrumentationScope: {\n name: scope.name,\n ...(scope.version === undefined ? {} : { version: scope.version }),\n },\n points: points.map((point) => ({ ...point })),\n enqueuedAt: options.clock.now(),\n });\n\n const sendSerializedBatch = async (batch: MetricSpoolBatch): Promise<SpoolSendOutcome> => {\n const batchResource = resourceFromAttributes(\n withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes),\n );\n const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);\n if (result.code === ExportResultCode.SUCCESS) {\n return true;\n }\n return isPermanentExportFailure(result) ? \"discard\" : false;\n };\n\n const exportPoints = async (\n points: readonly MetricPoint[],\n context?: Readonly<Record<string, string | number | boolean>>,\n ): Promise<MetricExportResult> => {\n if (points.length === 0) {\n return { accepted: 0, rejected: 0, errors: [] };\n }\n const batchResource = context === undefined ? resource : resourceWithContext(resource, context);\n const result = await exportResourceMetrics(points, batchResource, scope);\n if (result.code === ExportResultCode.SUCCESS) {\n health.recordSuccess(points.length, options.clock.now());\n return { accepted: points.length, rejected: 0, errors: [] };\n }\n health.recordFailure(\"telemetry-export-failure\", points.length, options.clock.now());\n const permanent = isPermanentExportFailure(result);\n if (options.spool !== undefined && !permanent) {\n const spooled = await options.spool.enqueue(toSpoolBatch(points, batchResource)).catch(() => ({\n spooled: false as const,\n reason: \"capacity-exceeded\" as const,\n }));\n if (spooled.spooled) {\n options.logger?.warn(\"metric batch not delivered; spooled for the next invocation\", {\n \"export.batch_size\": points.length,\n ...destinationFields,\n });\n return { accepted: points.length, rejected: 0, errors: [] };\n }\n }\n return {\n accepted: 0,\n rejected: points.length,\n errors: [\n createErrorInfo({\n code: \"telemetry-export-failure\",\n phase: \"export\",\n detail: permanent\n ? \"collector refused a metric batch with a non-retryable status\"\n : \"collector rejected or was unreachable for a metric batch\",\n details: {\n \"export.batch_size\": points.length,\n \"export.signal\": \"metrics\",\n ...destinationFields,\n },\n }),\n ],\n };\n };\n\n const drainSpool = async (\n maxBatches?: number,\n ): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }> => {\n if (options.spool === undefined) {\n return { drained: 0, remaining: 0, failed: 0 };\n }\n const result = await options.spool.drain(sendSerializedBatch, {\n ...(maxBatches === undefined ? {} : { maxBatches }),\n });\n if (result.drained > 0) {\n health.recordSuccess(result.drained, options.clock.now());\n }\n return result;\n };\n\n const flush = async (): Promise<void> => {\n try {\n await exporter.forceFlush();\n } catch {\n // Best-effort; reported through health.\n }\n await drainSpool().catch(() => undefined);\n };\n\n const shutdown = async (): Promise<void> => {\n if (shutdownCompleted) {\n return;\n }\n shutdownCompleted = true;\n await flush();\n try {\n await exporter.shutdown();\n } catch {\n // Idempotent and non-throwing.\n }\n };\n\n return {\n enabled: true,\n exportPoints,\n flush,\n shutdown,\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool,\n };\n};\n","import { ExportResultCode, type ExportResult } from \"@opentelemetry/core\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-proto\";\nimport type { InstrumentationScope } from \"@opentelemetry/core\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport type { ReadableSpan } from \"@opentelemetry/sdk-trace\";\n\nimport type { ExporterPolicy } from \"../config/schema.js\";\nimport { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport { createHealthTracker, type DeliveryHealthSnapshot } from \"../diagnostics/health.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { Clock, Logger, TelemetryEmitResult, TelemetrySink } from \"../runtime/ports.js\";\nimport type { DurableSpool, SerializedSpan, SpoolBatch } from \"./durable-spool.js\";\nimport { isPermanentExportFailure } from \"./export-failure.js\";\nimport type { SpoolSendOutcome } from \"./spool-queue.js\";\nimport {\n agreedContextAttributes,\n replayResource,\n resourceFromExporterPolicy,\n resourceWithContext,\n} from \"./exporter-resource.js\";\nimport {\n assembleReadableSpan,\n canonicalEventsToReadableSpans,\n DEFAULT_INSTRUMENTATION_SCOPE,\n type SpanCorrelation,\n type SpanCorrelationResolver,\n} from \"./semconv.js\";\n\nconst chunk = <T,>(items: readonly T[], size: number): readonly (readonly T[])[] => {\n if (size <= 0 || items.length <= size) {\n return [items];\n }\n const chunks: T[][] = [];\n for (let index = 0; index < items.length; index += size) {\n chunks.push(items.slice(index, index + size));\n }\n return chunks;\n};\n\nconst serializeSpan = (span: ReadableSpan): SerializedSpan => ({\n name: span.name,\n kind: span.kind,\n traceId: span.spanContext().traceId,\n spanId: span.spanContext().spanId,\n ...(span.parentSpanContext === undefined\n ? {}\n : { parentSpanId: span.parentSpanContext.spanId }),\n startMillis: span.startTime[0] * 1000 + Math.round(span.startTime[1] / 1e6),\n endMillis: span.endTime[0] * 1000 + Math.round(span.endTime[1] / 1e6),\n attributes: { ...span.attributes },\n statusCode: span.status.code,\n ...(span.status.message === undefined ? {} : { statusMessage: span.status.message }),\n});\n\nconst deserializeSpan = (\n serialized: SerializedSpan,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan =>\n assembleReadableSpan({\n name: serialized.name,\n kind: serialized.kind,\n startMillis: serialized.startMillis,\n endMillis: serialized.endMillis,\n attributes: serialized.attributes,\n status: { code: serialized.statusCode, ...(serialized.statusMessage === undefined ? {} : { message: serialized.statusMessage }) },\n traceId: serialized.traceId,\n spanId: serialized.spanId,\n ...(serialized.parentSpanId === undefined ? {} : { parentSpanId: serialized.parentSpanId }),\n resource,\n instrumentationScope: scope,\n });\n\nexport type OtlpTraceSinkOptions = {\n readonly exporter: ExporterPolicy;\n /** Header values, kept out of the resolved-config snapshot (ADR: config carries only header *names*). */\n readonly headers?: Readonly<Record<string, string>>;\n readonly providerId: string;\n readonly installationId: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Persists batches an unreachable collector rejected, for a later retry. */\n readonly spool?: DurableSpool;\n readonly instrumentationScope?: InstrumentationScope;\n /**\n * Supplies cross-process pairing for lifecycle spans, normally the\n * {@link SpanCorrelator}. Omitted, the sink pairs only within a batch.\n *\n * Injected as a plain function rather than as a correlator so the telemetry\n * layer keeps no dependency on lifecycle or on the state store (ADR 0006).\n */\n readonly correlate?: SpanCorrelationResolver;\n /**\n * Export destination this sink delivers to, when `exporter.destinations` is in\n * use. Labels health snapshots, diagnostics, and log lines; absent, all three are\n * exactly what a single-destination installation has always produced.\n */\n readonly destination?: string;\n};\n\nexport interface OtlpTelemetrySink extends TelemetrySink {\n health(): DeliveryHealthSnapshot;\n /** Attempts to resend previously spooled batches, bounded by `maxBatches`. */\n drainSpool(maxBatches?: number): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }>;\n}\n\n/** Sink that accepts every batch and does nothing else: exporter disabled or protocol `none`. */\nconst createDisabledSink = (destination?: string): OtlpTelemetrySink => {\n const health = createHealthTracker(\n \"telemetry-sink\",\n destination === undefined ? {} : { destination },\n );\n return {\n emit: (events): Promise<TelemetryEmitResult> => {\n health.recordSuccess(events.length);\n return Promise.resolve({ accepted: events.length, rejected: 0, errors: [] });\n },\n flush: (): Promise<void> => Promise.resolve(),\n shutdown: (): Promise<void> => Promise.resolve(),\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool: (): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }> =>\n Promise.resolve({ drained: 0, remaining: 0, failed: 0 }),\n };\n};\n\n/**\n * OTLP HTTP/protobuf {@link TelemetrySink}.\n *\n * Semantic mapping lives entirely in `semconv.ts`; this module only owns\n * batching, delivery, bounded flush/shutdown, health tracking, and — when a\n * spool is configured — persisting what a down collector rejected. Every\n * failure mode (disabled config, missing endpoint, export failure, timeout,\n * spool write failure, unreadable correlation state) degrades to a reported\n * diagnostic rather than a thrown error, preserving the hook's fail-open\n * contract.\n *\n * A disabled sink never calls `correlate`: with nothing being exported there is\n * no span to pair, and writing correlation state anyway would leave a disabled\n * installation quietly accumulating files.\n */\nexport const createOtlpTraceSink = (options: OtlpTraceSinkOptions): OtlpTelemetrySink => {\n const destinationFields =\n options.destination === undefined ? {} : { \"export.destination\": options.destination };\n if (!options.exporter.enabled || options.exporter.protocol === \"none\") {\n return createDisabledSink(options.destination);\n }\n if (options.exporter.endpoint === undefined) {\n options.logger?.warn(\"otlp sink disabled: no endpoint configured\", destinationFields);\n return createDisabledSink(options.destination);\n }\n if (options.exporter.protocol !== \"http/protobuf\") {\n options.logger?.warn(\"otlp sink: protocol not supported by this build, falling back to disabled\", {\n \"exporter.protocol\": options.exporter.protocol,\n ...destinationFields,\n });\n return createDisabledSink(options.destination);\n }\n\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const resource = resourceFromExporterPolicy(options.exporter);\n const health = createHealthTracker(\n \"telemetry-sink\",\n options.destination === undefined ? {} : { destination: options.destination },\n );\n const exporter = new OTLPTraceExporter({\n url: options.exporter.endpoint,\n headers: { ...options.headers },\n timeoutMillis: options.exporter.timeoutMillis,\n });\n let shutdownCompleted = false;\n\n const exportSpans = (spans: readonly ReadableSpan[]): Promise<ExportResult> =>\n new Promise((resolve) => {\n exporter.export([...spans], (result: ExportResult) => resolve(result));\n });\n\n const toSpoolBatch = (spans: readonly ReadableSpan[], batchResource: Resource): SpoolBatch => ({\n providerId: options.providerId,\n installationId: options.installationId,\n resourceAttributes: { ...batchResource.attributes },\n instrumentationScope: { name: scope.name, ...(scope.version === undefined ? {} : { version: scope.version }) },\n spans: spans.map(serializeSpan),\n enqueuedAt: options.clock.now(),\n });\n\n const sendSerializedBatch = async (batch: SpoolBatch): Promise<SpoolSendOutcome> => {\n const batchResource = replayResource(batch.resourceAttributes, options.exporter);\n const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));\n const result = await exportSpans(spans);\n if (result.code === ExportResultCode.SUCCESS) {\n return true;\n }\n return isPermanentExportFailure(result) ? \"discard\" : false;\n };\n\n /**\n * Cross-process pairing is an enrichment, never a precondition: if state is\n * unreadable the batch still exports, with each lifecycle span flagged\n * unpaired rather than dropped.\n *\n * `available` is reported separately from the (possibly empty) list because the\n * mapping needs the two apart. An empty list from a healthy correlator and an\n * empty list from a correlator that threw look identical, and only the first\n * means \"the state store is holding these starts\". Conflating them would drop an\n * unpaired start that nothing recorded, and the export would then report zero\n * rejections — so a caller would commit a callback whose telemetry went nowhere.\n */\n const resolveCorrelations = async (\n events: readonly CanonicalEvent[],\n ): Promise<{\n readonly correlations: readonly SpanCorrelation[];\n readonly available: boolean | undefined;\n }> => {\n if (options.correlate === undefined) {\n return { correlations: [], available: undefined };\n }\n try {\n return { correlations: await options.correlate(events), available: true };\n } catch {\n options.logger?.warn(\"span correlation unavailable; exporting unpaired spans\", {});\n return { correlations: [], available: false };\n }\n };\n\n const emit = async (events: Parameters<TelemetrySink[\"emit\"]>[0]): Promise<TelemetryEmitResult> => {\n if (events.length === 0) {\n return { accepted: 0, rejected: 0, errors: [] };\n }\n const resolved = await resolveCorrelations(events);\n // Session context overrides the same keys on the Resource for this batch, so\n // a backend reading the Resource sees what the records say.\n const batchResource = resourceWithContext(resource, agreedContextAttributes(events));\n const spans = canonicalEventsToReadableSpans(events, {\n resource: batchResource,\n instrumentationScope: scope,\n correlations: resolved.correlations,\n ...(resolved.available === undefined ? {} : { correlationAvailable: resolved.available }),\n });\n const errors: OtelHookErrorInfo[] = [];\n let accepted = 0;\n let rejected = 0;\n\n for (const batch of chunk(spans, options.exporter.maxBatchSize)) {\n if (batch.length === 0) {\n // A batch of only start edges maps to no span at all: a lone `*.start` is\n // held for its end rather than exported. Sending it anyway POSTed an\n // `ExportTraceServiceRequest` with no resource spans — an empty body at the\n // collector — and, against a down collector, spooled an empty batch that\n // the drain could only quarantine.\n continue;\n }\n let result: ExportResult;\n try {\n result = await exportSpans(batch);\n } catch (thrown) {\n result = { code: ExportResultCode.FAILED, error: thrown instanceof Error ? thrown : new Error(\"export threw\") };\n }\n if (result.code === ExportResultCode.SUCCESS) {\n accepted += batch.length;\n health.recordSuccess(batch.length, options.clock.now());\n continue;\n }\n\n health.recordFailure(\"telemetry-export-failure\", batch.length, options.clock.now());\n const permanent = isPermanentExportFailure(result);\n if (options.spool !== undefined && !permanent) {\n const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({\n spooled: false as const,\n reason: \"capacity-exceeded\" as const,\n }));\n if (spoolResult.spooled) {\n accepted += batch.length;\n options.logger?.warn(\"span batch not delivered; spooled for the next invocation\", {\n \"export.batch_size\": batch.length,\n ...destinationFields,\n });\n continue;\n }\n }\n rejected += batch.length;\n errors.push(\n createErrorInfo({\n code: \"telemetry-export-failure\",\n phase: \"export\",\n detail: permanent\n ? \"collector refused a span batch with a non-retryable status\"\n : \"collector rejected or was unreachable for a span batch\",\n details: { \"export.batch_size\": batch.length, ...destinationFields },\n }),\n );\n }\n\n return { accepted, rejected, errors };\n };\n\n const drainSpool = async (\n maxBatches?: number,\n ): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }> => {\n if (options.spool === undefined) {\n return { drained: 0, remaining: 0, failed: 0 };\n }\n const result = await options.spool.drain(sendSerializedBatch, { ...(maxBatches === undefined ? {} : { maxBatches }) });\n if (result.drained > 0) {\n health.recordSuccess(result.drained, options.clock.now());\n }\n return result;\n };\n\n const flush = async (): Promise<void> => {\n try {\n await exporter.forceFlush();\n } catch {\n // Best-effort: flush failures are reported through health, never thrown.\n }\n await drainSpool().catch(() => undefined);\n };\n\n const shutdown = async (): Promise<void> => {\n if (shutdownCompleted) {\n return;\n }\n shutdownCompleted = true;\n await flush();\n try {\n await exporter.shutdown();\n } catch {\n // Idempotent, non-throwing per the TelemetrySink contract.\n }\n };\n\n return {\n emit,\n flush,\n shutdown,\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool,\n };\n};\n","import 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 {\n DEFAULT_DESTINATION_NAME,\n effectiveSpoolPolicy,\n hasConfiguredDestinations,\n resolveDestinationHeaders,\n resolveExportDestinations,\n type ExportDestination,\n} from \"../config/destinations.js\";\nimport { siblingSignalEndpoint } from \"../config/otlp-endpoint.js\";\nimport { effectiveMetricsPolicy, type ExporterPolicy } from \"../config/schema.js\";\nimport type { DeliveryHealthSnapshot } from \"../diagnostics/health.js\";\nimport { createHealthTracker } from \"../diagnostics/health.js\";\nimport { errorInfoFromThrown, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { Clock, Logger, TelemetryEmitResult } from \"../runtime/ports.js\";\nimport { createFileDurableLogSpool, type DurableLogSpool } from \"./durable-log-spool.js\";\nimport { createFileDurableMetricSpool, type DurableMetricSpool } from \"./durable-metric-spool.js\";\nimport { createFileDurableSpool, type DurableSpool } from \"./durable-spool.js\";\nimport type { LogContentPolicy } from \"./log-records.js\";\nimport {\n createOtlpLogSink,\n resolveLogsEndpoint,\n type OtlpLogTelemetrySink,\n} from \"./otlp-log-sink.js\";\nimport {\n createDisabledOtlpMetricSink,\n createOtlpMetricSink,\n type OtlpMetricTelemetrySink,\n} from \"./otlp-metric-sink.js\";\nimport { createOtlpTraceSink, type OtlpTelemetrySink } from \"./otlp-sink.js\";\nimport type { SpanCorrelationResolver } from \"./semconv.js\";\nimport { createSignalFanout, type SignalFanoutSink } from \"./signal-fanout.js\";\n\n/**\n * Spool queue directories for one destination, below the identity namespace.\n *\n * `default` keeps the directories it has always had, so batches an earlier\n * version queued are still drained after an upgrade. Every other destination\n * queues under `destinations/<name>/`, so one destination's outage can never\n * consume another's budget or be drained by another's sender.\n */\nexport const spoolQueueNamesFor = (\n destination: string,\n): { readonly traces: string; readonly logs: string; readonly metrics: string } =>\n destination === DEFAULT_DESTINATION_NAME\n ? { traces: \"spool\", logs: \"spool-logs\", metrics: \"spool-metrics\" }\n : {\n traces: `destinations/${destination}/spool`,\n logs: `destinations/${destination}/spool-logs`,\n metrics: `destinations/${destination}/spool-metrics`,\n };\n\n/**\n * The exporter policy one destination's sinks are built from.\n *\n * Everything but where and how to send — timeout, batch sizes, service identity,\n * resource attributes, log content policy — is shared, so every destination\n * receives the same spans. The `default` destination gets the policy unchanged.\n */\nexport const exporterPolicyForDestination = (\n exporter: ExporterPolicy,\n destination: ExportDestination,\n): ExporterPolicy => {\n if (destination.source === \"exporter\") {\n return exporter;\n }\n const { destinations, endpoint, logs, ...shared } = exporter;\n void destinations;\n void endpoint;\n const tracesEndpoint = destination.tracesEndpoint ?? destination.endpoint;\n // An explicit logs URL wins; otherwise derive from `endpoint` (not from a\n // traces-only override), and failing that let the sink derive from the traces URL.\n const derivedLogs =\n destination.logsEndpoint ??\n (destination.endpoint === undefined\n ? undefined\n : (() => {\n const derived = resolveLogsEndpoint({\n ...exporter,\n endpoint: destination.endpoint,\n logs: { enabled: true, includeContent: false, maxBatchSize: logs.maxBatchSize },\n });\n return \"endpoint\" in derived ? derived.endpoint : undefined;\n })());\n const { metrics: sharedMetrics, ...rest } = shared;\n // Like logs: an explicit metrics URL wins; otherwise derive from `endpoint`, and\n // failing that let the sink derive from the traces URL.\n const derivedMetrics =\n destination.metricsEndpoint ??\n (destination.endpoint === undefined\n ? undefined\n : siblingSignalEndpoint(destination.endpoint, \"metrics\"));\n return {\n ...rest,\n protocol: destination.protocol,\n ...(tracesEndpoint === undefined ? {} : { endpoint: tracesEndpoint }),\n headerNames: Object.keys(destination.headers).sort(),\n logs: {\n ...logs,\n enabled: destination.signals.logs,\n ...(derivedLogs === undefined ? {} : { endpoint: derivedLogs }),\n },\n metrics: {\n ...effectiveMetricsPolicy({ ...exporter, metrics: sharedMetrics }),\n enabled: destination.signals.metrics,\n ...(derivedMetrics === undefined ? {} : { endpoint: derivedMetrics }),\n },\n };\n};\n\n/** The pair of sinks, and their spools, serving one destination. */\nexport type ExportDestinationSinks = {\n readonly name: string;\n readonly traces: OtlpTelemetrySink;\n readonly logs: OtlpLogTelemetrySink;\n readonly spool?: DurableSpool;\n readonly logSpool?: DurableLogSpool;\n /** Hook-derived metrics; a disabled sink unless this destination takes `metrics`. */\n readonly metrics: OtlpMetricTelemetrySink;\n readonly metricSpool?: DurableMetricSpool;\n};\n\n/** A destination left out of this invocation, and why — by name only. */\nexport type SkippedExportDestination = {\n readonly name: string;\n readonly reason: \"header-variable-missing\";\n /** Environment variable *names*; never a value. */\n readonly missingVariables: readonly string[];\n};\n\nexport type ExportDestinationsOptions = {\n readonly exporter: ExporterPolicy;\n /**\n * Header values for the `default` destination's traces: `--header` over\n * `OTEL_EXPORTER_OTLP_TRACES_HEADERS` over `OTEL_EXPORTER_OTLP_HEADERS`, as\n * resolved by `resolveOtlpHeaders`.\n */\n readonly defaultHeaders?: Readonly<Record<string, string>>;\n /**\n * Header values for the `default` destination's logs, when they differ from\n * its traces' (`OTEL_EXPORTER_OTLP_LOGS_HEADERS`). Defaults to {@link defaultHeaders}.\n */\n readonly defaultLogHeaders?: Readonly<Record<string, string>>;\n /**\n * The environment `env:` header references resolve against. Never read\n * implicitly; without it, a destination whose headers reference a variable is\n * skipped and reported.\n */\n readonly headerEnvironment?: Readonly<Record<string, string | undefined>>;\n readonly providerId: string;\n readonly installationId: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Root of the spool trees. Absent, nothing is spooled. */\n readonly spoolRootDir?: string;\n /** Whether the logs signal gets a spool at all; it is only built when logs are on. */\n readonly logContent: LogContentPolicy;\n readonly correlate?: SpanCorrelationResolver;\n};\n\n/**\n * A trace sink for a destination that does not take the traces signal.\n *\n * Contributes zero accepted and zero rejected — unlike a *disabled exporter*,\n * which accepts everything — because the counts decide commit-or-retry and a\n * signal that never tried must not make a real loss elsewhere look delivered.\n */\nconst createOptedOutTraceSink = (destination: string | undefined): OtlpTelemetrySink => {\n const health = createHealthTracker(\n \"telemetry-sink\",\n destination === undefined ? {} : { destination },\n );\n return {\n emit: (): Promise<TelemetryEmitResult> =>\n Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),\n flush: (): Promise<void> => Promise.resolve(),\n shutdown: (): Promise<void> => Promise.resolve(),\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool: (): Promise<{\n readonly drained: number;\n readonly remaining: number;\n readonly failed: number;\n }> => Promise.resolve({ drained: 0, remaining: 0, failed: 0 }),\n };\n};\n\n/**\n * Build one sink pair per enabled destination.\n *\n * With no `exporter.destinations`, this is exactly the single `default`\n * destination the runtime has always built: the same policy, the same header\n * values, the same spool directories.\n */\nexport const createExportDestinationSinks = (\n options: ExportDestinationsOptions,\n): {\n readonly destinations: readonly ExportDestinationSinks[];\n readonly skipped: readonly SkippedExportDestination[];\n} => {\n const labelled = hasConfiguredDestinations(options.exporter);\n const spoolPolicy = effectiveSpoolPolicy(options.exporter);\n const destinations: ExportDestinationSinks[] = [];\n const skipped: SkippedExportDestination[] = [];\n\n for (const destination of resolveExportDestinations(options.exporter)) {\n let headers: Readonly<Record<string, string>> | undefined;\n let logHeaders: Readonly<Record<string, string>> | undefined;\n if (destination.source === \"exporter\") {\n headers = options.defaultHeaders;\n logHeaders = options.defaultLogHeaders ?? options.defaultHeaders;\n } else {\n const resolved = resolveDestinationHeaders(destination.headers, options.headerEnvironment);\n if (resolved.missingVariables.length > 0) {\n // Sending without the header would be refused at best, and at worst\n // accepted into somebody else's unauthenticated tenant. So the destination\n // sits this invocation out, and says which variable it is waiting for.\n options.logger?.warn(\"export destination skipped: a header references an unset environment variable\", {\n \"export.destination\": destination.name,\n \"config.variables\": [...resolved.missingVariables],\n });\n skipped.push({\n name: destination.name,\n reason: \"header-variable-missing\",\n missingVariables: resolved.missingVariables,\n });\n continue;\n }\n headers = resolved.values;\n logHeaders = resolved.values;\n }\n\n const label = labelled ? destination.name : undefined;\n const policy = exporterPolicyForDestination(options.exporter, destination);\n const queues = spoolQueueNamesFor(destination.name);\n const bounds = {\n maxSpoolFiles: spoolPolicy.maxBatches,\n maxBytes: spoolPolicy.maxBytes,\n maxAgeMillis: spoolPolicy.maxAgeMillis,\n overflow: \"drop-oldest\" as const,\n };\n const shared = {\n providerId: options.providerId,\n installationId: options.installationId,\n clock: options.clock,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n };\n const spool =\n options.spoolRootDir === undefined || !destination.signals.traces\n ? undefined\n : createFileDurableSpool({\n rootDir: options.spoolRootDir,\n ...shared,\n ...bounds,\n queueName: queues.traces,\n });\n // Only built when logs are on: a default installation must not create a\n // directory for a signal it never emits.\n const logSpool =\n options.spoolRootDir === undefined || !destination.signals.logs\n ? undefined\n : createFileDurableLogSpool({\n rootDir: options.spoolRootDir,\n ...shared,\n ...bounds,\n queueName: queues.logs,\n });\n\n const metricSpool =\n options.spoolRootDir === undefined || !destination.signals.metrics\n ? undefined\n : createFileDurableMetricSpool({\n rootDir: options.spoolRootDir,\n ...shared,\n ...bounds,\n queueName: queues.metrics,\n });\n\n const sinkShared = {\n exporter: policy,\n ...shared,\n ...(options.correlate === undefined ? {} : { correlate: options.correlate }),\n ...(label === undefined ? {} : { destination: label }),\n };\n const traces = destination.signals.traces\n ? createOtlpTraceSink({\n ...sinkShared,\n ...(headers === undefined || Object.keys(headers).length === 0 ? {} : { headers }),\n ...(spool === undefined ? {} : { spool }),\n })\n : createOptedOutTraceSink(label);\n const logs = createOtlpLogSink({\n ...sinkShared,\n ...(logHeaders === undefined || Object.keys(logHeaders).length === 0\n ? {}\n : { headers: logHeaders }),\n ...(logSpool === undefined ? {} : { spool: logSpool }),\n content: options.logContent,\n });\n const metrics = destination.signals.metrics\n ? createOtlpMetricSink({\n exporter: policy,\n ...shared,\n ...(label === undefined ? {} : { destination: label }),\n ...(headers === undefined || Object.keys(headers).length === 0 ? {} : { headers }),\n ...(metricSpool === undefined ? {} : { spool: metricSpool }),\n })\n : createDisabledOtlpMetricSink(label);\n destinations.push({\n name: destination.name,\n traces,\n logs,\n metrics,\n ...(spool === undefined ? {} : { spool }),\n ...(logSpool === undefined ? {} : { logSpool }),\n ...(metricSpool === undefined ? {} : { metricSpool }),\n });\n }\n return { destinations, skipped };\n};\n\n/**\n * One canonical batch, every destination, in parallel.\n *\n * Each destination is its own {@link createSignalFanout} (traces then logs, which\n * must stay sequential so they share one correlation resolution); destinations run\n * concurrently, each bounded by the exporter's own timeout, so a slow or dead\n * destination costs at most that timeout and never another destination's delivery.\n * A destination that throws is contained to a rejection of its own share.\n *\n * Counts are summed across destinations, which gives the durability decision the\n * right inputs: everything delivered or spooled → `delivered`; nothing → `lost`\n * and safe to retry; some → `partial`, terminal, because retrying would re-export\n * to the destinations that already accepted.\n *\n * With one destination this returns that destination's fanout unchanged.\n */\nexport const createDestinationFanout = (\n destinations: readonly ExportDestinationSinks[],\n): SignalFanoutSink => {\n const fanouts = destinations.map((destination) => ({\n name: destination.name,\n sink: createSignalFanout({ traces: destination.traces, logs: destination.logs }),\n }));\n const only = fanouts.length === 1 ? fanouts[0] : undefined;\n if (only !== undefined) {\n return only.sink;\n }\n\n const emit = async (events: readonly CanonicalEvent[]): Promise<TelemetryEmitResult> => {\n const results = await Promise.all(\n fanouts.map((fanout) =>\n fanout.sink.emit(events).catch(\n (thrown: unknown): TelemetryEmitResult => ({\n accepted: 0,\n rejected: events.length,\n errors: [errorInfoFromThrown(thrown, { code: \"telemetry-export-failure\", phase: \"export\" })],\n }),\n ),\n ),\n );\n const errors: OtelHookErrorInfo[] = results.flatMap((result) => result.errors);\n return {\n accepted: results.reduce((sum, result) => sum + result.accepted, 0),\n rejected: results.reduce((sum, result) => sum + result.rejected, 0),\n errors,\n };\n };\n\n const settleAll = async (run: (sink: SignalFanoutSink) => Promise<void>): Promise<void> => {\n await Promise.all(fanouts.map((fanout) => run(fanout.sink).catch(() => undefined)));\n };\n\n return {\n emit,\n // Each destination drains its own spool in its flush; in parallel, so one\n // unreachable destination's drain cannot use up the others' flush window.\n flush: () => settleAll((sink) => sink.flush()),\n shutdown: () => settleAll((sink) => sink.shutdown()),\n health: (): readonly DeliveryHealthSnapshot[] => fanouts.flatMap((fanout) => fanout.sink.health()),\n };\n};\n","import { readsClaudeTranscriptUsage, sessionContextDir, 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 { createMetricSeriesStore, type MetricSeriesStore } from \"../lifecycle/metric-series.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 { createClaudeTranscriptUsageEnricher } from \"../providers/claude/transcript.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 {\n Clock,\n IdGenerator,\n Logger,\n PayloadEnricher,\n SessionContextReader,\n WorktreeLocator,\n} from \"../runtime/ports.js\";\nimport { createDirectorySessionContextReader } from \"../runtime/session-context.js\";\nimport { createAsyncLock } from \"../state/async-lock.js\";\nimport { createFilesystemStateStore, type FilesystemStateStore } from \"../state/filesystem-store.js\";\nimport type { DurableLogSpool } from \"../telemetry/durable-log-spool.js\";\nimport type { DurableSpool } from \"../telemetry/durable-spool.js\";\nimport {\n createDestinationFanout,\n createExportDestinationSinks,\n type ExportDestinationSinks,\n type SkippedExportDestination,\n} from \"../telemetry/export-destinations.js\";\nimport { effectiveMetricsPolicy } from \"../config/schema.js\";\nimport { agreedContextAttributes, resourceFromExporterPolicy } from \"../telemetry/exporter-resource.js\";\nimport {\n aggregateDeltaPoints,\n deriveMetricObservations,\n type GenerationStart,\n type MetricPoint,\n} from \"../telemetry/metric-model.js\";\nimport { createOtlpLogSink, type OtlpLogTelemetrySink } from \"../telemetry/otlp-log-sink.js\";\nimport { createOtlpTraceSink, type OtlpTelemetrySink } from \"../telemetry/otlp-sink.js\";\nimport {\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 /**\n * Hook-derived metrics for this callback (issue #69). Absent when no destination\n * takes metrics, or when nothing was recorded (a redelivery, a callback whose\n * telemetry was lost and will be retried, or a batch with nothing to measure).\n */\n readonly metrics?: MetricsReport;\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 MetricsReport = {\n /** Data points derived for this callback, before fan-out. */\n readonly points: number;\n /** Per destination taking metrics: points delivered or spooled, and refused. */\n readonly destinations: readonly {\n readonly name: string;\n readonly accepted: number;\n readonly rejected: number;\n }[];\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 /**\n * The traces signal of the primary destination — `default`, or the first entry\n * of `exporter.destinations` when there is no single-endpoint setting. Named\n * `sink` because it is the one every installation has.\n */\n readonly sink: OtlpTelemetrySink;\n /** The primary destination's 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 /** Every destination this runtime sends to, primary first. */\n readonly destinations: readonly ExportDestinationSinks[];\n /** Destinations left out of this invocation, by name, with the variables they lack. */\n readonly skippedDestinations: readonly SkippedExportDestination[];\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 /** Cumulative metric series state (issue #69). */\n readonly metricSeries: MetricSeriesStore;\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 /**\n * Header *values* for the `default` destination, deliberately absent from the\n * config snapshot.\n */\n readonly headers?: Readonly<Record<string, string>>;\n /**\n * Header values for the logs signal only, when they differ from the traces\n * signal's (`OTEL_EXPORTER_OTLP_LOGS_HEADERS`). Defaults to {@link headers}.\n */\n readonly logHeaders?: Readonly<Record<string, string>>;\n /**\n * Environment that `env:NAME` header references in `exporter.destinations`\n * resolve against. Never read implicitly; without it, a destination whose\n * headers reference a variable is skipped for the invocation and reported.\n */\n readonly headerEnvironment?: Readonly<Record<string, string | undefined>>;\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 * Payload enrichers run before the adapter parses (see `PayloadEnricher`).\n * When absent, the configuration decides: `providers.claudeCode.readTranscriptUsage`\n * adds the Claude Code transcript-usage enricher, and nothing else is added.\n * Pass `[]` to run none regardless of configuration.\n */\n readonly payloadEnrichers?: readonly PayloadEnricher[];\n /**\n * Reads session context files (`docs/session-context.md`). When absent, the\n * configuration decides: `sessionContext.dir` adds the directory reader, and\n * without it nothing is read. Pass `null` to read none regardless.\n */\n readonly sessionContextReader?: SessionContextReader | 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 spanCorrelator = createSpanCorrelator({\n stateStore,\n clock,\n maxStartAgeMillis: lifecycleMaxAge,\n });\n\n /**\n * One correlation resolution per batch, shared by every sink of every\n * destination.\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 signals (and the\n * destinations) pointing at different span ids for the same scope.\n */\n const correlate = shareCorrelationPerBatch((events) => spanCorrelator.correlateBatch(events));\n\n // One sink pair per export destination. Without `exporter.destinations` this is\n // the single `default` destination, built exactly as it always has been.\n const exportDestinations = createExportDestinationSinks({\n exporter: options.config.exporter,\n ...(options.headers === undefined ? {} : { defaultHeaders: options.headers }),\n ...(options.logHeaders === undefined ? {} : { defaultLogHeaders: options.logHeaders }),\n ...(options.headerEnvironment === undefined\n ? {}\n : { headerEnvironment: options.headerEnvironment }),\n providerId: options.providerNamespace,\n installationId: options.installationId,\n clock,\n logger,\n ...(options.enableSpool === false ? {} : { spoolRootDir: options.stateRootDir }),\n logContent: {\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 // The primary destination backs the single-destination accessors below: `default`\n // when it is configured, otherwise the first entry of the list.\n const primary = exportDestinations.destinations[0];\n const traceSink =\n primary?.traces ??\n createOtlpTraceSink({\n exporter: { ...options.config.exporter, enabled: false },\n providerId: options.providerNamespace,\n installationId: options.installationId,\n clock,\n });\n const logSink =\n primary?.logs ??\n createOtlpLogSink({\n exporter: { ...options.config.exporter, logs: { ...options.config.exporter.logs, enabled: false } },\n providerId: options.providerNamespace,\n installationId: options.installationId,\n clock,\n });\n const spool = primary?.spool;\n const logSpool = primary?.logSpool;\n\n const sink = createDestinationFanout(exportDestinations.destinations);\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 payloadEnrichers:\n options.payloadEnrichers ??\n (readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : []),\n ...(() => {\n if (options.sessionContextReader === null) {\n return {};\n }\n if (options.sessionContextReader !== undefined) {\n return { sessionContext: options.sessionContextReader };\n }\n const dir = sessionContextDir(options.config);\n return dir === undefined ? {} : { sessionContext: createDirectorySessionContextReader({ dir }) };\n })(),\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 metricSeries = createMetricSeriesStore({ stateStore, clock });\n const metricsPolicy = effectiveMetricsPolicy(options.config.exporter);\n const metricDestinations = exportDestinations.destinations.filter(\n (destination) => destination.metrics.enabled,\n );\n const metricResource = resourceFromExporterPolicy(options.config.exporter);\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 metricSeries,\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 * Start edges for generations whose `generation.start` was recorded by an earlier\n * process. Served from the batch's shared correlation, which the trace and log\n * sinks have already resolved for this exact batch, so this is normally a memo\n * hit rather than a second resolution.\n */\n const generationStartsFor = async (\n events: readonly CanonicalEvent[],\n ): Promise<((generationId: string) => GenerationStart | undefined) | undefined> => {\n const needed = events.some(\n (event) =>\n event.type === \"generation.end\" &&\n event.durationMillis === undefined &&\n !events.some(\n (other) => other.type === \"generation.start\" && other.generationId === event.generationId,\n ),\n );\n if (!needed) {\n return undefined;\n }\n try {\n const starts = new Map<string, GenerationStart>();\n for (const correlation of await correlate(events)) {\n if (correlation.ref.family !== \"generation\" || correlation.startMillis === undefined) {\n continue;\n }\n const requestModel = correlation.attributes?.[\"gen_ai.request.model\"];\n starts.set(correlation.ref.scopeKey, {\n startMillis: correlation.startMillis,\n ...(typeof requestModel === \"string\" ? { requestModel } : {}),\n });\n }\n return (generationId) => starts.get(generationId);\n } catch {\n return undefined;\n }\n };\n\n /**\n * Derive, aggregate, and send this callback's metrics (issue #69).\n *\n * Runs only for a callback whose accounting committed — the same condition the\n * usage deltas it reads were derived under — so a redelivery or a lost-and-retried\n * callback is measured exactly once. Fails open: a metrics failure is a\n * diagnostic, never a reason to retry the callback, whose traces are already out.\n */\n const recordMetrics = async (\n ingest: HookIngestOutcome,\n deliveryToken: string | undefined,\n diagnostics: OtelHookErrorInfo[],\n ): Promise<MetricsReport | undefined> => {\n if (metricDestinations.length === 0 || ingest.events.length === 0) {\n return undefined;\n }\n try {\n for (const event of ingest.events) {\n if (event.type === \"prompt.submitted\") {\n await metricSeries.recordTurnStart(event.sessionId, event.occurredAt);\n }\n }\n const generationStarts = await generationStartsFor(ingest.events);\n const turnStarts = new Map<string, number | undefined>();\n for (const event of ingest.events) {\n if (event.type === \"generation.end\" && !turnStarts.has(event.sessionId)) {\n turnStarts.set(event.sessionId, await metricSeries.readTurnStart(event.sessionId));\n }\n }\n const observations = deriveMetricObservations({\n events: ingest.events,\n usage: ingest.usageObservations,\n resource: metricResource,\n includeSessionId: metricsPolicy.includeSessionId,\n ...(generationStarts === undefined ? {} : { generationStarts }),\n turnStart: (sessionId) => turnStarts.get(sessionId),\n });\n if (observations.length === 0) {\n return undefined;\n }\n const points: readonly MetricPoint[] =\n metricsPolicy.temporality === \"delta\"\n ? aggregateDeltaPoints(observations, clock.now())\n : await metricSeries.recordCumulative(observations, {\n perSession: metricsPolicy.includeSessionId,\n ...(deliveryToken === undefined ? {} : { deliveryToken }),\n });\n const context = agreedContextAttributes(ingest.events);\n const results = await Promise.all(\n metricDestinations.map(async (destination) => {\n const result = await destination.metrics.exportPoints(points, context).catch(\n (thrown: unknown) => ({\n accepted: 0,\n rejected: points.length,\n errors: [\n errorInfoFromThrown(thrown, { code: \"telemetry-export-failure\", phase: \"export\" }),\n ],\n }),\n );\n diagnostics.push(...result.errors);\n return { name: destination.name, accepted: result.accepted, rejected: result.rejected };\n }),\n );\n return { points: points.length, destinations: results };\n } catch (thrown) {\n diagnostics.push(stateDiagnostic(thrown));\n logger.warn(\"hook-derived metrics could not be recorded for this callback\", {});\n return undefined;\n }\n };\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 const metrics =\n !duplicateDelivery && ingest.identity !== undefined && isCommittable(ingest.durability)\n ? await recordMetrics(\n ingest,\n identity === undefined ? undefined : rollupDeliveryToken(identity),\n diagnostics,\n )\n : undefined;\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 ...(metrics === undefined ? {} : { metrics }),\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[] => [\n ...sink.health(),\n ...metricDestinations.map((destination) => destination.metrics.health()),\n ];\n\n let shutdownReport: Promise<HookShutdownReport> | undefined;\n const shutdown = (): Promise<HookShutdownReport> => {\n shutdownReport ??= (async (): Promise<HookShutdownReport> => {\n const raced = await Promise.race([\n Promise.all([\n hook.shutdown(),\n // Metric sinks are not behind the hook's sink: they replay their own\n // spools here, inside the same bounded window.\n ...metricDestinations.map((destination) => destination.metrics.shutdown().catch(() => undefined)),\n ]).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 destinations: exportDestinations.destinations,\n skippedDestinations: exportDestinations.skipped,\n privacy,\n deduplicator,\n usageAccumulator,\n spanCorrelator,\n metricSeries,\n janitor,\n process: process_,\n shutdown,\n health: (): OverallHealth => summarizeHealth(snapshots()),\n };\n};\n"],"mappings":";AAAA,SAAS,kBAAkB;AAE3B,SAAS,KAAAA,UAAS;;;ACFlB,SAAS,SAAS;AAGX,IAAM,wBAAwB;AAG9B,IAAM,8BAA8B;AAGpC,IAAM,6BAA6B;AAEnC,IAAM,uBAAuB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,qBAAqB;AAGxE,IAAM,oBAAoB,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,MAAqB;AAI3E,IAAM,uBAAuB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,OAA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;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,cAAc,mBAAmB;AAAA,IACjC,qBAAqB,mBAAmB;AAAA,IACxC;AAAA,IACA;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","z","z","z","z","z","z","z","sessionScope","owner","z","z","z","z","z","z","z","parsed","z","z","z","z","z","z","z","event","event","ATTR_SESSION_ID","ATTR_OTELHOOK_PROVIDER_ID","event","createHash","ATTR_ERROR_TYPE","ATTR_GEN_AI_OPERATION_NAME","ATTR_GEN_AI_REQUEST_MODEL","ATTR_GEN_AI_RESPONSE_MODEL","ATTR_GEN_AI_TOOL_NAME","ATTR_OTELHOOK_OUTCOME","createHash","event","ATTR_GEN_AI_REQUEST_MODEL","ATTR_GEN_AI_OPERATION_NAME","ATTR_GEN_AI_RESPONSE_MODEL","ATTR_GEN_AI_TOOL_NAME","ATTR_ERROR_TYPE","parent","result","event","usageKey","createHash","createHash","path","createHash","z","z","z","asRecord","resolve","createHash","asRecord","z","createHash","digest","createHash","z","z","path","event","resolve","open","path","z","z","event","open","resolve","z","event","batch","open","stat","path","readBounded","randomBytes","open","path","createHash","resolve","randomBytes","open","randomBytes","mkdir","readFile","readdir","rename","stat","unlink","writeFile","path","readFile","readdir","stat","isErrnoException","mkdir","randomBytes","writeFile","rename","unlink","isPlainObject","isFiniteNonNegative","isBoundedString","isPrimitiveAttribute","TRACE_ID_PATTERN","SPAN_ID_PATTERN","isFiniteNonNegative","isBoundedString","isPlainObject","TraceFlags","millisToHrTime","event","TraceFlags","millisToHrTime","ATTR_ERROR_TYPE","ATTR_GEN_AI_OPERATION_NAME","ATTR_GEN_AI_REQUEST_MODEL","ATTR_GEN_AI_RESPONSE_MODEL","ATTR_GEN_AI_SYSTEM","ATTR_GEN_AI_TOOL_CALL_ID","ATTR_GEN_AI_TOOL_NAME","ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS","ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS","ATTR_GEN_AI_USAGE_INPUT_TOKENS","ATTR_GEN_AI_USAGE_OUTPUT_TOKENS","ATTR_OTELHOOK_OUTCOME","ATTR_OTELHOOK_TOOL_KIND","ATTR_OTELHOOK_DELEGATION_DEPTH","ATTR_OTELHOOK_AGENT_NAME","ATTR_OTELHOOK_AGENT_VERSION","ATTR_OTELHOOK_SESSION_KIND","ATTR_OTELHOOK_GENERATION_ID","ATTR_OTELHOOK_COMPACTION_TRIGGER","codePointLength","sliceCodePoints","event","event","identityAttributes","ATTR_OTELHOOK_SESSION_KIND","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","millisToHrTime","TraceFlags","TraceFlags","millisToHrTime","resolve","ExportResultCode","millisToHrTime","resourceFromAttributes","DISABLED_DETAIL","millisToHrTime","resourceFromAttributes","resolve","ExportResultCode","ExportResultCode","chunk","createDisabledSink","resolve","ExportResultCode","DEFAULT_STALE_CLAIM_MILLIS","resolve","event","options"]}
1
+ {"version":3,"sources":["../src/config/schema.ts","../src/model/primitives.ts","../src/privacy/policy.ts","../src/config/destinations.ts","../src/config/header-value.ts","../src/config/otlp-headers.ts","../src/config/resource-attributes.ts","../src/diagnostics/health.ts","../src/errors/index.ts","../src/errors/taxonomy.ts","../src/lifecycle/dedup.ts","../src/state/async-lock.ts","../src/state/store.ts","../src/lifecycle/keys.ts","../src/lifecycle/metric-series.ts","../src/telemetry/export-identity.ts","../src/model/events.ts","../src/model/content.ts","../src/model/extensions.ts","../src/model/identity.ts","../src/model/target.ts","../src/model/usage.ts","../src/model/version.ts","../src/telemetry/metric-model.ts","../src/lifecycle/janitor.ts","../src/telemetry/semconv.ts","../src/version.ts","../src/lifecycle/span-correlator.ts","../src/lifecycle/usage-accumulator.ts","../src/privacy/service.ts","../src/providers/claude/transcript.ts","../src/providers/adapter.ts","../src/providers/claude/schema.ts","../src/providers/claude/usage.ts","../src/providers/claude/payload-normalize.ts","../src/providers/claude/detect.ts","../src/runtime/clock.ts","../src/runtime/hook.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/session-context.ts","../src/runtime/git-worktree.ts","../src/state/filesystem-store.ts","../src/state/keys.ts","../src/config/otlp-endpoint.ts","../src/telemetry/spool-queue.ts","../src/telemetry/durable-log-spool.ts","../src/telemetry/durable-metric-spool.ts","../src/telemetry/durable-spool.ts","../src/telemetry/otlp-log-sink.ts","../src/telemetry/export-failure.ts","../src/telemetry/exporter-resource.ts","../src/telemetry/log-records.ts","../src/telemetry/otlp-metric-sink.ts","../src/telemetry/otlp-sink.ts","../src/telemetry/signal-fanout.ts","../src/telemetry/export-destinations.ts","../src/integration/hook-runtime.ts"],"sourcesContent":["import { isAbsolute } from \"node:path\";\n\nimport { z } from \"zod\";\n\nimport { detectionConfidenceSchema, nonEmptyStringSchema } from \"../model/primitives.js\";\nimport {\n contentModeSchema,\n DEFAULT_PRIVACY_POLICY,\n privacyPolicySchema,\n} from \"../privacy/policy.js\";\nimport { exportDestinationsSchema, spoolPolicySchema } from \"./destinations.js\";\nimport { EMPTY_RESOURCE_ATTRIBUTES, resourceAttributesSchema } from \"./resource-attributes.js\";\n\n/**\n * Policy for the OTLP logs signal.\n *\n * Two switches rather than one, because they answer different questions and an\n * operator needs to be able to answer them differently:\n *\n * - `enabled` — whether a second signal leaves this host at all. Off by default:\n * an installation that upgrades must not silently start sending a new stream to a\n * collector whose receivers, quotas, and retention were sized for traces.\n * - `includeContent` — whether *disclosed* text may appear in a log body. Also off\n * by default, and deliberately not the same knob as `privacy.contentMode`: spans\n * carry no content in any content mode, so an installation that set\n * `contentMode` to get a hash and a length has never had content on the wire.\n * Reusing that setting to also mean \"publish prompts\" would change what an\n * existing configuration discloses without anybody editing it.\n *\n * `raw` content additionally requires the pre-existing `privacy.allowRawContent`\n * opt-in, which the privacy service enforces before a fact is ever built and the\n * log mapping re-checks at the wire.\n */\nexport const logsPolicySchema = z.strictObject({\n enabled: z.boolean(),\n /**\n * Full URL for the logs signal.\n *\n * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes\n * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.\n */\n endpoint: z.string().url().max(2048).optional(),\n includeContent: z.boolean(),\n maxBatchSize: z.number().int().min(1).max(4096),\n});\nexport type LogsPolicy = z.infer<typeof logsPolicySchema>;\n\nexport const DEFAULT_LOGS_POLICY: LogsPolicy = Object.freeze({\n enabled: false,\n includeContent: false,\n maxBatchSize: 128,\n});\n\n/**\n * Policy for hook-derived metrics (issue #69).\n *\n * Off by default, like logs: an upgrade must not start a new stream to a\n * collector nobody sized for it. `enabled` governs the `default` destination\n * (the single-endpoint settings); an `exporter.destinations[]` entry receives\n * metrics when its `signals` list names `metrics`. Metrics carry no content, so\n * listing the signal is the whole opt-in.\n *\n * - `temporality`: `cumulative` (default) exports running totals per series,\n * kept in the state store across hook processes, so a receiver that merges\n * counters by keeping the largest value stays correct. `delta` exports what one\n * callback observed and keeps no state.\n * - `includeSessionId`: put `session.id` on every data point (default true). Turn\n * it off where per-session series are too many for the backend.\n */\nexport const metricsPolicySchema = z.strictObject({\n enabled: z.boolean(),\n /** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */\n endpoint: z.string().url().max(2048).optional(),\n temporality: z.enum([\"cumulative\", \"delta\"]),\n includeSessionId: z.boolean(),\n});\nexport type MetricsPolicy = z.infer<typeof metricsPolicySchema>;\n\nexport const DEFAULT_METRICS_POLICY: MetricsPolicy = Object.freeze({\n enabled: false,\n temporality: \"cumulative\",\n includeSessionId: true,\n});\n\n/**\n * Runtime exporter policy.\n *\n * This describes *where and how* telemetry goes. It deliberately contains no\n * session, invocation, or workspace field: see ADR 0001. Mixing the two would\n * make identity globally reachable through configuration.\n */\nexport const exporterPolicySchema = z.strictObject({\n enabled: z.boolean(),\n protocol: z.enum([\"http/protobuf\", \"http/json\", \"none\"]),\n endpoint: z.string().url().max(2048).optional(),\n /**\n * Header names only. Values are supplied separately at construction time and\n * are never part of a resolved-config snapshot, which is logged and exported.\n */\n headerNames: z.array(nonEmptyStringSchema).max(32).readonly(),\n timeoutMillis: z.number().int().min(1).max(600_000),\n maxBatchSize: z.number().int().min(1).max(4096),\n maxQueueSize: z.number().int().min(1).max(65_536),\n maxRetryAttempts: z.number().int().min(0).max(10),\n serviceName: nonEmptyStringSchema,\n serviceNamespace: nonEmptyStringSchema.optional(),\n /**\n * Custom attributes merged into the exported OTLP Resource.\n *\n * Bounded and validated, and refusing `service.name`/`service.namespace`,\n * which are the two fields above. Distinct from an invocation's\n * `consumerAttributes`: this describes the emitting deployment, carries no\n * identity, and is the same for every span this process exports.\n */\n resourceAttributes: resourceAttributesSchema,\n /**\n * The logs signal. Nested under the exporter because it shares the endpoint,\n * headers, timeout, protocol, service identity, and resource attributes above —\n * a second top-level section would invite two of each to drift apart.\n */\n logs: logsPolicySchema,\n /**\n * Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before\n * metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.\n */\n metrics: metricsPolicySchema.optional(),\n /**\n * Additional OTLP destinations, each sent every batch in parallel.\n *\n * Absent (the default), the exporter has exactly one destination — the\n * single-endpoint settings above, named `default` — and behaves exactly as it\n * did before this list existed. See `destinations.ts`.\n *\n * Merged as one leaf: a higher layer that sets the list replaces it whole,\n * because \"the union of two partial lists\" has no answer an operator could\n * predict.\n */\n destinations: exportDestinationsSchema.optional(),\n /**\n * Per-destination retry spool bounds, each optional and merged per leaf; any\n * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.\n */\n spool: spoolPolicySchema.partial().optional(),\n});\nexport type ExporterPolicy = z.infer<typeof exporterPolicySchema>;\n\nexport const detectionPolicySchema = z.strictObject({\n /** Detections below this confidence resolve to the unknown provider. */\n minimumConfidence: detectionConfidenceSchema,\n /** When false, an ambiguous detection is an error rather than unknown. */\n allowAmbiguousFallback: z.boolean(),\n /** Optional allow-list of provider ids; empty means \"any registered\". */\n allowedProviderIds: z.array(nonEmptyStringSchema).max(32).readonly(),\n});\nexport type DetectionPolicy = z.infer<typeof detectionPolicySchema>;\n\nexport const diagnosticsPolicySchema = z.strictObject({\n logLevel: z.enum([\"silent\", \"error\", \"warn\", \"info\", \"debug\"]),\n /** Emit `error.raised` events for contained failures. */\n emitErrorEvents: z.boolean(),\n});\nexport type DiagnosticsPolicy = z.infer<typeof diagnosticsPolicySchema>;\n\n/**\n * Per-provider behaviour that is not part of an adapter's parse.\n *\n * `claudeCode.readTranscriptUsage` is the one sanctioned exception to \"no\n * transcript reads in the hook\" (docs/claude-code-usage-contract.md, finding 8).\n * When true, the hook runtime — never the adapter — reads the session transcript\n * named by a Claude Code `Stop` / `StopFailure` payload, bounded, and attaches the\n * turn's model and summed token usage before the adapter parses it. Off by\n * default: without it, otel-hook reads no file a hook payload names.\n */\nexport const providersPolicySchema = z.strictObject({\n claudeCode: z\n .strictObject({\n readTranscriptUsage: z.boolean(),\n })\n .optional(),\n});\nexport type ProvidersPolicy = z.infer<typeof providersPolicySchema>;\n\n/**\n * Session context (`docs/session-context.md`): a directory a harness writes one\n * JSON file per agent session into, laid out `<dir>/<agent-tool>/<session-id>.json`.\n * With `dir` set, the hook reads that one file on every event and stamps the\n * attributes of the segment in force on every span, log record and metric point.\n * Absent (the default), nothing is read.\n *\n * Set in the configuration file or with `--session-context-dir`, never through\n * the environment: some agents (Claude Code) strip `OTEL_*` variables from the\n * hook processes they start.\n */\nexport const sessionContextPolicySchema = z.strictObject({\n /** Absolute path of the context directory. */\n dir: z\n .string()\n .min(1)\n .max(4096)\n .refine((value) => isAbsolute(value), { message: \"must be an absolute path\" }),\n});\nexport type SessionContextPolicy = z.infer<typeof sessionContextPolicySchema>;\n\nexport const otelHookConfigSchema = z.strictObject({\n exporter: exporterPolicySchema,\n privacy: privacyPolicySchema,\n detection: detectionPolicySchema,\n diagnostics: diagnosticsPolicySchema,\n /** Optional so a hand-built configuration from before it existed stays valid. */\n providers: providersPolicySchema.optional(),\n /** Optional: absent means no session context is read. */\n sessionContext: sessionContextPolicySchema.optional(),\n});\nexport type OtelHookConfig = z.infer<typeof otelHookConfigSchema>;\n\n/** Partial overlay accepted from a configuration layer. */\nexport const otelHookConfigPatchSchema = z.strictObject({\n // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:\n // merging happens per leaf, so a layer must be able to set `logs.enabled` alone\n // without also restating the endpoint and the batch size.\n exporter: exporterPolicySchema\n .omit({ logs: true, metrics: true, spool: true })\n .partial()\n .extend({\n logs: logsPolicySchema.partial().optional(),\n metrics: metricsPolicySchema.partial().optional(),\n spool: spoolPolicySchema.partial().optional(),\n })\n .optional(),\n privacy: privacyPolicySchema\n .omit({ limits: true })\n .partial()\n .extend({ limits: privacyPolicySchema.shape.limits.partial().optional() })\n .optional(),\n detection: detectionPolicySchema.partial().optional(),\n diagnostics: diagnosticsPolicySchema.partial().optional(),\n providers: z\n .strictObject({\n claudeCode: z.strictObject({ readTranscriptUsage: z.boolean() }).partial().optional(),\n })\n .partial()\n .optional(),\n sessionContext: sessionContextPolicySchema.partial().optional(),\n});\nexport type OtelHookConfigPatch = z.infer<typeof otelHookConfigPatchSchema>;\n\nexport const DEFAULT_EXPORTER_POLICY: ExporterPolicy = Object.freeze({\n enabled: true,\n protocol: \"http/protobuf\",\n headerNames: Object.freeze([]),\n timeoutMillis: 10_000,\n maxBatchSize: 128,\n maxQueueSize: 2048,\n maxRetryAttempts: 2,\n serviceName: \"coding-agent\",\n resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,\n logs: DEFAULT_LOGS_POLICY,\n metrics: DEFAULT_METRICS_POLICY,\n});\n\nexport const DEFAULT_DETECTION_POLICY: DetectionPolicy = Object.freeze({\n minimumConfidence: \"strong\",\n allowAmbiguousFallback: true,\n allowedProviderIds: Object.freeze([]),\n});\n\nexport const DEFAULT_DIAGNOSTICS_POLICY: DiagnosticsPolicy = Object.freeze({\n logLevel: \"warn\",\n emitErrorEvents: true,\n});\n\nexport const DEFAULT_PROVIDERS_POLICY: ProvidersPolicy = Object.freeze({\n claudeCode: Object.freeze({ readTranscriptUsage: false }),\n});\n\nexport const DEFAULT_CONFIG: OtelHookConfig = Object.freeze({\n exporter: DEFAULT_EXPORTER_POLICY,\n privacy: DEFAULT_PRIVACY_POLICY,\n detection: DEFAULT_DETECTION_POLICY,\n diagnostics: DEFAULT_DIAGNOSTICS_POLICY,\n providers: DEFAULT_PROVIDERS_POLICY,\n});\n\n/** Whether the runtime may read Claude Code transcripts at `Stop` (default false). */\nexport const readsClaudeTranscriptUsage = (config: OtelHookConfig): boolean =>\n config.providers?.claudeCode?.readTranscriptUsage === true;\n\n/** The session context directory in force, or `undefined` when none is configured. */\nexport const sessionContextDir = (config: OtelHookConfig): string | undefined => config.sessionContext?.dir;\n\n/** Content mode is re-exported for callers building patches. */\nexport { contentModeSchema };\n\n/** The metrics policy in force, defaults filled in. */\nexport const effectiveMetricsPolicy = (exporter: ExporterPolicy): MetricsPolicy => ({\n ...DEFAULT_METRICS_POLICY,\n ...(exporter.metrics ?? {}),\n});\n","import { z } from \"zod\";\n\n/** Maximum length accepted for short identifier-like strings. */\nexport const MAX_IDENTIFIER_LENGTH = 256;\n\n/** Maximum length accepted for a single string attribute value. */\nexport const MAX_ATTRIBUTE_STRING_LENGTH = 4096;\n\n/** Maximum number of entries accepted in an attribute array value. */\nexport const MAX_ATTRIBUTE_ARRAY_LENGTH = 128;\n\nexport const nonEmptyStringSchema = z.string().min(1).max(MAX_IDENTIFIER_LENGTH);\n\n/** Wall-clock time as whole milliseconds since the Unix epoch. */\nexport const epochMillisSchema = z.number().int().min(0).max(8_640_000_000_000_000);\nexport type EpochMillis = z.infer<typeof epochMillisSchema>;\n\n/** Non-negative duration in milliseconds; may be fractional. */\nexport const durationMillisSchema = z.number().min(0).finite();\n\n/** Token counts are always non-negative integers. */\nexport const tokenCountSchema = z.number().int().min(0);\n\n/** Monotonically increasing per-invocation ordering key. */\nexport const sequenceNumberSchema = z.number().int().min(0);\n\nconst brandedIdSchema = (): z.ZodString => z.string().min(1).max(MAX_IDENTIFIER_LENGTH);\n\nexport const invocationIdSchema = brandedIdSchema().brand<\"InvocationId\">();\nexport type InvocationId = z.infer<typeof invocationIdSchema>;\n\nexport const sessionIdSchema = brandedIdSchema().brand<\"SessionId\">();\nexport type SessionId = z.infer<typeof sessionIdSchema>;\n\nexport const eventIdSchema = brandedIdSchema().brand<\"EventId\">();\nexport type EventId = z.infer<typeof eventIdSchema>;\n\n/**\n * Workspace identifiers are opaque, privacy-safe handles of the form\n * `<scheme>:<token>`. Filesystem paths cannot satisfy this pattern, which keeps\n * home directories and repository paths out of telemetry by construction.\n */\nexport const WORKSPACE_ID_PATTERN = /^[a-z][a-z0-9]{0,15}:[A-Za-z0-9_-]{8,128}$/;\nexport const workspaceIdSchema = z\n .string()\n .regex(WORKSPACE_ID_PATTERN, \"workspace id must be an opaque `<scheme>:<token>` handle\")\n .brand<\"WorkspaceId\">();\nexport type WorkspaceId = z.infer<typeof workspaceIdSchema>;\n\n/** Provider ids are lowercase, hyphenated, and stable across releases. */\nexport const PROVIDER_ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\nexport const providerIdSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(PROVIDER_ID_PATTERN, \"provider id must be lowercase and hyphenated\")\n .brand<\"ProviderId\">();\nexport type ProviderId = z.infer<typeof providerIdSchema>;\n\n/** Sentinel used whenever the source provider could not be established. */\nexport const UNKNOWN_PROVIDER_ID = \"unknown\" as const;\nexport type UnknownProviderId = typeof UNKNOWN_PROVIDER_ID;\n\nexport const resolvedProviderIdSchema = z.union([\n providerIdSchema,\n z.literal(UNKNOWN_PROVIDER_ID),\n]);\nexport type ResolvedProviderId = z.infer<typeof resolvedProviderIdSchema>;\n\nexport const isUnknownProvider = (value: ResolvedProviderId): value is UnknownProviderId =>\n value === UNKNOWN_PROVIDER_ID;\n\n/**\n * Attribute values are restricted to OpenTelemetry-compatible primitives.\n *\n * This restriction is a containment boundary, not a convenience: because no\n * nested object can be represented, a raw provider payload cannot be smuggled\n * out of an adapter through attributes or extensions.\n */\nexport const attributePrimitiveSchema = z.union([\n z.string().max(MAX_ATTRIBUTE_STRING_LENGTH),\n z.number().finite(),\n z.boolean(),\n]);\nexport type AttributePrimitive = z.infer<typeof attributePrimitiveSchema>;\n\nexport const attributeValueSchema = z.union([\n attributePrimitiveSchema,\n z.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH),\n]);\nexport type AttributeValue = z.infer<typeof attributeValueSchema>;\n\nexport const attributesSchema = z.record(z.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);\nexport type Attributes = z.infer<typeof attributesSchema>;\n\n/** Ordered confidence ladder for provider detection. */\nexport const detectionConfidenceSchema = z.enum([\"none\", \"weak\", \"strong\", \"exact\"]);\nexport type DetectionConfidence = z.infer<typeof detectionConfidenceSchema>;\n\nexport const DETECTION_CONFIDENCE_RANK: Readonly<Record<DetectionConfidence, number>> =\n Object.freeze({\n none: 0,\n weak: 1,\n strong: 2,\n exact: 3,\n });\n\nexport const compareDetectionConfidence = (a: DetectionConfidence, b: DetectionConfidence): number =>\n DETECTION_CONFIDENCE_RANK[a] - DETECTION_CONFIDENCE_RANK[b];\n\n/** How the observed data reached this process. */\nexport const sourceTransportSchema = z.enum([\n \"hook-stdin\",\n \"cli-argument\",\n \"library-call\",\n \"test-fixture\",\n]);\nexport type SourceTransport = z.infer<typeof sourceTransportSchema>;\n","import { z } from \"zod\";\n\nimport type { ContentDisclosure } from \"../model/content.js\";\n\n/**\n * How much content the library is permitted to disclose.\n *\n * `omit` is the default and the only mode that requires no trust in the\n * downstream collector.\n */\nexport const contentModeSchema = z.enum([\"omit\", \"mask\", \"redact\", \"raw\"]);\nexport type ContentMode = z.infer<typeof contentModeSchema>;\n\nexport const CONTENT_MODE_DISCLOSURE: Readonly<Record<ContentMode, ContentDisclosure>> =\n Object.freeze({\n omit: \"omitted\",\n mask: \"masked\",\n redact: \"redacted\",\n raw: \"raw\",\n });\n\n/**\n * Default secret-key patterns, matched case-insensitively against object keys at\n * every depth. A key matching any of these has its value replaced before the\n * value itself is ever inspected.\n */\nexport const DEFAULT_SECRET_KEY_PATTERNS: readonly string[] = Object.freeze([\n \"(^|[._-])(secret|secrets)([._-]|$)\",\n \"(^|[._-])(token|tokens)([._-]|$)\",\n \"(^|[._-])(password|passwd|pwd)([._-]|$)\",\n \"(^|[._-])(credential|credentials)([._-]|$)\",\n \"(^|[._-])(api[._-]?key|apikey|access[._-]?key|secret[._-]?key|private[._-]?key)([._-]|$)\",\n \"(^|[._-])(authorization|auth[._-]?header|bearer)([._-]|$)\",\n \"(^|[._-])(cookie|set[._-]?cookie)([._-]|$)\",\n \"(^|[._-])(signature|sig)([._-]|$)\",\n]);\n\n/**\n * Default secret-value patterns applied to disclosed text in `redact` mode.\n * These are heuristics; they reduce accidental disclosure but are not a\n * substitute for `omit`.\n */\nexport const DEFAULT_SECRET_VALUE_PATTERNS: readonly string[] = Object.freeze([\n \"AKIA[0-9A-Z]{16}\",\n \"sk-[A-Za-z0-9_-]{16,}\",\n \"gh[pousr]_[A-Za-z0-9]{16,}\",\n \"xox[abprs]-[A-Za-z0-9-]{10,}\",\n \"-----BEGIN[A-Z ]*PRIVATE KEY-----\",\n \"eyJ[A-Za-z0-9_-]{10,}\\\\.[A-Za-z0-9_-]{10,}\\\\.[A-Za-z0-9_-]{10,}\",\n \"(?:Bearer|Basic)\\\\s+[A-Za-z0-9._~+/=-]{12,}\",\n]);\n\nexport const privacyLimitsSchema = z.strictObject({\n /** Maximum characters of disclosed text per content fact or string value. */\n maxStringLength: z.number().int().min(0).max(65_536),\n /** Maximum nesting depth walked when sanitizing structured values. */\n maxDepth: z.number().int().min(1).max(32),\n /** Maximum array entries retained when sanitizing structured values. */\n maxArrayLength: z.number().int().min(1).max(4096),\n /** Maximum canonical events emitted per invocation. */\n maxEventsPerInvocation: z.number().int().min(1).max(10_000),\n /** Maximum object keys retained per level when sanitizing. */\n maxObjectKeys: z.number().int().min(1).max(1024),\n});\nexport type PrivacyLimits = z.infer<typeof privacyLimitsSchema>;\n\nexport const privacyPolicySchema = z.strictObject({\n contentMode: contentModeSchema,\n /**\n * `raw` mode is refused unless this is also true, so a single mistyped\n * environment variable cannot start exporting prompts.\n */\n allowRawContent: z.boolean(),\n /**\n * Salt mixed into every hash. A per-deployment salt makes hashes\n * non-correlatable across deployments; an empty salt makes them globally\n * comparable. Both are legitimate; the choice is explicit.\n */\n hashSalt: z.string().max(256),\n maskCharacter: z.string().length(1),\n redactionPlaceholder: z.string().min(1).max(64),\n secretKeyPatterns: z.array(z.string().min(1)).max(128).readonly(),\n secretValuePatterns: z.array(z.string().min(1)).max(128).readonly(),\n limits: privacyLimitsSchema,\n});\nexport type PrivacyPolicy = z.infer<typeof privacyPolicySchema>;\n\nexport const DEFAULT_PRIVACY_LIMITS: PrivacyLimits = Object.freeze({\n maxStringLength: 1024,\n maxDepth: 6,\n maxArrayLength: 64,\n maxEventsPerInvocation: 512,\n maxObjectKeys: 128,\n});\n\nexport const DEFAULT_PRIVACY_POLICY: PrivacyPolicy = Object.freeze({\n contentMode: \"omit\",\n allowRawContent: false,\n hashSalt: \"\",\n maskCharacter: \"*\",\n redactionPlaceholder: \"[redacted]\",\n secretKeyPatterns: DEFAULT_SECRET_KEY_PATTERNS,\n secretValuePatterns: DEFAULT_SECRET_VALUE_PATTERNS,\n limits: DEFAULT_PRIVACY_LIMITS,\n});\n\nexport type PolicyResolution = {\n readonly policy: PrivacyPolicy;\n /** Non-sensitive notes about deterministic downgrades that were applied. */\n readonly notes: readonly string[];\n};\n\n/**\n * Validate a policy and apply the one deterministic downgrade the library\n * enforces: `raw` without `allowRawContent` becomes `omit`.\n */\nexport const resolvePrivacyPolicy = (policy: PrivacyPolicy): PolicyResolution => {\n const parsed = privacyPolicySchema.parse(policy);\n if (parsed.contentMode === \"raw\" && !parsed.allowRawContent) {\n return {\n policy: { ...parsed, contentMode: \"omit\" },\n notes: [\"contentMode=raw downgraded to omit because allowRawContent is false\"],\n };\n }\n return { policy: parsed, notes: [] };\n};\n","import { z } from \"zod\";\n\nimport { isUnsafeHeaderValue } from \"./header-value.js\";\nimport { MAX_OTLP_HEADERS } from \"./otlp-headers.js\";\nimport type { ExporterPolicy } from \"./schema.js\";\n\n/**\n * Export destinations: one batch, several OTLP endpoints.\n *\n * otel-hook is not a long-running process, so it cannot sit behind a proxy that\n * fans out for it. Instead every enabled destination is sent the same batch by the\n * same short-lived process, and what a destination could not take is kept in that\n * destination's own spool for the next invocation.\n *\n * ## The `default` destination\n *\n * The single-endpoint settings that predate this list — `exporter.endpoint`,\n * `exporter.logs.endpoint`, `exporter.protocol`, `--header`, and the standard\n * `OTEL_EXPORTER_OTLP_*` variables that feed them — describe one destination\n * named `default`. The name is therefore reserved: a `destinations[]` entry may\n * not take it, so there is exactly one place that destination is configured.\n *\n * A configuration with no `destinations` resolves to that one destination and\n * nothing else, exactly as before the list existed.\n */\n\nexport const DEFAULT_DESTINATION_NAME = \"default\";\n\n/**\n * Destination names become directory names (each destination spools on its own),\n * so they are held to a lowercase, filesystem-safe vocabulary rather than being\n * sanitized into something an operator would not recognize.\n */\nexport const DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;\n\nexport const MAX_EXPORT_DESTINATIONS = 16;\n/** The same bound `OTEL_EXPORTER_OTLP_*HEADERS` and `exporter.headerNames` have. */\nexport const MAX_DESTINATION_HEADERS = MAX_OTLP_HEADERS;\n\n/** Prefix of a header value that names an environment variable instead of holding a value. */\nexport const HEADER_ENV_REFERENCE_PREFIX = \"env:\";\n\n/** RFC 9110 `token`: the characters a header field name may use. */\nconst HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;\nconst ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;\nconst MAX_HEADER_VALUE_LENGTH = 8_192;\n\nexport const exportSignalSchema = z.enum([\"traces\", \"logs\", \"metrics\"]);\nexport type ExportSignal = z.infer<typeof exportSignalSchema>;\n\nconst headerValueSchema = z\n .string()\n .min(1)\n .max(MAX_HEADER_VALUE_LENGTH)\n // The rule `OTEL_EXPORTER_OTLP_*HEADERS` values are held to: a line break is a\n // request-splitting vector, and other controls or non-Latin-1 characters would\n // only make Node's HTTP client throw at send time.\n .refine(\n (value) => !isUnsafeHeaderValue(value),\n \"header values may not contain line breaks, control characters, or characters beyond Latin-1\",\n )\n .refine(\n (value) =>\n !value.startsWith(HEADER_ENV_REFERENCE_PREFIX) ||\n ENV_VARIABLE_NAME_PATTERN.test(value.slice(HEADER_ENV_REFERENCE_PREFIX.length)),\n \"an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN\",\n );\n\nconst endpointSchema = z.string().url().max(2048);\n\nexport const exportDestinationSchema = z\n .strictObject({\n /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */\n name: z\n .string()\n .regex(DESTINATION_NAME_PATTERN, \"destination names are lowercase letters, digits, _ and -\"),\n /** Default true. A disabled destination is neither sent to nor drained. */\n enabled: z.boolean().optional(),\n /**\n * Traces URL, with the same meaning as `exporter.endpoint`: the logs URL is\n * derived from it (`/v1/traces` becomes `/v1/logs`) unless `logsEndpoint` is set.\n */\n endpoint: endpointSchema.optional(),\n /** Per-signal override of `endpoint` for traces. */\n tracesEndpoint: endpointSchema.optional(),\n /** Per-signal override of the derived logs URL. */\n logsEndpoint: endpointSchema.optional(),\n /** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */\n metricsEndpoint: endpointSchema.optional(),\n /** Defaults to `exporter.protocol`. */\n protocol: z.enum([\"http/protobuf\", \"http/json\", \"none\"]).optional(),\n /**\n * Header name to value. A value of the form `env:NAME` is read from that\n * environment variable at send time, so a credential never has to be written\n * into the file. Values never appear in a snapshot, a diagnostic, or `doctor`.\n */\n headers: z\n .record(z.string().regex(HEADER_NAME_PATTERN, \"not a valid header name\"), headerValueSchema)\n .refine(\n (headers) => Object.keys(headers).length <= MAX_DESTINATION_HEADERS,\n `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`,\n )\n .optional(),\n /**\n * Which signals this destination receives. Default: traces and logs. The logs\n * signal is still governed by `exporter.logs.enabled`, which stays the one\n * opt-in for content-bearing records leaving the host. `metrics` is never on by\n * default: a destination receives hook-derived metrics only when it lists them.\n */\n signals: z.array(exportSignalSchema).min(1).max(3).readonly().optional(),\n })\n .refine(\n (destination) =>\n destination.endpoint !== undefined ||\n destination.tracesEndpoint !== undefined ||\n destination.logsEndpoint !== undefined ||\n destination.metricsEndpoint !== undefined,\n \"a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint\",\n );\nexport type ExportDestinationConfig = z.infer<typeof exportDestinationSchema>;\n\n/** Signals a destination receives when it does not list any: never metrics. */\nexport const DEFAULT_DESTINATION_SIGNALS: readonly ExportSignal[] = Object.freeze([\"traces\", \"logs\"]);\n\nexport const exportDestinationsSchema = z\n .array(exportDestinationSchema)\n .max(MAX_EXPORT_DESTINATIONS)\n .readonly()\n .superRefine((destinations, context) => {\n const seen = new Set<string>();\n destinations.forEach((destination, index) => {\n if (destination.name === DEFAULT_DESTINATION_NAME) {\n context.addIssue({\n code: \"custom\",\n path: [index, \"name\"],\n message:\n 'the name \"default\" is reserved for exporter.endpoint and the OTEL_EXPORTER_OTLP_* variables',\n });\n }\n if (seen.has(destination.name)) {\n context.addIssue({\n code: \"custom\",\n path: [index, \"name\"],\n message: `duplicate destination name \"${destination.name}\"`,\n });\n }\n seen.add(destination.name);\n });\n });\n\n/**\n * Bounds on each destination's retry spool, per signal.\n *\n * Every destination spools independently, so one long outage can only ever cost\n * its own budget. When a bound is reached the *oldest* batches are dropped first —\n * a recent batch is the one a reader is still likely to look for — and every drop\n * is counted on disk so `doctor` can report it.\n */\nexport const spoolPolicySchema = z.strictObject({\n /** Total bytes of queued batches. Default 16 MiB. */\n maxBytes: z.number().int().min(1_024).max(1_073_741_824),\n /** A batch older than this is dropped instead of sent. Default 72 hours. */\n maxAgeMillis: z.number().int().min(1_000).max(30 * 24 * 60 * 60 * 1000),\n /** Number of queued batches. Default 500. */\n maxBatches: z.number().int().min(1).max(65_536),\n});\nexport type SpoolPolicy = z.infer<typeof spoolPolicySchema>;\n\nexport const DEFAULT_SPOOL_POLICY: SpoolPolicy = Object.freeze({\n maxBytes: 16 * 1024 * 1024,\n maxAgeMillis: 72 * 60 * 60 * 1000,\n maxBatches: 500,\n});\n\n/** The spool policy in force, with defaults filled in for any bound left unset. */\nexport const effectiveSpoolPolicy = (exporter: ExporterPolicy): SpoolPolicy => ({\n maxBytes: exporter.spool?.maxBytes ?? DEFAULT_SPOOL_POLICY.maxBytes,\n maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,\n maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches,\n});\n\n/**\n * One destination as the runtime sends to it.\n *\n * `headers` holds what the configuration holds — literal values and `env:`\n * references, unresolved. Resolution against an environment happens only at the\n * point of sending ({@link resolveDestinationHeaders}), and the `default`\n * destination's header values never pass through configuration at all: they are\n * handed to the runtime separately, as they always have been.\n */\nexport type ExportDestination = {\n readonly name: string;\n /** `exporter` for the `default` destination, `destinations` for a list entry. */\n readonly source: \"exporter\" | \"destinations\";\n readonly protocol: ExporterPolicy[\"protocol\"];\n /** Traces URL as configured; for `default` this is `exporter.endpoint`. */\n readonly endpoint?: string;\n readonly tracesEndpoint?: string;\n readonly logsEndpoint?: string;\n readonly metricsEndpoint?: string;\n readonly signals: { readonly traces: boolean; readonly logs: boolean; readonly metrics: boolean };\n readonly headers: Readonly<Record<string, string>>;\n};\n\nconst legacyDestination = (exporter: ExporterPolicy): ExportDestination => ({\n name: DEFAULT_DESTINATION_NAME,\n source: \"exporter\",\n protocol: exporter.protocol,\n ...(exporter.endpoint === undefined ? {} : { endpoint: exporter.endpoint }),\n ...(exporter.logs.endpoint === undefined ? {} : { logsEndpoint: exporter.logs.endpoint }),\n ...(exporter.metrics?.endpoint === undefined ? {} : { metricsEndpoint: exporter.metrics.endpoint }),\n signals: { traces: true, logs: exporter.logs.enabled, metrics: exporter.metrics?.enabled === true },\n headers: {},\n});\n\n/** Whether a configuration uses the destination list at all. */\nexport const hasConfiguredDestinations = (exporter: ExporterPolicy): boolean =>\n exporter.destinations !== undefined && exporter.destinations.length > 0;\n\n/**\n * The destinations an exporter policy sends to, in a stable order: `default`\n * first when present, then the list in file order.\n *\n * - No `destinations`: exactly one `default` destination, even when it has no\n * endpoint — the sink then reports itself unconfigured, as it always has.\n * - With `destinations`: `default` is included only when a single-endpoint setting\n * actually names an endpoint, and disabled entries are left out.\n */\nexport const resolveExportDestinations = (\n exporter: ExporterPolicy,\n): readonly ExportDestination[] => {\n if (!hasConfiguredDestinations(exporter)) {\n return [legacyDestination(exporter)];\n }\n const resolved: ExportDestination[] = [];\n if (\n exporter.endpoint !== undefined ||\n exporter.logs.endpoint !== undefined ||\n exporter.metrics?.endpoint !== undefined\n ) {\n resolved.push(legacyDestination(exporter));\n }\n for (const destination of exporter.destinations ?? []) {\n if (destination.enabled === false) {\n continue;\n }\n const signals: readonly ExportSignal[] = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;\n resolved.push({\n name: destination.name,\n source: \"destinations\",\n protocol: destination.protocol ?? exporter.protocol,\n ...(destination.endpoint === undefined ? {} : { endpoint: destination.endpoint }),\n ...(destination.tracesEndpoint === undefined\n ? {}\n : { tracesEndpoint: destination.tracesEndpoint }),\n ...(destination.logsEndpoint === undefined ? {} : { logsEndpoint: destination.logsEndpoint }),\n ...(destination.metricsEndpoint === undefined\n ? {}\n : { metricsEndpoint: destination.metricsEndpoint }),\n signals: {\n traces: signals.includes(\"traces\"),\n logs: exporter.logs.enabled && signals.includes(\"logs\"),\n metrics: signals.includes(\"metrics\"),\n },\n headers: { ...(destination.headers ?? {}) },\n });\n }\n return resolved;\n};\n\n/** A header value's meaning, without its content. */\nexport type HeaderValueReference =\n | { readonly kind: \"literal\" }\n | { readonly kind: \"env\"; readonly variable: string };\n\nexport const parseHeaderValueReference = (value: string): HeaderValueReference =>\n value.startsWith(HEADER_ENV_REFERENCE_PREFIX)\n ? { kind: \"env\", variable: value.slice(HEADER_ENV_REFERENCE_PREFIX.length) }\n : { kind: \"literal\" };\n\nexport type ResolvedDestinationHeaders = {\n /** Header values ready to send. Never logged, never reported. */\n readonly values: Readonly<Record<string, string>>;\n /** Names of referenced environment variables that are unset or empty. */\n readonly missingVariables: readonly string[];\n};\n\n/**\n * Resolve `env:` references against an explicitly supplied environment.\n *\n * Pure: the process environment is never read implicitly. An unset or empty\n * variable is reported by *name* — the only part of a reference that is safe to\n * say out loud — and its header is left out of `values`.\n */\nexport const resolveDestinationHeaders = (\n headers: Readonly<Record<string, string>>,\n environment: Readonly<Record<string, string | undefined>> | undefined,\n): ResolvedDestinationHeaders => {\n const values: Record<string, string> = {};\n const missing: string[] = [];\n for (const [name, value] of Object.entries(headers)) {\n const reference = parseHeaderValueReference(value);\n if (reference.kind === \"literal\") {\n values[name] = value;\n continue;\n }\n const resolved = environment?.[reference.variable];\n if (resolved === undefined || resolved === \"\") {\n missing.push(reference.variable);\n continue;\n }\n values[name] = resolved;\n }\n return { values, missingVariables: [...new Set(missing)].sort() };\n};\n\n/**\n * Attribute-safe description of one destination: names, origins, and variable\n * names. Never a header value, and never an endpoint beyond its origin.\n */\nexport type DestinationDescription = {\n readonly name: string;\n readonly enabled: boolean;\n readonly protocol: ExporterPolicy[\"protocol\"];\n readonly signals: readonly ExportSignal[];\n readonly tracesEndpointOrigin?: string;\n readonly logsEndpointOrigin?: string;\n readonly metricsEndpointOrigin?: string;\n readonly headerNames: readonly string[];\n /** Environment variables this destination's headers reference. */\n readonly headerVariables: readonly string[];\n};\n\nexport const endpointOrigin = (endpoint: string | undefined): string | undefined => {\n if (endpoint === undefined) {\n return undefined;\n }\n try {\n return new URL(endpoint).origin;\n } catch {\n return \"<unparsable>\";\n }\n};\n\n/** Every configured destination, disabled ones included, for `doctor` and snapshots. */\nexport const describeExportDestinations = (\n exporter: ExporterPolicy,\n): readonly DestinationDescription[] => {\n const describe = (\n destination: ExportDestination,\n enabled: boolean,\n ): DestinationDescription => {\n const tracesOrigin = endpointOrigin(destination.tracesEndpoint ?? destination.endpoint);\n const logsOrigin = endpointOrigin(\n destination.logsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint,\n );\n const metricsOrigin = endpointOrigin(\n destination.metricsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint,\n );\n const variables = Object.values(destination.headers)\n .map(parseHeaderValueReference)\n .flatMap((reference) => (reference.kind === \"env\" ? [reference.variable] : []));\n return {\n name: destination.name,\n enabled,\n protocol: destination.protocol,\n signals: exportSignalSchema.options.filter((signal) => destination.signals[signal]),\n ...(tracesOrigin === undefined || !destination.signals.traces\n ? {}\n : { tracesEndpointOrigin: tracesOrigin }),\n ...(logsOrigin === undefined || !destination.signals.logs\n ? {}\n : { logsEndpointOrigin: logsOrigin }),\n ...(metricsOrigin === undefined || !destination.signals.metrics\n ? {}\n : { metricsEndpointOrigin: metricsOrigin }),\n headerNames:\n destination.source === \"exporter\"\n ? [...exporter.headerNames].sort()\n : Object.keys(destination.headers).sort(),\n headerVariables: [...new Set(variables)].sort(),\n };\n };\n const enabled = resolveExportDestinations(exporter).map((destination) =>\n describe(destination, true),\n );\n const disabled = (exporter.destinations ?? [])\n .filter((destination) => destination.enabled === false)\n .map((destination) =>\n describe(\n {\n name: destination.name,\n source: \"destinations\",\n protocol: destination.protocol ?? exporter.protocol,\n ...(destination.endpoint === undefined ? {} : { endpoint: destination.endpoint }),\n signals: { traces: false, logs: false, metrics: false },\n headers: { ...(destination.headers ?? {}) },\n },\n false,\n ),\n );\n return [...enabled, ...disabled];\n};\n","/**\n * Internal: shared by `OTEL_EXPORTER_OTLP_*HEADERS` parsing and the\n * `exporter.destinations[].headers` schema. Not re-exported from the package.\n */\n\n/**\n * Characters an HTTP field value must not contain once decoded. CR and LF would\n * split the request; the other controls and anything beyond Latin-1 are refused\n * by Node's HTTP client anyway, and refusing them here turns a failed export into\n * a reported, skipped entry.\n */\nexport const isUnsafeHeaderValue = (value: string): boolean =>\n [...value].some((char) => {\n const code = char.codePointAt(0) ?? 0;\n return (code < 0x20 && code !== 0x09) || code === 0x7f || code > 0xff;\n });\n","/**\n * The standard OTLP exporter header variables.\n *\n * `OTEL_EXPORTER_OTLP_HEADERS` applies to every signal;\n * `OTEL_EXPORTER_OTLP_TRACES_HEADERS` and `OTEL_EXPORTER_OTLP_LOGS_HEADERS`\n * apply to one signal each. They exist so a credential (`authorization=Basic …`)\n * can reach the exporter without being written on a command line, where `ps` and\n * `/proc/<pid>/cmdline` would show it to every local user.\n *\n * Header *values* never enter configuration. Parsing returns them to the caller,\n * which hands them straight to the sink at construction; configuration carries\n * header *names* only (`exporter.headerNames`), because a resolved-config\n * snapshot is logged and exported. Every diagnostic here names an entry by its\n * position and the variable by its name — never a key, never a value — because a\n * malformed entry may be the secret itself (`Basic abc` with no `=`).\n */\n\nimport { isUnsafeHeaderValue } from \"./header-value.js\";\n\n/** Upper bound on headers per variable, matching `exporter.headerNames`. */\nexport const MAX_OTLP_HEADERS = 32;\n\nexport const OTLP_HEADER_VARIABLES = Object.freeze({\n generic: \"OTEL_EXPORTER_OTLP_HEADERS\",\n traces: \"OTEL_EXPORTER_OTLP_TRACES_HEADERS\",\n logs: \"OTEL_EXPORTER_OTLP_LOGS_HEADERS\",\n});\n\n/** RFC 9110 `token`: the characters an HTTP field name may contain. */\nconst HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n\nexport type ParsedOtlpHeaders = {\n readonly headers: Readonly<Record<string, string>>;\n /** Position-only explanations; never a key or a value. */\n readonly warnings: readonly string[];\n};\n\nconst decode = (raw: string): string | undefined => {\n try {\n return decodeURIComponent(raw);\n } catch {\n return undefined;\n }\n};\n\n/**\n * Parse one `OTEL_EXPORTER_OTLP_*HEADERS` value.\n *\n * The OpenTelemetry exporter specification defines the format as W3C\n * Baggage-like: comma-separated `key=value` pairs, surrounding whitespace\n * trimmed, keys and values percent-decoded. So `authorization=Basic%20abc` is\n * the header `authorization: Basic abc`, and a `,` inside a value must be\n * written `%2C`. A malformed entry is skipped and reported; the rest of the\n * variable still applies. A repeated key takes its last value.\n */\nexport const parseOtlpHeadersValue = (raw: string): ParsedOtlpHeaders => {\n const headers: Record<string, string> = {};\n const warnings: string[] = [];\n let overflowed = false;\n\n for (const [index, rawEntry] of raw.split(\",\").entries()) {\n const position = String(index + 1);\n const entry = rawEntry.trim();\n if (entry === \"\") {\n continue;\n }\n const equals = entry.indexOf(\"=\");\n if (equals <= 0) {\n warnings.push(`entry ${position} is not a key=value pair; ignored`);\n continue;\n }\n const key = decode(entry.slice(0, equals).trim());\n // Split on the first `=` only: a base64 credential ends in `=` padding.\n const value = decode(entry.slice(equals + 1).trim());\n if (key === undefined || value === undefined) {\n warnings.push(`entry ${position} has malformed percent-encoding; ignored`);\n continue;\n }\n const name = key.trim();\n const trimmedValue = value.trim();\n if (!HEADER_NAME_PATTERN.test(name)) {\n warnings.push(`entry ${position} does not name a valid HTTP header; ignored`);\n continue;\n }\n if (trimmedValue === \"\") {\n warnings.push(`entry ${position} has an empty value; ignored`);\n continue;\n }\n if (isUnsafeHeaderValue(trimmedValue)) {\n warnings.push(`entry ${position} has a character not allowed in an HTTP header value; ignored`);\n continue;\n }\n const existing = findHeaderName(headers, name);\n if (existing === undefined && Object.keys(headers).length >= MAX_OTLP_HEADERS) {\n overflowed = true;\n continue;\n }\n if (existing !== undefined) {\n delete headers[existing];\n }\n headers[name] = trimmedValue;\n }\n\n if (overflowed) {\n warnings.push(`more than ${String(MAX_OTLP_HEADERS)} headers were supplied; the excess was ignored`);\n }\n return { headers, warnings };\n};\n\n/** HTTP field names are case-insensitive: `Authorization` and `authorization` are one header. */\nconst findHeaderName = (headers: Readonly<Record<string, string>>, name: string): string | undefined => {\n const lower = name.toLowerCase();\n return Object.keys(headers).find((candidate) => candidate.toLowerCase() === lower);\n};\n\n/**\n * Overlay header maps, lowest precedence first, per header name.\n *\n * A higher source replaces only the names it sets (case-insensitively), so a\n * signal-specific variable can override `authorization` while a generic tenant\n * header still applies — the same per-key merge the OpenTelemetry SDKs apply.\n */\nexport const mergeOtlpHeaders = (\n ...sources: readonly Readonly<Record<string, string>>[]\n): Readonly<Record<string, string>> => {\n const merged: Record<string, string> = {};\n for (const source of sources) {\n for (const [name, value] of Object.entries(source)) {\n const existing = findHeaderName(merged, name);\n if (existing !== undefined) {\n delete merged[existing];\n }\n merged[name] = value;\n }\n }\n return merged;\n};\n\nexport type ResolvedOtlpHeaders = {\n /** Headers for the traces exporter. */\n readonly traces: Readonly<Record<string, string>>;\n /** Headers for the logs exporter. */\n readonly logs: Readonly<Record<string, string>>;\n /** Variable-qualified, value-free explanations of skipped entries. */\n readonly warnings: readonly { readonly variable: string; readonly detail: string }[];\n};\n\n/**\n * Resolve exporter headers per signal.\n *\n * Precedence, per header name, highest first:\n *\n * ```\n * explicit headers (--header) > OTEL_EXPORTER_OTLP_{TRACES,LOGS}_HEADERS > OTEL_EXPORTER_OTLP_HEADERS\n * ```\n *\n * Pure: the environment is passed in, never read from `process.env`.\n */\nexport const resolveOtlpHeaders = (\n env: Readonly<Record<string, string | undefined>>,\n explicit: Readonly<Record<string, string>> = {},\n): ResolvedOtlpHeaders => {\n const warnings: { variable: string; detail: string }[] = [];\n const read = (variable: string): Readonly<Record<string, string>> => {\n const raw = env[variable];\n if (raw === undefined || raw.trim() === \"\") {\n return {};\n }\n const parsed = parseOtlpHeadersValue(raw);\n for (const detail of parsed.warnings) {\n warnings.push({ variable, detail });\n }\n return parsed.headers;\n };\n const generic = read(OTLP_HEADER_VARIABLES.generic);\n const traces = read(OTLP_HEADER_VARIABLES.traces);\n const logs = read(OTLP_HEADER_VARIABLES.logs);\n return {\n traces: mergeOtlpHeaders(generic, traces, explicit),\n logs: mergeOtlpHeaders(generic, logs, explicit),\n warnings,\n };\n};\n\n/**\n * Header names, deduplicated case-insensitively (first spelling kept), sorted\n * and bounded — the only part of a header that may enter configuration or a\n * diagnostic.\n */\nexport const unionOtlpHeaderNames = (...lists: readonly (readonly string[])[]): readonly string[] => {\n const names: string[] = [];\n const seen = new Set<string>();\n for (const name of lists.flat()) {\n if (!seen.has(name.toLowerCase())) {\n seen.add(name.toLowerCase());\n names.push(name);\n }\n }\n return names.sort().slice(0, MAX_OTLP_HEADERS);\n};\n\n/** {@link unionOtlpHeaderNames} over the names of header maps. */\nexport const describeOtlpHeaderNames = (\n ...sources: readonly Readonly<Record<string, string>>[]\n): readonly string[] => unionOtlpHeaderNames(...sources.map((source) => Object.keys(source)));\n","import { z } from \"zod\";\n\nimport { 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 type { OtelHookErrorCode } from \"../errors/index.js\";\nimport type { EpochMillis } from \"../model/primitives.js\";\n\n/**\n * One tracked delivery path.\n *\n * The two telemetry signals are separate subsystems because they fail\n * independently — a collector with no logs receiver leaves traces perfectly\n * healthy — and a single combined verdict would make an operator bisect which one\n * is broken. `telemetry-sink` remains the traces signal, unrenamed, so an existing\n * `doctor --json` consumer keeps reading the same field.\n */\nexport type DeliverySubsystem =\n | \"state-store\"\n | \"telemetry-sink\"\n | \"telemetry-log-sink\"\n | \"telemetry-metric-sink\"\n | \"lifecycle\";\n\n/**\n * Sanitized delivery health.\n *\n * Every field is a count, a timestamp, a boolean, or a closed-vocabulary error\n * code — the same restriction the privacy service applies to everything else\n * that might reach a sink, so a health snapshot is itself safe to export or log\n * without a second review.\n */\nexport type DeliveryHealthSnapshot = {\n readonly subsystem: DeliverySubsystem;\n readonly healthy: boolean;\n readonly totalAccepted: number;\n readonly totalRejected: number;\n readonly consecutiveFailures: number;\n readonly lastSuccessAt?: EpochMillis;\n readonly lastFailureAt?: EpochMillis;\n readonly lastErrorCode?: OtelHookErrorCode;\n /**\n * Export destination this snapshot describes. Present only when\n * `exporter.destinations` is in use, so a single-destination snapshot is\n * unchanged.\n */\n readonly destination?: string;\n};\n\nexport type HealthTrackerOptions = {\n /** Consecutive failures at or beyond this count flip `healthy` to false. Default 3. */\n readonly unhealthyAfterConsecutiveFailures?: number;\n /** Labels every snapshot with an export destination name. */\n readonly destination?: string;\n};\n\n/**\n * Accumulates success/failure counts for one subsystem instance.\n *\n * Deliberately per-instance rather than a module-level registry: a store or\n * sink constructs its own tracker and exposes a `health()` accessor, so two\n * instances in one process never share counters (see ADR 0001 on module-level\n * identity).\n */\nexport interface HealthTracker {\n recordSuccess(count?: number, at?: number): void;\n recordFailure(code: OtelHookErrorCode, count?: number, at?: number): void;\n snapshot(): DeliveryHealthSnapshot;\n}\n\nexport const createHealthTracker = (\n subsystem: DeliverySubsystem,\n options: HealthTrackerOptions = {},\n): HealthTracker => {\n const unhealthyThreshold = options.unhealthyAfterConsecutiveFailures ?? 3;\n let totalAccepted = 0;\n let totalRejected = 0;\n let consecutiveFailures = 0;\n let lastSuccessAt: number | undefined;\n let lastFailureAt: number | undefined;\n let lastErrorCode: OtelHookErrorCode | undefined;\n\n return {\n recordSuccess: (count = 1, at?: number): void => {\n totalAccepted += count;\n consecutiveFailures = 0;\n if (at !== undefined) {\n lastSuccessAt = at;\n }\n },\n recordFailure: (code: OtelHookErrorCode, count = 1, at?: number): void => {\n totalRejected += count;\n consecutiveFailures += 1;\n lastErrorCode = code;\n if (at !== undefined) {\n lastFailureAt = at;\n }\n },\n snapshot: (): DeliveryHealthSnapshot => ({\n subsystem,\n healthy: consecutiveFailures < unhealthyThreshold,\n totalAccepted,\n totalRejected,\n consecutiveFailures,\n ...(lastSuccessAt === undefined ? {} : { lastSuccessAt }),\n ...(lastFailureAt === undefined ? {} : { lastFailureAt }),\n ...(lastErrorCode === undefined ? {} : { lastErrorCode }),\n ...(options.destination === undefined ? {} : { destination: options.destination }),\n }),\n };\n};\n\nexport type OverallHealth = {\n readonly healthy: boolean;\n readonly subsystems: readonly DeliveryHealthSnapshot[];\n};\n\n/** Combines snapshots from every configured subsystem into one overall verdict. */\nexport const summarizeHealth = (snapshots: readonly DeliveryHealthSnapshot[]): OverallHealth => ({\n healthy: snapshots.every((snapshot) => snapshot.healthy),\n subsystems: [...snapshots],\n});\n","import { z } from \"zod\";\n\nimport { attributesSchema, epochMillisSchema, type Attributes } from \"../model/primitives.js\";\nimport {\n describeErrorCode,\n errorPhaseSchema,\n errorSeveritySchema,\n failurePostureSchema,\n otelHookErrorCodeSchema,\n type ErrorPhase,\n type OtelHookErrorCode,\n} from \"./taxonomy.js\";\n\nexport * from \"./taxonomy.js\";\n\n/**\n * Serializable, privacy-safe description of a failure.\n *\n * `message` is a fixed-vocabulary summary derived from the code and phase, never\n * a provider or exception string, because exception messages routinely contain\n * prompt text, file paths, and credentials. `details` is restricted to attribute\n * primitives for the same reason.\n */\nexport const otelHookErrorInfoSchema = z.strictObject({\n code: otelHookErrorCodeSchema,\n severity: errorSeveritySchema,\n phase: errorPhaseSchema,\n posture: failurePostureSchema,\n retryable: z.boolean(),\n message: z.string().min(1).max(512),\n details: attributesSchema.optional(),\n occurredAt: epochMillisSchema.optional(),\n});\nexport type OtelHookErrorInfo = z.infer<typeof otelHookErrorInfoSchema>;\n\nexport type CreateErrorInfoInput = {\n readonly code: OtelHookErrorCode;\n readonly phase: ErrorPhase;\n /** Short, non-sensitive detail, e.g. `\"2 adapters matched\"`. */\n readonly detail?: string;\n readonly details?: Attributes;\n readonly occurredAt?: number;\n};\n\nexport const createErrorInfo = (input: CreateErrorInfoInput): OtelHookErrorInfo => {\n const descriptor = describeErrorCode(input.code);\n const message =\n input.detail === undefined\n ? `${input.code} during ${input.phase}: ${descriptor.summary}`\n : `${input.code} during ${input.phase}: ${input.detail}`;\n return otelHookErrorInfoSchema.parse({\n code: descriptor.code,\n severity: descriptor.severity,\n phase: input.phase,\n posture: descriptor.posture,\n retryable: descriptor.retryable,\n message: message.slice(0, 512),\n ...(input.details === undefined ? {} : { details: input.details }),\n ...(input.occurredAt === undefined ? {} : { occurredAt: input.occurredAt }),\n });\n};\n\nexport class OtelHookError extends Error {\n public readonly info: OtelHookErrorInfo;\n\n public constructor(info: OtelHookErrorInfo) {\n super(info.message);\n this.name = \"OtelHookError\";\n this.info = info;\n }\n\n public static of(input: CreateErrorInfoInput): OtelHookError {\n return new OtelHookError(createErrorInfo(input));\n }\n}\n\nexport const isOtelHookError = (value: unknown): value is OtelHookError =>\n value instanceof OtelHookError;\n\n/**\n * Describe an arbitrary thrown value without disclosing its message.\n *\n * Only the constructor name crosses the boundary; the presence of a message is\n * reported as a boolean so operators can tell \"threw nothing useful\" from\n * \"threw something we deliberately did not log\".\n */\nexport const describeThrown = (\n thrown: unknown,\n): { readonly errorName: string; readonly hasMessage: boolean } => {\n if (thrown instanceof Error) {\n return {\n errorName: thrown.name.slice(0, 64) || \"Error\",\n hasMessage: typeof thrown.message === \"string\" && thrown.message.length > 0,\n };\n }\n return { errorName: typeof thrown, hasMessage: false };\n};\n\n/** Convert an unexpected throw into privacy-safe error info. */\nexport const errorInfoFromThrown = (\n thrown: unknown,\n input: { readonly code?: OtelHookErrorCode; readonly phase: ErrorPhase; readonly occurredAt?: number },\n): OtelHookErrorInfo => {\n if (isOtelHookError(thrown)) {\n return thrown.info;\n }\n const described = describeThrown(thrown);\n return createErrorInfo({\n code: input.code ?? \"internal-error\",\n phase: input.phase,\n detail: `contained ${described.errorName}`,\n details: { \"error.name\": described.errorName, \"error.has_message\": described.hasMessage },\n ...(input.occurredAt === undefined ? {} : { occurredAt: input.occurredAt }),\n });\n};\n","import { z } from \"zod\";\n\n/**\n * Closed set of error codes. Adding a code is a minor change; changing what a\n * code means is a breaking change.\n */\nexport const otelHookErrorCodeSchema = z.enum([\n /** Input was not usable at all (empty stdin, unparsable JSON). */\n \"invalid-input\",\n /** Input parsed but failed canonical schema validation. */\n \"schema-validation-failed\",\n /** No adapter claimed the input with sufficient confidence. */\n \"provider-unknown\",\n /** Several adapters claimed the input at the same confidence. */\n \"provider-detection-ambiguous\",\n /** An adapter threw or returned a malformed result. */\n \"provider-adapter-failure\",\n /** Two identity claims disagreed at equal confidence. */\n \"identity-conflict\",\n /** Required identity fields were absent. */\n \"identity-incomplete\",\n /** A usage report violated the canonical usage invariants. */\n \"usage-invalid\",\n /** The state store could not be read or written. */\n \"state-store-failure\",\n /** The telemetry sink rejected or could not deliver a batch. */\n \"telemetry-export-failure\",\n /** Content reached the sink boundary in a state the policy forbids. */\n \"privacy-policy-violation\",\n /** Configuration could not be resolved. */\n \"configuration-invalid\",\n /** A configured bound (events, batch size) dropped data. */\n \"limit-exceeded\",\n /**\n * No replay-stable delivery identifier was available for a callback while\n * deduplication was required.\n */\n \"delivery-identifier-unavailable\",\n \"delivery-claim-superseded\",\n /** Anything unanticipated. Always reported, never fatal to the host. */\n \"internal-error\",\n]);\nexport type OtelHookErrorCode = z.infer<typeof otelHookErrorCodeSchema>;\n\nexport const errorSeveritySchema = z.enum([\"warning\", \"error\"]);\nexport type ErrorSeverity = z.infer<typeof errorSeveritySchema>;\n\n/** Pipeline stage where a failure occurred. */\nexport const errorPhaseSchema = z.enum([\n \"configuration\",\n \"detection\",\n \"identity\",\n \"parsing\",\n \"normalization\",\n \"privacy\",\n \"state\",\n \"export\",\n \"shutdown\",\n]);\nexport type ErrorPhase = z.infer<typeof errorPhaseSchema>;\n\n/**\n * Which of the two safety postures a code participates in.\n *\n * - `fail-open`: the hook still reports success to the host agent. Telemetry may\n * be incomplete; the coding agent is never blocked.\n * - `fail-closed-attribution`: the observation is not attributed to a session or\n * provider. Data is dropped rather than labelled with a guess.\n */\nexport const failurePostureSchema = z.enum([\"fail-open\", \"fail-closed-attribution\"]);\nexport type FailurePosture = z.infer<typeof failurePostureSchema>;\n\nexport type ErrorCodeDescriptor = {\n readonly code: OtelHookErrorCode;\n readonly severity: ErrorSeverity;\n readonly posture: FailurePosture;\n /** Whether retrying the same input could succeed. */\n readonly retryable: boolean;\n readonly summary: string;\n};\n\nexport const ERROR_TAXONOMY: Readonly<Record<OtelHookErrorCode, ErrorCodeDescriptor>> =\n Object.freeze({\n \"invalid-input\": {\n code: \"invalid-input\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Input could not be read or decoded.\",\n },\n \"schema-validation-failed\": {\n code: \"schema-validation-failed\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"A canonical event failed schema validation and was dropped.\",\n },\n \"provider-unknown\": {\n code: \"provider-unknown\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"No adapter recognized the source provider; the input stays unattributed.\",\n },\n \"provider-detection-ambiguous\": {\n code: \"provider-detection-ambiguous\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Multiple adapters claimed the input at equal confidence.\",\n },\n \"provider-adapter-failure\": {\n code: \"provider-adapter-failure\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A provider adapter failed while parsing.\",\n },\n \"identity-conflict\": {\n code: \"identity-conflict\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Identity claims disagreed; attribution was declined.\",\n },\n \"identity-incomplete\": {\n code: \"identity-incomplete\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Required identity fields were missing; attribution was declined.\",\n },\n \"usage-invalid\": {\n code: \"usage-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A usage report violated the canonical usage invariants.\",\n },\n \"state-store-failure\": {\n code: \"state-store-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"State could not be read or written; derived values may be incomplete.\",\n },\n \"telemetry-export-failure\": {\n code: \"telemetry-export-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"The telemetry sink could not accept a batch.\",\n },\n \"privacy-policy-violation\": {\n code: \"privacy-policy-violation\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Content violated the resolved privacy policy and was dropped.\",\n },\n \"configuration-invalid\": {\n code: \"configuration-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Configuration could not be resolved; defaults apply.\",\n },\n \"limit-exceeded\": {\n code: \"limit-exceeded\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A configured bound was reached and data was dropped.\",\n },\n \"delivery-identifier-unavailable\": {\n code: \"delivery-identifier-unavailable\",\n severity: \"warning\",\n // Fail-open: the observation is still attributed and exported. Only the\n // at-most-once guarantee is missing, and refusing the telemetry to protect\n // a duplicate count would trade a certain loss for a possible one.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"No replay-stable delivery identifier was available; this callback was exported without deduplication.\",\n },\n \"delivery-claim-superseded\": {\n code: \"delivery-claim-superseded\",\n severity: \"warning\",\n // Fail-open, and specifically *not* silent. A peer reclaimed this callback's\n // claim while this process was still working on it, which means the\n // configured stale window is shorter than this installation's real worst\n // case. Both processes may now have exported the callback, so the\n // at-most-once guarantee did not hold for it — the only honest response is\n // to say so and let the operator raise the window.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"A delivery claim was reclaimed by another process before this one committed; the callback may have been exported twice.\",\n },\n \"internal-error\": {\n code: \"internal-error\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"An unexpected failure was contained.\",\n },\n });\n\nexport const describeErrorCode = (code: OtelHookErrorCode): ErrorCodeDescriptor =>\n ERROR_TAXONOMY[code];\n\n/** Outcome of attributing an observation to a provider and session. */\nexport const attributionOutcomeSchema = z.enum([\n /** Identity resolved; events carry provider and session identity. */\n \"attributed\",\n /** Identity could not be established safely; nothing was attributed. */\n \"declined\",\n /** Attribution was attempted and failed unexpectedly. */\n \"failed\",\n /** Input was recognized but intentionally carried no telemetry. */\n \"not-applicable\",\n]);\nexport type AttributionOutcome = z.infer<typeof attributionOutcomeSchema>;\n\nexport const attributionReasonSchema = z.enum([\n \"provider-unknown\",\n \"provider-detection-ambiguous\",\n \"identity-conflict\",\n \"identity-incomplete\",\n \"adapter-ignored-input\",\n \"adapter-failure\",\n \"invalid-input\",\n \"internal-error\",\n]);\nexport type AttributionReason = z.infer<typeof attributionReasonSchema>;\n","import { 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\n/**\n * Metric series state (issue #69): one record per series, under the provider\n * session it belongs to so the janitor can sweep a session's series with the rest\n * of its state. The scope segment is `s=<sessionId>` for a per-session series and\n * `all` for one that spans sessions (`session.id` switched off); the `s=` prefix\n * keeps the two from ever colliding, whatever a provider names its sessions.\n *\n * `seriesDigest` is a digest of the instrument and its attributes, never the\n * attributes themselves.\n */\nexport const metricSeriesKey = (sessionScope: string, seriesDigest: string): string =>\n `${metricSeriesScanPrefix(sessionScope)}${encodeSegment(seriesDigest)}`;\n\nexport const metricSeriesScanPrefix = (sessionScope?: string): string =>\n sessionScope === undefined\n ? `${LIFECYCLE_PREFIX}:metric:v1:`\n : `${LIFECYCLE_PREFIX}:metric:v1:${encodeSegment(sessionScope)}:`;\n","import { createHash } from \"node:crypto\";\n\nimport type { Clock, StateStore } from \"../runtime/ports.js\";\nimport { withOptionalSessionLock } from \"../state/store.js\";\nimport {\n emptyHistogram,\n METRIC_INSTRUMENTS,\n recordIntoHistogram,\n seriesIdentity,\n type HistogramState,\n type MetricObservation,\n type MetricPoint,\n} from \"../telemetry/metric-model.js\";\nimport { metricSeriesKey, metricSeriesScanPrefix } from \"./keys.js\";\n\n/**\n * Cumulative metric series kept across hook processes (issue #69).\n *\n * A hook process lives for one callback, so an in-process `MeterProvider` would\n * only ever see one observation and restart every series at zero. Cumulative\n * temporality — what receivers that merge counters by keeping the largest value\n * need — therefore requires the running total to outlive the process. Each series\n * is one state record: read, fold the batch's observations in, write back, and\n * export the new total as a point whose interval starts at the series' first\n * observation.\n *\n * Folding is idempotent per delivery: the record names the last delivery folded\n * into it, so a callback replayed after a crash between \"recorded\" and \"committed\"\n * restates the total instead of adding to it.\n *\n * Concurrency: the read-fold-write runs under the session lock of the series'\n * scope (the provider session, or one shared lock for series that span sessions),\n * the same lock usage accounting uses, so two concurrent processes cannot both add\n * to the same stale total.\n */\n\nexport type MetricSeriesStoreDependencies = {\n readonly stateStore: StateStore;\n readonly clock: Clock;\n};\n\nexport type RecordCumulativeOptions = {\n /** Opaque digest of the delivery these observations came from. */\n readonly deliveryToken?: string;\n /** Whether series are per session (`session.id` on the points). Default true. */\n readonly perSession?: boolean;\n};\n\nexport type MetricSeriesCleanupResult = { readonly removed: number; readonly scanned: number };\n\nexport interface MetricSeriesStore {\n /** Fold observations into their series; returns one cumulative point per touched series. */\n recordCumulative(\n observations: readonly MetricObservation[],\n options?: RecordCumulativeOptions,\n ): Promise<readonly MetricPoint[]>;\n /** Remember when the session's current turn began (its last prompt). */\n recordTurnStart(sessionId: string, startMillis: number): Promise<void>;\n /** When the session's current turn began, if a prompt was recorded. */\n readTurnStart(sessionId: string): Promise<number | undefined>;\n cleanup(\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<MetricSeriesCleanupResult>;\n}\n\n/** Not a base64url digest (43 chars), so it can never collide with a series key. */\nconst TURN_START_SEGMENT = \"turn-start\";\n\n/** Lock and key scope for series that are not per session. */\nconst SHARED_SCOPE = \"all\";\nconst SHARED_LOCK = \"otelhook.metrics.shared\";\n\nconst sessionScope = (sessionId: string): string => `s=${sessionId}`;\n\nconst digest = (identity: string): string =>\n createHash(\"sha256\").update(identity).digest(\"base64url\").slice(0, 43);\n\ntype SeriesRecord = {\n readonly startTimeMillis: number;\n readonly value?: number | undefined;\n readonly histogram?: HistogramState | undefined;\n readonly appliedDelivery?: string | undefined;\n};\n\nconst toStoredHistogram = (\n histogram: HistogramState,\n): { count: number; sum: number; min: number; max: number; bucketCounts: number[] } => ({\n count: histogram.count,\n sum: histogram.sum,\n // An empty histogram has infinite min/max, which JSON cannot hold. A stored\n // histogram always has at least one value, so these are finite in practice.\n min: Number.isFinite(histogram.min) ? histogram.min : 0,\n max: Number.isFinite(histogram.max) ? histogram.max : 0,\n bucketCounts: [...histogram.bucketCounts],\n});\n\nexport const createMetricSeriesStore = (deps: MetricSeriesStoreDependencies): MetricSeriesStore => {\n const { stateStore, clock } = deps;\n\n const readSeries = async (key: string): Promise<SeriesRecord | undefined> => {\n const record = await stateStore.read(key);\n if (record?.value.kind !== \"metric-series\") {\n return undefined;\n }\n return record.value;\n };\n\n const recordGroup = async (\n scope: string,\n observations: readonly MetricObservation[],\n deliveryToken: string | undefined,\n ): Promise<MetricPoint[]> => {\n const bySeries = new Map<string, MetricObservation[]>();\n for (const observation of observations) {\n const identity = seriesIdentity(observation.instrument, observation.attributes);\n const group = bySeries.get(identity) ?? [];\n group.push(observation);\n bySeries.set(identity, group);\n }\n\n const now = clock.now();\n const points: MetricPoint[] = [];\n for (const [identity, group] of bySeries) {\n const first = group[0];\n if (first === undefined) {\n continue;\n }\n const instrument = METRIC_INSTRUMENTS[first.instrument];\n const key = metricSeriesKey(scope, digest(identity));\n const existing = await readSeries(key);\n const boundaries = instrument.boundaries;\n // A stored histogram whose bucket layout no longer matches the instrument\n // cannot be continued; it restarts, with a new start time, which a receiver\n // reads as a reset rather than as a decrease.\n const compatible =\n existing !== undefined &&\n (boundaries === undefined\n ? existing.value !== undefined\n : existing.histogram?.bucketCounts.length === boundaries.length + 1);\n const base = compatible ? existing : undefined;\n const replay = deliveryToken !== undefined && base?.appliedDelivery === deliveryToken;\n\n const earliest = Math.min(...group.map((observation) => observation.timeMillis));\n const startTimeMillis = base?.startTimeMillis ?? Math.min(earliest, now);\n let value = base?.value ?? 0;\n let histogram: HistogramState | undefined =\n boundaries === undefined\n ? undefined\n : base?.histogram === undefined\n ? emptyHistogram(boundaries)\n : base.histogram;\n\n if (!replay) {\n for (const observation of group) {\n if (histogram !== undefined && boundaries !== undefined) {\n histogram = recordIntoHistogram(histogram, boundaries, observation.value);\n } else {\n value += observation.value;\n }\n }\n await stateStore.write(key, {\n kind: \"metric-series\",\n startTimeMillis,\n ...(histogram === undefined ? { value } : { histogram: toStoredHistogram(histogram) }),\n ...(deliveryToken === undefined ? {} : { appliedDelivery: deliveryToken }),\n });\n }\n\n points.push({\n instrument: first.instrument,\n temporality: \"cumulative\",\n attributes: first.attributes,\n startTimeMillis,\n timeMillis: Math.max(now, startTimeMillis),\n ...(histogram === undefined ? { value } : { histogram }),\n });\n }\n return points;\n };\n\n const recordCumulative = async (\n observations: readonly MetricObservation[],\n options?: RecordCumulativeOptions,\n ): Promise<readonly MetricPoint[]> => {\n if (observations.length === 0) {\n return [];\n }\n if (options?.perSession === false) {\n return withOptionalSessionLock(stateStore, SHARED_LOCK, () =>\n recordGroup(SHARED_SCOPE, observations, options.deliveryToken),\n );\n }\n const bySession = new Map<string, MetricObservation[]>();\n for (const observation of observations) {\n const group = bySession.get(observation.sessionId) ?? [];\n group.push(observation);\n bySession.set(observation.sessionId, group);\n }\n const points: MetricPoint[] = [];\n for (const [sessionId, group] of bySession) {\n points.push(\n ...(await withOptionalSessionLock(stateStore, sessionId, () =>\n recordGroup(sessionScope(sessionId), group, options?.deliveryToken),\n )),\n );\n }\n return points;\n };\n\n const cleanup = async (\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<MetricSeriesCleanupResult> => {\n const cap = options?.maxEntries ?? 1_000;\n const now = clock.now();\n let removed = 0;\n let scanned = 0;\n const prefix = metricSeriesScanPrefix(\n options?.sessionId === undefined ? undefined : sessionScope(options.sessionId),\n );\n for (const key of await stateStore.keys(prefix)) {\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 await stateStore.delete(key);\n removed += 1;\n }\n }\n return { removed, scanned };\n };\n\n const turnKey = (sessionId: string): string => metricSeriesKey(sessionScope(sessionId), TURN_START_SEGMENT);\n\n const recordTurnStart = (sessionId: string, startMillis: number): Promise<void> =>\n withOptionalSessionLock(stateStore, sessionId, async () => {\n const existing = await stateStore.read(turnKey(sessionId));\n const previous =\n existing?.value.kind === \"attributes\" && typeof existing.value.attributes.startMillis === \"number\"\n ? existing.value.attributes.startMillis\n : undefined;\n // Never move backwards: a late, redelivered prompt must not reopen an older turn.\n if (previous !== undefined && previous >= startMillis) {\n return;\n }\n await stateStore.write(turnKey(sessionId), { kind: \"attributes\", attributes: { startMillis } });\n });\n\n const readTurnStart = async (sessionId: string): Promise<number | undefined> => {\n const record = await stateStore.read(turnKey(sessionId));\n const value = record?.value.kind === \"attributes\" ? record.value.attributes.startMillis : undefined;\n return typeof value === \"number\" ? value : undefined;\n };\n\n return { recordCumulative, recordTurnStart, readTurnStart, cleanup };\n};\n","import type { Attributes } from \"@opentelemetry/api\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport { ATTR_SESSION_ID } from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport { isTargetedEvent, type CanonicalEvent } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\n\n/**\n * W3C hex identity attributes on every log and span.\n *\n * Mission Control (and any consumer that decodes OTLP protobuf with a JSON\n * `toObject` that stringifies bytes as UTF-8) cannot recover a usable id from\n * the protobuf `trace_id` / `span_id` fields. These attributes are already hex\n * in the OpenTelemetry JS API; they are copied onto the attribute map so a\n * consumer never has to stringify binary ids.\n */\nexport const ATTR_TRACE_ID = \"trace_id\";\nexport const ATTR_SPAN_ID = \"span_id\";\nexport const ATTR_PARENT_SPAN_ID = \"parent_span_id\";\n\n/** Provider session id, kept when `session.id` is an externally supplied key. */\nexport const ATTR_OTELHOOK_SESSION_ID = \"otelhook.session.id\";\n/** Same provider session id under the gen_ai conversation attribute. */\nexport const ATTR_GEN_AI_CONVERSATION_ID = \"gen_ai.conversation.id\";\n\nexport const TRACE_ID_HEX_PATTERN = /^[0-9a-f]{32}$/;\nexport const SPAN_ID_HEX_PATTERN = /^[0-9a-f]{16}$/;\n\nconst ATTR_OTELHOOK_INVOCATION_ID = \"otelhook.invocation.id\";\nconst ATTR_OTELHOOK_PROVIDER_ID = \"otelhook.provider.id\";\nconst ATTR_OTELHOOK_PROVIDER_VERSION = \"otelhook.provider.version\";\nconst ATTR_OTELHOOK_WORKSPACE_ID = \"otelhook.workspace.id\";\n\n/**\n * Resource attributes a launcher may set to supply the session key, in\n * preference order: the OpenTelemetry semantic-convention `session.id`, then the\n * legacy `har.session_key` that earlier launchers still send.\n */\nexport const EXTERNAL_SESSION_KEY_ATTRIBUTES: readonly string[] = Object.freeze([\n ATTR_SESSION_ID,\n \"har.session_key\",\n]);\n\n/**\n * The provider's own subagent id (Claude Code `agent_id`), on every record of an\n * event emitted inside a subagent. Same class as `session.id`: a provider-minted\n * opaque identifier, exported verbatim so a consumer can join it to the\n * provider's own per-subagent records.\n */\nexport const ATTR_OTELHOOK_SUBAGENT_ID = \"otelhook.subagent.id\";\n\n/**\n * Worktree an event targeted (ADR 0008): the one a tool call touched, or the one\n * a session runs in on its start and prompts. Branch under the OTel VCS\n * attribute; the worktree root, and its repository's main worktree root, only\n * as salted `git-root` handles.\n */\nexport const ATTR_VCS_REF_HEAD_NAME = \"vcs.ref.head.name\";\nexport const ATTR_OTELHOOK_TARGET_WORKSPACE_ID = \"otelhook.target.workspace.id\";\nexport const ATTR_OTELHOOK_TARGET_SOURCE = \"otelhook.target.source\";\nexport const ATTR_OTELHOOK_TARGET_REPOSITORY_ID = \"otelhook.target.repository.id\";\nexport const ATTR_OTELHOOK_TARGET_WORKTREE_KIND = \"otelhook.target.worktree.kind\";\n\n/** Whether `gen_ai.usage.*` on this record is a delta or a running total. */\nexport const ATTR_OTELHOOK_USAGE_TEMPORALITY = \"otelhook.usage.temporality\";\n\n/** Target attributes for a targeted event; empty when the core resolved none. */\nexport const targetAttributes = (event: CanonicalEvent): Attributes => {\n if (!isTargetedEvent(event) || event.target === undefined) {\n return {};\n }\n const { target } = event;\n return {\n [ATTR_OTELHOOK_TARGET_WORKSPACE_ID]: target.workspaceId,\n [ATTR_OTELHOOK_TARGET_SOURCE]: target.source,\n ...(target.vcsBranchName === undefined ? {} : { [ATTR_VCS_REF_HEAD_NAME]: target.vcsBranchName }),\n ...(target.repositoryId === undefined\n ? {}\n : { [ATTR_OTELHOOK_TARGET_REPOSITORY_ID]: target.repositoryId }),\n ...(target.worktreeKind === undefined\n ? {}\n : { [ATTR_OTELHOOK_TARGET_WORKTREE_KIND]: target.worktreeKind }),\n };\n};\n\n/** Temporality of reported usage, so a consumer never sums running totals. */\nexport const usageTemporalityAttributes = (usage: CanonicalUsage | undefined): Attributes =>\n usage === undefined ? {} : { [ATTR_OTELHOOK_USAGE_TEMPORALITY]: usage.temporality };\n\nconst isPrimitiveAttribute = (value: unknown): value is string | number | boolean =>\n typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\";\n\n/**\n * Resource attribute namespaces a launcher puts on the process that are also\n * copied onto every span and log record.\n *\n * Many backends index only record attributes (filters, search, dashboards), so a\n * value that exists only on the Resource is invisible there. Copied:\n *\n * - `har.*` — attributes earlier launchers send;\n * - `factory.*` — the Factory Commits telemetry profile (work unit, slot, …),\n * **except** `factory.local.*`, which the profile defines as local-only: it\n * stays on the Resource and never reaches a record;\n * - `vcs.*` — OpenTelemetry VCS attributes. An event's own resolved target\n * (ADR 0008) still wins for the keys it sets, such as `vcs.ref.head.name`.\n *\n * `session.id` is not copied: it is resolved separately (see\n * `resolveExportedSessionId`), so a resource value cannot overwrite the\n * trimmed, resolved one.\n */\nexport const PASSTHROUGH_RESOURCE_PREFIXES: readonly string[] = Object.freeze([\"har.\", \"factory.\", \"vcs.\"]);\n/** Local-only profile namespace: never copied from the Resource onto records. */\nexport const LOCAL_ONLY_RESOURCE_PREFIX = \"factory.local.\";\n\nconst isPassthroughKey = (key: string): boolean =>\n PASSTHROUGH_RESOURCE_PREFIXES.some((prefix) => key.startsWith(prefix)) &&\n !key.startsWith(LOCAL_ONLY_RESOURCE_PREFIX) &&\n key !== \"factory.local\";\n\n/**\n * Primitive resource attributes to copy onto every log and span record.\n *\n * Only the namespaces in `PASSTHROUGH_RESOURCE_PREFIXES` are forwarded, minus\n * `factory.local.*`; nothing is invented when they are absent.\n */\nexport const passthroughResourceAttributes = (resource: Resource): Attributes => {\n const attributes: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(resource.attributes)) {\n if (isPassthroughKey(key) && isPrimitiveAttribute(value)) {\n attributes[key] = value;\n }\n }\n return attributes;\n};\n\n/**\n * Session context attributes the core stamped on this event\n * (`docs/session-context.md`); empty when none applies.\n */\nexport const contextAttributesOf = (event: CanonicalEvent): Attributes =>\n event.contextAttributes === undefined ? {} : { ...event.contextAttributes };\n\n/**\n * The profile layer of a record: the Resource's passthrough namespaces,\n * overridden key by key by the event's session context.\n *\n * Context wins because it is the more specific and more recent statement: a\n * session that moved from one attempt to another still has the first one in its\n * process environment (and so on the Resource), but its context names the\n * second. Everything otel-hook derives for the event itself — `session.id`,\n * `otelhook.*`, `gen_ai.*`, trace ids, and a resolved worktree target — is\n * layered above this and is never overridden by it.\n */\nexport const profileAttributes = (event: CanonicalEvent, resource: Resource): Attributes => ({\n ...passthroughResourceAttributes(resource),\n ...contextAttributesOf(event),\n});\n\n/**\n * Session id to put on `session.id`, preferring an externally supplied key.\n *\n * A launcher supplies the key as a resource attribute (usually through\n * `OTEL_RESOURCE_ATTRIBUTES`): `session.id` first, then the legacy\n * `har.session_key`, then the provider's own session id. The provider's id is\n * never discarded: it is returned separately so callers can emit it as\n * `otelhook.session.id` / `gen_ai.conversation.id`.\n */\nexport const resolveExportedSessionId = (\n eventSessionId: string,\n resource: Resource,\n): { readonly sessionId: string; readonly providerSessionId: string } => {\n for (const key of EXTERNAL_SESSION_KEY_ATTRIBUTES) {\n const supplied = resource.attributes[key];\n if (typeof supplied === \"string\") {\n const trimmed = supplied.trim();\n if (trimmed.length > 0) {\n return { sessionId: trimmed, providerSessionId: eventSessionId };\n }\n }\n }\n return { sessionId: eventSessionId, providerSessionId: eventSessionId };\n};\n\nexport type ExportedTraceIds = {\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n};\n\n/**\n * Hex-only trace/span attributes. A value that is not W3C hex is omitted\n * rather than stringified — binary blobs must never appear in id fields.\n */\nexport const hexTraceAttributes = (ids: ExportedTraceIds): Attributes => ({\n ...(TRACE_ID_HEX_PATTERN.test(ids.traceId) ? { [ATTR_TRACE_ID]: ids.traceId } : {}),\n ...(SPAN_ID_HEX_PATTERN.test(ids.spanId) ? { [ATTR_SPAN_ID]: ids.spanId } : {}),\n ...(ids.parentSpanId !== undefined && SPAN_ID_HEX_PATTERN.test(ids.parentSpanId)\n ? { [ATTR_PARENT_SPAN_ID]: ids.parentSpanId }\n : {}),\n});\n\n/**\n * Identity attributes shared by the log and span mappings.\n *\n * `session.id` is the externally supplied session key when the resource carries\n * one (`session.id`, then `har.session_key`), otherwise the provider session id.\n * The provider id is always also emitted under `otelhook.session.id` and\n * `gen_ai.conversation.id`. Profile resource attributes and the event's session\n * context are copied on too, beneath them (see `profileAttributes`).\n */\nexport const exportIdentityAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n ids: ExportedTraceIds,\n): Attributes => {\n const { sessionId, providerSessionId } = resolveExportedSessionId(event.sessionId, resource);\n return {\n // First, so nothing in the profile layer can replace an identity attribute.\n ...profileAttributes(event, resource),\n [ATTR_SESSION_ID]: sessionId,\n [ATTR_OTELHOOK_SESSION_ID]: providerSessionId,\n [ATTR_GEN_AI_CONVERSATION_ID]: providerSessionId,\n [ATTR_OTELHOOK_INVOCATION_ID]: event.invocationId,\n [ATTR_OTELHOOK_PROVIDER_ID]: event.provenance.providerId,\n ...(event.provenance.providerVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event.provenance.providerVersion }),\n [ATTR_OTELHOOK_WORKSPACE_ID]: event.workspace.workspaceId,\n ...(event.subagentId === undefined ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event.subagentId }),\n ...hexTraceAttributes(ids),\n };\n};\n","import { z } from \"zod\";\n\nimport {\n errorPhaseSchema,\n errorSeveritySchema,\n otelHookErrorCodeSchema,\n} from \"../errors/taxonomy.js\";\nimport { contentFactSchema, contentFactsSchema } from \"./content.js\";\nimport { extensionsSchema, emptyExtensions } from \"./extensions.js\";\nimport { sourceProvenanceSchema, workspaceIdentitySchema } from \"./identity.js\";\nimport { subagentIdSchema, workspaceTargetSchema } from \"./target.js\";\nimport {\n durationMillisSchema,\n epochMillisSchema,\n eventIdSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n sequenceNumberSchema,\n sessionIdSchema,\n tokenCountSchema,\n} from \"./primitives.js\";\nimport { canonicalUsageSchema, type CanonicalUsage } from \"./usage.js\";\nimport { canonicalSchemaVersionSchema } from \"./version.js\";\n\n/** Model being invoked. Model identifiers are not treated as sensitive. */\nexport const modelDescriptorSchema = z.strictObject({\n modelId: nonEmptyStringSchema,\n /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */\n vendor: nonEmptyStringSchema.optional(),\n family: nonEmptyStringSchema.optional(),\n});\nexport type ModelDescriptor = z.infer<typeof modelDescriptorSchema>;\n\nexport const costFactsSchema = z.strictObject({\n /** ISO 4217 code. */\n currency: z.string().length(3),\n amount: z.number().min(0).finite(),\n source: z.enum([\"provider-reported\", \"computed\"]),\n});\nexport type CostFacts = z.infer<typeof costFactsSchema>;\n\nexport const canonicalEventTypeSchema = z.enum([\n \"session.start\",\n \"session.end\",\n \"prompt.submitted\",\n \"generation.start\",\n \"generation.end\",\n \"tool.start\",\n \"tool.end\",\n \"subagent.start\",\n \"subagent.end\",\n \"compaction.performed\",\n \"error.raised\",\n]);\nexport type CanonicalEventType = z.infer<typeof canonicalEventTypeSchema>;\n\nexport const CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;\n\nconst outcomeSchema = z.enum([\"ok\", \"error\", \"cancelled\", \"timeout\", \"denied\", \"unknown\"]);\nexport type EventOutcome = z.infer<typeof outcomeSchema>;\n\n/**\n * Fields present on every canonical event.\n *\n * Identity fields are duplicated onto each event rather than referenced through\n * shared state, so an event is self-describing once it leaves the process.\n */\nconst baseEventFields = {\n schemaVersion: canonicalSchemaVersionSchema,\n eventId: eventIdSchema,\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Per-invocation ordering key. Stable across replays of the same input. */\n sequence: sequenceNumberSchema,\n occurredAt: epochMillisSchema,\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n /**\n * The provider's own id for the subagent this event was emitted inside (e.g.\n * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event\n * factory, never by hand.\n */\n subagentId: subagentIdSchema.optional(),\n extensions: extensionsSchema.default(emptyExtensions),\n /**\n * Attributes of the session context segment in force when the event\n * occurred (`docs/session-context.md`), stamped by the core from a file a\n * harness wrote. Exported on every record of the event, over the same keys\n * from the Resource. Absent when no context applies. Set by the core only,\n * never by an adapter.\n */\n contextAttributes: z.record(z.string().min(1).max(255), z.union([z.string(), z.number(), z.boolean()])).optional(),\n} as const;\n\nconst event = <TShape extends z.ZodRawShape>(shape: TShape) =>\n z.strictObject({ ...baseEventFields, ...shape });\n\nexport const sessionStartEventSchema = event({\n type: z.literal(\"session.start\"),\n sessionKind: z.enum([\"interactive\", \"non-interactive\", \"unknown\"]),\n agentName: nonEmptyStringSchema.optional(),\n agentVersion: nonEmptyStringSchema.optional(),\n model: modelDescriptorSchema.optional(),\n /** The git worktree the session runs in, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const sessionEndEventSchema = event({\n type: z.literal(\"session.end\"),\n reason: z.enum([\"completed\", \"aborted\", \"error\", \"timeout\", \"unknown\"]),\n durationMillis: durationMillisSchema.optional(),\n /** Session totals, typically cumulative. */\n usage: canonicalUsageSchema.optional(),\n cost: costFactsSchema.optional(),\n});\n\nexport const promptSubmittedEventSchema = event({\n type: z.literal(\"prompt.submitted\"),\n promptSource: z.enum([\"user\", \"automation\", \"resumed\", \"unknown\"]),\n content: contentFactSchema.optional(),\n turnIndex: z.number().int().min(0).optional(),\n /** The git worktree the session runs in, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const generationStartEventSchema = event({\n type: z.literal(\"generation.start\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n requestedMaxOutputTokens: tokenCountSchema.optional(),\n inputContent: contentFactsSchema.optional(),\n});\n\nexport const generationEndEventSchema = event({\n type: z.literal(\"generation.end\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n outcome: outcomeSchema,\n stopReason: nonEmptyStringSchema.optional(),\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n /**\n * True when `usage` is known to cover only part of the generation (for\n * example the last model request of a multi-request turn); false when the\n * provider or harness said it is the whole. Absent: not stated. Meaningless\n * without `usage`.\n */\n usagePartial: z.boolean().optional(),\n cost: costFactsSchema.optional(),\n outputContent: contentFactsSchema.optional(),\n});\n\nexport const toolKindSchema = z.enum([\n \"read\",\n \"write\",\n \"execute\",\n \"search\",\n \"network\",\n \"delegate\",\n \"other\",\n \"unknown\",\n]);\nexport type ToolKind = z.infer<typeof toolKindSchema>;\n\nexport const toolStartEventSchema = event({\n type: z.literal(\"tool.start\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n toolKind: toolKindSchema,\n generationId: nonEmptyStringSchema.optional(),\n input: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const toolEndEventSchema = event({\n type: z.literal(\"tool.end\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n /** Present when the host asked for or recorded a permission decision. */\n permissionDecision: z.enum([\"allowed\", \"denied\", \"deferred\", \"not-required\"]).optional(),\n output: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const subagentStartEventSchema = event({\n type: z.literal(\"subagent.start\"),\n subagentInvocationId: invocationIdSchema,\n subagentType: nonEmptyStringSchema.optional(),\n /** 0 for the top-level agent; 1 for its direct children. */\n delegationDepth: z.number().int().min(0).max(64),\n model: modelDescriptorSchema.optional(),\n});\n\nexport const subagentEndEventSchema = event({\n type: z.literal(\"subagent.end\"),\n subagentInvocationId: invocationIdSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const compactionPerformedEventSchema = event({\n type: z.literal(\"compaction.performed\"),\n trigger: z.enum([\"automatic\", \"manual\", \"unknown\"]),\n /** Provider-reported context size before and after compaction, if known. */\n contextTokensBefore: tokenCountSchema.optional(),\n contextTokensAfter: tokenCountSchema.optional(),\n droppedMessageCount: z.number().int().min(0).optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const errorRaisedEventSchema = event({\n type: z.literal(\"error.raised\"),\n errorCode: otelHookErrorCodeSchema,\n severity: errorSeveritySchema,\n phase: errorPhaseSchema,\n retryable: z.boolean(),\n /** Error text is content: it is described, never embedded verbatim by default. */\n message: contentFactSchema.optional(),\n /** Non-sensitive, provider-agnostic short label. */\n detail: nonEmptyStringSchema.optional(),\n});\n\nexport const canonicalEventSchema = z.discriminatedUnion(\"type\", [\n sessionStartEventSchema,\n sessionEndEventSchema,\n promptSubmittedEventSchema,\n generationStartEventSchema,\n generationEndEventSchema,\n toolStartEventSchema,\n toolEndEventSchema,\n subagentStartEventSchema,\n subagentEndEventSchema,\n compactionPerformedEventSchema,\n errorRaisedEventSchema,\n]);\n\nexport type CanonicalEvent = z.infer<typeof canonicalEventSchema>;\nexport type CanonicalEventInput = z.input<typeof canonicalEventSchema>;\n\nexport type SessionStartEvent = z.infer<typeof sessionStartEventSchema>;\nexport type SessionEndEvent = z.infer<typeof sessionEndEventSchema>;\nexport type PromptSubmittedEvent = z.infer<typeof promptSubmittedEventSchema>;\nexport type GenerationStartEvent = z.infer<typeof generationStartEventSchema>;\nexport type GenerationEndEvent = z.infer<typeof generationEndEventSchema>;\nexport type ToolStartEvent = z.infer<typeof toolStartEventSchema>;\nexport type ToolEndEvent = z.infer<typeof toolEndEventSchema>;\nexport type SubagentStartEvent = z.infer<typeof subagentStartEventSchema>;\nexport type SubagentEndEvent = z.infer<typeof subagentEndEventSchema>;\nexport type CompactionPerformedEvent = z.infer<typeof compactionPerformedEventSchema>;\nexport type ErrorRaisedEvent = z.infer<typeof errorRaisedEventSchema>;\n\nexport type CanonicalEventOfType<TType extends CanonicalEventType> = Extract<\n CanonicalEvent,\n { type: TType }\n>;\n\n/**\n * The event types that may carry a resolved `target` (ADR 0008): a tool call\n * names the worktree it touched; a session start and a prompt name the one the\n * session runs in, so a consumer knows the session's place before its first\n * tool call.\n */\nexport const TARGETED_EVENT_TYPES = [\"session.start\", \"prompt.submitted\", \"tool.start\", \"tool.end\"] as const;\nexport type TargetedEventType = (typeof TARGETED_EVENT_TYPES)[number];\nexport type TargetedEvent = CanonicalEventOfType<TargetedEventType>;\n\nconst TARGETED: ReadonlySet<string> = new Set(TARGETED_EVENT_TYPES);\nexport const isTargetedEvent = (event: CanonicalEvent): event is TargetedEvent => TARGETED.has(event.type);\n\nexport type EventValidationResult =\n | { readonly status: \"ok\"; readonly event: CanonicalEvent }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nexport const validateCanonicalEvent = (value: unknown): EventValidationResult => {\n const parsed = canonicalEventSchema.safeParse(value);\n if (parsed.success) {\n return { status: \"ok\", event: parsed.data };\n }\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n};\n\n/** Parse or throw. Intended for fixtures and tests, not the hook path. */\nexport const parseCanonicalEvent = (value: unknown): CanonicalEvent =>\n canonicalEventSchema.parse(value);\n\n/** Usage carried by an event, if the event type can carry any. */\nexport const eventUsage = (event: CanonicalEvent): CanonicalUsage | undefined =>\n \"usage\" in event ? event.usage : undefined;\n\n/** Stable ordering: by sequence, then by timestamp, then by event id. */\nexport const compareEvents = (a: CanonicalEvent, b: CanonicalEvent): number =>\n a.sequence - b.sequence || a.occurredAt - b.occurredAt || a.eventId.localeCompare(b.eventId);\n","import { z } from \"zod\";\n\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 { attributeValueSchema, type AttributeValue } from \"./primitives.js\";\n\n/**\n * Extension keys must be namespaced: at least one dot-separated segment before\n * the leaf, e.g. `acme.deployment-tier`. Namespacing keeps provider- and\n * consumer-specific fields from colliding with core fields or each other.\n */\nexport const EXTENSION_KEY_PATTERN =\n /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;\n\n/** Namespaces owned by the core model; extensions may not use them. */\nexport const RESERVED_EXTENSION_NAMESPACES: readonly string[] = Object.freeze([\n \"otelhook\",\n \"otel\",\n \"telemetry\",\n]);\n\nexport const MAX_EXTENSION_ENTRIES = 64;\n\nexport const extensionKeyNamespace = (key: string): string => key.slice(0, key.indexOf(\".\"));\n\nexport const isReservedExtensionNamespace = (key: string): boolean =>\n RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));\n\nexport const isValidExtensionKey = (key: string): boolean =>\n EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);\n\n/**\n * Namespaced extension bag.\n *\n * Values are restricted to attribute primitives, so extensions cannot carry\n * nested provider payloads.\n */\nexport const extensionsSchema = z\n .record(z.string(), attributeValueSchema)\n .check((ctx) => {\n const keys = Object.keys(ctx.value);\n if (keys.length > MAX_EXTENSION_ENTRIES) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`,\n });\n }\n for (const key of keys) {\n if (!EXTENSION_KEY_PATTERN.test(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. \"acme.tier\"`,\n });\n continue;\n }\n if (isReservedExtensionNamespace(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`,\n });\n }\n }\n });\n\nexport type Extensions = Record<string, AttributeValue>;\n\nexport const EMPTY_EXTENSIONS: Extensions = Object.freeze({});\n\nexport const emptyExtensions = (): Extensions => ({});\n","import { z } from \"zod\";\n\nimport {\n attributesSchema,\n detectionConfidenceSchema,\n DETECTION_CONFIDENCE_RANK,\n epochMillisSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n resolvedProviderIdSchema,\n sessionIdSchema,\n sourceTransportSchema,\n workspaceIdSchema,\n type DetectionConfidence,\n type InvocationId,\n type SessionId,\n type WorkspaceId,\n} from \"./primitives.js\";\n\n/**\n * Where a workspace identifier came from.\n *\n * Ordered from most to least stable. The source is recorded so consumers can\n * tell a repository-scoped identity from a directory-scoped one instead of\n * assuming they are comparable.\n */\nexport const workspaceKeySourceSchema = z.enum([\n \"git-remote\",\n \"git-root\",\n \"working-directory\",\n \"explicit\",\n \"unknown\",\n]);\nexport type WorkspaceKeySource = z.infer<typeof workspaceKeySourceSchema>;\n\n/**\n * Privacy-safe workspace identity.\n *\n * Only opaque handles and explicitly allowed labels are modelled. There is no\n * field for a filesystem path, so paths cannot be exported through this type.\n */\nexport const workspaceIdentitySchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n keySource: workspaceKeySourceSchema,\n /** Repository name only; never an owner path or URL with credentials. */\n repositoryName: nonEmptyStringSchema.optional(),\n vcsBranchName: nonEmptyStringSchema.optional(),\n /** Opaque handle for the checked-out revision. */\n vcsRevisionId: nonEmptyStringSchema.optional(),\n })\n .readonly();\nexport type WorkspaceIdentity = z.infer<typeof workspaceIdentitySchema>;\n\nexport const UNKNOWN_WORKSPACE_ID = \"unknown:0000000000000000\" as WorkspaceId;\n\nexport const unknownWorkspaceIdentity = (): WorkspaceIdentity =>\n workspaceIdentitySchema.parse({\n workspaceId: UNKNOWN_WORKSPACE_ID,\n keySource: \"unknown\",\n });\n\n/**\n * Provenance of an observation: which provider produced it and which adapter\n * interpreted it, with the confidence of that attribution.\n */\nexport const sourceProvenanceSchema = z\n .strictObject({\n providerId: resolvedProviderIdSchema,\n providerVersion: nonEmptyStringSchema.optional(),\n adapterId: nonEmptyStringSchema,\n adapterVersion: nonEmptyStringSchema,\n detectionConfidence: detectionConfidenceSchema,\n /** The provider's own name for the source event, e.g. a hook event name. */\n sourceEventName: nonEmptyStringSchema.optional(),\n transport: sourceTransportSchema,\n })\n .readonly();\nexport type SourceProvenance = z.infer<typeof sourceProvenanceSchema>;\n\n/**\n * Opaque, immutable metadata supplied by the embedding consumer.\n *\n * The library never interprets these values; it only carries and exports them.\n */\nexport const consumerAttributesSchema = attributesSchema.readonly();\nexport type ConsumerAttributes = z.infer<typeof consumerAttributesSchema>;\n\n/**\n * Immutable identity of a single hook invocation.\n *\n * Frozen on parse. There is deliberately no setter, no builder that mutates in\n * place, and no module-level instance: identity is passed explicitly so two\n * concurrent invocations can never observe each other's fields.\n */\nexport const invocationIdentitySchema = z\n .strictObject({\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Set when this invocation runs beneath another agent invocation. */\n parentInvocationId: invocationIdSchema.optional(),\n /** Root of the session tree when the provider exposes one. */\n rootSessionId: sessionIdSchema.optional(),\n /** Stable handle for the agent process/instance, when available. */\n agentInstanceId: nonEmptyStringSchema.optional(),\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n startedAt: epochMillisSchema,\n consumerAttributes: consumerAttributesSchema,\n })\n .readonly();\nexport type InvocationIdentity = z.infer<typeof invocationIdentitySchema>;\n\n/** Fields an identity claim may contribute. */\nexport const identityClaimFieldsSchema = z.strictObject({\n invocationId: invocationIdSchema.optional(),\n sessionId: sessionIdSchema.optional(),\n parentInvocationId: invocationIdSchema.optional(),\n rootSessionId: sessionIdSchema.optional(),\n agentInstanceId: nonEmptyStringSchema.optional(),\n workspace: workspaceIdentitySchema.optional(),\n startedAt: epochMillisSchema.optional(),\n});\nexport type IdentityClaimFields = z.infer<typeof identityClaimFieldsSchema>;\n\n/**\n * A claim about invocation identity from one source.\n *\n * Claims are evidence, not truth. Resolution keeps the highest-confidence claim\n * per field and refuses to merge disagreeing peers.\n */\nexport const identityClaimSchema = z.strictObject({\n /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */\n source: nonEmptyStringSchema,\n confidence: detectionConfidenceSchema,\n fields: identityClaimFieldsSchema,\n});\nexport type IdentityClaim = z.infer<typeof identityClaimSchema>;\n\nexport type IdentityConflict = {\n readonly field: keyof IdentityClaimFields;\n readonly confidence: DetectionConfidence;\n /** Rendered, non-sensitive representations of the disagreeing values. */\n readonly values: readonly string[];\n readonly sources: readonly string[];\n};\n\nexport type IdentityResolution =\n | { readonly status: \"resolved\"; readonly identity: InvocationIdentity }\n | {\n readonly status: \"conflict\";\n readonly conflicts: readonly IdentityConflict[];\n }\n | {\n readonly status: \"incomplete\";\n readonly missing: readonly (keyof IdentityClaimFields)[];\n }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nconst CLAIM_FIELDS = [\n \"invocationId\",\n \"sessionId\",\n \"parentInvocationId\",\n \"rootSessionId\",\n \"agentInstanceId\",\n \"workspace\",\n \"startedAt\",\n] as const satisfies readonly (keyof IdentityClaimFields)[];\n\nconst renderClaimValue = (value: unknown): string => {\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (value !== null && typeof value === \"object\" && \"workspaceId\" in value) {\n const { workspaceId } = value;\n return typeof workspaceId === \"string\" ? workspaceId : \"<workspace>\";\n }\n return \"<opaque>\";\n};\n\nexport type ResolveIdentityInput = {\n readonly claims: readonly IdentityClaim[];\n readonly provenance: SourceProvenance;\n /** Used only for fields no claim provides and that have a safe default. */\n readonly fallback?: {\n readonly startedAt?: number;\n readonly workspace?: WorkspaceIdentity;\n };\n readonly consumerAttributes?: Readonly<Record<string, unknown>>;\n};\n\n/**\n * Resolve identity from claims, failing closed.\n *\n * Rules:\n * 1. For each field, only claims at the highest confidence that provided it are\n * considered. Lower-confidence claims never fill in or override.\n * 2. Two distinct values at that highest confidence produce a `conflict`. The\n * invocation is then not attributed at all — a mislabelled session is worse\n * than a missing one.\n * 3. `invocationId` and `sessionId` are mandatory. Missing either yields\n * `incomplete`; neither is invented here.\n * 4. `startedAt` and `workspace` may come from an explicit fallback, because a\n * clock reading and an `unknown` workspace handle assert nothing false.\n */\nexport const resolveInvocationIdentity = (input: ResolveIdentityInput): IdentityResolution => {\n const parsedClaims: IdentityClaim[] = [];\n const issues: string[] = [];\n for (const [index, claim] of input.claims.entries()) {\n const parsed = identityClaimSchema.safeParse(claim);\n if (parsed.success) {\n parsedClaims.push(parsed.data);\n } else {\n issues.push(\n `claim[${index}]: ${parsed.error.issues.map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`).join(\", \")}`,\n );\n }\n }\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const conflicts: IdentityConflict[] = [];\n const selected: Record<string, unknown> = {};\n\n for (const field of CLAIM_FIELDS) {\n const contributors = parsedClaims.filter((claim) => claim.fields[field] !== undefined);\n if (contributors.length === 0) {\n continue;\n }\n const bestRank = Math.max(\n ...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence]),\n );\n const best = contributors.filter(\n (claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank,\n );\n const rendered = new Map<string, string[]>();\n for (const claim of best) {\n const key = JSON.stringify(claim.fields[field]);\n const sources = rendered.get(key) ?? [];\n sources.push(claim.source);\n rendered.set(key, sources);\n }\n if (rendered.size > 1) {\n const [firstBest] = best;\n conflicts.push({\n field,\n confidence: firstBest?.confidence ?? \"none\",\n values: best.map((claim) => renderClaimValue(claim.fields[field])),\n sources: best.map((claim) => claim.source),\n });\n continue;\n }\n const [winner] = best;\n if (winner !== undefined) {\n selected[field] = winner.fields[field];\n }\n }\n\n if (conflicts.length > 0) {\n return { status: \"conflict\", conflicts };\n }\n\n const missing: (keyof IdentityClaimFields)[] = [];\n if (selected.invocationId === undefined) {\n missing.push(\"invocationId\");\n }\n if (selected.sessionId === undefined) {\n missing.push(\"sessionId\");\n }\n if (missing.length > 0) {\n return { status: \"incomplete\", missing };\n }\n\n const startedAt = (selected.startedAt as number | undefined) ?? input.fallback?.startedAt;\n if (startedAt === undefined) {\n return { status: \"incomplete\", missing: [\"startedAt\"] };\n }\n const workspace =\n (selected.workspace as WorkspaceIdentity | undefined) ??\n input.fallback?.workspace ??\n unknownWorkspaceIdentity();\n\n const candidate = {\n invocationId: selected.invocationId as InvocationId,\n sessionId: selected.sessionId as SessionId,\n ...(selected.parentInvocationId === undefined\n ? {}\n : { parentInvocationId: selected.parentInvocationId as InvocationId }),\n ...(selected.rootSessionId === undefined\n ? {}\n : { rootSessionId: selected.rootSessionId as SessionId }),\n ...(selected.agentInstanceId === undefined\n ? {}\n : { agentInstanceId: selected.agentInstanceId as string }),\n provenance: input.provenance,\n workspace,\n startedAt,\n consumerAttributes: input.consumerAttributes ?? {},\n };\n\n const parsed = invocationIdentitySchema.safeParse(candidate);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n }\n return { status: \"resolved\", identity: parsed.data };\n};\n","import { z } from \"zod\";\n\nimport { nonEmptyStringSchema, workspaceIdSchema } from \"./primitives.js\";\n\n/**\n * Per-event workspace targeting (ADR 0008).\n *\n * A session's `workspace` is where the agent was *started*. An agent routinely\n * works somewhere else — in a linked git worktree beside the checkout it was\n * launched from — and the session-level identity cannot show that. A tool event\n * can: the file it edited, or the directory its shell command ran in, names the\n * worktree it actually touched.\n *\n * Two values model that, and the split between them is the privacy boundary:\n *\n * - {@link TargetHint} is what an adapter observed — local paths. It is an\n * in-process value only: it is never part of a {@link CanonicalEvent}, never\n * persisted, never exported. The core resolves it and drops it.\n * - {@link WorkspaceTarget} is what the core resolved — salted handles of the\n * worktree and its repository, the worktree's kind, the checked-out branch, and\n * what the evidence was. It travels on the event.\n */\n\n/**\n * What a target was derived from, strongest evidence first.\n *\n * - `tool-path` — a path the tool call itself named (an edited or read file, a\n * patch header).\n * - `shell-cwd` — the working directory the provider reports a shell command ran in.\n * - `session-cwd` — only the session's own directory was known; the event may\n * have reached elsewhere (e.g. a shell `cd`) without the provider saying so.\n */\nexport const targetSourceSchema = z.enum([\"tool-path\", \"shell-cwd\", \"session-cwd\"]);\nexport type TargetSource = z.infer<typeof targetSourceSchema>;\n\n/** Most paths one hint may name; a bound, not a sampling rule (all must agree). */\nexport const MAX_TARGET_HINT_PATHS = 8;\n\n/** Longest local path a hint may carry. Longer input is dropped, never truncated. */\nexport const MAX_TARGET_PATH_LENGTH = 4096;\n\nconst localPathSchema = z\n .string()\n .min(1)\n .max(MAX_TARGET_PATH_LENGTH)\n .refine((value) => !value.includes(\"\\u0000\"), \"path must not contain NUL\");\n\n/**\n * An adapter's observation of where a tool event pointed. **Carries local paths**\n * — in-process only, see the module note.\n *\n * Every path in one hint must resolve to the same worktree, or the event gets no\n * target at all: a patch touching two worktrees did not target either of them.\n */\nexport const targetHintSchema = z\n .strictObject({\n source: targetSourceSchema,\n paths: z.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),\n /** Absolute directory that relative `paths` resolve against. */\n baseDirectory: localPathSchema.optional(),\n })\n .readonly();\nexport type TargetHint = z.infer<typeof targetHintSchema>;\n\n/**\n * The weakest hint: the session's own directory. Every adapter gives it to a\n * session start and a prompt, and to a tool call that names no path.\n */\nexport const sessionCwdHint = (cwd: string | undefined): TargetHint | undefined =>\n cwd === undefined || cwd.length === 0 ? undefined : { source: \"session-cwd\", paths: [cwd] };\n\n/**\n * Whether a worktree is its repository's main checkout (`main`) or one added\n * beside it with `git worktree add` (`linked`).\n */\nexport const worktreeKindSchema = z.enum([\"main\", \"linked\"]);\nexport type WorktreeKind = z.infer<typeof worktreeKindSchema>;\n\n/**\n * The git worktree a tool event targeted. Exported; carries no path.\n *\n * `workspaceId` is derived exactly like a `git-root` workspace identity, so a\n * consumer holding the same salt can match it against one it derived itself.\n * `repositoryId` is the same derivation applied to the repository's main\n * worktree, so every worktree of one repository shares it — and for a main\n * worktree it equals `workspaceId`.\n */\nexport const workspaceTargetSchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n /** Branch checked out in that worktree; absent on a detached HEAD. */\n vcsBranchName: nonEmptyStringSchema.optional(),\n source: targetSourceSchema,\n /** `git-root` handle of the repository's main worktree; absent when there is none to name. */\n repositoryId: workspaceIdSchema.optional(),\n worktreeKind: worktreeKindSchema.optional(),\n })\n .readonly();\nexport type WorkspaceTarget = z.infer<typeof workspaceTargetSchema>;\n\n/**\n * Shape a provider's own subagent identifier must have to be exported.\n *\n * Identifier-shaped on purpose — no whitespace, no path separators — so a\n * malformed payload field cannot carry prose or a path onto the wire under an id\n * attribute. A value that does not fit is dropped, not repaired.\n */\nexport const SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;\nexport const subagentIdSchema = z.string().regex(SUBAGENT_ID_PATTERN);\nexport type SubagentId = z.infer<typeof subagentIdSchema>;\n","import { z } from \"zod\";\n\nimport { tokenCountSchema } from \"./primitives.js\";\n\n/**\n * Whether an observation reports the change since the previous observation\n * (`delta`) or the running total for the session/generation (`cumulative`).\n *\n * The canonical model keeps temporality explicit rather than assuming one:\n * summing cumulative observations double-counts, and diffing delta observations\n * silently loses tokens.\n */\nexport const usageTemporalitySchema = z.enum([\"delta\", \"cumulative\"]);\nexport type UsageTemporality = z.infer<typeof usageTemporalitySchema>;\n\n/**\n * Whether the provider counts cache-creation tokens inside its input total or\n * reports them as a disjoint bucket.\n *\n * - `included-in-input`: `cacheCreationInputTokens` is a subset of `inputTokens`.\n * - `disjoint-from-input`: cache-creation tokens are billed in addition to\n * `inputTokens` and must be added when computing a total.\n * - `not-reported`: the provider exposes no cache-creation counter; the field is\n * pinned to zero.\n */\nexport const cacheCreationAccountingSchema = z.enum([\n \"included-in-input\",\n \"disjoint-from-input\",\n \"not-reported\",\n]);\nexport type CacheCreationAccounting = z.infer<typeof cacheCreationAccountingSchema>;\n\n/** Whether a provider-reported total agrees with the canonical computation. */\nexport const providerTotalAgreementSchema = z.enum([\"unreported\", \"agrees\", \"disagrees\"]);\nexport type ProviderTotalAgreement = z.infer<typeof providerTotalAgreementSchema>;\n\n/**\n * What an adapter reports, before normalization.\n *\n * `inputTokens` is *inclusive*: it counts every input token the provider\n * attributes to the call, including cache reads (and cache creation when the\n * provider folds it in). `outputTokens` is likewise inclusive of reasoning\n * output. Subset fields describe portions of those totals, never additions.\n */\nexport const usageReportSchema = z.strictObject({\n temporality: usageTemporalitySchema,\n /** Inclusive input tokens. */\n inputTokens: tokenCountSchema.optional(),\n /** Subset of `inputTokens` served from a prompt cache. */\n cachedInputTokens: tokenCountSchema.optional(),\n /** Tokens written to a prompt cache. */\n cacheCreationInputTokens: tokenCountSchema.optional(),\n /** Required when `cacheCreationInputTokens` is present and non-zero. */\n cacheCreationAccounting: cacheCreationAccountingSchema.optional(),\n /** Inclusive output tokens. */\n outputTokens: tokenCountSchema.optional(),\n /** Subset of `outputTokens` spent on reasoning. */\n reasoningOutputTokens: tokenCountSchema.optional(),\n /** Total exactly as the provider reported it, if it reported one. */\n providerTotalTokens: tokenCountSchema.optional(),\n});\nexport type UsageReport = z.infer<typeof usageReportSchema>;\n\n/**\n * Fully normalized usage.\n *\n * Derived fields (`uncachedInputTokens`, `totalTokens`,\n * `providerTotalAgreement`) are part of the schema and are re-checked on parse,\n * so an inconsistent object cannot exist. Construct values with\n * {@link normalizeUsage} rather than by hand.\n */\nexport const canonicalUsageSchema = z\n .strictObject({\n temporality: usageTemporalitySchema,\n inputTokens: tokenCountSchema,\n cachedInputTokens: tokenCountSchema,\n cacheCreationInputTokens: tokenCountSchema,\n cacheCreationAccounting: cacheCreationAccountingSchema,\n outputTokens: tokenCountSchema,\n reasoningOutputTokens: tokenCountSchema,\n /** Derived: input tokens that were neither cache reads nor cache writes. */\n uncachedInputTokens: tokenCountSchema,\n /** Derived: canonical billable total. */\n totalTokens: tokenCountSchema,\n providerTotalTokens: tokenCountSchema.optional(),\n providerTotalAgreement: providerTotalAgreementSchema,\n })\n .check((ctx) => {\n const usage = ctx.value;\n const push = (message: string): void => {\n ctx.issues.push({ code: \"custom\", input: usage, message });\n };\n\n if (usage.cachedInputTokens > usage.inputTokens) {\n push(\"cachedInputTokens must not exceed inputTokens (it is a subset)\");\n }\n if (usage.reasoningOutputTokens > usage.outputTokens) {\n push(\"reasoningOutputTokens must not exceed outputTokens (it is a subset)\");\n }\n if (usage.cacheCreationAccounting === \"not-reported\" && usage.cacheCreationInputTokens !== 0) {\n push(\"cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported\");\n }\n const creationInsideInput =\n usage.cacheCreationAccounting === \"included-in-input\" ? usage.cacheCreationInputTokens : 0;\n if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {\n push(\n \"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input\",\n );\n }\n const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;\n if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {\n push(`uncachedInputTokens must equal ${expectedUncached}`);\n }\n const creationOutsideInput =\n usage.cacheCreationAccounting === \"disjoint-from-input\" ? usage.cacheCreationInputTokens : 0;\n const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;\n if (usage.totalTokens !== expectedTotal) {\n push(`totalTokens must equal ${expectedTotal}`);\n }\n const expectedAgreement: ProviderTotalAgreement =\n usage.providerTotalTokens === undefined\n ? \"unreported\"\n : usage.providerTotalTokens === expectedTotal\n ? \"agrees\"\n : \"disagrees\";\n if (usage.providerTotalAgreement !== expectedAgreement) {\n push(`providerTotalAgreement must be ${expectedAgreement}`);\n }\n });\nexport type CanonicalUsage = z.infer<typeof canonicalUsageSchema>;\n\nexport type UsageNormalizationIssue = {\n readonly code:\n | \"invalid-report\"\n | \"cached-exceeds-input\"\n | \"reasoning-exceeds-output\"\n | \"cache-creation-exceeds-input\"\n | \"cache-creation-accounting-missing\";\n readonly message: string;\n};\n\nexport type UsageNormalizationResult =\n | { readonly status: \"ok\"; readonly usage: CanonicalUsage; readonly notes: readonly string[] }\n | { readonly status: \"invalid\"; readonly issues: readonly UsageNormalizationIssue[] };\n\n/**\n * Normalize a provider usage report into canonical usage.\n *\n * Deterministic rules:\n * 1. Absent counters default to `0`; `providerTotalTokens` stays absent.\n * 2. Non-integer, negative, or non-finite counters are rejected.\n * 3. A subset exceeding its total is rejected — never clamped — because\n * clamping would silently invent a billing story.\n * 4. `cacheCreationAccounting` defaults to `not-reported` when no cache-creation\n * tokens are reported, and is *required* when they are: guessing whether the\n * bucket is disjoint would mis-total every downstream cost calculation.\n * 5. A provider total that disagrees with the canonical total is preserved as\n * reported and flagged `disagrees`. Both numbers survive; neither is edited.\n */\nexport const normalizeUsage = (report: unknown): UsageNormalizationResult => {\n const parsed = usageReportSchema.safeParse(report);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map((issue) => ({\n code: \"invalid-report\" as const,\n message: `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n })),\n };\n }\n\n const input = parsed.data;\n const issues: UsageNormalizationIssue[] = [];\n const notes: string[] = [];\n\n const inputTokens = input.inputTokens ?? 0;\n const cachedInputTokens = input.cachedInputTokens ?? 0;\n const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;\n const outputTokens = input.outputTokens ?? 0;\n const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;\n\n let accounting: CacheCreationAccounting;\n if (cacheCreationInputTokens === 0) {\n accounting = input.cacheCreationAccounting ?? \"not-reported\";\n if (accounting !== \"not-reported\") {\n notes.push(\n `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`,\n );\n }\n } else if (input.cacheCreationAccounting === undefined) {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message:\n \"cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred\",\n });\n accounting = \"not-reported\";\n } else if (input.cacheCreationAccounting === \"not-reported\") {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message: \"cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens\",\n });\n accounting = \"not-reported\";\n } else {\n accounting = input.cacheCreationAccounting;\n }\n\n if (cachedInputTokens > inputTokens) {\n issues.push({\n code: \"cached-exceeds-input\",\n message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n if (reasoningOutputTokens > outputTokens) {\n issues.push({\n code: \"reasoning-exceeds-output\",\n message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`,\n });\n }\n\n const creationInsideInput = accounting === \"included-in-input\" ? cacheCreationInputTokens : 0;\n if (cachedInputTokens + creationInsideInput > inputTokens) {\n issues.push({\n code: \"cache-creation-exceeds-input\",\n message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const creationOutsideInput = accounting === \"disjoint-from-input\" ? cacheCreationInputTokens : 0;\n const totalTokens = inputTokens + creationOutsideInput + outputTokens;\n const providerTotalAgreement: ProviderTotalAgreement =\n input.providerTotalTokens === undefined\n ? \"unreported\"\n : input.providerTotalTokens === totalTokens\n ? \"agrees\"\n : \"disagrees\";\n\n if (providerTotalAgreement === \"disagrees\") {\n notes.push(\n `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`,\n );\n }\n\n const usage: CanonicalUsage = {\n temporality: input.temporality,\n inputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens,\n reasoningOutputTokens,\n uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,\n totalTokens,\n ...(input.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: input.providerTotalTokens }),\n providerTotalAgreement,\n };\n\n return { status: \"ok\", usage, notes };\n};\n\nexport class UsageNormalizationError extends Error {\n public readonly issues: readonly UsageNormalizationIssue[];\n\n public constructor(issues: readonly UsageNormalizationIssue[]) {\n super(`invalid usage report: ${issues.map((issue) => issue.message).join(\"; \")}`);\n this.name = \"UsageNormalizationError\";\n this.issues = issues;\n }\n}\n\n/** Convenience wrapper for call sites that treat invalid usage as a bug. */\nexport const normalizeUsageOrThrow = (report: unknown): CanonicalUsage => {\n const result = normalizeUsage(report);\n if (result.status === \"invalid\") {\n throw new UsageNormalizationError(result.issues);\n }\n return result.usage;\n};\n\nexport const EMPTY_DELTA_USAGE: CanonicalUsage = Object.freeze(\n normalizeUsageOrThrow({ temporality: \"delta\" }),\n);\n\nexport type UsageDeltaResult = {\n readonly usage: CanonicalUsage;\n /**\n * True when the current snapshot is smaller than the previous one on any\n * counter. That means the cumulative series restarted (new session, replayed\n * transcript, provider reset), so the current snapshot is emitted as the delta\n * instead of a negative difference.\n */\n readonly resetDetected: boolean;\n};\n\nconst requireCumulative = (usage: CanonicalUsage, label: string): void => {\n if (usage.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: `${label} must have cumulative temporality` },\n ]);\n }\n};\n\n/**\n * Convert two cumulative snapshots into a delta observation.\n *\n * Replay safety: re-processing the same snapshot yields an all-zero delta, and a\n * decreasing series is reported as a reset rather than a negative delta.\n * Accounting mode must match; mixing modes would make the subtraction meaningless.\n */\nexport const cumulativeToDelta = (\n previous: CanonicalUsage,\n current: CanonicalUsage,\n): UsageDeltaResult => {\n requireCumulative(previous, \"previous usage\");\n requireCumulative(current, \"current usage\");\n\n if (\n previous.cacheCreationAccounting !== current.cacheCreationAccounting &&\n previous.cacheCreationInputTokens !== 0 &&\n current.cacheCreationInputTokens !== 0\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot diff cumulative usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const resetDetected =\n current.inputTokens < previous.inputTokens ||\n current.cachedInputTokens < previous.cachedInputTokens ||\n current.cacheCreationInputTokens < previous.cacheCreationInputTokens ||\n current.outputTokens < previous.outputTokens ||\n current.reasoningOutputTokens < previous.reasoningOutputTokens;\n\n if (resetDetected) {\n return {\n usage: normalizeUsageOrThrow({ ...toReport(current), temporality: \"delta\" }),\n resetDetected: true,\n };\n }\n\n const usage = normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: current.inputTokens - previous.inputTokens,\n cachedInputTokens: current.cachedInputTokens - previous.cachedInputTokens,\n cacheCreationInputTokens:\n current.cacheCreationInputTokens - previous.cacheCreationInputTokens,\n cacheCreationAccounting: current.cacheCreationAccounting,\n outputTokens: current.outputTokens - previous.outputTokens,\n reasoningOutputTokens: current.reasoningOutputTokens - previous.reasoningOutputTokens,\n });\n\n return { usage, resetDetected: false };\n};\n\n/** Project canonical usage back onto the reported shape. */\nexport const toReport = (usage: CanonicalUsage): UsageReport => ({\n temporality: usage.temporality,\n inputTokens: usage.inputTokens,\n cachedInputTokens: usage.cachedInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n cacheCreationAccounting: usage.cacheCreationAccounting,\n outputTokens: usage.outputTokens,\n reasoningOutputTokens: usage.reasoningOutputTokens,\n ...(usage.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: usage.providerTotalTokens }),\n});\n\n/**\n * Add two delta observations. Cumulative usage is never summed, because two\n * running totals do not compose.\n */\nexport const addUsage = (a: CanonicalUsage, b: CanonicalUsage): CanonicalUsage => {\n if (a.temporality !== \"delta\" || b.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"only delta usage may be summed\" },\n ]);\n }\n const accounting =\n a.cacheCreationInputTokens === 0 && a.cacheCreationAccounting === \"not-reported\"\n ? b.cacheCreationAccounting\n : b.cacheCreationInputTokens === 0 && b.cacheCreationAccounting === \"not-reported\"\n ? a.cacheCreationAccounting\n : a.cacheCreationAccounting;\n\n if (\n a.cacheCreationInputTokens !== 0 &&\n b.cacheCreationInputTokens !== 0 &&\n a.cacheCreationAccounting !== b.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot sum usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n a.providerTotalTokens === undefined && b.providerTotalTokens === undefined\n ? undefined\n : (a.providerTotalTokens ?? 0) + (b.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: a.inputTokens + b.inputTokens,\n cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,\n cacheCreationInputTokens: a.cacheCreationInputTokens + b.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: a.outputTokens + b.outputTokens,\n reasoningOutputTokens: a.reasoningOutputTokens + b.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n","import { z } from \"zod\";\n\n/**\n * Version of the canonical event model.\n *\n * Every emitted event carries this value. Consumers must treat an unknown\n * version as unreadable rather than guessing field semantics.\n *\n * Compatibility rules:\n * - Additive optional fields do not change the version.\n * - Renaming, removing, or re-interpreting a field increments the version.\n */\nexport const CANONICAL_SCHEMA_VERSION = 1 as const;\n\nexport type CanonicalSchemaVersion = typeof CANONICAL_SCHEMA_VERSION;\n\nexport const canonicalSchemaVersionSchema = z.literal(CANONICAL_SCHEMA_VERSION);\n","import type { Attributes } from \"@opentelemetry/api\";\nimport type { Resource } from \"@opentelemetry/resources\";\n\nimport type { CanonicalEvent, GenerationEndEvent } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\nimport { resolveExportedSessionId } from \"./export-identity.js\";\n\n/**\n * Metrics derived from hook events (issue #69).\n *\n * otel-hook already normalizes every provider's hook callbacks into canonical\n * events; this module turns one batch of those events into *observations* — a\n * value recorded against an instrument, with attributes. It is pure: it reads no\n * state and sends nothing. Aggregating observations into OTLP data points\n * (cumulative across processes, or delta per batch) and exporting them are the\n * jobs of `lifecycle/metric-series.ts` and `otlp-metric-sink.ts`.\n *\n * ## Why observations come from the runtime's accounting, not from the events alone\n *\n * Token usage is taken from the orchestrator's `UsageObservation` deltas rather than\n * from `generation.end.usage` directly. A provider that reports a session-wide\n * running total (Codex) stamps the *cumulative* figure on every turn; summing those\n * into a histogram would bill a three-turn session several times over. The\n * orchestrator already diffs them against a persisted baseline, exactly once per\n * delivery, so the metric reuses that answer.\n *\n * ## What is never on a metric\n *\n * Session context attributes (`docs/session-context.md`) are on every data point\n * of an event that has them, so a new context starts a new series.\n *\n * No account identity (`user.*`, `enduser.*`, `organization.id`), no content, no\n * paths, and no per-event ids (`otelhook.event.id`, tool-call ids, generation ids):\n * an id per data point is a new series per data point. `session.id` is the one\n * high-cardinality attribute, and it can be switched off.\n */\n\n/** Recommended bucket boundaries from the GenAI semantic conventions. */\nexport const TOKEN_USAGE_BUCKETS: readonly number[] = Object.freeze([\n 1, 4, 16, 64, 256, 1_024, 4_096, 16_384, 65_536, 262_144, 1_048_576, 4_194_304, 16_777_216,\n 67_108_864,\n]);\nexport const OPERATION_DURATION_BUCKETS: readonly number[] = Object.freeze([\n 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24, 20.48, 40.96, 81.92,\n]);\n\nexport const METRIC_TOKEN_USAGE = \"gen_ai.client.token.usage\";\nexport const METRIC_OPERATION_DURATION = \"gen_ai.client.operation.duration\";\nexport const METRIC_SESSIONS = \"otelhook.sessions\";\nexport const METRIC_TOOL_CALLS = \"otelhook.tool.calls\";\nexport const METRIC_COST_USAGE = \"otelhook.cost.usage\";\n\nexport type MetricInstrumentName =\n | typeof METRIC_TOKEN_USAGE\n | typeof METRIC_OPERATION_DURATION\n | typeof METRIC_SESSIONS\n | typeof METRIC_TOOL_CALLS\n | typeof METRIC_COST_USAGE;\n\nexport type MetricInstrument = {\n readonly name: MetricInstrumentName;\n readonly kind: \"histogram\" | \"counter\";\n readonly unit: string;\n readonly description: string;\n /** Integer values (`asInt`) or doubles. Histograms always carry a double sum. */\n readonly valueType: \"int\" | \"double\";\n /** Histograms only. */\n readonly boundaries?: readonly number[];\n};\n\nexport const METRIC_INSTRUMENTS: Readonly<Record<MetricInstrumentName, MetricInstrument>> = Object.freeze({\n [METRIC_TOKEN_USAGE]: {\n name: METRIC_TOKEN_USAGE,\n kind: \"histogram\",\n unit: \"{token}\",\n description: \"Tokens used per generation, by token type (hook-derived)\",\n valueType: \"int\",\n boundaries: TOKEN_USAGE_BUCKETS,\n },\n [METRIC_OPERATION_DURATION]: {\n name: METRIC_OPERATION_DURATION,\n kind: \"histogram\",\n unit: \"s\",\n description: \"Generation duration, from its start hook to its end hook (hook-derived)\",\n valueType: \"double\",\n boundaries: OPERATION_DURATION_BUCKETS,\n },\n [METRIC_SESSIONS]: {\n name: METRIC_SESSIONS,\n kind: \"counter\",\n unit: \"{session}\",\n description: \"Agent sessions started\",\n valueType: \"int\",\n },\n [METRIC_TOOL_CALLS]: {\n name: METRIC_TOOL_CALLS,\n kind: \"counter\",\n unit: \"{call}\",\n description: \"Completed tool calls, by tool name and outcome\",\n valueType: \"int\",\n },\n [METRIC_COST_USAGE]: {\n name: METRIC_COST_USAGE,\n kind: \"counter\",\n unit: \"USD\",\n description: \"Cost reported by the provider; never estimated\",\n valueType: \"double\",\n },\n});\n\nexport const isMetricInstrumentName = (value: unknown): value is MetricInstrumentName =>\n typeof value === \"string\" && Object.hasOwn(METRIC_INSTRUMENTS, value);\n\nexport const ATTR_GEN_AI_TOKEN_TYPE = \"gen_ai.token.type\";\nexport const ATTR_GEN_AI_PROVIDER_NAME = \"gen_ai.provider.name\";\nconst ATTR_GEN_AI_OPERATION_NAME = \"gen_ai.operation.name\";\nconst ATTR_GEN_AI_REQUEST_MODEL = \"gen_ai.request.model\";\nconst ATTR_GEN_AI_RESPONSE_MODEL = \"gen_ai.response.model\";\nconst ATTR_GEN_AI_TOOL_NAME = \"gen_ai.tool.name\";\nconst ATTR_ERROR_TYPE = \"error.type\";\nconst ATTR_SESSION_ID = \"session.id\";\nconst ATTR_OTELHOOK_PROVIDER_ID = \"otelhook.provider.id\";\nconst ATTR_OTELHOOK_OUTCOME = \"otelhook.outcome\";\nconst ATTR_OTELHOOK_SESSION_KIND = \"otelhook.session.kind\";\n\n/**\n * Token types on `gen_ai.client.token.usage`.\n *\n * `input` is inclusive of cache reads, as the GenAI conventions define\n * `gen_ai.usage.input_tokens`. `cache_read` and `cache_creation` are extra series\n * describing parts of the input; summing every token type double-counts.\n */\nexport type TokenType = \"input\" | \"output\" | \"cache_read\" | \"cache_creation\";\n\nexport type MetricsTemporality = \"cumulative\" | \"delta\";\n\n/** One recorded value. */\nexport type MetricObservation = {\n readonly instrument: MetricInstrumentName;\n readonly value: number;\n /** Data-point attributes. Primitives only. */\n readonly attributes: Readonly<Record<string, string | number | boolean>>;\n /** When the observed thing happened, in epoch milliseconds. */\n readonly timeMillis: number;\n /** Provider session the observation belongs to; scopes cumulative state. */\n readonly sessionId: string;\n};\n\n/** A start time recovered for a generation, by generation id. */\nexport type GenerationStart = {\n readonly startMillis: number;\n readonly requestModel?: string;\n};\n\n/** The usage delta the orchestrator derived for one usage-bearing event. */\nexport type MetricUsageInput = {\n readonly eventId: string;\n readonly scope: string;\n readonly delta: CanonicalUsage;\n};\n\nexport type DeriveMetricObservationsInput = {\n readonly events: readonly CanonicalEvent[];\n readonly usage: readonly MetricUsageInput[];\n /** The exported resource; supplies the launcher's `session.id` when it sets one. */\n readonly resource: Resource;\n /** Put `session.id` on every data point. Default true. */\n readonly includeSessionId?: boolean;\n /**\n * Start times for generations whose start edge is not in this batch (it was\n * recorded by an earlier hook process). Looked up by generation id.\n */\n readonly generationStarts?: (generationId: string) => GenerationStart | undefined;\n /**\n * When the session's current turn began: the last `prompt.submitted` recorded,\n * by an earlier callback or this one. The fallback duration source for\n * providers whose generation is a turn (Claude Code, Codex).\n */\n readonly turnStart?: (sessionId: string) => number | undefined;\n};\n\nconst commonAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n includeSessionId: boolean,\n): Record<string, string | number | boolean> => ({\n // Session context first, so the metric's own attributes always win; and never\n // anything account-shaped, whatever the context says.\n ...(event.contextAttributes === undefined\n ? {}\n : (withoutAccountIdentity(event.contextAttributes) as Record<string, string | number | boolean>)),\n [ATTR_OTELHOOK_PROVIDER_ID]: event.provenance.providerId,\n ...(includeSessionId\n ? { [ATTR_SESSION_ID]: resolveExportedSessionId(event.sessionId, resource).sessionId }\n : {}),\n});\n\nconst generationAttributes = (\n end: GenerationEndEvent,\n requestModel: string | undefined,\n): Record<string, string> => ({\n [ATTR_GEN_AI_OPERATION_NAME]: \"chat\",\n ...(end.model.vendor === undefined ? {} : { [ATTR_GEN_AI_PROVIDER_NAME]: end.model.vendor }),\n [ATTR_GEN_AI_REQUEST_MODEL]: requestModel ?? end.model.modelId,\n [ATTR_GEN_AI_RESPONSE_MODEL]: end.model.modelId,\n});\n\nconst TOKEN_FIELDS: readonly (readonly [TokenType, (usage: CanonicalUsage) => number])[] = [\n [\"input\", (usage) => usage.inputTokens],\n [\"output\", (usage) => usage.outputTokens],\n [\"cache_read\", (usage) => usage.cachedInputTokens],\n [\"cache_creation\", (usage) => usage.cacheCreationInputTokens],\n];\n\nconst isFailedOutcome = (outcome: string): boolean =>\n outcome !== \"ok\" && outcome !== \"unknown\" && outcome !== \"cancelled\";\n\n/**\n * Observations for one batch.\n *\n * - `otelhook.sessions`: one per `session.start`.\n * - `otelhook.tool.calls`: one per `tool.end`.\n * - `gen_ai.client.operation.duration`: one per `generation.end` whose duration is\n * known, from the first source that has it:\n * 1. the duration the provider stated (`durationMillis`);\n * 2. a `generation.start` recorded by an *earlier* callback;\n * 3. the turn's start: the last `prompt.submitted` of the session, no later than\n * the end. For Claude Code and Codex a generation is a turn, so this is the\n * turn's wall-clock time, tool calls included. Not for a subagent's\n * generation, which did not start with the parent's prompt.\n * A `generation.start` in the *same* batch as its end is not a start: an\n * adapter that emits both from one callback (Claude Code's `Stop`) synthesized\n * it, and measuring from it would record a zero.\n * - `gen_ai.client.token.usage`: per generation-scoped usage delta, one per token\n * type. A zero `cache_read` / `cache_creation` is not recorded: a provider that\n * never reports cache tokens would otherwise fill the low bucket with zeros.\n * `input` and `output` are always recorded, zero included, so the count of a\n * token histogram is the number of generations with usage.\n * - `otelhook.cost.usage`: per `generation.end` with a provider-reported USD cost.\n */\nexport const deriveMetricObservations = (\n input: DeriveMetricObservationsInput,\n): readonly MetricObservation[] => {\n const includeSessionId = input.includeSessionId ?? true;\n const observations: MetricObservation[] = [];\n const byId = new Map<string, CanonicalEvent>();\n const startsInBatch = new Map<string, GenerationStart>();\n for (const event of input.events) {\n byId.set(event.eventId, event);\n if (event.type === \"generation.start\") {\n startsInBatch.set(event.generationId, {\n startMillis: event.occurredAt,\n requestModel: event.model.modelId,\n });\n }\n }\n // Request model only: a start in this batch says what was asked for, but not when.\n const requestModelOf = (generationId: string): string | undefined =>\n startsInBatch.get(generationId)?.requestModel ?? input.generationStarts?.(generationId)?.requestModel;\n let lastPromptInBatch: Map<string, number> | undefined;\n for (const event of input.events) {\n if (event.type === \"prompt.submitted\") {\n lastPromptInBatch ??= new Map();\n lastPromptInBatch.set(event.sessionId, Math.max(lastPromptInBatch.get(event.sessionId) ?? 0, event.occurredAt));\n }\n }\n const measuredDurationOf = (end: GenerationEndEvent): number | undefined => {\n if (end.durationMillis !== undefined) {\n return end.durationMillis;\n }\n const recovered = startsInBatch.has(end.generationId) ? undefined : input.generationStarts?.(end.generationId);\n if (recovered !== undefined) {\n return end.occurredAt - recovered.startMillis;\n }\n // The turn's prompt is the parent's: a subagent's generation started later,\n // when the subagent did, so measuring from the prompt would overstate it.\n if (end.subagentId !== undefined) {\n return undefined;\n }\n const turn = lastPromptInBatch?.get(end.sessionId) ?? input.turnStart?.(end.sessionId);\n return turn === undefined || turn > end.occurredAt ? undefined : end.occurredAt - turn;\n };\n\n const push = (\n event: CanonicalEvent,\n instrument: MetricInstrumentName,\n value: number,\n attributes: Record<string, string | number | boolean>,\n ): void => {\n if (!Number.isFinite(value) || value < 0) {\n return;\n }\n observations.push({\n instrument,\n value,\n attributes: { ...commonAttributes(event, input.resource, includeSessionId), ...attributes },\n timeMillis: event.occurredAt,\n sessionId: event.sessionId,\n });\n };\n\n for (const event of input.events) {\n switch (event.type) {\n case \"session.start\":\n push(event, METRIC_SESSIONS, 1, { [ATTR_OTELHOOK_SESSION_KIND]: event.sessionKind });\n break;\n case \"tool.end\":\n push(event, METRIC_TOOL_CALLS, 1, {\n [ATTR_GEN_AI_TOOL_NAME]: event.toolName,\n [ATTR_OTELHOOK_OUTCOME]: event.outcome,\n });\n break;\n case \"generation.end\": {\n const attributes = generationAttributes(event, requestModelOf(event.generationId));\n const durationMillis = measuredDurationOf(event);\n if (durationMillis !== undefined && durationMillis >= 0) {\n push(event, METRIC_OPERATION_DURATION, durationMillis / 1000, {\n ...attributes,\n ...(isFailedOutcome(event.outcome) ? { [ATTR_ERROR_TYPE]: event.outcome } : {}),\n });\n }\n if (\n event.cost !== undefined &&\n event.cost.source === \"provider-reported\" &&\n event.cost.currency === \"USD\"\n ) {\n push(event, METRIC_COST_USAGE, event.cost.amount, attributes);\n }\n break;\n }\n default:\n break;\n }\n }\n\n for (const observation of input.usage) {\n if (observation.scope !== \"generation\") {\n // Session totals and subagent rollups restate generation spend; counting them\n // too would double it.\n continue;\n }\n const event = byId.get(observation.eventId);\n if (event?.type !== \"generation.end\") {\n continue;\n }\n const attributes = generationAttributes(event, requestModelOf(event.generationId));\n for (const [tokenType, read] of TOKEN_FIELDS) {\n const value = read(observation.delta);\n if (value === 0 && (tokenType === \"cache_read\" || tokenType === \"cache_creation\")) {\n continue;\n }\n push(event, METRIC_TOKEN_USAGE, value, { ...attributes, [ATTR_GEN_AI_TOKEN_TYPE]: tokenType });\n }\n }\n return observations;\n};\n\n/** Accumulated histogram state for one series. */\nexport type HistogramState = {\n readonly count: number;\n readonly sum: number;\n readonly min: number;\n readonly max: number;\n /** One more entry than the instrument's boundaries. */\n readonly bucketCounts: readonly number[];\n};\n\n/**\n * One OTLP data point, as plain JSON so it can be spooled.\n *\n * A point is self-describing: the instrument, its temporality, and its interval.\n * A cumulative point is a snapshot of a running total, so resending one (from a\n * spool) restates a value rather than adding to it.\n */\nexport type MetricPoint = {\n readonly instrument: MetricInstrumentName;\n readonly temporality: MetricsTemporality;\n readonly attributes: Readonly<Record<string, string | number | boolean>>;\n readonly startTimeMillis: number;\n readonly timeMillis: number;\n /** Counters. */\n readonly value?: number;\n /** Histograms. */\n readonly histogram?: HistogramState;\n};\n\nexport const emptyHistogram = (boundaries: readonly number[]): HistogramState => ({\n count: 0,\n sum: 0,\n min: Number.POSITIVE_INFINITY,\n max: Number.NEGATIVE_INFINITY,\n bucketCounts: new Array<number>(boundaries.length + 1).fill(0),\n});\n\n/** OTLP explicit buckets: bucket `i` holds values in `(boundaries[i-1], boundaries[i]]`. */\nexport const bucketIndex = (boundaries: readonly number[], value: number): number => {\n for (let index = 0; index < boundaries.length; index += 1) {\n const bound = boundaries[index];\n if (bound !== undefined && value <= bound) {\n return index;\n }\n }\n return boundaries.length;\n};\n\nexport const recordIntoHistogram = (\n state: HistogramState,\n boundaries: readonly number[],\n value: number,\n): HistogramState => {\n const bucketCounts = [...state.bucketCounts];\n const index = bucketIndex(boundaries, value);\n bucketCounts[index] = (bucketCounts[index] ?? 0) + 1;\n return {\n count: state.count + 1,\n sum: state.sum + value,\n min: Math.min(state.min, value),\n max: Math.max(state.max, value),\n bucketCounts,\n };\n};\n\n/**\n * Stable identity of a series: instrument plus sorted attributes.\n *\n * Used as a map key and, digested, as a state key. JSON of sorted entries is\n * unambiguous where a joined string would not be.\n */\nexport const seriesIdentity = (\n instrument: MetricInstrumentName,\n attributes: Readonly<Record<string, string | number | boolean>>,\n): string =>\n JSON.stringify([\n instrument,\n Object.entries(attributes).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),\n ]);\n\n/**\n * Delta points for one batch: observations of the same series folded together,\n * over the interval from the earliest observation to `nowMillis`.\n */\nexport const aggregateDeltaPoints = (\n observations: readonly MetricObservation[],\n nowMillis: number,\n): readonly MetricPoint[] => {\n const series = new Map<\n string,\n { observation: MetricObservation; start: number; value: number; histogram?: HistogramState }\n >();\n for (const observation of observations) {\n const instrument = METRIC_INSTRUMENTS[observation.instrument];\n const key = seriesIdentity(observation.instrument, observation.attributes);\n const existing =\n series.get(key) ??\n ({\n observation,\n start: observation.timeMillis,\n value: 0,\n ...(instrument.boundaries === undefined ? {} : { histogram: emptyHistogram(instrument.boundaries) }),\n });\n existing.start = Math.min(existing.start, observation.timeMillis);\n if (existing.histogram !== undefined && instrument.boundaries !== undefined) {\n existing.histogram = recordIntoHistogram(existing.histogram, instrument.boundaries, observation.value);\n } else {\n existing.value += observation.value;\n }\n series.set(key, existing);\n }\n return [...series.values()].map((entry) => ({\n instrument: entry.observation.instrument,\n temporality: \"delta\",\n attributes: entry.observation.attributes,\n startTimeMillis: Math.min(entry.start, nowMillis),\n timeMillis: Math.max(nowMillis, entry.start),\n ...(entry.histogram === undefined ? { value: entry.value } : { histogram: entry.histogram }),\n }));\n};\n\n/** Data-point attribute keys that must never appear on a metric. */\nexport const FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES: readonly string[] = Object.freeze([\n \"user.\",\n \"enduser.\",\n \"organization.\",\n]);\n\n/** Strip anything account-shaped from attributes, as a last line of defence. */\nexport const withoutAccountIdentity = (attributes: Attributes): Attributes =>\n Object.fromEntries(\n Object.entries(attributes).filter(\n ([key]) => !FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES.some((prefix) => key.startsWith(prefix)),\n ),\n );\n","import type { CallbackDeduplicator } from \"./dedup.js\";\nimport type { SpanCorrelator } from \"./span-correlator.js\";\nimport type { MetricSeriesStore } from \"./metric-series.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 /** Cumulative metric series state; swept by age, like usage rollups. */\n readonly metricSeries?: MetricSeriesStore;\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 readonly metrics?: 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, metrics] = 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 options.metricSeries?.cleanup(usageMaxAge, scope),\n ]);\n return {\n ...(span === undefined ? {} : { span }),\n ...(dedup === undefined ? {} : { dedup }),\n ...(usage === undefined ? {} : { usage }),\n ...(metrics === undefined ? {} : { metrics }),\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_REPOSITORY_ID,\n ATTR_OTELHOOK_TARGET_SOURCE,\n ATTR_OTELHOOK_TARGET_WORKSPACE_ID,\n ATTR_OTELHOOK_TARGET_WORKTREE_KIND,\n ATTR_VCS_REF_HEAD_NAME,\n exportIdentityAttributes,\n profileAttributes,\n targetAttributes,\n usageTemporalityAttributes,\n} from \"./export-identity.js\";\n\nconst SCOPE_NAME = \"@osfactory/otel-hook\";\n\nexport const DEFAULT_INSTRUMENTATION_SCOPE: InstrumentationScope = Object.freeze({\n name: SCOPE_NAME,\n version: VERSION,\n});\n\nconst ATTR_OTELHOOK_SPAN_PAIRED = \"otelhook.span.paired\";\nconst ATTR_OTELHOOK_SPAN_PAIRING = \"otelhook.span.pairing\";\nconst ATTR_OTELHOOK_SPAN_ORPHAN = \"otelhook.span.orphan\";\nconst ATTR_OTELHOOK_OUTCOME = \"otelhook.outcome\";\nconst ATTR_OTELHOOK_RESET_DETECTED = \"otelhook.usage.reset_detected\";\n/** True when a generation's usage covers only part of it; see `generation.end.usagePartial`. */\nexport const ATTR_OTELHOOK_USAGE_PARTIAL = \"otelhook.usage.partial\";\nconst ATTR_OTELHOOK_TOOL_KIND = \"otelhook.tool.kind\";\nconst ATTR_OTELHOOK_DELEGATION_DEPTH = \"otelhook.delegation_depth\";\nconst ATTR_OTELHOOK_COMPACTION_TRIGGER = \"otelhook.compaction.trigger\";\nconst ATTR_OTELHOOK_AGENT_NAME = \"otelhook.agent.name\";\nconst ATTR_OTELHOOK_AGENT_VERSION = \"otelhook.agent.version\";\nconst ATTR_OTELHOOK_GENERATION_ID = \"otelhook.generation.id\";\n\n/**\n * Pure, stateless canonical-event-to-span mapping.\n *\n * Isolated in one module so every other piece of the telemetry pipeline\n * — batching, retry, spooling — can change without touching what an attribute\n * means. Two edges of the same lifecycle scope are merged into one span when\n * they appear in the same batch; when they arrive in *different* short-lived\n * hook processes they are merged through a {@link SpanCorrelation} the caller\n * resolved from persisted state. Either way the mapping itself stays a pure\n * function: state is read by the correlator, never by this module.\n *\n * ## Identity of a span\n *\n * Trace and span ids are derived, never random, so two processes that never\n * meet still agree on them:\n *\n * - `traceId = H(providerId, sessionId)` — one trace per session per provider.\n * Deriving it from the session rather than the invocation is what lets a\n * `tool.end` emitted minutes later land in the same trace as its `tool.start`;\n * including the provider is what stops two providers that happen to reuse a\n * session id from being stitched into one trace.\n * - `spanId = H(providerId, sessionId, family, scopeKey)` — stable across\n * processes and idempotent under redelivery, so a collector that sees a\n * start-only span and later the completed span treats them as one span\n * rather than two.\n */\n// NUL, so joined parts cannot collide across a different split: no identifier\n// this library accepts can contain one, which a printable separator cannot\n// promise. Never emitted — only hashed, or used as an in-memory map key.\nconst FIELD_SEPARATOR = \"\\u0000\";\n\nconst digestHex = (parts: readonly string[], length: number): string =>\n createHash(\"sha256\").update(parts.join(FIELD_SEPARATOR)).digest(\"hex\").slice(0, length);\n\n/** Lifecycle scopes that pair a `*.start` edge with a later `*.end` edge. */\nexport type SpanFamily = \"session\" | \"generation\" | \"tool\" | \"subagent\";\n\n/** Identifies one lifecycle span within a session. */\nexport type SpanScopeRef = {\n readonly family: SpanFamily;\n readonly scopeKey: string;\n};\n\n/**\n * Why a lifecycle span is, or is not, a complete pair.\n *\n * Deliberately explicit rather than a bare boolean: \"we never saw the start\",\n * \"we saw it but it aged out of state\", and \"state could not be read at all\"\n * are different operational facts, and a dashboard that cannot tell them apart\n * cannot tell a broken host from a broken exporter.\n */\nexport type SpanOrphanClassification =\n /** Both edges are known — from this batch, or from persisted state. */\n | \"none\"\n /** The start is known; its end has not arrived yet. */\n | \"missing-end\"\n /** An end arrived and no start was ever recorded for this scope. */\n | \"missing-start\"\n /** A start was recorded but aged past the retention window before the end arrived. */\n | \"expired-start\"\n /** A start exists but was recorded by a different provider; pairing it would be a guess. */\n | \"provider-mismatch\"\n /** A second, distinct end arrived for a scope that was already closed. */\n | \"already-closed\"\n /** The persisted record was written by an incompatible version and was discarded. */\n | \"state-incompatible\"\n /** The persisted record could not be understood. */\n | \"state-corrupt\"\n /** State could not be consulted at all; the mapping degraded rather than failing. */\n | \"state-unavailable\";\n\nexport type SpanPairing =\n /** Both edges were present in this batch. */\n | \"in-batch\"\n /** The other edge came from state written by an earlier process. */\n | \"cross-process\"\n | \"unpaired\";\n\n/**\n * Whether this scope should produce an OTLP record now.\n *\n * OTLP has no notion of updating a span: a span is exported once, when it ends,\n * and a second record carrying the same trace and span id is not a revision of\n * the first — it is a duplicate that backends variously drop, keep the older of,\n * or display twice. Since every lifecycle span id here is *derived* from\n * `(provider, session, family, scopeKey)`, a `*.start` edge and its later `*.end`\n * edge compute the identical id, so exporting on both is precisely that\n * duplicate.\n *\n * `defer` is therefore the answer for a start whose end has not arrived: the\n * start is durable in the state store, and the end edge exports the one complete\n * span using the times recovered from it. Nothing is lost by waiting, and what is\n * gained is that the record a collector receives has a real duration.\n */\nexport type SpanDisposition =\n /** Export a record for this scope now. */\n | \"emit\"\n /** Hold: the start is recorded, and the end edge will export the complete span. */\n | \"defer\";\n\n/**\n * One scope's correlation facts, resolved from persisted state by the caller.\n *\n * Plain data on purpose: the telemetry layer must not reach into the state\n * store itself (ADR 0006), so it declares what it needs and the lifecycle layer\n * supplies it.\n */\nexport type SpanCorrelation = {\n readonly providerId: string;\n readonly sessionId: string;\n readonly ref: SpanScopeRef;\n readonly pairing: SpanPairing;\n readonly orphan: SpanOrphanClassification;\n /**\n * Whether to export a record for this scope now. Defaults to `emit` when a\n * correlation is supplied without one.\n */\n readonly disposition?: SpanDisposition;\n /**\n * Extra component mixed into the derived span id.\n *\n * Set only when this record is a genuinely *additional* observation of a scope\n * that has already been exported once — a second, distinct end for a scope that\n * was already closed. Both records are real, so neither is dropped, and the\n * discriminator keeps them from claiming the same span id.\n */\n readonly spanIdDiscriminator?: string;\n /** Start recovered from state; authoritative over the batch's own start edge. */\n readonly startMillis?: number;\n /** End recovered from state; authoritative so a redelivered end re-exports an identical span. */\n readonly endMillis?: number;\n /** Parent recorded at start time, so an end-only process hangs the span in the same place. */\n readonly parent?: SpanScopeRef;\n /** Attributes only the start edge could supply, recovered for an end-only span. */\n readonly attributes?: Attributes;\n};\n\n/**\n * Resolves persisted correlation for one batch.\n *\n * Must never reject: a state failure is a degraded span, never a lost export.\n */\nexport type SpanCorrelationResolver = (\n events: readonly CanonicalEvent[],\n) => Promise<readonly SpanCorrelation[]>;\n\n/**\n * Upper bound on how many start-edge attributes the correlator may carry\n * forward, so persisted state cannot grow with provider-controlled input.\n */\nexport const MAX_RECOVERED_START_ATTRIBUTES = 16;\n\nconst familyOf = (type: CanonicalEventType): SpanFamily | undefined => {\n switch (type) {\n case \"session.start\":\n case \"session.end\":\n return \"session\";\n case \"generation.start\":\n case \"generation.end\":\n return \"generation\";\n case \"tool.start\":\n case \"tool.end\":\n return \"tool\";\n case \"subagent.start\":\n case \"subagent.end\":\n return \"subagent\";\n default:\n return undefined;\n }\n};\n\n/** The lifecycle span an event is an edge of, or undefined for a point-in-time event. */\nexport const spanScopeRefOf = (event: CanonicalEvent): SpanScopeRef | undefined => {\n const family = familyOf(event.type);\n if (family === undefined) {\n return undefined;\n }\n switch (event.type) {\n case \"session.start\":\n case \"session.end\":\n return { family, scopeKey: event.sessionId };\n case \"generation.start\":\n case \"generation.end\":\n return { family, scopeKey: event.generationId };\n case \"tool.start\":\n case \"tool.end\":\n return { family, scopeKey: event.toolCallId };\n case \"subagent.start\":\n case \"subagent.end\":\n return { family, scopeKey: event.subagentInvocationId };\n default:\n return undefined;\n }\n};\n\n/**\n * Where a span hangs in the trace, judged from this event alone.\n *\n * Everything in a session descends from the session span. A tool call names its\n * generation only on `tool.start`, which is exactly why the correlator persists\n * the parent: the `tool.end` process would otherwise reparent the same span to\n * the session and produce a tree whose shape depends on which edge happened to\n * be exported last.\n */\nexport const parentScopeRefOf = (event: CanonicalEvent): SpanScopeRef | undefined => {\n if (event.type === \"session.start\" || event.type === \"session.end\") {\n return undefined;\n }\n if (event.type === \"tool.start\" && event.generationId !== undefined) {\n return { family: \"generation\", scopeKey: event.generationId };\n }\n return { family: \"session\", scopeKey: event.sessionId };\n};\n\n/**\n * Span attributes that only a `*.start` edge can supply.\n *\n * The correlator persists these verbatim so an end-only span in a later process\n * still carries the tool kind, requested model, delegation depth, or agent name\n * the start process saw. An allowlist, and bounded, so persisted state can\n * never become a second route for provider payload content to escape.\n */\nexport const startOnlySpanAttributes = (event: CanonicalEvent): Attributes => {\n switch (event.type) {\n // The session's own worktree is carried forward like a tool's target, so\n // the session span a later `session.end` process exports still names it.\n case \"session.start\":\n return {\n ...(event.agentName === undefined ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: event.agentName }),\n ...(event.agentVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_AGENT_VERSION]: event.agentVersion }),\n ...targetAttributes(event),\n };\n case \"generation.start\":\n return {\n [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId,\n ...(event.model.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: event.model.vendor }),\n };\n // `toolName` and `toolCallId` are on both tool edges, so they are not\n // start-only and persisting them would just pad every record.\n // The target is carried forward too: an end-only process may see a payload\n // with less to go on (no tool input), and the start's evidence still holds.\n case \"tool.start\":\n return { [ATTR_OTELHOOK_TOOL_KIND]: event.toolKind, ...targetAttributes(event) };\n case \"subagent.start\":\n return { [ATTR_OTELHOOK_DELEGATION_DEPTH]: event.delegationDepth };\n default:\n return {};\n }\n};\n\nconst deriveTraceId = (providerId: string, sessionId: string): string =>\n digestHex([\"otelhook/trace\", providerId, sessionId], 32);\n\nconst deriveSpanId = (providerId: string, sessionId: string, ref: SpanScopeRef): string =>\n digestHex([\"otelhook/span\", providerId, sessionId, ref.family, ref.scopeKey], 16);\n\nconst deriveStandaloneSpanId = (\n providerId: string,\n sessionId: string,\n eventType: string,\n eventId: string,\n): string => digestHex([\"otelhook/span\", providerId, sessionId, \"event\", eventType, eventId], 16);\n\nconst correlationKey = (providerId: string, sessionId: string, ref: SpanScopeRef): string =>\n [providerId, sessionId, ref.family, ref.scopeKey].join(FIELD_SEPARATOR);\n\nconst outcomeStatus = (outcome: string | undefined): SpanStatus => {\n if (outcome === undefined || outcome === \"ok\" || outcome === \"unknown\") {\n return { code: SpanStatusCode.UNSET };\n }\n if (outcome === \"cancelled\") {\n return { code: SpanStatusCode.UNSET };\n }\n return { code: SpanStatusCode.ERROR, message: outcome };\n};\n\nconst identityAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n ids: { readonly traceId: string; readonly spanId: string; readonly parentSpanId?: string },\n): Attributes => exportIdentityAttributes(event, resource, ids);\n\nconst usageAttributes = (usage: CanonicalUsage | undefined, resetDetected: boolean): Attributes => {\n if (usage === undefined) {\n return {};\n }\n return {\n [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: usage.inputTokens,\n [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: usage.outputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: usage.cachedInputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: usage.cacheCreationInputTokens,\n [ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]: usage.reasoningOutputTokens,\n ...usageTemporalityAttributes(usage),\n ...(resetDetected ? { [ATTR_OTELHOOK_RESET_DETECTED]: true } : {}),\n };\n};\n\n/** Evidence strength of a target source; see `targetSourceSchema`. */\nconst TARGET_SOURCE_RANK: Readonly<Record<string, number>> = Object.freeze({\n \"tool-path\": 3,\n \"shell-cwd\": 2,\n \"session-cwd\": 1,\n});\n\nconst TARGET_KEYS = [\n ATTR_OTELHOOK_TARGET_WORKSPACE_ID,\n ATTR_OTELHOOK_TARGET_SOURCE,\n ATTR_VCS_REF_HEAD_NAME,\n ATTR_OTELHOOK_TARGET_REPOSITORY_ID,\n ATTR_OTELHOOK_TARGET_WORKTREE_KIND,\n] as const;\n\nconst pickTarget = (attributes: Attributes): Attributes => {\n const picked: Attributes = {};\n for (const key of TARGET_KEYS) {\n if (attributes[key] !== undefined) {\n picked[key] = attributes[key];\n }\n }\n return picked;\n};\n\n/**\n * Drop the target keys so they can be re-chosen as one unit, keeping only what\n * the launcher put on the Resource or the session context named (a\n * `vcs.ref.head.name` passed through by `exportIdentityAttributes`) as the\n * fallback beneath the chosen target.\n */\nconst withoutTarget = (attributes: Attributes, resource: Resource, event: CanonicalEvent): Attributes => {\n const rest: Attributes = { ...attributes };\n for (const key of TARGET_KEYS) {\n delete rest[key];\n }\n return { ...rest, ...pickTarget(profileAttributes(event, resource)) };\n};\n\nconst rankOf = (candidate: Attributes): number => {\n const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];\n return typeof source === \"string\" && Object.hasOwn(TARGET_SOURCE_RANK, source)\n ? (TARGET_SOURCE_RANK[source] ?? 0)\n : 0;\n};\n\n/**\n * One span, one target: the strongest evidence among the recovered start,\n * the live start, and the live end — later wins a tie. A Cursor shell call's\n * start knows its `cwd` and its end does not; the span must keep the former,\n * not be downgraded to the workspace root by whichever edge exported last.\n */\nconst strongestTarget = (candidates: readonly Attributes[]): Attributes => {\n let best: Attributes = {};\n let bestRank = 0;\n for (const candidate of candidates) {\n const rank = rankOf(candidate);\n if (rank > 0 && rank >= bestRank) {\n best = candidate;\n bestRank = rank;\n }\n }\n return best;\n};\n\ntype SpanGroup = {\n readonly ref: SpanScopeRef;\n start?: CanonicalEvent;\n end?: CanonicalEvent;\n};\n\nconst buildSpanContext = (traceId: string, spanId: string): SpanContext => ({\n traceId,\n spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n});\n\nexport type ReadableSpanInput = {\n readonly name: string;\n readonly kind: SpanKind;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly attributes: Attributes;\n readonly status: SpanStatus;\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n};\n\n/** Reconstructs a {@link ReadableSpan} from plain, serializable fields. Used by the durable spool to replay a span it persisted earlier. */\nexport const assembleReadableSpan = (input: ReadableSpanInput): ReadableSpan => toReadableSpan(input);\n\nconst toReadableSpan = (input: ReadableSpanInput): ReadableSpan => {\n const startTime = millisToHrTime(input.startMillis);\n const endTime = millisToHrTime(Math.max(input.startMillis, input.endMillis));\n const duration = millisToHrTime(Math.max(0, input.endMillis - input.startMillis));\n return {\n name: input.name,\n kind: input.kind,\n spanContext: (): SpanContext => buildSpanContext(input.traceId, input.spanId),\n ...(input.parentSpanId === undefined\n ? {}\n : { parentSpanContext: buildSpanContext(input.traceId, input.parentSpanId) }),\n startTime,\n endTime,\n status: input.status,\n attributes: input.attributes,\n links: [],\n events: [],\n duration,\n ended: true,\n resource: input.resource,\n instrumentationScope: input.instrumentationScope,\n droppedAttributesCount: 0,\n droppedEventsCount: 0,\n droppedLinksCount: 0,\n };\n};\n\ntype ResolvedPairing = {\n readonly pairing: SpanPairing;\n readonly orphan: SpanOrphanClassification;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly parent: SpanScopeRef | undefined;\n readonly recovered: Attributes;\n};\n\nconst resolvePairing = (\n group: SpanGroup,\n anchor: CanonicalEvent,\n correlation: SpanCorrelation | undefined,\n): ResolvedPairing => {\n const inBatch = group.start !== undefined && group.end !== undefined;\n const batchStart = group.start?.occurredAt ?? anchor.occurredAt;\n const batchEnd = group.end?.occurredAt ?? anchor.occurredAt;\n\n if (correlation === undefined) {\n return {\n pairing: inBatch ? \"in-batch\" : \"unpaired\",\n orphan: inBatch ? \"none\" : group.start === undefined ? \"missing-start\" : \"missing-end\",\n startMillis: batchStart,\n endMillis: inBatch ? batchEnd : batchStart,\n parent: parentScopeRefOf(anchor),\n recovered: {},\n };\n }\n\n // A correlation that reports no start (an orphaned end) must not fabricate\n // one: the span collapses onto the end instant rather than claiming a\n // duration measured from an event nobody ever saw.\n const startMillis = correlation.startMillis ?? (inBatch ? batchStart : batchEnd);\n const endMillis = correlation.endMillis ?? (group.end === undefined ? startMillis : batchEnd);\n return {\n pairing: correlation.pairing,\n orphan: correlation.orphan,\n startMillis,\n endMillis,\n parent: correlation.parent ?? parentScopeRefOf(anchor),\n recovered: correlation.attributes ?? {},\n };\n};\n\nconst buildLifecycleSpan = (\n plan: GroupPlan,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan => {\n const group = plan.group;\n const anchor = plan.anchor;\n const correlation = plan.correlation;\n const providerId = anchor.provenance.providerId;\n const sessionId = anchor.sessionId;\n const resolved = resolvePairing(group, anchor, correlation);\n const traceId = plan.traceId;\n const spanId = plan.spanId;\n const parentSpanId =\n resolved.parent === undefined ? undefined : deriveSpanId(providerId, sessionId, resolved.parent);\n\n let name: string = group.ref.family;\n let kind: SpanKind = SpanKind.INTERNAL;\n let status: SpanStatus = { code: SpanStatusCode.UNSET };\n // Attributes recovered from the start process sit *beneath* whatever this\n // batch observed: a live edge always wins over a remembered one.\n let attributes: Attributes = {\n ...identityAttributes(anchor, resource, {\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n }),\n ...resolved.recovered,\n [ATTR_OTELHOOK_SPAN_PAIRED]: resolved.pairing !== \"unpaired\",\n [ATTR_OTELHOOK_SPAN_PAIRING]: resolved.pairing,\n [ATTR_OTELHOOK_SPAN_ORPHAN]: resolved.orphan,\n };\n\n switch (group.ref.family) {\n case \"session\": {\n const end = group.end?.type === \"session.end\" ? group.end : undefined;\n const start = group.start?.type === \"session.start\" ? group.start : undefined;\n name = \"session\";\n kind = SpanKind.INTERNAL;\n attributes = {\n ...withoutTarget(attributes, resource, anchor),\n ...strongestTarget([pickTarget(resolved.recovered), start === undefined ? {} : targetAttributes(start)]),\n ...(start?.agentName === undefined ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName }),\n ...(start?.agentVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion }),\n ...(end === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.reason }),\n ...usageAttributes(end?.usage, false),\n };\n if (end?.reason === \"error\" || end?.reason === \"timeout\") {\n status = { code: SpanStatusCode.ERROR, message: end.reason };\n }\n break;\n }\n case \"generation\": {\n const start = group.start?.type === \"generation.start\" ? group.start : undefined;\n const end = group.end?.type === \"generation.end\" ? group.end : undefined;\n const model = end?.model ?? start?.model;\n name = model === undefined ? \"generation\" : `generation ${model.modelId}`;\n kind = SpanKind.CLIENT;\n attributes = {\n ...attributes,\n [ATTR_GEN_AI_OPERATION_NAME]: \"chat\",\n ...(model?.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: model.vendor }),\n ...(start?.model?.modelId === undefined ? {} : { [ATTR_GEN_AI_REQUEST_MODEL]: start.model.modelId }),\n ...(end?.model?.modelId === undefined ? {} : { [ATTR_GEN_AI_RESPONSE_MODEL]: end.model.modelId }),\n // The provider's own id for this unit of work (Cursor generation,\n // Codex turn): the key a consumer stores a usage observation under.\n [ATTR_OTELHOOK_GENERATION_ID]: group.ref.scopeKey,\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...usageAttributes(end?.usage, false),\n ...(end?.usage === undefined || end.usagePartial === undefined\n ? {}\n : { [ATTR_OTELHOOK_USAGE_PARTIAL]: end.usagePartial }),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n case \"tool\": {\n const start = group.start?.type === \"tool.start\" ? group.start : undefined;\n const end = group.end?.type === \"tool.end\" ? group.end : undefined;\n const toolName = start?.toolName ?? end?.toolName ?? \"unknown\";\n name = `tool ${toolName}`;\n kind = SpanKind.CLIENT;\n attributes = {\n // Target keys are re-chosen below as one unit, never mixed across edges.\n ...withoutTarget(attributes, resource, anchor),\n [ATTR_GEN_AI_TOOL_NAME]: toolName,\n [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,\n ...(start?.toolKind === undefined ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind }),\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...strongestTarget([\n pickTarget(resolved.recovered),\n start === undefined ? {} : targetAttributes(start),\n end === undefined ? {} : targetAttributes(end),\n ]),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n case \"subagent\": {\n const start = group.start?.type === \"subagent.start\" ? group.start : undefined;\n const end = group.end?.type === \"subagent.end\" ? group.end : undefined;\n name = \"subagent\";\n kind = SpanKind.INTERNAL;\n attributes = {\n ...attributes,\n ...(start?.delegationDepth === undefined\n ? {}\n : { [ATTR_OTELHOOK_DELEGATION_DEPTH]: start.delegationDepth }),\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...usageAttributes(end?.usage, false),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n }\n\n if (status.code === SpanStatusCode.ERROR) {\n attributes = { ...attributes, [ATTR_ERROR_TYPE]: status.message ?? \"error\" };\n }\n\n return toReadableSpan({\n name,\n kind,\n startMillis: resolved.startMillis,\n endMillis: resolved.endMillis,\n attributes,\n status,\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n resource,\n instrumentationScope: scope,\n });\n};\n\nconst buildStandaloneSpan = (\n event: CanonicalEvent,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan => {\n const providerId = event.provenance.providerId;\n const traceId = deriveTraceId(providerId, event.sessionId);\n const spanId = deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId);\n const parent = parentScopeRefOf(event);\n const parentSpanId =\n parent === undefined ? undefined : deriveSpanId(providerId, event.sessionId, parent);\n let attributes: Attributes = {\n ...identityAttributes(event, resource, {\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n }),\n [ATTR_OTELHOOK_SPAN_PAIRED]: true,\n };\n let status: SpanStatus = { code: SpanStatusCode.UNSET };\n let name: string = event.type;\n\n switch (event.type) {\n case \"prompt.submitted\":\n name = \"prompt\";\n attributes = { ...attributes, \"otelhook.prompt.source\": event.promptSource, ...targetAttributes(event) };\n break;\n case \"compaction.performed\":\n name = \"compaction\";\n attributes = {\n ...attributes,\n [ATTR_OTELHOOK_COMPACTION_TRIGGER]: event.trigger,\n ...usageAttributes(event.usage, false),\n };\n break;\n case \"error.raised\":\n name = \"error\";\n status = { code: SpanStatusCode.ERROR, message: event.errorCode };\n attributes = {\n ...attributes,\n [ATTR_ERROR_TYPE]: event.errorCode,\n \"otelhook.error.phase\": event.phase,\n \"otelhook.error.retryable\": event.retryable,\n };\n break;\n default:\n break;\n }\n\n return toReadableSpan({\n name,\n kind: SpanKind.INTERNAL,\n startMillis: event.occurredAt,\n endMillis: event.occurredAt,\n attributes,\n status,\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n resource,\n instrumentationScope: scope,\n });\n};\n\nexport type SemanticMappingOptions = {\n readonly resource: Resource;\n readonly instrumentationScope?: InstrumentationScope;\n /**\n * Cross-process pairing facts, at most one entry per lifecycle scope in\n * `events`. Omitted entirely, the mapping degrades to in-batch pairing only —\n * the behavior of a host that wired no state store.\n */\n readonly correlations?: readonly SpanCorrelation[];\n /**\n * Whether a correlator was consulted at all, and whether it answered.\n *\n * This is what separates \"the state store is holding this start, so the end edge\n * will publish it\" from \"nothing recorded this start\". Both look like an empty\n * `correlations` list, and only the first is safe to drop — dropping the second\n * would discard an observation that was neither persisted nor exported, while a\n * caller that saw zero rejections went on to mark the callback handled.\n *\n * - `true` — the correlator ran; an absent or non-`defer` entry means emit.\n * - `false` — the correlator failed; every unpaired start is emitted as an\n * explicitly labelled, uniquely identified fallback.\n * - omitted — no correlator is wired, so cross-process pairing was never on\n * offer and an unpaired start is deferred (the documented no-state-root\n * degradation).\n */\n readonly correlationAvailable?: boolean;\n};\n\n/**\n * Fill in a correlation for an unpaired start that nothing recorded.\n *\n * Reached when a correlator was consulted and either failed outright or reported\n * nothing for this scope. The synthesized entry says what is true — the state was\n * not consulted successfully, so this span is unpaired and no end can complete it\n * — and carries a discriminator so the record cannot claim the span id a later end\n * will publish for the same scope.\n */\nconst effectiveCorrelation = (\n group: SpanGroup,\n correlation: SpanCorrelation | undefined,\n): SpanCorrelation | undefined => {\n if (correlation !== undefined || group.end !== undefined || group.start === undefined) {\n return correlation;\n }\n return {\n providerId: group.start.provenance.providerId,\n sessionId: group.start.sessionId,\n ref: group.ref,\n pairing: \"unpaired\",\n orphan: \"state-unavailable\",\n disposition: \"emit\",\n spanIdDiscriminator: group.start.eventId,\n };\n};\n\n/** How one batch's events distribute over the lifecycle scopes they are edges of. */\ntype BatchLayout = {\n readonly groups: ReadonlyMap<string, SpanGroup>;\n readonly standalone: readonly CanonicalEvent[];\n /** Event id of each lifecycle edge, mapped to the group key it belongs to. */\n readonly groupOf: ReadonlyMap<string, string>;\n};\n\nconst layoutBatch = (events: readonly CanonicalEvent[]): BatchLayout => {\n const groups = new Map<string, SpanGroup>();\n const standalone: CanonicalEvent[] = [];\n const groupOf = new Map<string, string>();\n\n for (const event of events) {\n const ref = spanScopeRefOf(event);\n if (ref === undefined) {\n standalone.push(event);\n continue;\n }\n const groupKey = correlationKey(event.provenance.providerId, event.sessionId, ref);\n const group: SpanGroup = groups.get(groupKey) ?? { ref };\n if (event.type.endsWith(\".start\")) {\n group.start = event;\n } else {\n group.end = event;\n }\n groups.set(groupKey, group);\n groupOf.set(event.eventId, groupKey);\n }\n return { groups, standalone, groupOf };\n};\n\nconst indexCorrelations = (\n correlations: readonly SpanCorrelation[] | undefined,\n): ReadonlyMap<string, SpanCorrelation> => {\n const indexed = new Map<string, SpanCorrelation>();\n for (const correlation of correlations ?? []) {\n indexed.set(\n correlationKey(correlation.providerId, correlation.sessionId, correlation.ref),\n correlation,\n );\n }\n return indexed;\n};\n\n/**\n * What this batch does with one lifecycle scope, decided once.\n *\n * Both the span mapping and the log mapping need the *same* answer to \"which\n * span id identifies this scope, and is a record for it going out now?\" — a log\n * record whose `spanContext` names a span id the exporter never published would\n * dangle at the collector. Computing it in one place is what keeps the two\n * signals pointing at the same span rather than at two plausible derivations of\n * it.\n */\ntype GroupPlan = {\n readonly group: SpanGroup;\n /** The event the span's identity and provenance are read from. */\n readonly anchor: CanonicalEvent;\n /**\n * False when the start is deferred: the state store is holding it and the end\n * edge will publish the one complete span, so nothing is exported for it now.\n */\n readonly emits: boolean;\n readonly correlation: SpanCorrelation | undefined;\n readonly traceId: string;\n readonly spanId: string;\n};\n\nconst planGroup = (\n group: SpanGroup,\n correlation: SpanCorrelation | undefined,\n correlationAvailable: boolean | undefined,\n): GroupPlan | undefined => {\n const anchor = group.start ?? group.end;\n if (anchor === undefined) {\n // Unreachable: a group exists only because an event was filed into it.\n return undefined;\n }\n const providerId = anchor.provenance.providerId;\n const sessionId = anchor.sessionId;\n\n // A start with no end in this batch is dropped **only** when something states\n // that it is durably recorded, because its span id is a pure function of the\n // scope: emitting here and again at the end edge would put two records with one\n // id on the wire, and OTLP has no update operation.\n //\n // `defer` is that statement, and it is the correlator's to make — it just wrote\n // the record. Anything else means nothing is holding this start, so dropping it\n // would lose an observation that was neither persisted nor exported, while the\n // caller saw zero rejections and marked the callback handled. Those are exported\n // under a discriminated span id instead.\n const durablyRecorded =\n group.end === undefined &&\n (correlation?.disposition === \"defer\" ||\n // No correlator wired at all: cross-process pairing was never on offer, so\n // this is the documented no-state-root degradation rather than a failure to\n // persist something that should have been persisted.\n (correlation === undefined && correlationAvailable === undefined));\n\n // A deferred start keeps the scope's *plain* span id, because that is the id the\n // end edge will publish. Only a record actually going out now may claim a\n // discriminated one.\n const effective = durablyRecorded ? correlation : effectiveCorrelation(group, correlation);\n const discriminator = durablyRecorded ? undefined : effective?.spanIdDiscriminator;\n\n return {\n group,\n anchor,\n emits: !durablyRecorded,\n correlation: effective,\n traceId: deriveTraceId(providerId, sessionId),\n spanId:\n discriminator === undefined\n ? deriveSpanId(providerId, sessionId, group.ref)\n : digestHex(\n [\n \"otelhook/span\",\n providerId,\n sessionId,\n group.ref.family,\n group.ref.scopeKey,\n discriminator,\n ],\n 16,\n ),\n };\n};\n\n/** Trace and span a record derived from one canonical event belongs to. */\nexport type EventTraceIdentity = {\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n};\n\n/**\n * Resolve the trace and span identity of every event in one batch.\n *\n * Exposed for signals other than traces — a log record correlates by carrying\n * the *same* derived ids the span mapping would compute, including the deferred\n * and discriminated cases. Whole batch at once because a start's identity\n * depends on whether its end is in the same batch.\n *\n * Both ids come from the event's own `(providerId, sessionId)`, never from a\n * batch-level or module-level value, which is what makes cross-session\n * contamination structurally impossible: two sessions in one batch derive two\n * different trace ids.\n */\nexport const canonicalEventTraceIdentities = (\n events: readonly CanonicalEvent[],\n options: {\n readonly correlations?: readonly SpanCorrelation[];\n readonly correlationAvailable?: boolean;\n } = {},\n): ReadonlyMap<string, EventTraceIdentity> => {\n const layout = layoutBatch(events);\n const correlations = indexCorrelations(options.correlations);\n const plans = new Map<string, GroupPlan>();\n for (const [groupKey, group] of layout.groups) {\n const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);\n if (plan !== undefined) {\n plans.set(groupKey, plan);\n }\n }\n\n const identities = new Map<string, EventTraceIdentity>();\n for (const event of events) {\n const providerId = event.provenance.providerId;\n const groupKey = layout.groupOf.get(event.eventId);\n const plan = groupKey === undefined ? undefined : plans.get(groupKey);\n if (plan === undefined) {\n const parent = parentScopeRefOf(event);\n identities.set(event.eventId, {\n traceId: deriveTraceId(providerId, event.sessionId),\n spanId: deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId),\n ...(parent === undefined\n ? {}\n : { parentSpanId: deriveSpanId(providerId, event.sessionId, parent) }),\n });\n continue;\n }\n const parent = plan.correlation?.parent ?? parentScopeRefOf(event);\n identities.set(event.eventId, {\n traceId: plan.traceId,\n spanId: plan.spanId,\n ...(parent === undefined\n ? {}\n : { parentSpanId: deriveSpanId(providerId, event.sessionId, parent) }),\n });\n }\n return identities;\n};\n\n/** Maps one invocation's canonical event batch into OTLP-ready spans. */\nexport const canonicalEventsToReadableSpans = (\n events: readonly CanonicalEvent[],\n options: SemanticMappingOptions,\n): readonly ReadableSpan[] => {\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const layout = layoutBatch(events);\n const correlations = indexCorrelations(options.correlations);\n\n const spans: ReadableSpan[] = [];\n for (const [groupKey, group] of layout.groups) {\n const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);\n if (plan === undefined || !plan.emits) {\n continue;\n }\n spans.push(buildLifecycleSpan(plan, options.resource, scope));\n }\n for (const event of layout.standalone) {\n spans.push(buildStandaloneSpan(event, options.resource, scope));\n }\n return spans;\n};\n","/**\n * Package version, kept in its own module so the CLI can report it without\n * importing the whole library barrel (and every provider adapter with it).\n *\n * Updated by `scripts/release/sync-version.mjs` during semantic-release.\n */\nexport const VERSION = \"0.13.0\";\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 {\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 { createHash } from \"node:crypto\";\nimport { open, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport type { PayloadEnricher, PayloadEnrichment, ReadCursor } from \"../../runtime/ports.js\";\nimport { CLAUDE_CODE_PROVIDER_ID } from \"./detect.js\";\nimport type { ClaudeUsage } from \"./schema.js\";\nimport { coerceClaudeUsage } from \"./usage.js\";\n\n/**\n * Bounded readers for one Claude Code session transcript, and the enricher that\n * uses them to attach a turn's model and token usage to a `Stop` payload.\n *\n * None of this is part of the Claude Code adapter, and the adapter never calls\n * it: `ProviderContext` gives adapters no filesystem handle (ADR 0003). Two\n * callers use it instead:\n *\n * - a wrapping harness, through {@link attachClaudeTranscriptTurn}, which reads\n * the last assistant message only;\n * - the hook runtime, through {@link createClaudeTranscriptUsageEnricher}, when\n * the host turns on `providers.claudeCode.readTranscriptUsage` — the one\n * sanctioned exception to \"no transcript reads in the hook\". It sums the whole\n * turn, from a byte cursor the runtime keeps in the state store.\n *\n * Why the transcript at all: no Claude Code hook callback carries a token\n * counter, and only `SessionStart` names a model. The per-turn model\n * (`message.model`, which follows `/model`) and the Anthropic usage object\n * (`message.usage`) exist only on assistant transcript records, one record per\n * content block, each repeating its request's `message.id`.\n *\n * Every bound is hard, and nothing here throws:\n * - only regular `.jsonl` files at an absolute path are opened, so a FIFO or a\n * device cannot stall the hook, and no directory is ever listed;\n * - a read is capped in bytes and raced against a time budget;\n * - a malformed or truncated line is skipped, never fatal.\n *\n * Nothing but model ids and numeric counters leaves this module: a record's\n * content (prompt, response, thinking, tool input) is parsed only to be dropped.\n */\n\nexport type ClaudeTranscriptUnavailableReason =\n | \"invalid-path\"\n | \"not-a-file\"\n | \"unreadable\"\n | \"timeout\"\n | \"no-assistant-message\";\n\nexport type ClaudeTranscriptTurn =\n | {\n readonly status: \"found\";\n /** `message.model`; absent when the record named none. */\n readonly model?: string;\n /** `message.usage`, coerced onto the shape the `Stop` schema accepts. */\n readonly usage?: ClaudeUsage;\n }\n | { readonly status: \"unavailable\"; readonly reason: ClaudeTranscriptUnavailableReason };\n\nexport type ReadClaudeTranscriptTurnOptions = {\n /** Bytes read from the end of the file. Default 1 MiB, clamped to 64 KiB..16 MiB. */\n readonly maxTailBytes?: number;\n /** Budget for the whole read. Default 250 ms, clamped to 10 ms..5 s. */\n readonly timeoutMillis?: number;\n};\n\nexport const DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES = 1_048_576;\nexport const DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS = 250;\nexport const DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES = 8_388_608;\nexport const DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS = 500;\n\nconst MIN_TAIL_BYTES = 65_536;\nconst MAX_TAIL_BYTES = 16_777_216;\nconst MAX_RANGE_BYTES = 67_108_864;\nconst MIN_TIMEOUT_MILLIS = 10;\nconst MAX_TIMEOUT_MILLIS = 5_000;\n/** Longer than any real model id; a longer value is not one. */\nconst MAX_MODEL_ID_LENGTH = 256;\n/** Bounds the request ids held while summing one range. */\nconst MAX_REQUESTS_PER_RANGE = 10_000;\n/**\n * Claude Code writes `<synthetic>` as the model of assistant records it made up\n * itself (an API error, an interrupted turn). Those name no real model and carry\n * zeroed usage, so they are skipped.\n */\nconst SYNTHETIC_MODEL = \"<synthetic>\";\n\nconst TIMED_OUT = Symbol(\"timed-out\");\n\nconst clamp = (value: number | undefined, fallback: number, min: number, max: number): number => {\n if (value === undefined || !Number.isFinite(value)) {\n return fallback;\n }\n return Math.min(max, Math.max(min, Math.floor(value)));\n};\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\nconst isTranscriptPath = (transcriptPath: unknown): transcriptPath is string =>\n typeof transcriptPath === \"string\" &&\n transcriptPath.length > 0 &&\n !transcriptPath.includes(\"\\0\") &&\n path.isAbsolute(transcriptPath) &&\n path.extname(transcriptPath) === \".jsonl\";\n\n/**\n * A record of subagent `agentId`: a sidechain record naming that agent, or\n * naming none (the file is the agent's own; only a different name excludes it).\n */\nconst isRecordOfAgent = (record: Record<string, unknown>, agentId: string): boolean =>\n record.isSidechain === true && (typeof record.agentId !== \"string\" || record.agentId === agentId);\n\ntype AssistantRecord = { readonly id?: string; readonly model?: string; readonly usage?: ClaudeUsage };\n\n/**\n * The request id, model and usage of one transcript line, or `undefined` when\n * it is not a usable assistant record of the thread being read.\n *\n * Without `agentId` that thread is the main one: sidechain records are a\n * subagent's conversation, and the parent's `Stop` is not about them. With\n * `agentId` it is that subagent's, read from its own transcript\n * (`agent_transcript_path`), where every record is a sidechain record; a record\n * naming another agent is skipped.\n */\nconst assistantRecordOf = (line: string, agentId?: string): AssistantRecord | undefined => {\n // Cheap pre-filter: most lines are user, tool-result, or summary records, and\n // parsing every one of them would spend the budget on records never used.\n if (!line.includes('\"assistant\"')) {\n return undefined;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n return undefined;\n }\n const record = asRecord(parsed);\n if (record === undefined || record.type !== \"assistant\") {\n return undefined;\n }\n if (agentId === undefined ? record.isSidechain === true : !isRecordOfAgent(record, agentId)) {\n return undefined;\n }\n const message = asRecord(record.message);\n if (message === undefined || message.model === SYNTHETIC_MODEL) {\n return undefined;\n }\n const model =\n typeof message.model === \"string\" && message.model.length > 0 && message.model.length <= MAX_MODEL_ID_LENGTH\n ? message.model\n : undefined;\n const usage = coerceClaudeUsage(message.usage);\n if (model === undefined && usage === undefined) {\n return undefined;\n }\n const id =\n typeof message.id === \"string\" && message.id.length > 0 && message.id.length <= 256 ? message.id : undefined;\n return {\n ...(id === undefined ? {} : { id }),\n ...(model === undefined ? {} : { model }),\n ...(usage === undefined ? {} : { usage }),\n };\n};\n\nconst cacheCreationOf = (usage: ClaudeUsage): number =>\n usage.cache_creation_input_tokens ??\n (usage.cache_creation === undefined\n ? 0\n : (usage.cache_creation.ephemeral_5m_input_tokens ?? 0) + (usage.cache_creation.ephemeral_1h_input_tokens ?? 0));\n\n/**\n * Sum per-request usage into one turn total.\n *\n * Only the four counters are summed. The TTL split and `iterations[]` are\n * breakdowns of one request's counters (docs/claude-code-usage-contract.md,\n * findings 3 and 4); carrying them across requests would add nothing a consumer\n * reads, and the adapter would only audit them against the sums.\n */\nconst sumUsage = (usages: readonly ClaudeUsage[]): ClaudeUsage => {\n let input = 0;\n let output = 0;\n let cacheRead = 0;\n let cacheCreation = 0;\n for (const usage of usages) {\n input += usage.input_tokens;\n output += usage.output_tokens;\n cacheRead += usage.cache_read_input_tokens ?? 0;\n cacheCreation += cacheCreationOf(usage);\n }\n return {\n input_tokens: input,\n output_tokens: output,\n cache_read_input_tokens: cacheRead,\n cache_creation_input_tokens: cacheCreation,\n };\n};\n\n/** Race `work` against a budget; a rejection becomes `onError`. */\nconst withTimeout = async <T>(\n work: Promise<T>,\n timeoutMillis: number,\n onError: T,\n): Promise<T | typeof TIMED_OUT> => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(() => {\n resolve(TIMED_OUT);\n }, timeoutMillis);\n // A hook process must be free to exit the moment its real work is done.\n timer.unref();\n });\n try {\n return await Promise.race([work.catch(() => onError), timeout]);\n } finally {\n clearTimeout(timer);\n }\n};\n\ntype FileUnavailable = { readonly status: \"unavailable\"; readonly reason: \"not-a-file\" | \"unreadable\" };\n\ntype FileHandle = Awaited<ReturnType<typeof open>>;\n\n/** Open a regular file and run `body` with its handle and size; always closes. */\nconst withRegularFile = async <T>(\n transcriptPath: string,\n body: (handle: FileHandle, size: number) => Promise<T>,\n): Promise<T | FileUnavailable> => {\n let info;\n try {\n info = await stat(transcriptPath);\n } catch {\n return { status: \"unavailable\", reason: \"unreadable\" };\n }\n if (!info.isFile()) {\n return { status: \"unavailable\", reason: \"not-a-file\" };\n }\n let handle;\n try {\n handle = await open(transcriptPath, \"r\");\n } catch {\n return { status: \"unavailable\", reason: \"unreadable\" };\n }\n try {\n const { size } = await handle.stat();\n return await body(handle, size);\n } catch {\n return { status: \"unavailable\", reason: \"unreadable\" };\n } finally {\n await handle.close().catch(() => undefined);\n }\n};\n\nconst readBytes = async (handle: FileHandle, start: number, length: number): Promise<Buffer> => {\n const buffer = Buffer.alloc(length);\n let filled = 0;\n while (filled < length) {\n const { bytesRead } = await handle.read(buffer, filled, length - filled, start + filled);\n if (bytesRead === 0) {\n break;\n }\n filled += bytesRead;\n }\n return buffer.subarray(0, filled);\n};\n\n/** Offset just past the last complete line of `bytes`, read from `start`. */\nconst completeLinesEnd = (bytes: Buffer, start: number): number => {\n const lastNewline = bytes.lastIndexOf(0x0a);\n return lastNewline < 0 ? start : start + lastNewline + 1;\n};\n\ntype TailRead = { readonly turn: ClaudeTranscriptTurn; readonly endOffset: number };\n\nconst readTail = (\n transcriptPath: string,\n maxTailBytes: number,\n agentId: string | undefined,\n): Promise<TailRead | FileUnavailable> =>\n withRegularFile(transcriptPath, async (handle, size): Promise<TailRead> => {\n const length = Math.min(size, maxTailBytes);\n const start = size - length;\n const bytes = await readBytes(handle, start, length);\n const endOffset = completeLinesEnd(bytes, start);\n const lines = bytes.toString(\"utf8\").split(\"\\n\");\n // A tail that starts mid-file starts mid-line: that first fragment is not a\n // record, and parsing it could only fail or, worse, half-succeed.\n if (start > 0) {\n lines.shift();\n }\n for (let index = lines.length - 1; index >= 0; index -= 1) {\n const record = assistantRecordOf((lines[index] ?? \"\").trim(), agentId);\n if (record !== undefined) {\n return {\n turn: {\n status: \"found\",\n ...(record.model === undefined ? {} : { model: record.model }),\n ...(record.usage === undefined ? {} : { usage: record.usage }),\n },\n endOffset,\n };\n }\n }\n return { turn: { status: \"unavailable\", reason: \"no-assistant-message\" }, endOffset };\n });\n\nconst boundedTail = async (\n transcriptPath: string,\n options: ReadClaudeTranscriptTurnOptions,\n agentId?: string,\n): Promise<TailRead | FileUnavailable | typeof TIMED_OUT> =>\n withTimeout<TailRead | FileUnavailable>(\n readTail(\n transcriptPath,\n clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES),\n agentId,\n ),\n clamp(options.timeoutMillis, DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS, MIN_TIMEOUT_MILLIS, MAX_TIMEOUT_MILLIS),\n { status: \"unavailable\", reason: \"unreadable\" },\n );\n\n/**\n * Read the model and usage of the last main-thread assistant message in a\n * Claude Code transcript. Never throws, never rejects.\n *\n * The usage is that **one message's** — the final model request of the turn. A\n * turn that called tools made several requests, and the earlier ones are not\n * summed in; {@link readClaudeTranscriptRange} sums a whole turn.\n */\nexport const readClaudeTranscriptTurn = async (\n transcriptPath: string,\n options: ReadClaudeTranscriptTurnOptions = {},\n): Promise<ClaudeTranscriptTurn> => {\n if (!isTranscriptPath(transcriptPath)) {\n return { status: \"unavailable\", reason: \"invalid-path\" };\n }\n const read = await boundedTail(transcriptPath, options);\n if (read === TIMED_OUT) {\n return { status: \"unavailable\", reason: \"timeout\" };\n }\n return \"turn\" in read ? read.turn : read;\n};\n\nexport type ClaudeTranscriptRange =\n | {\n readonly status: \"found\";\n /** Model of the last main-thread assistant record in the range. */\n readonly model?: string;\n /** Summed usage of every distinct request; absent when none reported usage. */\n readonly usage?: ClaudeUsage;\n /** Distinct main-thread requests (by `message.id`) in the range. */\n readonly requestCount: number;\n /** Offset just past the last complete line read: the next range starts here. */\n readonly endOffset: number;\n }\n | {\n readonly status: \"unavailable\";\n readonly reason:\n | \"invalid-path\"\n | \"not-a-file\"\n | \"unreadable\"\n | \"timeout\"\n /** The file is shorter than the offset: it was replaced or truncated. */\n | \"truncated\"\n /** More than the range cap was written since the offset. */\n | \"over-cap\";\n };\n\nexport type ReadClaudeTranscriptRangeOptions = {\n /** Most bytes a range may span. Default 8 MiB, clamped to 64 KiB..64 MiB. */\n readonly maxRangeBytes?: number;\n /** Budget for the whole range read. Default 500 ms, clamped to 10 ms..5 s. */\n readonly rangeTimeoutMillis?: number;\n /**\n * Read subagent `agentId`'s requests (its sidechain records) instead of the\n * main thread's. For a subagent's own transcript, `agent_transcript_path`.\n */\n readonly agentId?: string;\n};\n\n/**\n * Sum every main-thread model request (or, with `agentId`, every request of that\n * subagent) written between `fromOffset` and the end of the transcript. Never\n * throws, never rejects.\n *\n * Records of one request share a `message.id` and each repeats its usage, so the\n * last record per id is the one counted; a record without an id counts alone.\n * A trailing partial line is left for the next range.\n */\nexport const readClaudeTranscriptRange = async (\n transcriptPath: string,\n fromOffset: number,\n options: ReadClaudeTranscriptRangeOptions = {},\n): Promise<ClaudeTranscriptRange> => {\n if (!isTranscriptPath(transcriptPath) || !Number.isSafeInteger(fromOffset) || fromOffset < 0) {\n return { status: \"unavailable\", reason: \"invalid-path\" };\n }\n const maxRangeBytes = clamp(options.maxRangeBytes, DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES, MIN_TAIL_BYTES, MAX_RANGE_BYTES);\n const timeoutMillis = clamp(\n options.rangeTimeoutMillis,\n DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS,\n MIN_TIMEOUT_MILLIS,\n MAX_TIMEOUT_MILLIS,\n );\n const work = withRegularFile(transcriptPath, async (handle, size): Promise<ClaudeTranscriptRange> => {\n if (size < fromOffset) {\n return { status: \"unavailable\", reason: \"truncated\" };\n }\n if (size - fromOffset > maxRangeBytes) {\n return { status: \"unavailable\", reason: \"over-cap\" };\n }\n const bytes = await readBytes(handle, fromOffset, size - fromOffset);\n const endOffset = completeLinesEnd(bytes, fromOffset);\n const complete = bytes.subarray(0, endOffset - fromOffset).toString(\"utf8\");\n const requests = new Map<string, AssistantRecord>();\n let anonymous = 0;\n let model: string | undefined;\n for (const line of complete.split(\"\\n\")) {\n const record = assistantRecordOf(line.trim(), options.agentId);\n if (record === undefined) {\n continue;\n }\n if (record.model !== undefined) {\n model = record.model;\n }\n anonymous += record.id === undefined ? 1 : 0;\n // The last record of a request carries its final usage, so it replaces the earlier ones.\n requests.set(record.id ?? `#${String(anonymous)}`, record);\n if (requests.size > MAX_REQUESTS_PER_RANGE) {\n return { status: \"unavailable\", reason: \"over-cap\" };\n }\n }\n const usages = [...requests.values()].flatMap((record) => (record.usage === undefined ? [] : [record.usage]));\n return {\n status: \"found\",\n ...(model === undefined ? {} : { model }),\n ...(usages.length === 0 ? {} : { usage: sumUsage(usages) }),\n requestCount: requests.size,\n endOffset,\n };\n });\n const result = await withTimeout<ClaudeTranscriptRange | FileUnavailable>(work, timeoutMillis, {\n status: \"unavailable\",\n reason: \"unreadable\",\n });\n return result === TIMED_OUT ? { status: \"unavailable\", reason: \"timeout\" } : result;\n};\n\nconst STOP_EVENTS: ReadonlySet<string> = new Set([\"Stop\", \"StopFailure\"]);\n\nconst hasUsage = (record: Record<string, unknown>): boolean =>\n record.usage !== undefined || record.token_usage !== undefined || record.tokenUsage !== undefined;\n\nconst eventNameOf = (record: Record<string, unknown>): unknown => record.hook_event_name ?? record.hookEventName;\nconst transcriptPathOf = (record: Record<string, unknown>): unknown =>\n record.transcript_path ?? record.transcriptPath;\n\n/**\n * Attach the last assistant message's `{ model, usage }` to a Claude Code\n * `Stop` / `StopFailure` payload, for a wrapper to hand to otel-hook.\n *\n * The usage is one request's, so it is attached with `usage_partial: true`,\n * which the exported generation reports as `otelhook.usage.partial`. For whole\n * turn totals, turn on `providers.claudeCode.readTranscriptUsage` instead.\n *\n * Returns the payload unchanged when it is not a stop, names no\n * `transcript_path`, already carries both fields, or the transcript yields\n * nothing — so a wrapper can call it unconditionally. A field the payload\n * already carries is never overwritten. Never throws, never rejects.\n */\nexport const attachClaudeTranscriptTurn = async (\n payload: unknown,\n options: ReadClaudeTranscriptTurnOptions = {},\n): Promise<unknown> => {\n const record = asRecord(payload);\n if (record === undefined) {\n return payload;\n }\n const eventName = eventNameOf(record);\n if (typeof eventName !== \"string\" || !STOP_EVENTS.has(eventName)) {\n return payload;\n }\n const transcriptPath = transcriptPathOf(record);\n if (typeof transcriptPath !== \"string\") {\n return payload;\n }\n const needsModel = record.model === undefined;\n const needsUsage = !hasUsage(record);\n if (!needsModel && !needsUsage) {\n return payload;\n }\n const turn = await readClaudeTranscriptTurn(transcriptPath, options);\n if (turn.status !== \"found\") {\n return payload;\n }\n return {\n ...record,\n ...(needsModel && turn.model !== undefined ? { model: turn.model } : {}),\n ...(needsUsage && turn.usage !== undefined ? { usage: turn.usage, usage_partial: true } : {}),\n };\n};\n\nexport type ClaudeTranscriptUsageEnricherOptions = ReadClaudeTranscriptTurnOptions &\n Omit<ReadClaudeTranscriptRangeOptions, \"agentId\">;\n\nexport const CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = \"claude-transcript-usage\";\n\n/** Opaque, path-free name for a transcript, stored beside its cursor. */\nconst sourceDigest = (transcriptPath: string): string =>\n createHash(\"sha256\").update(transcriptPath, \"utf8\").digest(\"hex\").slice(0, 32);\n\nconst SUBAGENT_STOP = \"SubagentStop\";\n\nconst agentIdOf = (record: Record<string, unknown>): string | undefined => {\n const agentId = record.agent_id ?? record.agentId;\n return typeof agentId === \"string\" && agentId.length > 0 && agentId.length <= 256 ? agentId : undefined;\n};\n\nconst agentTranscriptPathOf = (record: Record<string, unknown>): unknown =>\n record.agent_transcript_path ?? record.agentTranscriptPath;\n\n/**\n * The cursor scope of a `SubagentStop`: one cursor per subagent, beside the\n * session's own. An opaque digest of the agent id, never the id or a path.\n */\nconst subagentCursorScope = (payload: unknown): string | undefined => {\n const record = asRecord(payload);\n if (record === undefined || eventNameOf(record) !== SUBAGENT_STOP) {\n return undefined;\n }\n const agentId = agentIdOf(record);\n return agentId === undefined\n ? undefined\n : `agent-${createHash(\"sha256\").update(agentId, \"utf8\").digest(\"hex\").slice(0, 32)}`;\n};\n\n/**\n * The hook-runtime side of `providers.claudeCode.readTranscriptUsage`: attach\n * each turn's model and **summed** usage to its `Stop` / `StopFailure`, and each\n * subagent run's to its `SubagentStop`.\n *\n * The runtime keeps a byte cursor per session (state value `read-cursor`):\n *\n * - `SessionStart` records where the transcript ends now (0 when it does not\n * exist yet), unless a cursor for the same transcript is already stored — a\n * compaction restart must not skip the turn it interrupted.\n * - `Stop` sums every main-thread request from the cursor to the end, and moves\n * the cursor there. That is the exact turn total: `usage_partial: false`.\n * - With no usable cursor (enabled mid-session, an expired or lost store, a\n * different transcript), a range over the cap, or a transcript that shrank, it\n * falls back to the last request in the bounded tail, attaches it with\n * `usage_partial: true`, and moves the cursor to the end so the next turn is\n * exact again.\n * - A timeout or an unreadable file attaches nothing and keeps the cursor, so\n * the next turn's range includes this one: tokens are counted late, never\n * twice and never lost.\n *\n * `SubagentStop` does the same over the subagent's own transcript\n * (`agent_transcript_path`), with a cursor of its own per subagent (see\n * {@link PayloadEnricher.cursorScope}), summing that agent's sidechain records.\n * A subagent with no cursor yet is read from the start of its file: the file is\n * that subagent's alone, so the first stop is its exact total, not a fallback.\n * The parent's cursor is never touched, and the parent's `Stop` never counts\n * sidechain records, so a subagent's requests are counted once, on its own\n * generation (issue #68).\n *\n * A payload that already carries `usage` (a wrapper attached it) is left as it\n * is, and the cursor moves past it so those tokens are not counted again.\n */\nexport const createClaudeTranscriptUsageEnricher = (\n options: ClaudeTranscriptUsageEnricherOptions = {},\n): PayloadEnricher => {\n const fileSize = async (transcriptPath: string): Promise<number | \"absent\" | undefined> => {\n try {\n const info = await stat(transcriptPath);\n return info.isFile() ? info.size : undefined;\n } catch (thrown) {\n return (thrown as { code?: unknown } | undefined)?.code === \"ENOENT\" ? \"absent\" : undefined;\n }\n };\n\n const readOptions = (agentId: string | undefined): ReadClaudeTranscriptRangeOptions => ({\n ...(options.maxRangeBytes === undefined ? {} : { maxRangeBytes: options.maxRangeBytes }),\n ...(options.rangeTimeoutMillis === undefined ? {} : { rangeTimeoutMillis: options.rangeTimeoutMillis }),\n ...(agentId === undefined ? {} : { agentId }),\n });\n\n /**\n * Sum one transcript since `fromOffset` and attach the result, or fall back to\n * the bounded tail. `fromOffset` undefined means there is no usable cursor.\n */\n const attachSince = async (\n record: Record<string, unknown>,\n transcriptPath: string,\n fromOffset: number | undefined,\n agentId: string | undefined,\n ): Promise<PayloadEnrichment> => {\n const source = sourceDigest(transcriptPath);\n const attach = (\n model: string | undefined,\n usage: ClaudeUsage | undefined,\n partial: boolean,\n ): Record<string, unknown> => ({\n ...record,\n ...(record.model === undefined && model !== undefined ? { model } : {}),\n ...(usage === undefined ? {} : { usage, usage_partial: partial }),\n });\n\n if (fromOffset !== undefined) {\n const range = await readClaudeTranscriptRange(transcriptPath, fromOffset, readOptions(agentId));\n if (range.status === \"found\") {\n return {\n payload: attach(range.model, range.usage, false),\n cursor: { source, offset: range.endOffset },\n notes: [`summed ${String(range.requestCount)} request(s) since the last stop`],\n };\n }\n if (range.reason !== \"truncated\" && range.reason !== \"over-cap\") {\n return { payload: record, notes: [`transcript range not read (${range.reason}); cursor kept`] };\n }\n }\n\n // No usable cursor, or a range that cannot be summed within bounds.\n const tail = await boundedTail(transcriptPath, options, agentId);\n if (tail === TIMED_OUT || !(\"turn\" in tail)) {\n return { payload: record, notes: [`transcript tail not read (${tail === TIMED_OUT ? \"timeout\" : tail.reason})`] };\n }\n const why = fromOffset === undefined ? \"no cursor for this transcript\" : \"range not summable within bounds\";\n return {\n payload: tail.turn.status === \"found\" ? attach(tail.turn.model, tail.turn.usage, true) : record,\n cursor: { source, offset: tail.endOffset },\n notes: [`${why}; attached the last request only (usage_partial)`],\n };\n };\n\n /** A wrapper attached usage: keep it, and move the cursor past what it covered. */\n const skipAttached = async (payload: unknown, transcriptPath: string): Promise<PayloadEnrichment> => {\n const size = await fileSize(transcriptPath);\n return typeof size === \"number\"\n ? { payload, cursor: { source: sourceDigest(transcriptPath), offset: size } }\n : { payload };\n };\n\n const enrich = async (input: {\n readonly payload: unknown;\n readonly cursor?: ReadCursor;\n }): Promise<PayloadEnrichment> => {\n const unchanged: PayloadEnrichment = { payload: input.payload };\n const record = asRecord(input.payload);\n if (record === undefined) {\n return unchanged;\n }\n const eventName = eventNameOf(record);\n\n if (eventName === SUBAGENT_STOP) {\n const agentTranscriptPath = agentTranscriptPathOf(record);\n const agentId = agentIdOf(record);\n if (agentId === undefined || !isTranscriptPath(agentTranscriptPath)) {\n return unchanged;\n }\n if (hasUsage(record)) {\n return skipAttached(input.payload, agentTranscriptPath);\n }\n const cursor = input.cursor?.source === sourceDigest(agentTranscriptPath) ? input.cursor : undefined;\n return attachSince(record, agentTranscriptPath, cursor?.offset ?? 0, agentId);\n }\n\n const transcriptPath = transcriptPathOf(record);\n if (typeof eventName !== \"string\" || !isTranscriptPath(transcriptPath)) {\n return unchanged;\n }\n const source = sourceDigest(transcriptPath);\n const cursor = input.cursor?.source === source ? input.cursor : undefined;\n\n if (eventName === \"SessionStart\") {\n if (cursor !== undefined) {\n return unchanged;\n }\n const size = await fileSize(transcriptPath);\n if (size === undefined) {\n return { ...unchanged, notes: [\"transcript is not a readable regular file; no cursor recorded\"] };\n }\n return { payload: input.payload, cursor: { source, offset: size === \"absent\" ? 0 : size } };\n }\n\n if (!STOP_EVENTS.has(eventName)) {\n return unchanged;\n }\n if (hasUsage(record)) {\n return skipAttached(input.payload, transcriptPath);\n }\n return attachSince(record, transcriptPath, cursor?.offset, undefined);\n };\n\n return Object.freeze({\n id: CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,\n providerId: CLAUDE_CODE_PROVIDER_ID,\n cursorScope: subagentCursorScope,\n enrich,\n });\n};\n","import { z } from \"zod\";\n\nimport type { AttributionOutcome, AttributionReason, OtelHookErrorInfo } from \"../errors/index.js\";\nimport {\n canonicalEventTypeSchema,\n type CanonicalEvent,\n type CanonicalEventType,\n type ModelDescriptor,\n} 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 * The model this session last reported, as the core remembers it across\n * invocations (`session.start` or a `generation.*` edge with a known model).\n *\n * Read from the state store by the core and handed in, because an adapter must\n * not hold cross-invocation state itself (ADR 0006). Absent when no earlier\n * invocation of this session named a model, or when the store is unreadable.\n * An adapter whose generation callbacks carry no model id (Claude Code's\n * `Stop`) uses it instead of the `unknown` sentinel; one whose callbacks carry\n * their own model can ignore it.\n */\n readonly sessionModel?: ModelDescriptor;\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\n/**\n * Raw Claude Code hook payload shapes.\n *\n * Field names and event names are taken from Claude Code's published hooks\n * reference (`code.claude.com/docs/en/hooks`). Objects are intentionally\n * non-strict: an unrecognized field is ignored rather than rejected, so a\n * protocol addition does not break detection or parsing. Discriminants\n * (`hook_event_name`, and the enum-shaped fields we do constrain) are strict.\n */\n\n/** Fields Claude Code includes on effectively every hook invocation. */\nconst commonFields = {\n session_id: z.string().min(1),\n transcript_path: z.string().min(1).optional(),\n cwd: z.string().min(1).optional(),\n permission_mode: z.string().min(1).optional(),\n /** Correlates a hook firing with the user prompt that triggered it (Claude Code v2.1.196+). */\n prompt_id: z.string().min(1).optional(),\n /** Present when the hook fired while running inside a subagent. */\n agent_id: z.string().min(1).optional(),\n agent_type: z.string().min(1).optional(),\n};\n\n/**\n * Cache-creation tokens split by cache TTL.\n *\n * A *breakdown* of `cache_creation_input_tokens`, not tokens beside it: the two\n * sub-buckets summed to that counter in 4,999 of 4,999 real usage objects. See\n * `usage.ts` for why they are verified and never added, and\n * docs/claude-code-usage-contract.md (finding 3) for the capture.\n */\nexport const claudeCacheCreationSchema = z.object({\n ephemeral_5m_input_tokens: z.number().int().min(0).optional(),\n ephemeral_1h_input_tokens: z.number().int().min(0).optional(),\n});\n\n/**\n * One model request inside a turn that took more than one.\n *\n * Also a breakdown: the per-iteration counters summed to the outer counters\n * exactly, for all four fields, in every capture (finding 4).\n */\nexport const claudeUsageIterationSchema = z.object({\n input_tokens: z.number().int().min(0).optional(),\n output_tokens: z.number().int().min(0).optional(),\n cache_creation_input_tokens: z.number().int().min(0).optional(),\n cache_read_input_tokens: z.number().int().min(0).optional(),\n});\n\n/**\n * Anthropic Messages API usage shape, as a wrapping harness may attach it\n * after correlating a hook firing with the transcript.\n *\n * **No Claude Code hook callback carries this object.** Confirmed against the\n * CLI's own hook-input schemas at 2.1.220: not `Stop`, not `SubagentStop`, not\n * `PostCompact` — no hook event in the protocol reports a token counter at all\n * (docs/claude-code-usage-contract.md, finding 1). The tokens exist only at\n * `message.usage` in the transcript, and this adapter never reads the transcript\n * itself (AGENTS.md and ADR 0003: an adapter has no filesystem handle). So the\n * field is accepted only when a caller has already placed it on the payload, and\n * the shape mirrors `message.usage` exactly so a harness can attach what it read\n * without reshaping it — `readClaudeTranscriptTurn` / `attachClaudeTranscriptTurn`\n * (`transcript.ts`) are the bounded helper a wrapper can call to do that.\n *\n * `input_tokens` is the **fresh** portion of the prompt only; cache reads and\n * cache writes are separate, additive buckets (finding 2). `usage.ts` documents\n * the fold that turns those three into the canonical inclusive total.\n */\nexport const claudeUsageSchema = z.object({\n input_tokens: z.number().int().min(0),\n output_tokens: z.number().int().min(0),\n cache_creation_input_tokens: z.number().int().min(0).optional(),\n cache_read_input_tokens: z.number().int().min(0).optional(),\n cache_creation: claudeCacheCreationSchema.optional(),\n iterations: z.array(claudeUsageIterationSchema).optional(),\n /**\n * Counters the canonical model has a home for but Claude Code never reports:\n * 0 of 4,999 real usage objects carried either (finding 5).\n *\n * Named here rather than left to the object's forward-compatible looseness so\n * that a harness attaching one gets told it was excluded, instead of watching\n * it vanish. See `CLAUDE_EXCLUDED_USAGE_COUNTERS`.\n */\n total_tokens: z.number().int().min(0).optional(),\n reasoning_output_tokens: z.number().int().min(0).optional(),\n});\nexport type ClaudeUsage = z.infer<typeof claudeUsageSchema>;\n\nexport const sessionStartPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"SessionStart\"),\n /** Matcher values: startup | resume | clear | compact | fork. Forward-compatible: any string. */\n source: z.string().min(1).optional(),\n model: z.string().min(1).optional(),\n session_title: z.string().min(1).optional(),\n});\nexport type SessionStartPayload = z.infer<typeof sessionStartPayloadSchema>;\n\nexport const sessionEndPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"SessionEnd\"),\n /** Current Claude Code field; values include clear, logout, prompt_input_exit, and other. */\n reason: z.string().min(1).optional(),\n /** Compatibility alias emitted by older wrappers and hook integrations. */\n end_reason: z.string().min(1).optional(),\n});\nexport type SessionEndPayload = z.infer<typeof sessionEndPayloadSchema>;\n\nexport const userPromptSubmitPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"UserPromptSubmit\"),\n prompt: z.string(),\n});\nexport type UserPromptSubmitPayload = z.infer<typeof userPromptSubmitPayloadSchema>;\n\nexport const preToolUsePayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"PreToolUse\"),\n tool_name: z.string().min(1),\n tool_input: z.unknown(),\n tool_use_id: z.string().min(1),\n});\nexport type PreToolUsePayload = z.infer<typeof preToolUsePayloadSchema>;\n\nexport const postToolUsePayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"PostToolUse\"),\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n tool_response: z.unknown(),\n tool_use_id: z.string().min(1),\n});\nexport type PostToolUsePayload = z.infer<typeof postToolUsePayloadSchema>;\n\nexport const postToolUseFailurePayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"PostToolUseFailure\"),\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n tool_error: z.unknown(),\n tool_use_id: z.string().min(1),\n});\nexport type PostToolUseFailurePayload = z.infer<typeof postToolUseFailurePayloadSchema>;\n\nexport const permissionRequestPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"PermissionRequest\"),\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n tool_use_id: z.string().min(1),\n});\nexport type PermissionRequestPayload = z.infer<typeof permissionRequestPayloadSchema>;\n\nexport const subagentStartPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"SubagentStart\"),\n agent_type: z.string().min(1),\n agent_id: z.string().min(1),\n});\nexport type SubagentStartPayload = z.infer<typeof subagentStartPayloadSchema>;\n\nexport const subagentStopPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"SubagentStop\"),\n agent_type: z.string().min(1),\n agent_id: z.string().min(1),\n last_assistant_message: z.string().optional(),\n /** True when this stop fired because a hook continued the subagent's turn. */\n stop_hook_active: z.boolean().optional(),\n /**\n * The subagent run's tokens since its previous stop — harness- or\n * enricher-supplied, never upstream. Reported on the subagent's own\n * generation, never on the parent turn (issue #68).\n */\n usage: claudeUsageSchema.optional(),\n /** Harness-supplied, never upstream: the subagent's model, from its transcript. */\n model: z.string().min(1).max(256).optional().catch(undefined),\n /** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */\n usage_partial: z.boolean().optional().catch(undefined),\n});\nexport type SubagentStopPayload = z.infer<typeof subagentStopPayloadSchema>;\n\n/**\n * Compaction callbacks.\n *\n * The upstream contract at 2.1.220 is `PreCompact { trigger, custom_instructions }`\n * and `PostCompact { trigger, compact_summary }`. **Neither reports a token\n * count** — no context size before or after, no dropped-message count\n * (docs/claude-code-usage-contract.md, finding 6). The counters below are\n * accepted for a wrapping harness that computed them; they are not a claim that\n * Claude Code sends them, and `capabilities.ts` excludes `contextTokensBefore`\n * accordingly.\n *\n * `custom_instructions` and `compact_summary` are deliberately absent. The\n * summary is a model-generated précis of the conversation — content — and\n * compaction telemetry needs the trigger and the sizes, not the text. Both are\n * ignored by the object's forward-compatible looseness rather than read and\n * screened, so there is no path by which they could reach an event.\n */\nexport const preCompactPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"PreCompact\"),\n /** Upstream values: manual | auto. Forward-compatible: any string. */\n trigger: z.string().min(1).optional(),\n /** Compatibility alias emitted by older wrappers and hook integrations. */\n compact_trigger: z.string().min(1).optional(),\n /**\n * Harness-supplied, never upstream. Reported as an explicit exclusion rather\n * than carried across the process boundary: see `events.ts`.\n */\n context_tokens_before: z.number().int().min(0).optional(),\n estimated_tokens_removed: z.number().int().min(0).optional(),\n});\nexport type PreCompactPayload = z.infer<typeof preCompactPayloadSchema>;\n\nexport const postCompactPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"PostCompact\"),\n trigger: z.string().min(1).optional(),\n compact_trigger: z.string().min(1).optional(),\n /** Harness-supplied, never upstream; accepted here because one callback carries both. */\n context_tokens_before: z.number().int().min(0).optional(),\n context_tokens_after: z.number().int().min(0).optional(),\n dropped_message_count: z.number().int().min(0).optional(),\n usage: claudeUsageSchema.optional(),\n});\nexport type PostCompactPayload = z.infer<typeof postCompactPayloadSchema>;\n\nexport const stopPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"Stop\"),\n /**\n * Interactive Stop field (Claude Code ≥ 2.1.47). Print / `-p` / Agent SDK\n * result messages use `result` instead; `events.ts` reads both (and camelCase\n * `lastAssistantMessage`) through `extractClaudeAssistantText`.\n */\n last_assistant_message: z.string().optional(),\n /** Print / `-p` JSON result field; accepted so a harness can attach it as-is. */\n result: z.string().optional(),\n /**\n * True when this stop fired because a hook continued the turn.\n *\n * Required upstream, optional here. It is what separates the once-per-prompt\n * stop from a continuation stop, which is what lets `delivery.ts` deduplicate\n * the former without suppressing the latter.\n */\n stop_hook_active: z.boolean().optional(),\n usage: claudeUsageSchema.optional(),\n /**\n * The model that answered this turn — harness-supplied, never upstream.\n *\n * Claude Code's `Stop` carries no model id; the per-turn model sits only at\n * `message.model` in the transcript, beside `message.usage`. A wrapping harness\n * that read it (for instance with `readClaudeTranscriptTurn`) attaches it here\n * with `usage`, and it becomes the generation's response model. An unusable\n * value (empty, over 256 characters, not a string) is dropped rather than\n * failing the whole payload: the turn is still worth reporting without it.\n */\n model: z.string().min(1).max(256).optional().catch(undefined),\n /**\n * Harness-supplied, never upstream: whether `usage` covers only part of the\n * turn. `true` when it is the last model request alone (the tail fallback),\n * `false` when it sums every request since the previous stop. Exported as\n * `otelhook.usage.partial`; absent means the attacher did not say.\n */\n usage_partial: z.boolean().optional().catch(undefined),\n});\nexport type StopPayload = z.infer<typeof stopPayloadSchema>;\n\nexport const stopFailurePayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"StopFailure\"),\n /**\n * Matcher values: rate_limit | overloaded | authentication_failed |\n * oauth_org_not_allowed | billing_error | invalid_request | model_not_found\n * | server_error | max_output_tokens | unknown.\n */\n error_type: z.string().min(1),\n error_message: z.string().optional(),\n usage: claudeUsageSchema.optional(),\n /** Harness-supplied, never upstream: see `stopPayloadSchema.model`. */\n model: z.string().min(1).max(256).optional().catch(undefined),\n /** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */\n usage_partial: z.boolean().optional().catch(undefined),\n});\nexport type StopFailurePayload = z.infer<typeof stopFailurePayloadSchema>;\n\nexport const claudeHookPayloadSchema = z.discriminatedUnion(\"hook_event_name\", [\n sessionStartPayloadSchema,\n sessionEndPayloadSchema,\n userPromptSubmitPayloadSchema,\n preToolUsePayloadSchema,\n postToolUsePayloadSchema,\n postToolUseFailurePayloadSchema,\n permissionRequestPayloadSchema,\n subagentStartPayloadSchema,\n subagentStopPayloadSchema,\n preCompactPayloadSchema,\n postCompactPayloadSchema,\n stopPayloadSchema,\n stopFailurePayloadSchema,\n]);\nexport type ClaudeHookPayload = z.infer<typeof claudeHookPayloadSchema>;\n\n/** Every `hook_event_name` this adapter recognizes. */\nexport const CLAUDE_HOOK_EVENT_NAMES = [\n \"SessionStart\",\n \"SessionEnd\",\n \"UserPromptSubmit\",\n \"PreToolUse\",\n \"PostToolUse\",\n \"PostToolUseFailure\",\n \"PermissionRequest\",\n \"SubagentStart\",\n \"SubagentStop\",\n \"PreCompact\",\n \"PostCompact\",\n \"Stop\",\n \"StopFailure\",\n] as const;\nexport type ClaudeHookEventName = (typeof CLAUDE_HOOK_EVENT_NAMES)[number];\n\n/**\n * Minimal shape identity resolution needs. Deliberately looser than\n * {@link claudeHookPayloadSchema}: a payload that is missing an\n * event-specific field (e.g. `PreToolUse` without `tool_use_id`) can still be\n * attributed to a session, so the deeper failure surfaces from `parse`\n * instead of silently declining attribution.\n */\nexport const claudeIdentityFieldsSchema = z.object({\n session_id: z.string().min(1),\n hook_event_name: z.string().min(1),\n cwd: z.string().min(1).optional(),\n prompt_id: z.string().min(1).optional(),\n agent_id: z.string().min(1).optional(),\n tool_use_id: z.string().min(1).optional(),\n /** Read by `delivery.ts` to tell a once-per-prompt stop from a continuation. */\n stop_hook_active: z.boolean().optional(),\n});\nexport type ClaudeIdentityFields = z.infer<typeof claudeIdentityFieldsSchema>;\n","import { normalizeUsage, type CanonicalUsage } from \"../../model/index.js\";\nimport { claudeUsageSchema, type ClaudeUsage } from \"./schema.js\";\n\nexport type ClaudeUsageNormalization = {\n readonly usage?: CanonicalUsage;\n readonly warnings: readonly string[];\n};\n\n/**\n * Counters this adapter deliberately does not read.\n *\n * Both are absent from Claude Code's usage shape — 0 of 4,999 real usage objects\n * carried either (docs/claude-code-usage-contract.md, finding 5) — and both have\n * a home in the canonical model, which is exactly why reading a\n * harness-supplied one would be wrong: `providerTotalAgreement` would start\n * reporting `agrees`/`disagrees` for a provider that reports no total, and\n * `reasoningOutputTokens` would carry a figure `reportsReasoningOutput: false`\n * says does not exist. A consumer's ability to tell \"not reported\" from \"zero\"\n * depends on the capability declaration staying true.\n *\n * So the field is excluded and *said out loud*, rather than silently dropped.\n */\nexport const CLAUDE_EXCLUDED_USAGE_COUNTERS = Object.freeze({\n total_tokens:\n \"usage.total_tokens is outside Claude Code's usage contract (capability reportsProviderTotal=false): \" +\n \"it is not read, so providerTotalAgreement stays \\\"unreported\\\"\",\n reasoning_output_tokens:\n \"usage.reasoning_output_tokens is outside Claude Code's usage contract (capability \" +\n \"reportsReasoningOutput=false): Anthropic bills thinking tokens inside output_tokens with no separate \" +\n \"counter, so it is not read and reasoningOutputTokens stays 0\",\n});\n\n/** The four counters `usage.iterations[]` itemizes, and the outer fields they must match. */\nconst ITERATION_COUNTERS = [\n \"input_tokens\",\n \"output_tokens\",\n \"cache_read_input_tokens\",\n \"cache_creation_input_tokens\",\n] as const;\n\n/**\n * Cache-creation tokens split by TTL, or `undefined` when the split is absent.\n *\n * The two sub-buckets summed to `cache_creation_input_tokens` in every capture,\n * so this is a *breakdown* to reconcile against, never an addend.\n */\nconst ttlSplitTotal = (raw: ClaudeUsage): number | undefined => {\n const split = raw.cache_creation;\n if (split === undefined) {\n return undefined;\n }\n return (split.ephemeral_5m_input_tokens ?? 0) + (split.ephemeral_1h_input_tokens ?? 0);\n};\n\n/**\n * Settle on one cache-creation figure from the two places it can be stated.\n *\n * The explicit counter wins when both are present: it is the billed total, and\n * preferring a sum of parts over a stated whole would let a future third TTL\n * bucket silently deflate it. A disagreement is reported rather than resolved\n * quietly, because only one of the two numbers can be the billing story.\n */\nconst resolveCacheCreationTokens = (raw: ClaudeUsage, warnings: string[]): number => {\n const declared = raw.cache_creation_input_tokens;\n const split = ttlSplitTotal(raw);\n if (declared === undefined) {\n // Only the TTL split was attached. Deriving the total is the whole point of\n // accepting the sub-object: the tokens were reported, just itemized.\n return split ?? 0;\n }\n if (split !== undefined && split !== declared) {\n warnings.push(\n `usage.cache_creation TTL buckets sum to ${String(split)} but ` +\n `usage.cache_creation_input_tokens reports ${String(declared)}; the explicit counter is used and the ` +\n `buckets are never added to it`,\n );\n }\n return declared;\n};\n\n/**\n * Reconcile `usage.iterations[]` against the outer counters without adding it.\n *\n * A multi-request turn itemizes the same tokens per model request, and the\n * per-iteration figures summed to the outer ones exactly in every capture. Adding\n * a breakdown to its own total is the archetypal double-count — it would double\n * every counter of every turn — so the sums are *checked* and a disagreement is\n * reported, which is the only reading under which either number could be wrong.\n */\nconst auditIterations = (\n raw: ClaudeUsage,\n cacheCreationInputTokens: number,\n warnings: string[],\n): void => {\n const iterations = raw.iterations;\n if (iterations === undefined || iterations.length === 0) {\n return;\n }\n const outer: Readonly<Record<(typeof ITERATION_COUNTERS)[number], number>> = {\n input_tokens: raw.input_tokens,\n output_tokens: raw.output_tokens,\n cache_read_input_tokens: raw.cache_read_input_tokens ?? 0,\n cache_creation_input_tokens: cacheCreationInputTokens,\n };\n for (const counter of ITERATION_COUNTERS) {\n const summed = iterations.reduce((total, iteration) => total + (iteration[counter] ?? 0), 0);\n if (summed !== outer[counter]) {\n warnings.push(\n `usage.iterations[].${counter} sums to ${String(summed)} but usage.${counter} reports ` +\n `${String(outer[counter])}; the outer counter is used and per-iteration figures are never added to it`,\n );\n }\n }\n};\n\nconst auditExcludedCounters = (raw: ClaudeUsage, warnings: string[]): void => {\n if (raw.total_tokens !== undefined) {\n warnings.push(CLAUDE_EXCLUDED_USAGE_COUNTERS.total_tokens);\n }\n if (raw.reasoning_output_tokens !== undefined) {\n warnings.push(CLAUDE_EXCLUDED_USAGE_COUNTERS.reasoning_output_tokens);\n }\n};\n\n/**\n * `normalizeUsage` notes when a caller declared a cache-creation accounting mode\n * on a snapshot with zero cache-creation tokens. That note is aimed at a caller\n * choosing the mode per observation; this adapter's mode is a fixed property of\n * the provider, so on any turn that wrote nothing to cache the note restates the\n * design rather than reporting anything. It would fire on most turns and bury the\n * warnings that do mean something, so it is dropped here — by prefix, so a note\n * this adapter has not considered still reaches the caller.\n */\nconst ACCOUNTING_RETAINED_NOTE_PREFIX = \"cacheCreationAccounting=\";\n\nconst forwardableNotes = (notes: readonly string[]): readonly string[] =>\n notes.filter((note) => !note.startsWith(ACCOUNTING_RETAINED_NOTE_PREFIX));\n\n/**\n * Normalize Anthropic's on-wire usage shape into canonical usage.\n *\n * `input_tokens` is the *fresh* portion of the prompt only: cache reads and cache\n * writes are separate, additive buckets. Confirmed against real captures rather\n * than assumed — across 4,999 usage objects `input_tokens` stayed within\n * 1..5,656 while `cache_read_input_tokens` reached 713,543\n * (docs/claude-code-usage-contract.md, finding 2). The canonical model instead\n * wants an inclusive `inputTokens`, so this folds all three into one total and\n * marks cache creation `included-in-input` — `uncachedInputTokens` then falls out\n * to exactly Anthropic's own `input_tokens`.\n *\n * The fold is what makes the canonical buckets **non-overlapping by\n * construction**: each subset is one of the addends of the total it is a subset\n * of, so no subset can exceed its total and no bucket is counted twice. That\n * holds structurally, not by a range check a provider change could invalidate.\n * The two places tokens are *itemized* rather than reported — the cache-creation\n * TTL split and `iterations[]` — are reconciled against the totals and never\n * added, which is where a double-count would otherwise come from within a single\n * callback. Double-counting *across* callbacks is the delivery layer's job; see\n * `delivery.ts`.\n *\n * Each usage snapshot corresponds to a single turn, subagent invocation, or\n * compaction — never a running session total — so it is always reported as a\n * `delta` observation.\n */\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\nconst asNonNegativeInt = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isInteger(value) && value >= 0 ? value : undefined;\n\n/**\n * Coerce one usage-shaped object onto {@link claudeUsageSchema}.\n *\n * Accepts the Anthropic Messages API snake_case counters and the camelCase\n * aliases a print/`-p` result or wrapping harness may use. Both `input_tokens`\n * and `output_tokens` must be present — a lone counter is not a usage object,\n * and inventing the missing side as zero would report tokens the provider\n * never sent.\n */\nexport const coerceClaudeUsage = (value: unknown): ClaudeUsage | undefined => {\n const record = asRecord(value);\n if (record === undefined) {\n return undefined;\n }\n const inputTokens = asNonNegativeInt(record.input_tokens ?? record.inputTokens);\n const outputTokens = asNonNegativeInt(record.output_tokens ?? record.outputTokens);\n if (inputTokens === undefined || outputTokens === undefined) {\n return undefined;\n }\n const cacheCreation = asRecord(record.cache_creation ?? record.cacheCreation);\n const parsed = claudeUsageSchema.safeParse({\n input_tokens: inputTokens,\n output_tokens: outputTokens,\n ...(asNonNegativeInt(record.cache_creation_input_tokens ?? record.cacheCreationInputTokens) ===\n undefined\n ? {}\n : {\n cache_creation_input_tokens: asNonNegativeInt(\n record.cache_creation_input_tokens ?? record.cacheCreationInputTokens,\n ),\n }),\n ...(asNonNegativeInt(record.cache_read_input_tokens ?? record.cacheReadInputTokens) === undefined\n ? {}\n : {\n cache_read_input_tokens: asNonNegativeInt(\n record.cache_read_input_tokens ?? record.cacheReadInputTokens,\n ),\n }),\n ...(cacheCreation === undefined\n ? {}\n : {\n cache_creation: {\n ...(asNonNegativeInt(\n cacheCreation.ephemeral_5m_input_tokens ?? cacheCreation.ephemeral5mInputTokens,\n ) === undefined\n ? {}\n : {\n ephemeral_5m_input_tokens: asNonNegativeInt(\n cacheCreation.ephemeral_5m_input_tokens ?? cacheCreation.ephemeral5mInputTokens,\n ),\n }),\n ...(asNonNegativeInt(\n cacheCreation.ephemeral_1h_input_tokens ?? cacheCreation.ephemeral1hInputTokens,\n ) === undefined\n ? {}\n : {\n ephemeral_1h_input_tokens: asNonNegativeInt(\n cacheCreation.ephemeral_1h_input_tokens ?? cacheCreation.ephemeral1hInputTokens,\n ),\n }),\n },\n }),\n ...(Array.isArray(record.iterations) ? { iterations: record.iterations } : {}),\n ...(asNonNegativeInt(record.total_tokens ?? record.totalTokens) === undefined\n ? {}\n : { total_tokens: asNonNegativeInt(record.total_tokens ?? record.totalTokens) }),\n ...(asNonNegativeInt(record.reasoning_output_tokens ?? record.reasoningOutputTokens) ===\n undefined\n ? {}\n : {\n reasoning_output_tokens: asNonNegativeInt(\n record.reasoning_output_tokens ?? record.reasoningOutputTokens,\n ),\n }),\n });\n return parsed.success ? parsed.data : undefined;\n};\n\n/**\n * Find a usage object on a Stop / print-result / SessionEnd payload.\n *\n * Looks at `usage`, `token_usage`, `message.usage`, and top-level token\n * counters. The first object that coerces to {@link ClaudeUsage} wins. Absence\n * is reported as `undefined` — never as a zeroed snapshot.\n */\nexport const extractClaudeUsage = (payload: unknown): ClaudeUsage | undefined => {\n const record = asRecord(payload);\n if (record === undefined) {\n return undefined;\n }\n const message = asRecord(record.message);\n const candidates: readonly unknown[] = [\n record.usage,\n record.token_usage,\n record.tokenUsage,\n message?.usage,\n record,\n ];\n for (const candidate of candidates) {\n const usage = coerceClaudeUsage(candidate);\n if (usage !== undefined) {\n return usage;\n }\n }\n return undefined;\n};\n\nexport const normalizeClaudeUsage = (raw: ClaudeUsage | undefined): ClaudeUsageNormalization => {\n if (raw === undefined) {\n return { warnings: [] };\n }\n\n const warnings: string[] = [];\n const cachedInputTokens = raw.cache_read_input_tokens ?? 0;\n const cacheCreationInputTokens = resolveCacheCreationTokens(raw, warnings);\n auditIterations(raw, cacheCreationInputTokens, warnings);\n auditExcludedCounters(raw, warnings);\n\n const result = normalizeUsage({\n temporality: \"delta\",\n inputTokens: raw.input_tokens + cachedInputTokens + cacheCreationInputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: \"included-in-input\",\n outputTokens: raw.output_tokens,\n });\n\n if (result.status === \"invalid\") {\n return { warnings: [...warnings, ...result.issues.map((issue) => issue.message)] };\n }\n return { usage: result.usage, warnings: [...warnings, ...forwardableNotes(result.notes)] };\n};\n","import { coerceClaudeUsage } from \"./usage.js\";\n\n/**\n * Fold Claude Code hook and print/`-p` payload aliases onto the snake_case\n * shapes {@link claudeHookPayloadSchema} already accepts.\n *\n * Interactive Stop payloads document `last_assistant_message`. Print / `-p` /\n * Agent SDK result messages use `type: \"result\"` and `result` instead, and some\n * wrappers emit camelCase field names. None of these are invented: each alias\n * is a name Claude Code or its published result JSON has actually used. An\n * unrecognized shape is returned unchanged so detection can decline it.\n */\n\nconst FIELD_ALIASES = Object.freeze({\n hookEventName: \"hook_event_name\",\n sessionId: \"session_id\",\n lastAssistantMessage: \"last_assistant_message\",\n transcriptPath: \"transcript_path\",\n promptId: \"prompt_id\",\n toolUseId: \"tool_use_id\",\n toolName: \"tool_name\",\n toolInput: \"tool_input\",\n toolResponse: \"tool_response\",\n toolError: \"tool_error\",\n stopHookActive: \"stop_hook_active\",\n agentId: \"agent_id\",\n agentType: \"agent_type\",\n errorType: \"error_type\",\n errorMessage: \"error_message\",\n tokenUsage: \"token_usage\",\n} as const);\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\n/**\n * Copy documented camelCase aliases onto their snake_case names when the\n * snake_case field is absent. Existing snake_case values win, so a payload that\n * carries both is not rewritten.\n */\nconst applyFieldAliases = (record: Record<string, unknown>): Record<string, unknown> => {\n const normalized: Record<string, unknown> = { ...record };\n for (const [alias, canonical] of Object.entries(FIELD_ALIASES)) {\n if (normalized[canonical] === undefined && normalized[alias] !== undefined) {\n normalized[canonical] = normalized[alias];\n }\n }\n return normalized;\n};\n\n/**\n * Claude Code print / `-p` / Agent SDK result messages are not hook events, but\n * they are the stop/result payload a non-interactive session actually produces.\n * When one arrives with a session id and no `hook_event_name`, treat it as the\n * Stop (or StopFailure) the interactive protocol would have fired.\n */\nconst applyPrintResultShape = (record: Record<string, unknown>): Record<string, unknown> => {\n if (record.hook_event_name !== undefined || record.type !== \"result\") {\n return record;\n }\n if (typeof record.session_id !== \"string\" || record.session_id.length === 0) {\n return record;\n }\n\n const isError = record.subtype === \"error\" || record.is_error === true;\n const normalized: Record<string, unknown> = {\n ...record,\n hook_event_name: isError ? \"StopFailure\" : \"Stop\",\n };\n if (\n normalized.last_assistant_message === undefined &&\n typeof record.result === \"string\" &&\n record.result.length > 0\n ) {\n normalized.last_assistant_message = record.result;\n }\n if (isError && (typeof normalized.error_type !== \"string\" || normalized.error_type.length === 0)) {\n normalized.error_type = \"unknown\";\n }\n return normalized;\n};\n\n/**\n * Return a Claude-shaped payload with documented aliases folded onto canonical\n * field names, or the original value when it is not an object.\n */\nexport const normalizeClaudeHookPayload = (payload: unknown): unknown => {\n const record = asRecord(payload);\n if (record === undefined) {\n return payload;\n }\n return applyUsageShape(applyPrintResultShape(applyFieldAliases(record)));\n};\n\n/**\n * Coerce `usage` / `token_usage` onto the Anthropic snake_case object the\n * Stop schema accepts, so a camelCase print-result usage object is not\n * rejected as an invalid `usage` field.\n */\nconst applyUsageShape = (record: Record<string, unknown>): Record<string, unknown> => {\n const usage =\n coerceClaudeUsage(record.usage) ??\n coerceClaudeUsage(record.token_usage) ??\n coerceClaudeUsage(record.tokenUsage);\n if (usage === undefined) {\n return record;\n }\n return { ...record, usage };\n};\n","import {\n asProviderId,\n providerDetectionSchema,\n type ProviderDetection,\n type ProviderDetectionInput,\n} from \"../adapter.js\";\nimport { normalizeClaudeHookPayload } from \"./payload-normalize.js\";\nimport { CLAUDE_HOOK_EVENT_NAMES } from \"./schema.js\";\n\n/** Stable, hyphenated provider id for Claude Code. */\nexport const CLAUDE_CODE_PROVIDER_ID = asProviderId(\"claude-code\");\n\nconst KNOWN_EVENT_NAMES: ReadonlySet<string> = new Set(CLAUDE_HOOK_EVENT_NAMES);\n\nconst none = (reason: string): ProviderDetection =>\n providerDetectionSchema.parse({\n providerId: \"unknown\",\n confidence: \"none\",\n reasons: [reason],\n });\n\n/**\n * Recognize a Claude Code hook payload.\n *\n * Confidence is never `exact` from shape alone: Claude Code hook JSON has no\n * self-identifying `provider` field, so `hook_event_name` plus `session_id`\n * is the strongest evidence a shape check can offer. A caller-supplied\n * `providerHint` naming this adapter is treated as the stronger claim.\n */\nexport const detectClaudeCode = (input: ProviderDetectionInput): ProviderDetection => {\n const payload = normalizeClaudeHookPayload(input.payload);\n if (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) {\n return none(\"payload is not a JSON object\");\n }\n\n const record = payload as Record<string, unknown>;\n const hookEventName = record.hook_event_name;\n if (typeof hookEventName !== \"string\" || !KNOWN_EVENT_NAMES.has(hookEventName)) {\n return none(\"hook_event_name is missing or not a recognized Claude Code hook event\");\n }\n\n const sessionId = record.session_id;\n if (typeof sessionId !== \"string\" || sessionId.length === 0) {\n return none(\"session_id is missing\");\n }\n\n const hasTranscriptPath =\n typeof record.transcript_path === \"string\" && record.transcript_path.length > 0;\n const isPrintResult = record.type === \"result\";\n const hinted = input.providerHint === CLAUDE_CODE_PROVIDER_ID;\n\n return providerDetectionSchema.parse({\n providerId: CLAUDE_CODE_PROVIDER_ID,\n confidence: hinted ? \"exact\" : hasTranscriptPath || isPrintResult ? \"strong\" : \"weak\",\n reasons: [\n `hook_event_name=${hookEventName} matches the Claude Code hooks protocol`,\n \"session_id present\",\n ...(hasTranscriptPath ? [\"transcript_path present\"] : []),\n ...(isPrintResult ? [\"type=result print/SDK result message\"] : []),\n ...(hinted ? [\"caller asserted providerHint=claude-code\"] : []),\n ],\n sourceEventName: hookEventName,\n });\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, ModelDescriptor } 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 PayloadEnricher,\n ReadCursor,\n SessionContextReader,\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\";\nimport { stampSessionContext } from \"./session-context.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 * Host-configured payload enrichers (see {@link PayloadEnricher}). Empty by\n * default: nothing reads beyond the payload unless a host asks for it.\n */\n readonly payloadEnrichers?: readonly PayloadEnricher[];\n /**\n * Reads the session context a harness wrote (`docs/session-context.md`). Absent\n * means none: no event carries `contextAttributes`. The filesystem\n * implementation is `createDirectorySessionContextReader`.\n */\n readonly sessionContext?: SessionContextReader;\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 sessionModelKey = (sessionId: string): string => `model:${sessionId}`;\nconst readCursorKey = (enricherId: string, sessionId: string, scope: string | undefined): string =>\n scope === undefined ? `cursor:${enricherId}:${sessionId}` : `cursor:${enricherId}:${sessionId}:${scope}`;\n\n/**\n * The placeholder an adapter uses when its payload names no model. Never\n * remembered: storing it would overwrite a real model the session reported.\n */\nconst UNKNOWN_MODEL_ID = \"unknown\";\n\n/**\n * The last model a batch reports for the top-level agent, if any.\n *\n * `session.start` and `generation.*` edges count; a subagent's events do not,\n * because a subagent can run on a different model than the session it serves and\n * must not rename the session's own generations. The last such event wins, so a\n * turn that reports a model switch updates what the session remembers.\n */\nconst latestSessionModel = (events: readonly CanonicalEvent[]): ModelDescriptor | undefined => {\n let latest: ModelDescriptor | undefined;\n for (const event of events) {\n if (event.subagentId !== undefined) {\n continue;\n }\n if (\n (event.type === \"session.start\" || event.type === \"generation.start\" || event.type === \"generation.end\") &&\n event.model !== undefined &&\n event.model.modelId !== UNKNOWN_MODEL_ID\n ) {\n latest = event.model;\n }\n }\n return latest;\n};\n\nconst sameModel = (left: ModelDescriptor | undefined, right: ModelDescriptor): boolean =>\n left !== undefined &&\n left.modelId === right.modelId &&\n left.vendor === right.vendor &&\n left.family === right.family;\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 * Run the configured enrichers for this provider over the payload.\n *\n * Inside the session lock, so a cursor is read, advanced, and written by one\n * process at a time. Every failure is contained: a throwing enricher or an\n * unusable store leaves the payload as it was, and a cursor write that fails\n * is a diagnostic — the next read then starts from the old cursor, which can\n * count a turn into the next one but never twice.\n */\n const enrichPayload = async (\n payload: unknown,\n providerId: string,\n sessionId: string,\n diagnostics: OtelHookErrorInfo[],\n ): Promise<unknown> => {\n let current = payload;\n for (const enricher of deps.payloadEnrichers ?? []) {\n if (enricher.providerId !== providerId) {\n continue;\n }\n let scope: string | undefined;\n try {\n scope = enricher.cursorScope?.(current);\n } catch (thrown) {\n logger.warn(\"payload enricher failed; parsing the payload as delivered\", {\n \"enricher.id\": enricher.id,\n \"error.name\": thrown instanceof Error ? thrown.name : typeof thrown,\n });\n continue;\n }\n const key = readCursorKey(enricher.id, sessionId, scope);\n let cursor: ReadCursor | undefined;\n try {\n const record = await deps.stateStore.read(key);\n if (record?.value.kind === \"read-cursor\") {\n cursor = { source: record.value.source, offset: record.value.offset };\n }\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, { code: \"state-store-failure\", phase: \"state\", occurredAt: clock.now() }),\n );\n // Without the stored cursor a read would start from the wrong place.\n continue;\n }\n let result;\n try {\n result = await enricher.enrich({ payload: current, sessionId, ...(cursor === undefined ? {} : { cursor }) });\n } catch (thrown) {\n logger.warn(\"payload enricher failed; parsing the payload as delivered\", {\n \"enricher.id\": enricher.id,\n \"error.name\": thrown instanceof Error ? thrown.name : typeof thrown,\n });\n continue;\n }\n current = result.payload;\n if (result.notes !== undefined && result.notes.length > 0) {\n logger.debug(\"payload enricher notes\", {\n \"enricher.id\": enricher.id,\n \"enricher.notes\": result.notes.slice(0, 8).map((note) => note.slice(0, 200)),\n });\n }\n const next = result.cursor;\n if (next !== undefined && (next.source !== cursor?.source || next.offset !== cursor.offset)) {\n try {\n await deps.stateStore.write(key, { kind: \"read-cursor\", source: next.source, offset: next.offset });\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, { code: \"state-store-failure\", phase: \"state\", occurredAt: clock.now() }),\n );\n }\n }\n }\n return current;\n };\n\n /**\n * The model this session last reported, or `undefined`.\n *\n * Fails open: an unreadable store costs the model name, never the observation,\n * so a read failure is a diagnostic and the adapter falls back to `unknown`.\n */\n const readSessionModel = async (\n sessionId: string,\n diagnostics: OtelHookErrorInfo[],\n ): Promise<ModelDescriptor | undefined> => {\n try {\n const record = await deps.stateStore.read(sessionModelKey(sessionId));\n return record?.value.kind === \"session-model\" ? record.value.model : undefined;\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, { code: \"state-store-failure\", phase: \"state\", occurredAt: clock.now() }),\n );\n return undefined;\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 const sessionModel = await readSessionModel(identity.sessionId, diagnostics);\n const payload = suppress\n ? detectionInput.payload\n : await enrichPayload(detectionInput.payload, detection.providerId, identity.sessionId, diagnostics);\n\n let parsed;\n try {\n parsed = adapter.parse(\n {\n ...detectionInput,\n payload,\n detection,\n identity,\n sequenceBase,\n ...(sessionModel === undefined ? {} : { sessionModel }),\n },\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 // Remember the session's model for the invocations whose payload names\n // none. Written only when it changed, so a session costs one record and\n // a steady session no extra writes; never written for a redelivery,\n // which is not a new observation.\n const reportedModel = latestSessionModel(screened.kept);\n if (reportedModel !== undefined && !sameModel(sessionModel, reportedModel)) {\n try {\n await deps.stateStore.write(sessionModelKey(identity.sessionId), {\n kind: \"session-model\",\n model: reportedModel,\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\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 // Session context: a core step, never adapter code (ADR 0003), outside the\n // session lock like target resolution. One bounded read of the file for this\n // invocation's session — for a subagent event that is its parent's session,\n // because events carry the invocation's session id, never the subagent's.\n // Always run, so an event can only ever carry the core's stamp.\n batch = stampSessionContext(\n batch,\n !suppress && batch.length > 0 && deps.sessionContext !== undefined\n ? await readSessionContext(deps.sessionContext, detection.providerId, identity.sessionId)\n : undefined,\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\n/** Fail-open wrapper: a reader that throws despite its contract stamps nothing. */\nconst readSessionContext = async (\n reader: SessionContextReader,\n providerId: string,\n sessionId: string,\n): Promise<Awaited<ReturnType<SessionContextReader[\"read\"]>>> => {\n try {\n return await reader.read({ providerId, sessionId });\n } catch {\n return undefined;\n }\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 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 { modelDescriptorSchema, 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 type { WorktreeKind } from \"../model/target.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 /**\n * The model a session last reported, so a later invocation whose payload names\n * none (Claude Code's `Stop`) can still say which model it was. A model id is\n * not sensitive (`modelDescriptorSchema`), and the descriptor is the strict,\n * bounded canonical shape, never a payload fragment.\n */\n z.strictObject({\n kind: z.literal(\"session-model\"),\n model: modelDescriptorSchema,\n }),\n /**\n * How far a {@link PayloadEnricher} has read a session's append-only source\n * (Claude Code's transcript), so the next read starts where the last ended.\n * `source` is an opaque digest of what was read, never a path.\n */\n /**\n * Running state of one metric series (issue #69), so a cumulative data point\n * exported by a later hook process continues the same total. Holds numbers and\n * a series digest only; the series' attributes are re-supplied by the caller\n * and never read back from disk.\n */\n z.strictObject({\n kind: z.literal(\"metric-series\"),\n /** Start of the cumulative interval. */\n startTimeMillis: epochMillisSchema,\n /** Counters: the running total. */\n value: z.number().finite().min(0).optional(),\n /** Histograms: the running aggregation. */\n histogram: z\n .strictObject({\n count: z.number().int().min(0),\n sum: z.number().finite().min(0),\n min: z.number().finite(),\n max: z.number().finite(),\n bucketCounts: z.array(z.number().int().min(0)).max(64),\n })\n .optional(),\n /** Opaque digest of the last delivery folded in; makes a replay a no-op. */\n appliedDelivery: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional(),\n }),\n z.strictObject({\n kind: z.literal(\"read-cursor\"),\n source: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/),\n offset: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),\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 /** Main checkout or linked worktree; absent when the locator does not tell. */\n readonly kind?: WorktreeKind;\n /**\n * Absolute path of the repository's main worktree — `root` itself for a main\n * worktree. Absent when there is none to name: a bare repository, a main\n * checkout that is gone, or a layout the locator cannot read.\n */\n readonly mainRoot?: 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\n/** Where an enricher stopped reading a session's source; see the `read-cursor` state value. */\nexport type ReadCursor = {\n /** Opaque digest naming the source, so a cursor never applies to another file. */\n readonly source: string;\n /** Byte offset the next read starts at. */\n readonly offset: number;\n};\n\nexport type PayloadEnrichmentInput = {\n readonly payload: unknown;\n readonly sessionId: string;\n /** The cursor this enricher stored for this session (and cursor scope) last time, if any. */\n readonly cursor?: ReadCursor;\n};\n\nexport type PayloadEnrichment = {\n /** The payload the adapter parses: the input, or a copy with fields attached. */\n readonly payload: unknown;\n /** A cursor to store for this session; absent leaves the stored one as it is. */\n readonly cursor?: ReadCursor;\n /** Short, non-sensitive notes for the debug log (why a read fell back, ...). */\n readonly notes?: readonly string[];\n};\n\n/**\n * Host-side step that attaches facts to a provider payload before its adapter\n * parses it — for facts the provider writes somewhere other than the hook\n * payload, such as Claude Code's transcript.\n *\n * Not an adapter capability, on purpose: adapters get no filesystem handle (ADR\n * 0003). An enricher is configured by the host, runs inside the session lock so\n * its cursor is read and written atomically, and must be bounded and never throw\n * (a throw is contained and the original payload is parsed). It never runs for a\n * redelivered callback, which is not a new observation.\n */\nexport interface PayloadEnricher {\n /** Stable id; namespaces the enricher's cursor in the state store. */\n readonly id: string;\n /** The provider whose payloads it enriches. Others are never passed to it. */\n readonly providerId: string;\n /**\n * Which of the session's cursors this payload reads, when a session has more\n * than one source (Claude Code writes each subagent to its own transcript).\n * `undefined`, or no function, selects the session's own cursor. A scope is\n * part of a state key, never exported; it must not hold a path.\n */\n cursorScope?(payload: unknown): string | undefined;\n enrich(input: PayloadEnrichmentInput): Promise<PayloadEnrichment>;\n}\n\n/**\n * One window of a session's context: the attributes in force from `from`\n * (inclusive) until `to` (exclusive), or open-ended when `to` is `null`.\n * Attributes are already screened (see `sanitizeSessionContextAttributes`).\n */\nexport type SessionContextSegment = {\n readonly from: EpochMillis;\n readonly to: EpochMillis | null;\n readonly attributes: Readonly<Record<string, string | number | boolean>>;\n};\n\nexport type SessionContextRequest = {\n /** The detected provider, e.g. `claude-code`. The reader maps it to its directory name. */\n readonly providerId: string;\n /**\n * The session whose context applies: always the invocation's session, which\n * for a subagent event is its parent's — never the subagent's own id.\n */\n readonly sessionId: string;\n};\n\n/**\n * Reads the session context a harness wrote for one agent session.\n *\n * A port for the same reason {@link WorktreeLocator} is one: the core decides\n * when to ask and what of the answer reaches a record; the implementation only\n * reads. Adapters never see it (ADR 0003). Implementations must never throw or\n * reject: no file, an unreadable file, an invalid one, or one of an unknown\n * version are all `undefined`, and the core then stamps nothing.\n */\nexport interface SessionContextReader {\n read(request: SessionContextRequest): Promise<readonly SessionContextSegment[] | 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 { isTargetedEvent, 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, branch, and repository through the injected {@link WorktreeLocator};\n * only salted `git-root` handles of the root and of its repository's main\n * worktree, the worktree's kind, 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 // The repository is named by its main worktree, as that worktree would name\n // itself — so a main worktree's repository id is its own workspace id.\n const repository =\n first.mainRoot === undefined\n ? undefined\n : deriveWorkspaceIdentity(privacy, { kind: \"git-root\", absolutePath: first.mainRoot });\n const parsed = workspaceTargetSchema.safeParse({\n workspaceId: identity.workspaceId,\n ...(identity.vcsBranchName === undefined ? {} : { vcsBranchName: identity.vcsBranchName }),\n source: hint.source,\n ...(repository?.keySource === \"git-root\" ? { repositoryId: repository.workspaceId } : {}),\n ...(first.kind === undefined ? {} : { worktreeKind: first.kind }),\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 targeted event (`TARGETED_EVENT_TYPES`) 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((event) => isTargetedEvent(event) && input.hints.has(event.eventId));\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 || !isTargetedEvent(event)) {\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 } from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport { z } from \"zod\";\n\nimport {\n checkResourceAttributeKey,\n MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH,\n MAX_RESOURCE_ATTRIBUTES,\n} from \"../config/resource-attributes.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { SessionContextReader, SessionContextSegment } from \"./ports.js\";\n\n/**\n * Session context: attributes a harness wants on every record of one agent\n * session, for a window of time.\n *\n * A harness (HAR, or anything else) writes one JSON file per agent session:\n *\n * ```text\n * <dir>/<agent-tool>/<session-id>.json\n * { \"version\": 1, \"agentTool\": \"claude_code\", \"sessionId\": \"…\",\n * \"segments\": [ { \"from\": \"<ISO-8601>\", \"to\": \"<ISO-8601>\" | null,\n * \"reason\": \"launch\", \"attributes\": { \"k\": \"v\" } } ] }\n * ```\n *\n * On every hook event the core reads the one file for the event's session,\n * picks the segment in force at each event's time, and stamps its attributes on\n * every record the event produces. otel-hook knows nothing about what the\n * attributes mean: it applies an attribute map. See `docs/session-context.md`.\n *\n * Fail-open throughout: a missing, unreadable, oversized, invalid, or\n * wrong-version file — or no segment in force — stamps nothing and never fails\n * the hook.\n */\n\n/** The only file format version this build reads. Any other is ignored whole. */\nexport const SESSION_CONTEXT_FILE_VERSION = 1 as const;\n\n/** Largest file read; anything bigger is ignored rather than truncated. */\nexport const DEFAULT_SESSION_CONTEXT_MAX_BYTES = 256 * 1024;\n\n/** Ceiling on one read; a slow filesystem costs the stamp, never the hook. */\nexport const DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS = 100;\n\n/** Upper bound on segments considered in one file. */\nexport const MAX_SESSION_CONTEXT_SEGMENTS = 1024;\n\n/**\n * otel-hook provider id → the agent-tool directory a harness writes under.\n *\n * The names are the ones HAR derives from the agent process it finds\n * (`claude_code`, `codex`, `cursor`). A provider absent from this table has no\n * session context: nothing is read for it.\n */\nexport const SESSION_CONTEXT_AGENT_TOOLS: Readonly<Record<string, string>> = Object.freeze({\n \"claude-code\": \"claude_code\",\n codex: \"codex\",\n cursor: \"cursor\",\n \"gemini-cli\": \"gemini_cli\",\n antigravity: \"antigravity\",\n});\n\nexport const sessionContextAgentTool = (providerId: string): string | undefined =>\n Object.hasOwn(SESSION_CONTEXT_AGENT_TOOLS, providerId) ? SESSION_CONTEXT_AGENT_TOOLS[providerId] : undefined;\n\n/**\n * A session id is used as a file name, so it must be one: no separators, no\n * `.`/`..`, nothing a path could be steered with. Real session ids (UUIDs) pass.\n */\nconst SESSION_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;\n\nexport const isSessionContextFileName = (sessionId: string): boolean =>\n SESSION_FILE_NAME_PATTERN.test(sessionId) && !sessionId.includes(\"..\");\n\n/**\n * Where the context of one session lives, or `undefined` when the provider has\n * no agent-tool directory or the session id cannot be a file name.\n */\nexport const sessionContextFilePath = (\n dir: string,\n providerId: string,\n sessionId: string,\n): string | undefined => {\n const tool = sessionContextAgentTool(providerId);\n if (tool === undefined || !isSessionContextFileName(sessionId) || !path.isAbsolute(dir)) {\n return undefined;\n }\n return path.join(dir, tool, `${sessionId}.json`);\n};\n\n/**\n * Keys a context may never set, whatever it says.\n *\n * - `factory.local.*`: the Factory Commits telemetry profile defines it as\n * local-only (paths and the like); it must never reach a record.\n * - otel-hook's own record identity (`session.id`, `otelhook.*`, the hex trace\n * ids, `gen_ai.conversation.id`): a context file describes the work a session\n * does, it does not get to rename the session or forge its trace.\n * - Everything `checkResourceAttributeKey` refuses: malformed keys, the\n * `service.*` exporter policy keys, and secret-like names.\n */\nconst RESERVED_CONTEXT_KEYS: ReadonlySet<string> = new Set([\n \"session.id\",\n \"trace_id\",\n \"span_id\",\n \"parent_span_id\",\n \"gen_ai.conversation.id\",\n \"factory.local\",\n]);\nconst RESERVED_CONTEXT_PREFIXES: readonly string[] = Object.freeze([\"factory.local.\", \"otelhook.\"]);\n\nexport const isReservedSessionContextKey = (key: string): boolean =>\n RESERVED_CONTEXT_KEYS.has(key) || RESERVED_CONTEXT_PREFIXES.some((prefix) => key.startsWith(prefix));\n\n/**\n * Screen one segment's attribute map: primitive values only, bounded, and no\n * reserved or unsafe key. Dropped entries are dropped silently, one by one; the\n * rest of the map still applies.\n */\nexport const sanitizeSessionContextAttributes = (\n attributes: Readonly<Record<string, unknown>>,\n): Readonly<Record<string, string | number | boolean>> => {\n const kept: Record<string, string | number | boolean> = {};\n let count = 0;\n for (const [key, value] of Object.entries(attributes)) {\n if (count >= MAX_RESOURCE_ATTRIBUTES) {\n break;\n }\n if (checkResourceAttributeKey(key) !== undefined || isReservedSessionContextKey(key)) {\n continue;\n }\n if (typeof value === \"string\") {\n if (value.length > MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) {\n continue;\n }\n } else if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n continue;\n }\n } else if (typeof value !== \"boolean\") {\n continue;\n }\n kept[key] = value;\n count += 1;\n }\n return kept;\n};\n\nconst ISO_INSTANT_PATTERN =\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?(?:Z|[+-]\\d{2}:\\d{2})$/;\n\nconst isoInstantSchema = z\n .string()\n .max(64)\n .regex(ISO_INSTANT_PATTERN)\n .transform((value, ctx) => {\n const millis = Date.parse(value);\n if (!Number.isFinite(millis)) {\n ctx.issues.push({ code: \"custom\", input: value, message: \"not a valid instant\" });\n return z.NEVER;\n }\n return millis;\n });\n\nconst segmentSchema = z.object({\n from: isoInstantSchema,\n to: isoInstantSchema.nullable(),\n reason: z.string().max(256).optional(),\n attributes: z.record(z.string(), z.unknown()),\n});\n\n/**\n * The file format. Unknown extra fields are tolerated (a later minor revision\n * may add some); a different `version` is not, because its fields may mean\n * something else.\n */\nconst sessionContextFileSchema = z.object({\n version: z.literal(SESSION_CONTEXT_FILE_VERSION),\n agentTool: z.string().max(64).optional(),\n sessionId: z.string().max(256).optional(),\n segments: z.array(segmentSchema).max(MAX_SESSION_CONTEXT_SEGMENTS),\n});\n\n/**\n * Parse a decoded context file into screened segments.\n *\n * `expected` guards against a file that names another session or tool than the\n * one it was read for (a copy, a misplaced write): such a file applies to\n * nobody. Returns `undefined` for anything invalid; never throws.\n */\nexport const parseSessionContextFile = (\n value: unknown,\n expected?: { readonly agentTool?: string; readonly sessionId?: string },\n): readonly SessionContextSegment[] | undefined => {\n const parsed = sessionContextFileSchema.safeParse(value);\n if (!parsed.success) {\n return undefined;\n }\n const file = parsed.data;\n if (\n (expected?.agentTool !== undefined && file.agentTool !== undefined && file.agentTool !== expected.agentTool) ||\n (expected?.sessionId !== undefined && file.sessionId !== undefined && file.sessionId !== expected.sessionId)\n ) {\n return undefined;\n }\n return file.segments.map((segment) => ({\n from: segment.from,\n to: segment.to,\n attributes: sanitizeSessionContextAttributes(segment.attributes),\n }));\n};\n\n/**\n * The segment in force at `at`: `from <= at` and (`to` is null or `at < to`).\n * Should a writer ever leave two overlapping, the one that started last wins,\n * because it is the more recent statement.\n */\nexport const segmentInForce = (\n segments: readonly SessionContextSegment[],\n at: number,\n): SessionContextSegment | undefined => {\n let best: SessionContextSegment | undefined;\n for (const segment of segments) {\n if (segment.from <= at && (segment.to === null || at < segment.to)) {\n if (best === undefined || segment.from >= best.from) {\n best = segment;\n }\n }\n }\n return best;\n};\n\n/**\n * Stamp each event with the attributes of the segment in force at its own\n * `occurredAt`, and strip any `contextAttributes` an event already carried: only\n * this core step may set them. An event with no segment in force, or one whose\n * segment has no usable attribute, carries none.\n */\nexport const stampSessionContext = (\n events: readonly CanonicalEvent[],\n segments: readonly SessionContextSegment[] | undefined,\n): readonly CanonicalEvent[] =>\n events.map((event) => {\n const { contextAttributes: _discarded, ...rest } = event;\n const segment = segments === undefined ? undefined : segmentInForce(segments, event.occurredAt);\n if (segment === undefined || Object.keys(segment.attributes).length === 0) {\n return _discarded === undefined ? event : (rest);\n }\n return { ...rest, contextAttributes: { ...segment.attributes } };\n });\n\nexport type DirectorySessionContextReaderOptions = {\n /** Absolute directory holding `<agent-tool>/<session-id>.json`. */\n readonly dir: string;\n readonly maxBytes?: number;\n readonly budgetMillis?: number;\n};\n\nconst readBounded = async (file: string, maxBytes: number): Promise<string | undefined> => {\n let handle;\n try {\n handle = await open(file, \"r\");\n } catch {\n return undefined;\n }\n try {\n const stats = await handle.stat();\n if (!stats.isFile() || stats.size > maxBytes) {\n return undefined;\n }\n const buffer = Buffer.alloc(maxBytes + 1);\n let length = 0;\n while (length < buffer.length) {\n const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);\n if (bytesRead === 0) {\n break;\n }\n length += bytesRead;\n }\n if (length > maxBytes) {\n return undefined;\n }\n return buffer.subarray(0, length).toString(\"utf8\");\n } catch {\n return undefined;\n } finally {\n await handle.close().catch(() => undefined);\n }\n};\n\n/**\n * The filesystem {@link SessionContextReader}: one bounded read of one file per\n * call, never a directory scan. Never throws.\n */\nexport const createDirectorySessionContextReader = (\n options: DirectorySessionContextReaderOptions,\n): SessionContextReader => {\n const maxBytes = options.maxBytes ?? DEFAULT_SESSION_CONTEXT_MAX_BYTES;\n const budgetMillis = options.budgetMillis ?? DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS;\n\n const readOnce = async (\n providerId: string,\n sessionId: string,\n ): Promise<readonly SessionContextSegment[] | undefined> => {\n const file = sessionContextFilePath(options.dir, providerId, sessionId);\n if (file === undefined) {\n return undefined;\n }\n const text = await readBounded(file, maxBytes);\n if (text === undefined) {\n return undefined;\n }\n let decoded: unknown;\n try {\n decoded = JSON.parse(text);\n } catch {\n return undefined;\n }\n const agentTool = sessionContextAgentTool(providerId);\n return parseSessionContextFile(decoded, {\n ...(agentTool === undefined ? {} : { agentTool }),\n sessionId,\n });\n };\n\n return {\n read: async (request) => {\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<undefined>((resolve) => {\n timer = setTimeout(() => resolve(undefined), budgetMillis);\n timer.unref?.();\n });\n try {\n return await Promise.race([\n readOnce(request.providerId, request.sessionId).catch(() => undefined),\n timeout,\n ]);\n } finally {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n }\n },\n };\n};\n","import { lstat, 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.\n *\n * Which repository the worktree belongs to is read the same way git reads it:\n *\n * - A git dir holding a `commondir` file is a **linked** worktree's; that file\n * names the repository's common git dir, relative to the git dir. When the\n * common dir is a directory named `.git`, its parent is the main worktree —\n * the path `git worktree list` prints first. Any other common dir (a bare\n * repository, a `--separate-git-dir` repository, a submodule's\n * `.git/modules/<name>`) or one that no longer exists names no main worktree.\n * - A git dir without one is a **main** worktree's, including a submodule's\n * (`gitdir: <super>/.git/modules/<name>`): a submodule is its own repository,\n * not a linked worktree of the superproject.\n *\n * A `.git` entry that cannot be read, points nowhere, or has no readable `HEAD`\n * makes the answer `undefined` — a broken worktree is not evidence, and the walk\n * does not skip past it to an enclosing repository that the event did not\n * target. A repository that cannot be named costs only `mainRoot`.\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\nconst firstLine = (content: string): string => content.split(/\\r?\\n/, 1)[0]?.trim() ?? \"\";\n\nconst resolveGitPath = (target: string | undefined, base: string): string | undefined =>\n target === undefined || target.length === 0 || target.includes(\"\\u0000\")\n ? undefined\n : path.resolve(base, target);\n\n/** `gitdir: <path>` → the path, resolved against the worktree root. */\nexport const parseGitDirFile = (content: string, worktreeRoot: string): string | undefined => {\n const line = firstLine(content);\n // A prefix check, not a regex: `gitdir:` followed by long runs of spaces made\n // the former `/^gitdir:\\s*(.+)$/` backtrack polynomially (CodeQL).\n return resolveGitPath(\n line.startsWith(\"gitdir:\") ? line.slice(\"gitdir:\".length).trim() : undefined,\n worktreeRoot,\n );\n};\n\n/** A `commondir` file → the common git dir it names, resolved against the git dir. */\nexport const parseCommonDirFile = (content: string, gitDir: string): string | undefined =>\n resolveGitPath(firstLine(content), gitDir);\n\nconst isMissing = async (filePath: string): Promise<boolean> => {\n try {\n await lstat(filePath);\n return false;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n return code === \"ENOENT\" || code === \"ENOTDIR\";\n }\n};\n\nconst isDirectory = async (directory: string): Promise<boolean> => {\n try {\n return (await stat(directory)).isDirectory();\n } catch {\n return false;\n }\n};\n\ntype Repository = Pick<LocatedWorktree, \"kind\" | \"mainRoot\">;\n\n/** Kind and main worktree for a `.git` file's git dir; see the module note. */\nconst repositoryOf = async (worktreeRoot: string, gitDir: string): Promise<Repository> => {\n const commonDirFile = path.join(gitDir, \"commondir\");\n const content = await readBounded(commonDirFile);\n if (content === undefined) {\n // Only a missing file makes this a main worktree. An unreadable one is still\n // a linked worktree's, of a repository it cannot name.\n return (await isMissing(commonDirFile)) ? { kind: \"main\", mainRoot: worktreeRoot } : { kind: \"linked\" };\n }\n const commonDir = parseCommonDirFile(content, gitDir);\n const mainRoot =\n commonDir !== undefined && path.basename(commonDir) === \".git\" && (await isDirectory(commonDir))\n ? path.dirname(commonDir)\n : undefined;\n return { kind: \"linked\", ...(mainRoot === undefined ? {} : { mainRoot }) };\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 // A `.git` directory is always a main worktree's git dir: nothing more to read.\n const repository: Repository = info.isDirectory()\n ? { kind: \"main\", mainRoot: directory }\n : await repositoryOf(directory, gitDir);\n return {\n kind: \"worktree\",\n located: { root: directory, ...(branch === undefined ? {} : { branch }), ...repository },\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","/**\n * OTLP/HTTP endpoint URLs per signal, as the OpenTelemetry exporter\n * specification defines them.\n *\n * - `OTEL_EXPORTER_OTLP_ENDPOINT` is a **base** URL: the signal path\n * (`/v1/traces`, `/v1/logs`) is appended to it.\n * - `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` / `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`\n * are full URLs, used as they are.\n *\n * One compatibility rule: earlier releases read `OTEL_EXPORTER_OTLP_ENDPOINT`\n * as the full traces URL. A base URL that already ends in `/v1/traces` is\n * therefore taken to be that full URL, not a base to append to, so an existing\n * `…/v1/traces` value keeps posting where it did.\n */\n\n/**\n * The standard endpoint variables. `generic` and `logs` also appear in\n * `ENVIRONMENT_VARIABLES`; `traces` does not, because that list is guarded\n * against identity-looking (`TRACE`) names.\n */\nexport const OTLP_ENDPOINT_VARIABLES = Object.freeze({\n generic: \"OTEL_EXPORTER_OTLP_ENDPOINT\",\n traces: \"OTEL_EXPORTER_OTLP_TRACES_ENDPOINT\",\n logs: \"OTEL_EXPORTER_OTLP_LOGS_ENDPOINT\",\n metrics: \"OTEL_EXPORTER_OTLP_METRICS_ENDPOINT\",\n});\n\nexport const OTLP_TRACES_PATH = \"/v1/traces\";\nexport const OTLP_LOGS_PATH = \"/v1/logs\";\nexport const OTLP_METRICS_PATH = \"/v1/metrics\";\n\nexport type OtlpSignal = \"traces\" | \"logs\" | \"metrics\";\n\nconst SIGNAL_PATHS: Readonly<Record<OtlpSignal, string>> = Object.freeze({\n traces: OTLP_TRACES_PATH,\n logs: OTLP_LOGS_PATH,\n metrics: OTLP_METRICS_PATH,\n});\n\n/**\n * Strip trailing slashes, by scan rather than by regex.\n *\n * `/\\/+$/` is a polynomial-ReDoS on this input: an endpoint of many `/` followed by\n * anything else makes the engine retry the `+` from every position. The endpoint is\n * operator-supplied configuration bounded to 2048 characters, so the practical cost\n * is small — but a linear scan is just as short, and the bound is not the guarantee.\n */\nexport const withoutTrailingSlashes = (value: string): string => {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === 0x2f) {\n end -= 1;\n }\n return value.slice(0, end);\n};\n\n/**\n * The URL a signal posts to, given an `OTEL_EXPORTER_OTLP_ENDPOINT` base.\n *\n * Trailing slashes on the base are dropped before the signal path is appended,\n * so `https://host/otlp` and `https://host/otlp/` both give\n * `https://host/otlp/v1/traces`. A base ending in `/v1/traces` (the legacy\n * full-URL form) is used as-is for traces and has that suffix swapped for\n * `/v1/logs` for logs.\n */\nexport const otlpSignalEndpointFromBase = (base: string, signal: OtlpSignal): string => {\n const trimmed = withoutTrailingSlashes(base);\n if (trimmed.endsWith(OTLP_TRACES_PATH)) {\n return signal === \"traces\"\n ? trimmed\n : `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${SIGNAL_PATHS[signal]}`;\n }\n return `${trimmed}${SIGNAL_PATHS[signal]}`;\n};\n\n/**\n * A sibling signal's URL derived from a traces URL: a trailing `/v1/traces` (or\n * the target signal's own path) is swapped for the target path, and any other URL\n * is treated as a base and has the path appended. The rule logs have always used.\n */\nexport const siblingSignalEndpoint = (tracesEndpoint: string, signal: OtlpSignal): string => {\n const trimmed = withoutTrailingSlashes(tracesEndpoint);\n const target = SIGNAL_PATHS[signal];\n if (trimmed.endsWith(target)) {\n return trimmed;\n }\n if (trimmed.endsWith(OTLP_TRACES_PATH)) {\n return `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${target}`;\n }\n return `${trimmed}${target}`;\n};\n","import { randomBytes } from \"node:crypto\";\nimport { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport type { Clock, Logger } from \"../runtime/ports.js\";\nimport { namespaceSegments, type StoreNamespace } from \"../state/keys.js\";\n\nexport type SpoolEnqueueResult =\n | { readonly spooled: true }\n | { readonly spooled: false; readonly reason: \"capacity-exceeded\" };\n\nexport type SpoolDrainResult = {\n readonly drained: number;\n readonly remaining: number;\n readonly failed: number;\n /**\n * Batches removed from the queue because they were unusable rather than\n * undeliverable.\n *\n * Distinct from `failed`, which means \"the collector would not take it, try\n * later\". A quarantined batch will never become deliverable, so counting it\n * separately is what stops a permanent problem from reading as transient.\n */\n readonly quarantined: number;\n};\n\n/**\n * Why a queued batch was dropped rather than delivered.\n *\n * - `age` — older than the queue's `maxAgeMillis`.\n * - `size` — evicted (or refused) to stay within `maxBytes`.\n * - `count` — evicted (or refused) to stay within the batch-count bound.\n * - `rejected` — the destination answered with a non-retryable status on replay,\n * so sending it again could never succeed.\n */\nexport type SpoolDropReason = \"age\" | \"size\" | \"count\" | \"rejected\";\n\n/** Drop counts, persisted beside the queue so they outlive the process that dropped. */\nexport type SpoolDropCounts = {\n readonly total: number;\n readonly age: number;\n readonly size: number;\n readonly count: number;\n readonly rejected: number;\n readonly lastDroppedAt?: number;\n};\n\nexport type SpoolStats = {\n readonly batches: number;\n readonly bytes: number;\n /** Enqueue time of the oldest queued batch. Absent when the queue is empty. */\n readonly oldestEnqueuedAt?: number;\n readonly dropped: SpoolDropCounts;\n};\n\n/**\n * What a queue does when a new batch would exceed a bound.\n *\n * `refuse-new` keeps what is queued and reports the new batch as lost — the\n * original behavior, still the default for a queue built directly. `drop-oldest`\n * evicts from the head until the new batch fits, which is what the runtime's\n * per-destination spools use.\n */\nexport type SpoolOverflowPolicy = \"refuse-new\" | \"drop-oldest\";\n\n/**\n * What a drain's sender reports for one batch: delivered (`true`), still\n * undeliverable and worth retrying (`false`), or permanently undeliverable\n * (`\"discard\"`), which removes it and counts it as a `rejected` drop instead of\n * stopping the drain behind it.\n */\nexport type SpoolSendOutcome = boolean | \"discard\";\n\nexport const EMPTY_SPOOL_DROP_COUNTS: SpoolDropCounts = Object.freeze({\n total: 0,\n age: 0,\n size: 0,\n count: 0,\n rejected: 0,\n});\n\n/** Outcome of validating one batch read back from a queue file. */\nexport type SpoolValidation<TBatch> =\n | { readonly batch: TBatch }\n | { readonly rejection: string };\n\nexport type SpoolQueueOptions<TBatch> = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Bound on the number of queued batches. */\n readonly maxFiles: number;\n /** Bound on the total bytes of queued batches. Unbounded when absent. */\n readonly maxBytes?: number;\n /** A batch older than this is dropped, at enqueue and at drain. No age bound when absent. */\n readonly maxAgeMillis?: number;\n /** Default `refuse-new`. */\n readonly overflow?: SpoolOverflowPolicy;\n /**\n * Directory holding the queue, under the identity namespace. One name per\n * signal, so a batch of one signal can never be drained by the other's sender —\n * the two encode different payloads and a mixed queue would quarantine\n * perfectly good batches.\n */\n readonly queueName: string;\n /** Re-validates a batch read back from disk, before any of it reaches a sender. */\n readonly validate: (value: unknown, identity: StoreNamespace) => SpoolValidation<TBatch>;\n};\n\n/**\n * Durable filesystem queue for export batches a collector could not accept.\n *\n * A hook process is short-lived, so \"retry later\" means \"persist and let a later\n * invocation retry\" rather than an in-process backoff loop. Each instance is\n * rooted at `<rootDir>/<providerId>/<installationId>/<queueName>`; two queues for\n * different providers, installations, or signals never share a directory, so a\n * batch from one identity cannot physically land in another's drain — batches\n * cannot mix identities by construction, not by a runtime check alone (the check\n * inside {@link SpoolQueue.drain} is defense in depth for a hand-edited or\n * misplaced file).\n *\n * Shared by the trace and log spools rather than written twice: the drain's\n * quarantine-and-continue behavior is the subtle part, and a second copy of it is\n * a second place for the head-of-queue-blocking bug to come back.\n */\nexport interface SpoolQueue<TBatch> {\n enqueue(batch: TBatch): Promise<SpoolEnqueueResult>;\n /** Sequential, bounded drain: stops after the first failed send, or after `maxBatches`. */\n drain(\n send: (batch: TBatch) => Promise<SpoolSendOutcome>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\n /** Depth, bytes, and persisted drop counts. Read-only: creates no directory. */\n stats(): Promise<SpoolStats>;\n}\n\n/** Name of the drop-count file, inside the queue directory and outside its `*.json` listing. */\nexport const SPOOL_DROPS_FILE = \".drops\";\n\n/** Enqueue time encoded in a queue file name, or undefined for a foreign name. */\nconst enqueuedAtOf = (fileName: string): number | undefined => {\n const match = /^(\\d{16})-/.exec(fileName);\n return match?.[1] === undefined ? undefined : Number(match[1]);\n};\n\nconst isCount = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isInteger(value) && value >= 0;\n\n/** Read a queue directory's drop counts. Missing or unreadable reads as zero. */\nexport const readSpoolDropCounts = async (queueDir: string): Promise<SpoolDropCounts> => {\n try {\n const parsed = JSON.parse(await readFile(path.join(queueDir, SPOOL_DROPS_FILE), \"utf8\")) as unknown;\n if (typeof parsed !== \"object\" || parsed === null) {\n return EMPTY_SPOOL_DROP_COUNTS;\n }\n const record = parsed as Record<string, unknown>;\n const field = (name: string): number => (isCount(record[name]) ? record[name] : 0);\n return {\n total: field(\"total\"),\n age: field(\"age\"),\n size: field(\"size\"),\n count: field(\"count\"),\n rejected: field(\"rejected\"),\n ...(isCount(record.lastDroppedAt) ? { lastDroppedAt: record.lastDroppedAt } : {}),\n };\n } catch {\n return EMPTY_SPOOL_DROP_COUNTS;\n }\n};\n\n/**\n * Depth, bytes, and drop counts of one queue directory, without creating it.\n *\n * Exported for `doctor`, which inspects queues on disk without constructing the\n * sinks that own them.\n */\nexport const readSpoolQueueStats = async (queueDir: string): Promise<SpoolStats> => {\n let entries: string[];\n try {\n entries = await readdir(queueDir);\n } catch {\n return { batches: 0, bytes: 0, dropped: await readSpoolDropCounts(queueDir) };\n }\n const files = entries.filter((entry) => entry.endsWith(\".json\") && !entry.startsWith(\".tmp-\")).sort();\n let bytes = 0;\n for (const file of files) {\n try {\n bytes += (await stat(path.join(queueDir, file))).size;\n } catch {\n // Drained by a peer between the listing and the stat.\n }\n }\n const oldest = files[0] === undefined ? undefined : enqueuedAtOf(files[0]);\n return {\n batches: files.length,\n bytes,\n ...(oldest === undefined ? {} : { oldestEnqueuedAt: oldest }),\n dropped: await readSpoolDropCounts(queueDir),\n };\n};\n\n/** Default bound on a single drain pass, so one invocation's flush stays short. */\nexport const DEFAULT_DRAIN_MAX_BATCHES = 20;\n\nconst isErrnoException = (thrown: unknown, code: string): boolean =>\n thrown instanceof Error && (thrown as NodeJS.ErrnoException).code === code;\n\nexport const createSpoolQueue = <TBatch>(\n options: SpoolQueueOptions<TBatch>,\n): SpoolQueue<TBatch> => {\n const [providerSegment, installationSegment] = namespaceSegments(options);\n const queueDir = path.join(options.rootDir, providerSegment, installationSegment, options.queueName);\n const corruptDir = path.join(\n options.rootDir,\n providerSegment,\n installationSegment,\n `${options.queueName}-corrupt`,\n );\n\n let dirsReady: Promise<void> | undefined;\n const ensureDirs = async (): Promise<void> => {\n if (dirsReady !== undefined) {\n return dirsReady;\n }\n const promise = (async (): Promise<void> => {\n await mkdir(queueDir, { recursive: true });\n await mkdir(corruptDir, { recursive: true });\n })();\n dirsReady = promise;\n try {\n await promise;\n } catch (thrown) {\n dirsReady = undefined;\n throw thrown;\n }\n };\n\n const listSorted = async (): Promise<readonly string[]> => {\n let entries: string[];\n try {\n entries = await readdir(queueDir);\n } catch (thrown) {\n if (isErrnoException(thrown, \"ENOENT\")) {\n return [];\n }\n throw thrown;\n }\n return entries.filter((entry) => entry.endsWith(\".json\") && !entry.startsWith(\".tmp-\")).sort();\n };\n\n /**\n * Add drops to the persisted counts.\n *\n * A read-modify-write without a lock: two processes dropping at the same moment\n * can lose one increment. The counts are a diagnostic, not an invoice, and a\n * lock here would put a second contention point on the failure path.\n */\n const recordDrops = async (reason: SpoolDropReason, dropped: number): Promise<void> => {\n if (dropped <= 0) {\n return;\n }\n try {\n const current = await readSpoolDropCounts(queueDir);\n const next: SpoolDropCounts = {\n ...current,\n total: current.total + dropped,\n [reason]: current[reason] + dropped,\n lastDroppedAt: options.clock.now(),\n };\n const tmp = path.join(queueDir, `.tmp-${randomBytes(6).toString(\"hex\")}.drops`);\n await writeFile(tmp, JSON.stringify(next), \"utf8\");\n await rename(tmp, path.join(queueDir, SPOOL_DROPS_FILE));\n } catch {\n // Counting is best-effort; the drop itself already happened.\n }\n options.logger?.warn(\"durable spool dropped batches\", {\n \"spool.queue\": options.queueName,\n \"spool.drop_reason\": reason,\n \"spool.dropped\": dropped,\n });\n };\n\n type QueuedFile = { readonly name: string; readonly enqueuedAt?: number; readonly bytes: number };\n\n const listWithSizes = async (): Promise<QueuedFile[]> => {\n const names = await listSorted();\n const files: QueuedFile[] = [];\n for (const name of names) {\n let bytes = 0;\n if (options.maxBytes !== undefined) {\n try {\n bytes = (await stat(path.join(queueDir, name))).size;\n } catch {\n continue;\n }\n }\n const enqueuedAt = enqueuedAtOf(name);\n files.push({ name, bytes, ...(enqueuedAt === undefined ? {} : { enqueuedAt }) });\n }\n return files;\n };\n\n /** Remove queued files; the count is what actually left the queue. */\n const evict = async (files: readonly QueuedFile[]): Promise<number> => {\n let removed = 0;\n for (const file of files) {\n try {\n await unlink(path.join(queueDir, file.name));\n removed += 1;\n } catch {\n // Already drained or evicted by a peer: it left the queue either way, but\n // not because of this process, so it is not counted here.\n }\n }\n return removed;\n };\n\n const isExpired = (file: QueuedFile, now: number): boolean =>\n options.maxAgeMillis !== undefined &&\n file.enqueuedAt !== undefined &&\n now - file.enqueuedAt > options.maxAgeMillis;\n\n const enqueue = async (batch: TBatch): Promise<SpoolEnqueueResult> => {\n await ensureDirs();\n const serialized = JSON.stringify(batch);\n const bytes = Buffer.byteLength(serialized, \"utf8\");\n const refuse = async (reason: \"size\" | \"count\"): Promise<SpoolEnqueueResult> => {\n options.logger?.warn(\"durable spool at capacity; batch dropped\", {\n \"spool.max_files\": options.maxFiles,\n ...(options.maxBytes === undefined ? {} : { \"spool.max_bytes\": options.maxBytes }),\n \"spool.queue\": options.queueName,\n });\n await recordDrops(reason, 1);\n return { spooled: false, reason: \"capacity-exceeded\" };\n };\n\n if (options.maxBytes !== undefined && bytes > options.maxBytes) {\n // Larger than the whole budget: evicting everything else still would not\n // make room, so it is the one batch that is refused under either policy.\n return refuse(\"size\");\n }\n\n let queued = await listWithSizes();\n const now = options.clock.now();\n const expired = queued.filter((file) => isExpired(file, now));\n if (expired.length > 0) {\n await recordDrops(\"age\", await evict(expired));\n queued = queued.filter((file) => !isExpired(file, now));\n }\n\n const overflow = options.overflow ?? \"refuse-new\";\n const totalBytes = (): number => queued.reduce((sum, file) => sum + file.bytes, 0);\n if (overflow === \"refuse-new\") {\n if (queued.length >= options.maxFiles) {\n return refuse(\"count\");\n }\n if (options.maxBytes !== undefined && totalBytes() + bytes > options.maxBytes) {\n return refuse(\"size\");\n }\n } else {\n // Oldest first: the listing is sorted by enqueue time.\n const overCount = Math.max(0, queued.length + 1 - options.maxFiles);\n if (overCount > 0) {\n await recordDrops(\"count\", await evict(queued.slice(0, overCount)));\n queued = queued.slice(overCount);\n }\n if (options.maxBytes !== undefined) {\n let excess = totalBytes() + bytes - options.maxBytes;\n let cut = 0;\n while (excess > 0 && cut < queued.length) {\n excess -= queued[cut]?.bytes ?? 0;\n cut += 1;\n }\n if (cut > 0) {\n await recordDrops(\"size\", await evict(queued.slice(0, cut)));\n queued = queued.slice(cut);\n }\n }\n }\n\n const fileName = `${String(now).padStart(16, \"0\")}-${randomBytes(6).toString(\"hex\")}.json`;\n const target = path.join(queueDir, fileName);\n const tmp = path.join(queueDir, `.tmp-${randomBytes(6).toString(\"hex\")}.json`);\n await writeFile(tmp, serialized, \"utf8\");\n await rename(tmp, target);\n return { spooled: true };\n };\n\n const drain = async (\n send: (batch: TBatch) => Promise<SpoolSendOutcome>,\n drainOptions?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult> => {\n await ensureDirs();\n const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;\n let files = await listSorted();\n if (options.maxAgeMillis !== undefined) {\n // Expired batches are dropped, not sent: a collector would place them far in\n // the past, and they would spend this invocation's short flush window.\n const now = options.clock.now();\n const expired = files\n .map((name): QueuedFile => {\n const enqueuedAt = enqueuedAtOf(name);\n return { name, bytes: 0, ...(enqueuedAt === undefined ? {} : { enqueuedAt }) };\n })\n .filter((file) => isExpired(file, now));\n if (expired.length > 0) {\n await recordDrops(\"age\", await evict(expired));\n const gone = new Set(expired.map((file) => file.name));\n files = files.filter((name) => !gone.has(name));\n }\n }\n let drained = 0;\n let failed = 0;\n let quarantined = 0;\n let index = 0;\n\n for (; index < files.length && index < cap; index += 1) {\n const fileName = files[index];\n if (fileName === undefined) {\n break;\n }\n const filePath = path.join(queueDir, fileName);\n\n /**\n * Move a file out of the queue, or delete it if quarantine is unavailable.\n *\n * Getting it *out of the queue* is the part that matters. A file the drain\n * cannot use and cannot move would be re-read on every pass, and because the\n * head is processed first it would block every healthy batch behind it — the\n * one failure mode a retry queue must not have. So a failed quarantine falls\n * back to deleting: losing one unusable batch beats losing all the usable\n * ones queued behind it.\n */\n const quarantine = async (rejection: string): Promise<void> => {\n quarantined += 1;\n options.logger?.error(\"durable spool quarantined an unusable batch\", {\n \"spool.rejection\": rejection,\n \"spool.file\": fileName,\n \"spool.queue\": options.queueName,\n });\n try {\n await rename(filePath, path.join(corruptDir, fileName));\n } catch {\n await unlink(filePath).catch(() => undefined);\n }\n };\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(await readFile(filePath, \"utf8\")) as unknown;\n } catch {\n await quarantine(\"unparseable-json\");\n continue;\n }\n\n const validation = options.validate(parsed, {\n providerId: options.providerId,\n installationId: options.installationId,\n });\n if (\"rejection\" in validation) {\n await quarantine(validation.rejection);\n continue;\n }\n\n let delivered: SpoolSendOutcome;\n try {\n delivered = await send(validation.batch);\n } catch {\n delivered = false;\n }\n if (delivered === \"discard\") {\n // Permanently refused: retrying can never succeed, and stopping here would\n // wedge every batch queued behind it.\n if (await unlink(filePath).then(() => true, () => false)) {\n await recordDrops(\"rejected\", 1);\n }\n continue;\n }\n if (delivered) {\n await unlink(filePath).catch(() => undefined);\n drained += 1;\n } else {\n failed += 1;\n break;\n }\n }\n\n const remaining = (await listSorted()).length;\n return { drained, remaining, failed, quarantined };\n };\n\n return {\n enqueue,\n drain,\n size: async (): Promise<number> => {\n await ensureDirs();\n return (await listSorted()).length;\n },\n stats: (): Promise<SpoolStats> => readSpoolQueueStats(queueDir),\n };\n};\n","import type { Attributes } from \"@opentelemetry/api\";\n\nimport type { Clock, Logger } from \"../runtime/ports.js\";\nimport type { StoreNamespace } from \"../state/keys.js\";\nimport {\n createSpoolQueue,\n type SpoolDrainResult,\n type SpoolEnqueueResult,\n type SpoolValidation,\n type SpoolOverflowPolicy,\n type SpoolSendOutcome,\n type SpoolStats,\n} from \"./spool-queue.js\";\n\n/**\n * One log record, flattened to plain JSON so it survives a process exit.\n *\n * `body` is a string or absent, never a nested value: the mapping only ever\n * produces a disclosed text body, and admitting anything richer here would make a\n * spool file a route for a structure the live path would have refused.\n */\nexport type SerializedLogRecord = {\n readonly eventName: string;\n readonly severityNumber: number;\n readonly severityText?: string;\n readonly body?: string;\n readonly timeMillis: number;\n readonly observedTimeMillis: number;\n /** Absent only on a record that was mapped without trace correlation. */\n readonly traceId?: string;\n readonly spanId?: string;\n readonly attributes: Attributes;\n};\n\nexport type LogSpoolBatch = {\n readonly providerId: string;\n readonly installationId: string;\n readonly resourceAttributes: Attributes;\n readonly instrumentationScope: { readonly name: string; readonly version?: string };\n readonly records: readonly SerializedLogRecord[];\n readonly enqueuedAt: number;\n};\n\n/** Upper bounds on a replayed batch. A spool file is untrusted input. */\nexport const MAX_SPOOLED_LOG_RECORDS_PER_BATCH = 4_096;\nexport const MAX_SPOOLED_LOG_STRING_LENGTH = 8_192;\n/**\n * Longest replayed body.\n *\n * Matches the live mapping's `MAX_LOG_BODY_CHARACTERS`, because \"what the mapping\n * would have put on the wire\" and \"what is accepted back off disk\" diverging is\n * the whole vulnerability — a hand-edited spool file must not be able to export a\n * body the live path would have cut.\n */\nexport const MAX_SPOOLED_LOG_BODY_LENGTH = 8_192;\nconst MAX_SPOOLED_ATTRIBUTES_PER_RECORD = 256;\nconst TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;\nconst SPAN_ID_PATTERN = /^[0-9a-f]{16}$/;\n\nconst isFiniteNonNegative = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n\nconst isBoundedString = (value: unknown, maxLength = MAX_SPOOLED_LOG_STRING_LENGTH): value is string =>\n typeof value === \"string\" && value.length > 0 && value.length <= maxLength;\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isReplayableAttributeValue = (value: unknown): boolean => {\n if (Array.isArray(value)) {\n // OTLP permits homogeneous primitive arrays; anything nested is not an\n // attribute and would fail encoding.\n return value.every(\n (item) =>\n (typeof item === \"string\" && item.length <= MAX_SPOOLED_LOG_STRING_LENGTH) ||\n (typeof item === \"number\" && Number.isFinite(item)) ||\n typeof item === \"boolean\" ||\n item === null,\n );\n }\n return (\n (typeof value === \"string\" && value.length <= MAX_SPOOLED_LOG_STRING_LENGTH) ||\n (typeof value === \"number\" && Number.isFinite(value)) ||\n typeof value === \"boolean\" ||\n value === undefined\n );\n};\n\n/**\n * Whether one recorded log record can be replayed.\n *\n * Every field is checked, not just the ones a happy path reads. The rebuilt record\n * goes straight to the OTLP encoder, which assumes the shapes the type declares —\n * so a `severityNumber` of `null`, a nested object in `attributes`, or a trace id\n * of the wrong width becomes an encoder error deep inside the exporter rather than\n * a rejected file here. Trace and span ids are held to their hex forms because a\n * malformed id is not a correlation a collector can resolve.\n */\nconst isReplayableLogRecord = (value: unknown): value is SerializedLogRecord => {\n if (!isPlainObject(value)) {\n return false;\n }\n if (!isBoundedString(value.eventName)) {\n return false;\n }\n if (!isFiniteNonNegative(value.severityNumber)) {\n return false;\n }\n if (value.severityText !== undefined && typeof value.severityText !== \"string\") {\n return false;\n }\n if (\n value.body !== undefined &&\n (typeof value.body !== \"string\" || value.body.length > MAX_SPOOLED_LOG_BODY_LENGTH)\n ) {\n return false;\n }\n if (!isFiniteNonNegative(value.timeMillis) || !isFiniteNonNegative(value.observedTimeMillis)) {\n return false;\n }\n // Correlation is all-or-nothing: a trace id without a span id (or the reverse)\n // is not a span reference, and half of one would export as a record pointing at\n // span `0000000000000000`.\n const hasTrace = value.traceId !== undefined;\n const hasSpan = value.spanId !== undefined;\n if (hasTrace !== hasSpan) {\n return false;\n }\n if (hasTrace && (typeof value.traceId !== \"string\" || !TRACE_ID_PATTERN.test(value.traceId))) {\n return false;\n }\n if (hasSpan && (typeof value.spanId !== \"string\" || !SPAN_ID_PATTERN.test(value.spanId))) {\n return false;\n }\n if (!isPlainObject(value.attributes)) {\n return false;\n }\n const entries = Object.entries(value.attributes);\n if (entries.length > MAX_SPOOLED_ATTRIBUTES_PER_RECORD) {\n return false;\n }\n return entries.every(([, attribute]) => isReplayableAttributeValue(attribute));\n};\n\nexport type LogSpoolBatchRejection =\n | \"not-an-object\"\n | \"identity-mismatch\"\n | \"resource-attributes-invalid\"\n | \"instrumentation-scope-invalid\"\n | \"records-invalid\"\n | \"record-field-invalid\";\n\n/**\n * Validate a whole batch read back from disk, before any of it reaches an exporter.\n *\n * The identity check alone is not enough. `records` being anything other than an\n * array makes the sender's `records.map(...)` throw, and a throwing send is\n * indistinguishable from an unreachable collector — so the drain would treat a\n * permanently poisoned file as a transient failure and stop at it on every pass,\n * wedging the queue head and every batch behind it forever. Validation is what\n * turns that into a single quarantined file.\n */\nexport const validateLogSpoolBatch = (\n value: unknown,\n identity: StoreNamespace,\n): SpoolValidation<LogSpoolBatch> => {\n if (!isPlainObject(value)) {\n return { rejection: \"not-an-object\" satisfies LogSpoolBatchRejection };\n }\n if (\n value.providerId !== identity.providerId ||\n value.installationId !== identity.installationId\n ) {\n return { rejection: \"identity-mismatch\" satisfies LogSpoolBatchRejection };\n }\n if (!isPlainObject(value.resourceAttributes)) {\n // Not merely absent: the resource is rebuilt by iterating it, and a string or\n // an array would silently produce a resource built from its indices.\n return { rejection: \"resource-attributes-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (\n !isPlainObject(value.instrumentationScope) ||\n !isBoundedString(value.instrumentationScope.name)\n ) {\n return { rejection: \"instrumentation-scope-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (\n value.instrumentationScope.version !== undefined &&\n typeof value.instrumentationScope.version !== \"string\"\n ) {\n return { rejection: \"instrumentation-scope-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (!Array.isArray(value.records) || value.records.length === 0) {\n return { rejection: \"records-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (value.records.length > MAX_SPOOLED_LOG_RECORDS_PER_BATCH) {\n return { rejection: \"records-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (!value.records.every(isReplayableLogRecord)) {\n return { rejection: \"record-field-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (!isFiniteNonNegative(value.enqueuedAt)) {\n return { rejection: \"not-an-object\" satisfies LogSpoolBatchRejection };\n }\n return { batch: value as unknown as LogSpoolBatch };\n};\n\nexport type DurableLogSpoolOptions = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Refuses new entries once this many are queued. Default 500. */\n readonly maxSpoolFiles?: number;\n /**\n * Queue directory below the identity namespace. Default `spool-logs`; each\n * export destination other than `default` gets its own.\n */\n readonly queueName?: string;\n /** Bound on total queued bytes. Unbounded when absent. */\n readonly maxBytes?: number;\n /** Batches older than this are dropped rather than sent. No age bound when absent. */\n readonly maxAgeMillis?: number;\n /** Default `refuse-new`, the original behavior. */\n readonly overflow?: SpoolOverflowPolicy;\n};\n\n/**\n * Durable filesystem queue for log batches a collector could not accept.\n *\n * Rooted at `<rootDir>/<providerId>/<installationId>/spool-logs`, deliberately a\n * different directory from the trace spool: the two hold different encodings, so a\n * single mixed queue would have each signal's sender quarantining the other's\n * perfectly deliverable batches. Separate directories also mean a logs outage\n * cannot consume the trace spool's capacity, which is what keeps the primary\n * signal unaffected by a misconfigured logs endpoint.\n */\nexport interface DurableLogSpool {\n enqueue(batch: LogSpoolBatch): Promise<SpoolEnqueueResult>;\n /** Sequential, bounded drain: stops after the first failed send, or after `maxBatches`. */\n drain(\n send: (batch: LogSpoolBatch) => Promise<SpoolSendOutcome>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\n /**\n * Depth, bytes, and persisted drop counts. Optional so a host's own\n * implementation of this interface keeps compiling; the file-backed one has it.\n */\n stats?(): Promise<SpoolStats>;\n}\n\nexport const DEFAULT_MAX_LOG_SPOOL_FILES = 500;\n\nexport const createFileDurableLogSpool = (options: DurableLogSpoolOptions): DurableLogSpool =>\n createSpoolQueue<LogSpoolBatch>({\n rootDir: options.rootDir,\n providerId: options.providerId,\n installationId: options.installationId,\n clock: options.clock,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_LOG_SPOOL_FILES,\n queueName: options.queueName ?? \"spool-logs\",\n ...(options.maxBytes === undefined ? {} : { maxBytes: options.maxBytes }),\n ...(options.maxAgeMillis === undefined ? {} : { maxAgeMillis: options.maxAgeMillis }),\n ...(options.overflow === undefined ? {} : { overflow: options.overflow }),\n validate: validateLogSpoolBatch,\n });\n","import type { Attributes } from \"@opentelemetry/api\";\n\nimport type { Clock, Logger } from \"../runtime/ports.js\";\nimport type { StoreNamespace } from \"../state/keys.js\";\nimport { isMetricInstrumentName, METRIC_INSTRUMENTS, type MetricPoint } from \"./metric-model.js\";\nimport {\n createSpoolQueue,\n type SpoolDrainResult,\n type SpoolEnqueueResult,\n type SpoolOverflowPolicy,\n type SpoolSendOutcome,\n type SpoolStats,\n type SpoolValidation,\n} from \"./spool-queue.js\";\n\n/**\n * A batch of metric points a destination could not take, kept for the next\n * invocation.\n *\n * Points are plain JSON (`MetricPoint`), so a batch replays without the process\n * that recorded it. A cumulative point is a snapshot of a running total: replaying\n * an old one after a newer one was delivered restates an earlier value with an\n * earlier timestamp, which a receiver orders by time rather than adding.\n */\nexport type MetricSpoolBatch = {\n readonly providerId: string;\n readonly installationId: string;\n readonly resourceAttributes: Attributes;\n readonly instrumentationScope: { readonly name: string; readonly version?: string };\n readonly points: readonly MetricPoint[];\n readonly enqueuedAt: number;\n};\n\nexport const MAX_SPOOLED_METRIC_POINTS_PER_BATCH = 4_096;\nconst MAX_STRING_LENGTH = 8_192;\nconst MAX_ATTRIBUTES_PER_POINT = 64;\nconst MAX_BUCKETS = 64;\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isFiniteNonNegative = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n\nconst isBoundedString = (value: unknown): value is string =>\n typeof value === \"string\" && value.length > 0 && value.length <= MAX_STRING_LENGTH;\n\nconst isPrimitiveAttribute = (value: unknown): boolean =>\n (typeof value === \"string\" && value.length <= MAX_STRING_LENGTH) ||\n (typeof value === \"number\" && Number.isFinite(value)) ||\n typeof value === \"boolean\";\n\n/**\n * Whether one spooled point can be replayed. A spool file is untrusted input, and\n * a malformed point would otherwise fail inside the OTLP encoder, where it reads\n * as an unreachable collector and wedges the queue head.\n */\nconst isReplayablePoint = (value: unknown): value is MetricPoint => {\n if (!isPlainObject(value) || !isMetricInstrumentName(value.instrument)) {\n return false;\n }\n if (value.temporality !== \"cumulative\" && value.temporality !== \"delta\") {\n return false;\n }\n if (!isFiniteNonNegative(value.startTimeMillis) || !isFiniteNonNegative(value.timeMillis)) {\n return false;\n }\n if (!isPlainObject(value.attributes)) {\n return false;\n }\n const entries = Object.entries(value.attributes);\n if (entries.length > MAX_ATTRIBUTES_PER_POINT || !entries.every(([, item]) => isPrimitiveAttribute(item))) {\n return false;\n }\n const instrument = METRIC_INSTRUMENTS[value.instrument];\n if (instrument.kind === \"counter\") {\n return isFiniteNonNegative(value.value) && value.histogram === undefined;\n }\n const histogram = value.histogram;\n if (!isPlainObject(histogram) || value.value !== undefined) {\n return false;\n }\n const buckets = histogram.bucketCounts;\n return (\n isFiniteNonNegative(histogram.count) &&\n Number.isInteger(histogram.count) &&\n isFiniteNonNegative(histogram.sum) &&\n typeof histogram.min === \"number\" &&\n typeof histogram.max === \"number\" &&\n Array.isArray(buckets) &&\n buckets.length <= MAX_BUCKETS &&\n buckets.length === (instrument.boundaries?.length ?? 0) + 1 &&\n buckets.every((count) => isFiniteNonNegative(count) && Number.isInteger(count))\n );\n};\n\nexport const validateMetricSpoolBatch = (\n value: unknown,\n identity: StoreNamespace,\n): SpoolValidation<MetricSpoolBatch> => {\n if (!isPlainObject(value)) {\n return { rejection: \"not-an-object\" };\n }\n if (value.providerId !== identity.providerId || value.installationId !== identity.installationId) {\n return { rejection: \"identity-mismatch\" };\n }\n if (!isPlainObject(value.resourceAttributes)) {\n return { rejection: \"resource-attributes-invalid\" };\n }\n if (!isPlainObject(value.instrumentationScope) || !isBoundedString(value.instrumentationScope.name)) {\n return { rejection: \"instrumentation-scope-invalid\" };\n }\n if (\n value.instrumentationScope.version !== undefined &&\n typeof value.instrumentationScope.version !== \"string\"\n ) {\n return { rejection: \"instrumentation-scope-invalid\" };\n }\n if (\n !Array.isArray(value.points) ||\n value.points.length === 0 ||\n value.points.length > MAX_SPOOLED_METRIC_POINTS_PER_BATCH\n ) {\n return { rejection: \"points-invalid\" };\n }\n if (!value.points.every(isReplayablePoint)) {\n return { rejection: \"point-field-invalid\" };\n }\n if (!isFiniteNonNegative(value.enqueuedAt)) {\n return { rejection: \"not-an-object\" };\n }\n return { batch: value as unknown as MetricSpoolBatch };\n};\n\nexport interface DurableMetricSpool {\n enqueue(batch: MetricSpoolBatch): Promise<SpoolEnqueueResult>;\n drain(\n send: (batch: MetricSpoolBatch) => Promise<SpoolSendOutcome>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\n stats?(): Promise<SpoolStats>;\n}\n\nexport type DurableMetricSpoolOptions = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n readonly maxSpoolFiles?: number;\n /** Queue directory below the identity namespace. Default `spool-metrics`. */\n readonly queueName?: string;\n readonly maxBytes?: number;\n readonly maxAgeMillis?: number;\n readonly overflow?: SpoolOverflowPolicy;\n};\n\nexport const DEFAULT_MAX_METRIC_SPOOL_FILES = 500;\n\n/** Durable queue for metric batches, in its own directory beside the trace and log spools. */\nexport const createFileDurableMetricSpool = (options: DurableMetricSpoolOptions): DurableMetricSpool =>\n createSpoolQueue<MetricSpoolBatch>({\n rootDir: options.rootDir,\n providerId: options.providerId,\n installationId: options.installationId,\n clock: options.clock,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_METRIC_SPOOL_FILES,\n queueName: options.queueName ?? \"spool-metrics\",\n ...(options.maxBytes === undefined ? {} : { maxBytes: options.maxBytes }),\n ...(options.maxAgeMillis === undefined ? {} : { maxAgeMillis: options.maxAgeMillis }),\n ...(options.overflow === undefined ? {} : { overflow: options.overflow }),\n validate: validateMetricSpoolBatch,\n });\n","import type { Attributes } from \"@opentelemetry/api\";\n\nimport type { Clock, Logger } from \"../runtime/ports.js\";\nimport type { StoreNamespace } from \"../state/keys.js\";\n// Deliberately not re-exported: `spool-queue.js` is their one home, and a second\n// `export *` path to the same names makes them ambiguous in the barrel below.\nimport {\n createSpoolQueue,\n type SpoolDrainResult,\n type SpoolEnqueueResult,\n type SpoolOverflowPolicy,\n type SpoolSendOutcome,\n type SpoolStats,\n} from \"./spool-queue.js\";\n\nexport type SerializedSpan = {\n readonly name: string;\n readonly kind: number;\n readonly traceId: string;\n readonly spanId: string;\n /** Absent on batches spooled before cross-process parenting existed, and on root spans. */\n readonly parentSpanId?: string;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly attributes: Attributes;\n readonly statusCode: number;\n readonly statusMessage?: string;\n};\n\nexport type SpoolBatch = {\n readonly providerId: string;\n readonly installationId: string;\n readonly resourceAttributes: Attributes;\n readonly instrumentationScope: { readonly name: string; readonly version?: string };\n readonly spans: readonly SerializedSpan[];\n readonly enqueuedAt: number;\n};\n\n/** Upper bounds on a replayed batch. A spool file is untrusted input. */\nexport const MAX_SPOOLED_SPANS_PER_BATCH = 4_096;\nexport const MAX_SPOOLED_STRING_LENGTH = 8_192;\nconst MAX_SPOOLED_ATTRIBUTES_PER_SPAN = 256;\nconst TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;\nconst SPAN_ID_PATTERN = /^[0-9a-f]{16}$/;\n\nconst isFiniteNonNegative = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n\nconst isBoundedString = (value: unknown, maxLength = MAX_SPOOLED_STRING_LENGTH): value is string =>\n typeof value === \"string\" && value.length > 0 && value.length <= maxLength;\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * Whether one recorded span can be replayed.\n *\n * Every field is checked, not just the ones a happy path reads. `assembleReadableSpan`\n * hands its output straight to the OTLP encoder, which assumes the shapes the type\n * declares — so a `spanId` of the wrong length, a `startMillis` of `null`, or an\n * `attributes` value holding a nested object becomes an encoder error deep inside\n * the exporter rather than a rejected file here. Trace and span ids are further held\n * to their hex forms, because a malformed id is not a span a collector can place.\n */\nconst isReplayableSpan = (value: unknown): value is SerializedSpan => {\n if (!isPlainObject(value)) {\n return false;\n }\n if (!isBoundedString(value.name) || !isFiniteNonNegative(value.kind)) {\n return false;\n }\n if (typeof value.traceId !== \"string\" || !TRACE_ID_PATTERN.test(value.traceId)) {\n return false;\n }\n if (typeof value.spanId !== \"string\" || !SPAN_ID_PATTERN.test(value.spanId)) {\n return false;\n }\n if (\n value.parentSpanId !== undefined &&\n (typeof value.parentSpanId !== \"string\" || !SPAN_ID_PATTERN.test(value.parentSpanId))\n ) {\n return false;\n }\n if (!isFiniteNonNegative(value.startMillis) || !isFiniteNonNegative(value.endMillis)) {\n return false;\n }\n if (!isFiniteNonNegative(value.statusCode)) {\n return false;\n }\n if (\n value.statusMessage !== undefined &&\n typeof value.statusMessage !== \"string\"\n ) {\n return false;\n }\n if (!isPlainObject(value.attributes)) {\n return false;\n }\n const entries = Object.entries(value.attributes);\n if (entries.length > MAX_SPOOLED_ATTRIBUTES_PER_SPAN) {\n return false;\n }\n return entries.every(([, attribute]) => {\n if (Array.isArray(attribute)) {\n // OTLP permits homogeneous primitive arrays; anything nested is not a span\n // attribute and would fail encoding.\n return attribute.every(\n (item) =>\n (typeof item === \"string\" && item.length <= MAX_SPOOLED_STRING_LENGTH) ||\n (typeof item === \"number\" && Number.isFinite(item)) ||\n typeof item === \"boolean\" ||\n item === null,\n );\n }\n return (\n (typeof attribute === \"string\" && attribute.length <= MAX_SPOOLED_STRING_LENGTH) ||\n (typeof attribute === \"number\" && Number.isFinite(attribute)) ||\n typeof attribute === \"boolean\" ||\n attribute === undefined\n );\n });\n};\n\nexport type SpoolBatchRejection =\n | \"not-an-object\"\n | \"identity-mismatch\"\n | \"resource-attributes-invalid\"\n | \"instrumentation-scope-invalid\"\n | \"spans-invalid\"\n | \"span-field-invalid\";\n\n/**\n * Validate a whole batch read back from disk, before any of it reaches an exporter.\n *\n * The identity check alone is not enough. `spans` being anything other than an array\n * makes the sink's `spans.map(...)` throw, and a throwing send is indistinguishable\n * from an unreachable collector — so the drain would treat a permanently poisoned\n * file as a transient failure and stop at it on every pass, wedging the queue head\n * and every batch behind it forever. Validation is what turns that into a single\n * quarantined file.\n */\nexport const validateSpoolBatch = (\n value: unknown,\n identity: StoreNamespace,\n): { readonly batch: SpoolBatch } | { readonly rejection: SpoolBatchRejection } => {\n if (!isPlainObject(value)) {\n return { rejection: \"not-an-object\" };\n }\n if (\n value.providerId !== identity.providerId ||\n value.installationId !== identity.installationId\n ) {\n return { rejection: \"identity-mismatch\" };\n }\n if (!isPlainObject(value.resourceAttributes)) {\n // Not merely absent: `replayResource` iterates it, and a string or an array\n // would silently produce a resource built from its indices.\n return { rejection: \"resource-attributes-invalid\" };\n }\n if (!isPlainObject(value.instrumentationScope) || !isBoundedString(value.instrumentationScope.name)) {\n return { rejection: \"instrumentation-scope-invalid\" };\n }\n if (\n value.instrumentationScope.version !== undefined &&\n typeof value.instrumentationScope.version !== \"string\"\n ) {\n return { rejection: \"instrumentation-scope-invalid\" };\n }\n if (!Array.isArray(value.spans) || value.spans.length === 0) {\n return { rejection: \"spans-invalid\" };\n }\n if (value.spans.length > MAX_SPOOLED_SPANS_PER_BATCH) {\n return { rejection: \"spans-invalid\" };\n }\n if (!value.spans.every(isReplayableSpan)) {\n return { rejection: \"span-field-invalid\" };\n }\n if (!isFiniteNonNegative(value.enqueuedAt)) {\n return { rejection: \"not-an-object\" };\n }\n return { batch: value as unknown as SpoolBatch };\n};\n\nexport type DurableSpoolOptions = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Refuses new entries once this many are queued, rather than growing without bound. Default 500. */\n readonly maxSpoolFiles?: number;\n /**\n * Queue directory below the identity namespace. Default `spool`; each\n * export destination other than `default` gets its own.\n */\n readonly queueName?: string;\n /** Bound on total queued bytes. Unbounded when absent. */\n readonly maxBytes?: number;\n /** Batches older than this are dropped rather than sent. No age bound when absent. */\n readonly maxAgeMillis?: number;\n /** Default `refuse-new`, the original behavior. */\n readonly overflow?: SpoolOverflowPolicy;\n};\n\n/**\n * Durable filesystem queue for export batches a collector could not accept.\n *\n * A hook process is short-lived, so \"retry later\" means \"persist and let a\n * later invocation retry\" rather than an in-process backoff loop. Each\n * instance is rooted at `<rootDir>/<providerId>/<installationId>/spool`; two\n * spools for different providers or installations never share a directory,\n * so a batch from one identity cannot physically land in another's drain —\n * batches cannot mix identities by construction, not by a runtime check\n * alone (the check in {@link DurableSpool.drain} is defense in depth for a\n * hand-edited or misplaced file).\n */\nexport interface DurableSpool {\n enqueue(batch: SpoolBatch): Promise<SpoolEnqueueResult>;\n /** Sequential, bounded drain: stops after the first failed send, or after `maxBatches`. */\n drain(\n send: (batch: SpoolBatch) => Promise<SpoolSendOutcome>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\n /**\n * Depth, bytes, and persisted drop counts. Optional so a host's own\n * implementation of this interface keeps compiling; the file-backed one has it.\n */\n stats?(): Promise<SpoolStats>;\n}\n\n/** Default bound on queued trace batches, so the spool cannot grow without limit. */\nexport const DEFAULT_MAX_SPOOL_FILES = 500;\n\nexport const createFileDurableSpool = (options: DurableSpoolOptions): DurableSpool =>\n createSpoolQueue<SpoolBatch>({\n rootDir: options.rootDir,\n providerId: options.providerId,\n installationId: options.installationId,\n clock: options.clock,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_SPOOL_FILES,\n queueName: options.queueName ?? \"spool\",\n ...(options.maxBytes === undefined ? {} : { maxBytes: options.maxBytes }),\n ...(options.maxAgeMillis === undefined ? {} : { maxAgeMillis: options.maxAgeMillis }),\n ...(options.overflow === undefined ? {} : { overflow: options.overflow }),\n validate: validateSpoolBatch,\n });\n","import { TraceFlags, type AttributeValue, type Attributes, type SpanContext } from \"@opentelemetry/api\";\nimport { ExportResultCode, type ExportResult } from \"@opentelemetry/core\";\nimport { millisToHrTime, type InstrumentationScope } from \"@opentelemetry/core\";\nimport { OTLPLogExporter } from \"@opentelemetry/exporter-logs-otlp-proto\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport type { ReadableLogRecord } from \"@opentelemetry/sdk-logs\";\n\nimport { OTLP_LOGS_PATH, OTLP_TRACES_PATH, withoutTrailingSlashes } from \"../config/otlp-endpoint.js\";\nimport type { ExporterPolicy } from \"../config/schema.js\";\nimport { createHealthTracker, type DeliveryHealthSnapshot } from \"../diagnostics/health.js\";\nimport { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { Clock, Logger, TelemetryEmitResult, TelemetrySink } from \"../runtime/ports.js\";\nimport type { DurableLogSpool, LogSpoolBatch, SerializedLogRecord } from \"./durable-log-spool.js\";\nimport { isPermanentExportFailure } from \"./export-failure.js\";\nimport type { SpoolSendOutcome } from \"./spool-queue.js\";\nimport {\n agreedContextAttributes,\n replayResource,\n resourceFromExporterPolicy,\n resourceWithContext,\n} from \"./exporter-resource.js\";\nimport {\n canonicalEventsToLogRecords,\n NO_LOG_CONTENT,\n type LogContentPolicy,\n} from \"./log-records.js\";\nimport {\n DEFAULT_INSTRUMENTATION_SCOPE,\n type SpanCorrelation,\n type SpanCorrelationResolver,\n} from \"./semconv.js\";\n\n/**\n * OTLP HTTP/protobuf log sink.\n *\n * The logs counterpart of `otlp-sink.ts`, and deliberately its mirror image:\n * semantic mapping lives entirely in `log-records.ts`, and this module owns only\n * batching, delivery, bounded flush/shutdown, health tracking, and — when a spool\n * is configured — persisting what a down collector rejected. Every failure mode\n * (disabled config, missing or underivable endpoint, export failure, timeout,\n * spool write failure) degrades to a reported diagnostic rather than a thrown\n * error, preserving the hook's fail-open contract.\n *\n * The two sinks are separate objects rather than one exporter with two encoders\n * because they fail independently: a collector that has no logs receiver, or an\n * operator who pointed logs at the wrong port, must cost the logs signal and\n * nothing else. The trace pipeline is the one an installation already depends on.\n */\n\n/**\n * Where log records are posted.\n *\n * Resolution order, highest first:\n *\n * 1. `logs.endpoint` — stated outright, used verbatim.\n * 2. the trace endpoint with a trailing `/v1/traces` swapped for `/v1/logs`, which\n * is the shape a collector configured for both signals actually has.\n * 3. the trace endpoint treated as a base URL, with `/v1/logs` appended — the\n * convention the OTLP specification defines for a signal-less endpoint.\n *\n * Returned as a discriminated result rather than a bare string because \"no logs\n * endpoint could be derived\" has to be reportable: silently posting an\n * `ExportLogsServiceRequest` to a traces receiver produces a rejection whose cause\n * is a configuration mistake, and an operator reading \"collector rejected a batch\"\n * would go looking at the collector.\n */\nexport const resolveLogsEndpoint = (\n exporter: ExporterPolicy,\n): { readonly endpoint: string; readonly derived: boolean } | { readonly unresolvable: \"no-endpoint\" } => {\n if (exporter.logs.endpoint !== undefined) {\n return { endpoint: exporter.logs.endpoint, derived: false };\n }\n if (exporter.endpoint === undefined) {\n return { unresolvable: \"no-endpoint\" };\n }\n const trimmed = withoutTrailingSlashes(exporter.endpoint);\n if (trimmed.endsWith(OTLP_LOGS_PATH)) {\n return { endpoint: trimmed, derived: true };\n }\n if (trimmed.endsWith(OTLP_TRACES_PATH)) {\n return {\n endpoint: `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${OTLP_LOGS_PATH}`,\n derived: true,\n };\n }\n return { endpoint: `${trimmed}${OTLP_LOGS_PATH}`, derived: true };\n};\n\n/**\n * Narrow a log record's attributes to what a spool file can hold.\n *\n * Log attributes admit any value (`AnyValue` is `unknown` since api 1.10); the spool's own validator\n * does not, and neither does `assembleReadableSpan`'s sibling contract for traces.\n * This mapping only ever produces primitives, so the filter is unreachable in\n * practice — it is here so that \"what the live path emits\" and \"what survives a\n * spool round-trip\" cannot silently diverge if a future attribute is richer than\n * the queue's schema.\n */\nconst toSpoolAttributes = (attributes: Attributes): Attributes => {\n const safe: Record<string, AttributeValue> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n safe[key] = value;\n continue;\n }\n if (Array.isArray(value) && value.every((item) => typeof item === \"string\")) {\n safe[key] = value;\n }\n }\n return safe;\n};\n\nconst serializeRecord = (record: ReadableLogRecord): SerializedLogRecord => {\n const context = record.spanContext;\n return {\n eventName: record.eventName ?? \"otelhook.record\",\n severityNumber: record.severityNumber ?? 0,\n ...(record.severityText === undefined ? {} : { severityText: record.severityText }),\n ...(typeof record.body === \"string\" ? { body: record.body } : {}),\n timeMillis: record.hrTime[0] * 1000 + Math.round(record.hrTime[1] / 1e6),\n observedTimeMillis:\n record.hrTimeObserved[0] * 1000 + Math.round(record.hrTimeObserved[1] / 1e6),\n ...(context === undefined ? {} : { traceId: context.traceId, spanId: context.spanId }),\n attributes: toSpoolAttributes(record.attributes),\n };\n};\n\nconst deserializeRecord = (\n serialized: SerializedLogRecord,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableLogRecord => {\n const spanContext: SpanContext | undefined =\n serialized.traceId === undefined || serialized.spanId === undefined\n ? undefined\n : {\n traceId: serialized.traceId,\n spanId: serialized.spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n };\n return {\n hrTime: millisToHrTime(serialized.timeMillis),\n hrTimeObserved: millisToHrTime(serialized.observedTimeMillis),\n ...(spanContext === undefined ? {} : { spanContext }),\n severityNumber: serialized.severityNumber,\n ...(serialized.severityText === undefined ? {} : { severityText: serialized.severityText }),\n ...(serialized.body === undefined ? {} : { body: serialized.body }),\n eventName: serialized.eventName,\n resource,\n instrumentationScope: scope,\n attributes: serialized.attributes,\n droppedAttributesCount: 0,\n };\n};\n\nconst chunk = <T,>(items: readonly T[], size: number): readonly (readonly T[])[] => {\n if (size <= 0 || items.length <= size) {\n return [items];\n }\n const chunks: T[][] = [];\n for (let index = 0; index < items.length; index += size) {\n chunks.push(items.slice(index, index + size));\n }\n return chunks;\n};\n\nexport type OtlpLogSinkOptions = {\n readonly exporter: ExporterPolicy;\n /** Header values, kept out of the resolved-config snapshot (ADR: config carries only header *names*). */\n readonly headers?: Readonly<Record<string, string>>;\n readonly providerId: string;\n readonly installationId: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Persists batches an unreachable collector rejected, for a later retry. */\n readonly spool?: DurableLogSpool;\n readonly instrumentationScope?: InstrumentationScope;\n /**\n * Whether disclosed content text may reach a log body. Defaults to\n * {@link NO_LOG_CONTENT}, which is what an unconfigured installation gets.\n */\n readonly content?: LogContentPolicy;\n /**\n * Supplies cross-process pairing so a record correlates to the span id the trace\n * pipeline actually exported. Omitted, records still carry a derived trace and\n * span id, computed from the batch alone.\n *\n * Injected as a plain function rather than as a correlator so the telemetry layer\n * keeps no dependency on lifecycle or on the state store (ADR 0006). When both\n * sinks are wired, the fanout resolves correlation *once* and hands the same\n * answer to each — `correlateBatch` writes state, so calling it twice per batch\n * would record a start edge twice.\n */\n readonly correlate?: SpanCorrelationResolver;\n /** Export destination this sink delivers to; see `OtlpTraceSinkOptions.destination`. */\n readonly destination?: string;\n};\n\nexport interface OtlpLogTelemetrySink extends TelemetrySink {\n health(): DeliveryHealthSnapshot;\n /** Attempts to resend previously spooled batches, bounded by `maxBatches`. */\n drainSpool(\n maxBatches?: number,\n ): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }>;\n}\n\n/**\n * Sink that swallows every batch: logs disabled, or configured but unroutable.\n *\n * Reports **zero accepted and zero rejected**, which is the one place this differs\n * from the trace sink's disabled path — and it has to. The counts a sink returns are\n * what `classifyDurability` decides commit-or-retry from, and they are summed across\n * signals. A disabled signal that claimed to have accepted the batch would make a\n * *total* trace loss look like a partial delivery: `accepted > 0` from a sink that\n * sent nothing, `rejected > 0` from the sink that failed, so the callback would\n * commit as terminally-partial instead of releasing its claim for retry. Contributing\n * nothing is the truthful answer, and it leaves durability decided entirely by the\n * signals that actually tried — so an installation with logs off behaves exactly as\n * it did before logs existed.\n *\n * Health still records the batch as accepted: nothing failed, and a disabled signal\n * must not read as unhealthy.\n */\nconst createDisabledSink = (destination?: string): OtlpLogTelemetrySink => {\n const health = createHealthTracker(\n \"telemetry-log-sink\",\n destination === undefined ? {} : { destination },\n );\n return {\n emit: (events): Promise<TelemetryEmitResult> => {\n health.recordSuccess(events.length);\n return Promise.resolve({ accepted: 0, rejected: 0, errors: [] });\n },\n flush: (): Promise<void> => Promise.resolve(),\n shutdown: (): Promise<void> => Promise.resolve(),\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool: (): Promise<{\n readonly drained: number;\n readonly remaining: number;\n readonly failed: number;\n }> => Promise.resolve({ drained: 0, remaining: 0, failed: 0 }),\n };\n};\n\n/**\n * Whether this configuration can deliver logs at all.\n *\n * Separated from the constructor so `doctor` can report the same verdict without\n * building an exporter, and so each refusal names itself rather than collapsing\n * into one \"disabled\" state an operator then has to bisect.\n */\nexport type LogsDeliverability =\n | { readonly status: \"configured\"; readonly endpoint: string; readonly derivedEndpoint: boolean }\n | {\n readonly status: \"disabled\";\n readonly reason:\n | \"logs-disabled\"\n | \"exporter-disabled\"\n | \"protocol-none\"\n | \"protocol-unsupported\"\n | \"no-endpoint\";\n };\n\nexport const describeLogsDeliverability = (exporter: ExporterPolicy): LogsDeliverability => {\n if (!exporter.logs.enabled) {\n return { status: \"disabled\", reason: \"logs-disabled\" };\n }\n if (!exporter.enabled) {\n return { status: \"disabled\", reason: \"exporter-disabled\" };\n }\n if (exporter.protocol === \"none\") {\n return { status: \"disabled\", reason: \"protocol-none\" };\n }\n if (exporter.protocol !== \"http/protobuf\") {\n return { status: \"disabled\", reason: \"protocol-unsupported\" };\n }\n const resolved = resolveLogsEndpoint(exporter);\n if (\"unresolvable\" in resolved) {\n return { status: \"disabled\", reason: \"no-endpoint\" };\n }\n return { status: \"configured\", endpoint: resolved.endpoint, derivedEndpoint: resolved.derived };\n};\n\nconst DISABLED_DETAIL: Readonly<Record<Extract<LogsDeliverability, { status: \"disabled\" }>[\"reason\"], string>> =\n Object.freeze({\n \"logs-disabled\": \"otlp log sink disabled: exporter.logs.enabled is false\",\n \"exporter-disabled\": \"otlp log sink disabled: the exporter is disabled\",\n \"protocol-none\": \"otlp log sink disabled: protocol is none\",\n \"protocol-unsupported\":\n \"otlp log sink disabled: protocol not supported by this build, falling back to disabled\",\n \"no-endpoint\": \"otlp log sink disabled: no logs endpoint configured and none could be derived\",\n });\n\n/**\n * OTLP HTTP/protobuf {@link TelemetrySink} for the logs signal.\n *\n * A disabled sink never calls `correlate`: with nothing being exported there is no\n * span to correlate to, and writing correlation state anyway would leave a disabled\n * installation quietly accumulating files.\n */\nexport const createOtlpLogSink = (options: OtlpLogSinkOptions): OtlpLogTelemetrySink => {\n const destinationFields =\n options.destination === undefined ? {} : { \"export.destination\": options.destination };\n const deliverability = describeLogsDeliverability(options.exporter);\n if (deliverability.status === \"disabled\") {\n if (deliverability.reason !== \"logs-disabled\") {\n // `logs-disabled` is the default posture, not a misconfiguration, so it is\n // not worth a warning on every invocation. The rest are: somebody asked for\n // logs and will not get them.\n options.logger?.warn(DISABLED_DETAIL[deliverability.reason], {\n \"exporter.protocol\": options.exporter.protocol,\n ...destinationFields,\n });\n }\n return createDisabledSink(options.destination);\n }\n\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const resource = resourceFromExporterPolicy(options.exporter);\n const content = options.content ?? NO_LOG_CONTENT;\n const health = createHealthTracker(\n \"telemetry-log-sink\",\n options.destination === undefined ? {} : { destination: options.destination },\n );\n const exporter = new OTLPLogExporter({\n url: deliverability.endpoint,\n headers: { ...options.headers },\n timeoutMillis: options.exporter.timeoutMillis,\n });\n let shutdownCompleted = false;\n\n const exportRecords = (records: readonly ReadableLogRecord[]): Promise<ExportResult> =>\n new Promise((resolve) => {\n exporter.export([...records], (result: ExportResult) => resolve(result));\n });\n\n const toSpoolBatch = (records: readonly ReadableLogRecord[], batchResource: Resource): LogSpoolBatch => ({\n providerId: options.providerId,\n installationId: options.installationId,\n resourceAttributes: { ...batchResource.attributes },\n instrumentationScope: {\n name: scope.name,\n ...(scope.version === undefined ? {} : { version: scope.version }),\n },\n records: records.map(serializeRecord),\n enqueuedAt: options.clock.now(),\n });\n\n const sendSerializedBatch = async (batch: LogSpoolBatch): Promise<SpoolSendOutcome> => {\n const batchResource = replayResource(batch.resourceAttributes, options.exporter);\n const records = batch.records.map((record) =>\n deserializeRecord(record, batchResource, batch.instrumentationScope),\n );\n const result = await exportRecords(records);\n if (result.code === ExportResultCode.SUCCESS) {\n return true;\n }\n return isPermanentExportFailure(result) ? \"discard\" : false;\n };\n\n /**\n * Cross-process pairing is an enrichment, never a precondition: if state is\n * unreadable the batch still exports, with each record correlated from the batch\n * alone rather than dropped.\n */\n const resolveCorrelations = async (\n events: readonly CanonicalEvent[],\n ): Promise<{\n readonly correlations: readonly SpanCorrelation[];\n readonly available: boolean | undefined;\n }> => {\n if (options.correlate === undefined) {\n return { correlations: [], available: undefined };\n }\n try {\n return { correlations: await options.correlate(events), available: true };\n } catch {\n options.logger?.warn(\"span correlation unavailable; exporting uncorrelated log records\", {});\n return { correlations: [], available: false };\n }\n };\n\n const emit = async (events: Parameters<TelemetrySink[\"emit\"]>[0]): Promise<TelemetryEmitResult> => {\n if (events.length === 0) {\n return { accepted: 0, rejected: 0, errors: [] };\n }\n const resolved = await resolveCorrelations(events);\n // Session context overrides the same keys on the Resource for this batch.\n const batchResource = resourceWithContext(resource, agreedContextAttributes(events));\n const mapped = canonicalEventsToLogRecords(events, {\n resource: batchResource,\n instrumentationScope: scope,\n content,\n correlations: resolved.correlations,\n ...(resolved.available === undefined ? {} : { correlationAvailable: resolved.available }),\n });\n if (mapped.droppedFacts > 0) {\n // Said out loud rather than truncated silently: a caller that saw only\n // \"accepted\" would read a clipped batch as a complete one.\n options.logger?.warn(\"log records dropped: batch or per-event bound reached\", {\n \"logs.dropped_facts\": mapped.droppedFacts,\n });\n }\n const errors: OtelHookErrorInfo[] = [];\n let accepted = 0;\n let rejected = 0;\n\n for (const batch of chunk(mapped.records, options.exporter.logs.maxBatchSize)) {\n if (batch.length === 0) {\n continue;\n }\n let result: ExportResult;\n try {\n result = await exportRecords(batch);\n } catch (thrown) {\n result = {\n code: ExportResultCode.FAILED,\n error: thrown instanceof Error ? thrown : new Error(\"export threw\"),\n };\n }\n if (result.code === ExportResultCode.SUCCESS) {\n accepted += batch.length;\n health.recordSuccess(batch.length, options.clock.now());\n continue;\n }\n\n health.recordFailure(\"telemetry-export-failure\", batch.length, options.clock.now());\n const permanent = isPermanentExportFailure(result);\n if (options.spool !== undefined && !permanent) {\n const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({\n spooled: false as const,\n reason: \"capacity-exceeded\" as const,\n }));\n if (spoolResult.spooled) {\n accepted += batch.length;\n options.logger?.warn(\"log record batch not delivered; spooled for the next invocation\", {\n \"export.batch_size\": batch.length,\n ...destinationFields,\n });\n continue;\n }\n }\n rejected += batch.length;\n errors.push(\n createErrorInfo({\n code: \"telemetry-export-failure\",\n phase: \"export\",\n detail: permanent\n ? \"collector refused a log record batch with a non-retryable status\"\n : \"collector rejected or was unreachable for a log record batch\",\n details: {\n \"export.batch_size\": batch.length,\n \"export.signal\": \"logs\",\n ...destinationFields,\n },\n }),\n );\n }\n\n return { accepted, rejected, errors };\n };\n\n const drainSpool = async (\n maxBatches?: number,\n ): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }> => {\n if (options.spool === undefined) {\n return { drained: 0, remaining: 0, failed: 0 };\n }\n const result = await options.spool.drain(sendSerializedBatch, {\n ...(maxBatches === undefined ? {} : { maxBatches }),\n });\n if (result.drained > 0) {\n health.recordSuccess(result.drained, options.clock.now());\n }\n return result;\n };\n\n const flush = async (): Promise<void> => {\n try {\n await exporter.forceFlush();\n } catch {\n // Best-effort: flush failures are reported through health, never thrown.\n }\n await drainSpool().catch(() => undefined);\n };\n\n const shutdown = async (): Promise<void> => {\n if (shutdownCompleted) {\n return;\n }\n shutdownCompleted = true;\n await flush();\n try {\n await exporter.shutdown();\n } catch {\n // Idempotent, non-throwing per the TelemetrySink contract.\n }\n };\n\n return {\n emit,\n flush,\n shutdown,\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool,\n };\n};\n","import type { ExportResult } from \"@opentelemetry/core\";\n\n/**\n * HTTP statuses that mean \"try again later\" rather than \"never send this\".\n *\n * The OTLP specification's retryable set (429, 502, 503, 504), plus:\n *\n * - 408, which is a timeout by another name;\n * - 500, by decision for this project: a backend that is restarting, overloaded,\n * or briefly broken commonly answers 500, and losing those batches costs more\n * than retrying them. A backend that answers 500 *forever* cannot pin a batch\n * in the spool: every spooled batch is still subject to the spool's age,\n * size, and count bounds (`exporter.spool`), and is dropped and counted when\n * it exceeds them.\n *\n * Anything else the server answered with a status for is a refusal of *this\n * batch*: replaying it can only fail the same way, and a spool that kept it would\n * retry it on every invocation and stop behind it.\n */\nexport const RETRYABLE_HTTP_STATUSES: ReadonlySet<number> = new Set([408, 429, 500, 502, 503, 504]);\n\n/**\n * Whether a failed export was a permanent refusal.\n *\n * With `@opentelemetry/otlp-exporter-base` (OpenTelemetry JS 3.x), the HTTP\n * transport reports a status outside its own retryable set (429, 502, 503, 504)\n * as an `OTLPExporterError` whose numeric `code` is the HTTP status — so 400,\n * 401, 408, 413, and 500 all arrive with a `code`, and 408 and 500 are then held\n * retryable here. Its retryable statuses are retried inside the exporter and,\n * once retries or the timeout run out, arrive without a `code`, as do a refused\n * connection, a timeout, and an oversized response. Those are exactly the \"never\n * reached it, or asked us to come back\" failures a spool is for.\n */\nexport const isPermanentExportFailure = (result: ExportResult): boolean => {\n const code = (result.error as { readonly code?: unknown } | undefined)?.code;\n return (\n typeof code === \"number\" &&\n Number.isInteger(code) &&\n code >= 400 &&\n code < 600 &&\n !RETRYABLE_HTTP_STATUSES.has(code)\n );\n};\n","import { resourceFromAttributes, type Resource } from \"@opentelemetry/resources\";\nimport type { Attributes } from \"@opentelemetry/api\";\n\nimport {\n checkResourceAttributeKey,\n isReservedResourceAttributeKey,\n MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH,\n MAX_RESOURCE_ATTRIBUTES,\n sanitizeResourceAttributes,\n} from \"../config/resource-attributes.js\";\nimport type { ExporterPolicy } from \"../config/schema.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport { MAX_IDENTIFIER_LENGTH } from \"../model/primitives.js\";\n\n/**\n * The OTLP `Resource` every record of a signal is exported under.\n *\n * Shared by the trace and log sinks rather than written twice: a resource carries\n * the service identity, so two sinks disagreeing about how it is built or\n * re-validated would attribute the same installation's two signals to two\n * services — and the divergence would only be visible in a backend, long after.\n */\n\n/**\n * Resource for the live path, from exporter policy.\n *\n * Custom attributes first, then service identity: spread order makes the policy\n * fields structurally unoverridable. `sanitizeResourceAttributes` already drops\n * the reserved keys, so this is belt-and-braces for a caller who hand-built an\n * `ExporterPolicy` without running it through the schema — but between them,\n * `service.name` can only ever come from policy.\n */\nexport const resourceFromExporterPolicy = (policy: ExporterPolicy): Resource =>\n resourceFromAttributes({\n ...sanitizeResourceAttributes(policy.resourceAttributes),\n \"service.name\": policy.serviceName,\n ...(policy.serviceNamespace === undefined\n ? {}\n : { \"service.namespace\": policy.serviceNamespace }),\n });\n\n/**\n * A spool file is a plain JSON file in a state directory, so everything read back\n * out of one is untrusted input — it can be hand-edited, truncated, or written by\n * an older release with a different schema. These bounds mirror the live path's,\n * because \"what the exporter would have refused from a flag\" and \"what it accepts\n * from disk\" diverging is the whole vulnerability.\n */\nconst isReplayableValue = (value: unknown): value is string | number | boolean =>\n (typeof value === \"string\" && value.length <= MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) ||\n (typeof value === \"number\" && Number.isFinite(value)) ||\n typeof value === \"boolean\";\n\n/**\n * Validate a service identity read back from a spool file.\n *\n * `service.name` decides which service every replayed record is attributed to, so\n * a spool that could set it freely could attribute this installation's telemetry\n * to somebody else's service — the one resource field where a forged value is a\n * reporting-integrity problem rather than a cosmetic one. It is therefore held to\n * the same contract as the typed policy field: a non-empty string within\n * {@link MAX_IDENTIFIER_LENGTH}. Anything else is not \"replayed as recorded\", it is\n * discarded in favour of the draining process's own policy.\n */\nconst replayableServiceIdentity = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 && value.length <= MAX_IDENTIFIER_LENGTH\n ? value\n : undefined;\n\n/**\n * Rebuild the resource a spooled batch was recorded with.\n *\n * A recorded `service.name` is a fact about the process that made the observation,\n * not about the one draining the spool, so a *valid* one is replayed as recorded.\n * But every field is re-validated on the way out, at the same bounds the live path\n * enforces: custom keys must pass {@link checkResourceAttributeKey} (which refuses\n * reserved and secret-looking names), values must be primitives within the length\n * bound, the custom count is capped, and the two reserved service fields must look\n * like the identifiers they are. A batch that fails the service check falls back to\n * the live policy rather than exporting with no service identity, because a resource\n * without `service.name` is rejected or bucketed as \"unknown_service\" by most\n * collectors — losing the batch to a tampered byte would make the validation itself\n * the outage.\n */\nexport const replayResource = (attributes: Attributes, policy: ExporterPolicy): Resource => {\n const safe: Record<string, string | number | boolean> = {};\n let customCount = 0;\n for (const [key, value] of Object.entries(attributes)) {\n if (isReservedResourceAttributeKey(key)) {\n // Handled below against the policy fallback, never copied verbatim.\n continue;\n }\n if (!isReplayableValue(value)) {\n continue;\n }\n if (checkResourceAttributeKey(key) !== undefined || customCount >= MAX_RESOURCE_ATTRIBUTES) {\n continue;\n }\n customCount += 1;\n safe[key] = value;\n }\n\n // Reserved keys last and unconditionally, so a spooled custom attribute can\n // never occupy the slot a service field is about to be written into.\n const recordedName = replayableServiceIdentity(attributes[\"service.name\"]);\n const recordedNamespace = replayableServiceIdentity(attributes[\"service.namespace\"]);\n safe[\"service.name\"] = recordedName ?? policy.serviceName;\n const namespace = recordedNamespace ?? policy.serviceNamespace;\n if (namespace !== undefined) {\n safe[\"service.namespace\"] = namespace;\n }\n\n return resourceFromAttributes(safe);\n};\n\n/**\n * The session context attributes every event of a batch agrees on.\n *\n * The core stamps one invocation's events from one context file, so a batch\n * normally agrees on everything. Should two events disagree on a key (a segment\n * boundary inside one callback), or one event lack it, the key is left out: the\n * Resource is shared by the whole batch and must not state a value one of its\n * records contradicts. Each record still carries its own value.\n */\nexport const agreedContextAttributes = (\n events: readonly CanonicalEvent[],\n): Readonly<Record<string, string | number | boolean>> => {\n const [first, ...rest] = events;\n if (first?.contextAttributes === undefined) {\n return {};\n }\n const agreed: Record<string, string | number | boolean> = { ...first.contextAttributes };\n for (const event of rest) {\n for (const key of Object.keys(agreed)) {\n if (event.contextAttributes?.[key] !== agreed[key]) {\n delete agreed[key];\n }\n }\n }\n return agreed;\n};\n\n/**\n * The Resource a batch is exported under, with session context applied.\n *\n * Context overrides only keys the Resource already carries — a stale\n * `factory.attempt.id` from the process environment, say — so the Resource and\n * the records say the same thing to a backend that reads either. It adds no new\n * key: the Resource describes the producer, and the context's own keys are on\n * every record already. Service identity is never touched (context cannot carry\n * it). Returns the input unchanged when nothing applies.\n */\nexport const resourceWithContext = (\n resource: Resource,\n context: Readonly<Record<string, string | number | boolean>>,\n): Resource => {\n const overrides: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(context)) {\n if (\n Object.hasOwn(resource.attributes, key) &&\n !isReservedResourceAttributeKey(key) &&\n resource.attributes[key] !== value\n ) {\n overrides[key] = value;\n }\n }\n if (Object.keys(overrides).length === 0) {\n return resource;\n }\n return resourceFromAttributes({ ...resource.attributes, ...overrides });\n};\n","import { SeverityNumber, TraceFlags, type Attributes, type SpanContext } from \"@opentelemetry/api\";\nimport { millisToHrTime, type InstrumentationScope } from \"@opentelemetry/core\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport type { ReadableLogRecord } from \"@opentelemetry/sdk-logs\";\nimport {\n ATTR_ERROR_TYPE,\n ATTR_GEN_AI_OPERATION_NAME,\n ATTR_GEN_AI_REQUEST_MODEL,\n ATTR_GEN_AI_RESPONSE_MODEL,\n ATTR_GEN_AI_SYSTEM,\n ATTR_GEN_AI_TOOL_CALL_ID,\n ATTR_GEN_AI_TOOL_NAME,\n ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n} from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport type { ContentFact } from \"../model/content.js\";\nimport type { CanonicalEvent, CanonicalEventType } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\nimport {\n exportIdentityAttributes,\n targetAttributes,\n usageTemporalityAttributes,\n} from \"./export-identity.js\";\nimport {\n ATTR_OTELHOOK_USAGE_PARTIAL,\n canonicalEventTraceIdentities,\n DEFAULT_INSTRUMENTATION_SCOPE,\n type SpanCorrelation,\n} from \"./semconv.js\";\n\n/**\n * Pure, stateless canonical-event-to-OTLP-log-record mapping.\n *\n * The counterpart of `semconv.ts` for the logs signal, and deliberately the same\n * shape: no state is read here, no clock is consulted, and the only inputs are\n * the batch plus the correlations the caller already resolved. Batching, retry,\n * spooling, and delivery live in `otlp-log-sink.ts`.\n *\n * ## Why logs at all, when traces already exist\n *\n * A span reports that a tool call happened, how long it took, and whether it\n * failed. It does not report *what was in it*, and it cannot: span attributes are\n * a flat bounded map, one record per span, exported once. A conversation turn is a\n * sequence of distinct pieces of content — a prompt, a response, reasoning, a tool\n * input, a tool output — each with its own role, its own length, and its own\n * disclosure decision. That is a log stream, and OTLP has one.\n *\n * So this mapping emits **one record per content fact**, plus one record per event\n * that carries no content, and correlates every record to the span the same batch\n * produced (or will produce). Nothing here decides *whether* content is\n * disclosed — the privacy service already did that, upstream, once — but the\n * gate is re-checked here because this is the last boundary before the wire.\n *\n * ## Identity and correlation\n *\n * Every record carries the same identity attributes a span does, and a\n * `spanContext` built from {@link canonicalEventTraceIdentities}: the trace id and\n * span id are derived from the event's own `(providerId, sessionId)` and its\n * lifecycle scope, so a record lands in the same trace as its span without either\n * signal knowing about the other. Two sessions in one batch derive two trace ids;\n * there is no batch-level or module-level trace state to contaminate.\n */\n\n/**\n * Version of this mapping.\n *\n * Consumers pin it. Bumped on any change to what an existing attribute or signal\n * *means*; adding a new attribute or a new signal value does not bump it, on the\n * same additive-compatibility rule the canonical model follows\n * (`CANONICAL_SCHEMA_VERSION`). Every record carries it as\n * `otelhook.log.mapping_version`, so a consumer never has to infer which\n * vocabulary it is reading.\n */\nexport const LOG_MAPPING_VERSION = 1 as const;\n\n/**\n * Coarse routing key for one log record.\n *\n * The fact's own `otelhook.content.kind` states precisely what the content is;\n * this states which *pipeline* it belongs to, so an operator can route or drop a\n * whole class (\"no tool output off this host\") with one collector rule rather\n * than an enumeration of event types.\n */\nexport const LOG_SIGNALS = [\n \"session\",\n \"prompt\",\n \"response\",\n \"reasoning\",\n \"tool\",\n \"shell\",\n \"file-operation\",\n \"mcp\",\n \"delegation\",\n \"compaction\",\n \"error\",\n] as const;\nexport type LogSignal = (typeof LOG_SIGNALS)[number];\n\n/**\n * Naming convention that marks a tool call as MCP-mediated.\n *\n * The canonical model has no \"this went through MCP\" field, because no provider\n * contract this package has verified carries one: what they carry is a *tool\n * name*, and three of the four non-synthetic contracts (Claude Code, Codex,\n * Gemini CLI) name MCP tools `mcp__<server>__<tool>`. So the convention is the\n * evidence, matched on the canonical tool name rather than on any provider's\n * payload.\n *\n * This deliberately **under-reports**: a provider whose MCP tool names do not\n * follow the convention classifies as `tool`, which is true but less specific.\n * The alternative — per-provider branching in the canonical layer, or a canonical\n * field no adapter can populate from a verified contract — would either leak\n * provider knowledge across the boundary or invent a contract. See\n * `docs/canonical-log-mapping.md`.\n */\nexport const MCP_TOOL_NAME_PATTERN = /^mcp__/i;\n\n/**\n * Most records one event may produce.\n *\n * Matches `contentFactsSchema`'s own cap, so in practice the mapping never drops\n * a fact an adapter produced; it is the backstop for a hand-built event, not a\n * routine truncation.\n */\nexport const MAX_LOG_RECORDS_PER_EVENT = 64;\n\n/** Most records one batch may produce, whatever the batch contains. */\nexport const MAX_LOG_RECORDS_PER_BATCH = 2_048;\n\n/**\n * Longest disclosed body this mapping will put on the wire.\n *\n * Separate from, and stricter than, the privacy policy's `maxStringLength` (which\n * may be configured up to 64Ki characters): a policy bound is about *disclosure*,\n * this is about the size of one OTLP record. A body cut here is reported as\n * `otelhook.content.body_truncated` rather than as the fact's own `truncated`\n * flag, so \"the privacy policy shortened this\" and \"the log record shortened\n * this\" stay distinguishable.\n */\nexport const MAX_LOG_BODY_CHARACTERS = 8_192;\n\nconst ATTR_OTELHOOK_EVENT_TYPE = \"otelhook.event.type\";\nconst ATTR_OTELHOOK_EVENT_ID = \"otelhook.event.id\";\nconst ATTR_OTELHOOK_EVENT_SEQUENCE = \"otelhook.event.sequence\";\nconst ATTR_OTELHOOK_LOG_SIGNAL = \"otelhook.log.signal\";\nconst ATTR_OTELHOOK_LOG_MAPPING_VERSION = \"otelhook.log.mapping_version\";\nconst ATTR_OTELHOOK_OUTCOME = \"otelhook.outcome\";\nconst ATTR_OTELHOOK_TOOL_KIND = \"otelhook.tool.kind\";\nconst ATTR_OTELHOOK_TOOL_PERMISSION = \"otelhook.tool.permission_decision\";\nconst ATTR_OTELHOOK_DELEGATION_DEPTH = \"otelhook.delegation_depth\";\nconst ATTR_OTELHOOK_SUBAGENT_TYPE = \"otelhook.subagent.type\";\nconst ATTR_OTELHOOK_AGENT_NAME = \"otelhook.agent.name\";\nconst ATTR_OTELHOOK_AGENT_VERSION = \"otelhook.agent.version\";\nconst ATTR_OTELHOOK_SESSION_KIND = \"otelhook.session.kind\";\nconst ATTR_OTELHOOK_PROMPT_SOURCE = \"otelhook.prompt.source\";\nconst ATTR_OTELHOOK_PROMPT_TURN_INDEX = \"otelhook.prompt.turn_index\";\nconst ATTR_OTELHOOK_GENERATION_ID = \"otelhook.generation.id\";\nconst ATTR_OTELHOOK_STOP_REASON = \"otelhook.generation.stop_reason\";\nconst ATTR_OTELHOOK_COMPACTION_TRIGGER = \"otelhook.compaction.trigger\";\nconst ATTR_OTELHOOK_CONTEXT_TOKENS_BEFORE = \"otelhook.compaction.context_tokens_before\";\nconst ATTR_OTELHOOK_CONTEXT_TOKENS_AFTER = \"otelhook.compaction.context_tokens_after\";\nconst ATTR_OTELHOOK_DROPPED_MESSAGES = \"otelhook.compaction.dropped_message_count\";\nconst ATTR_OTELHOOK_ERROR_PHASE = \"otelhook.error.phase\";\nconst ATTR_OTELHOOK_ERROR_RETRYABLE = \"otelhook.error.retryable\";\nconst ATTR_OTELHOOK_ERROR_SEVERITY = \"otelhook.error.severity\";\n\nconst ATTR_CONTENT_KIND = \"otelhook.content.kind\";\nconst ATTR_CONTENT_ROLE = \"otelhook.content.role\";\nconst ATTR_CONTENT_DISCLOSURE = \"otelhook.content.disclosure\";\nconst ATTR_CONTENT_CHARACTER_LENGTH = \"otelhook.content.character_length\";\nconst ATTR_CONTENT_BYTE_LENGTH = \"otelhook.content.byte_length\";\nconst ATTR_CONTENT_HASH = \"otelhook.content.hash\";\nconst ATTR_CONTENT_TRUNCATED = \"otelhook.content.truncated\";\nconst ATTR_CONTENT_SECRETS_REDACTED = \"otelhook.content.secrets_redacted\";\nconst ATTR_CONTENT_LABEL = \"otelhook.content.label\";\nconst ATTR_CONTENT_WITHHELD = \"otelhook.content.withheld\";\nconst ATTR_CONTENT_BODY_TRUNCATED = \"otelhook.content.body_truncated\";\n\n/**\n * Why a content fact reached the wire without its text.\n *\n * Stated rather than left as an absence, because \"this prompt was empty\", \"this\n * deployment omits content\", and \"this deployment discloses content but not to\n * the logs pipeline\" are three different operational facts that all look like a\n * missing body.\n */\nexport type ContentWithholdingReason =\n /** The privacy policy produced no text at all — the default `omit` posture. */\n | \"privacy-policy\"\n /** Content is disclosed elsewhere, but the logs pipeline is not permitted it. */\n | \"logs-content-disabled\"\n /** The fact carries verbatim text and `allowRawContent` is not set. */\n | \"raw-not-permitted\";\n\n/**\n * Whether disclosed content text may reach a log body.\n *\n * Two gates rather than one, and both must open. `includeContent` is the logs\n * pipeline's own switch, and it exists because spans carry no content in *any*\n * content mode: without it, turning on `privacy.contentMode` to get a hash and a\n * length — which is all it ever bought before — would start putting prompts on\n * the wire. `allowRawContent` is the pre-existing verbatim-content opt-in,\n * re-checked here because the sink is the last boundary before the wire and a\n * hand-built fact could otherwise carry `disclosure: \"raw\"` past a policy that\n * never permitted it.\n */\nexport type LogContentPolicy = {\n readonly includeContent: boolean;\n readonly allowRawContent: boolean;\n};\n\n/** Content disabled, which is what an unconfigured installation gets. */\nexport const NO_LOG_CONTENT: LogContentPolicy = Object.freeze({\n includeContent: false,\n allowRawContent: false,\n});\n\nconst codePointLength = (value: string): number => [...value].length;\n\nconst sliceCodePoints = (value: string, max: number): string => {\n let result = \"\";\n let count = 0;\n for (const char of value) {\n if (count >= max) {\n break;\n }\n result += char;\n count += 1;\n }\n return result;\n};\n\n/**\n * Which pipeline an event's records belong to.\n *\n * `factKind` refines the answer where one event type carries more than one kind\n * of content: a `generation.end` holds the response *and*, on providers that\n * report it, the reasoning that produced it, and collapsing those into one signal\n * would make \"drop reasoning, keep responses\" unexpressible.\n */\nexport const logSignalOf = (event: CanonicalEvent, factKind?: ContentFact[\"kind\"]): LogSignal => {\n switch (event.type) {\n case \"session.start\":\n case \"session.end\":\n return \"session\";\n case \"prompt.submitted\":\n return \"prompt\";\n case \"generation.start\":\n return factKind === \"reasoning\" ? \"reasoning\" : \"prompt\";\n case \"generation.end\":\n return factKind === \"reasoning\" ? \"reasoning\" : \"response\";\n case \"subagent.start\":\n case \"subagent.end\":\n return \"delegation\";\n case \"compaction.performed\":\n return \"compaction\";\n case \"error.raised\":\n return \"error\";\n case \"tool.start\":\n return toolSignal(event.toolName, event.toolKind);\n case \"tool.end\":\n // A `tool.end` carries no `toolKind`: only the start edge does. Classifying\n // from the name alone is what the canonical model permits here, so a shell\n // or file operation whose name does not say so lands on `tool` — and the\n // span for the same scope, which *did* recover the kind from state, is where\n // that detail is authoritative.\n return toolSignal(event.toolName, undefined);\n }\n};\n\nconst toolSignal = (\n toolName: string,\n toolKind: Extract<CanonicalEvent, { type: \"tool.start\" }>[\"toolKind\"] | undefined,\n): LogSignal => {\n if (MCP_TOOL_NAME_PATTERN.test(toolName)) {\n return \"mcp\";\n }\n switch (toolKind) {\n case \"execute\":\n return \"shell\";\n case \"read\":\n case \"write\":\n return \"file-operation\";\n case \"delegate\":\n return \"delegation\";\n default:\n return \"tool\";\n }\n};\n\n/**\n * Log signals an adapter declaring these lifecycle events can produce.\n *\n * Derived from the adapter's existing `lifecycleEvents` declaration rather than\n * declared separately, which is the whole point: a hand-maintained second list\n * can disagree with the first, and a capability declaration that has gone stale is\n * worse than none — a consumer cannot tell \"this provider reports no tool output\"\n * from \"this declaration was never updated\".\n *\n * The tool refinements (`shell`, `file-operation`, `mcp`) are reported whenever\n * the adapter emits tool events at all, because which of them a given callback\n * produces depends on the payload, not on the adapter. So this is a statement\n * about what *may* appear, not what always will.\n */\nexport const logSignalsForLifecycleEvents = (\n lifecycleEvents: readonly CanonicalEventType[],\n): readonly LogSignal[] => {\n const signals = new Set<LogSignal>();\n const add = (...values: readonly LogSignal[]): void => {\n for (const value of values) {\n signals.add(value);\n }\n };\n for (const type of lifecycleEvents) {\n switch (type) {\n case \"session.start\":\n case \"session.end\":\n add(\"session\");\n break;\n case \"prompt.submitted\":\n add(\"prompt\");\n break;\n case \"generation.start\":\n add(\"prompt\");\n break;\n case \"generation.end\":\n add(\"response\", \"reasoning\");\n break;\n case \"tool.start\":\n case \"tool.end\":\n add(\"tool\", \"shell\", \"file-operation\", \"mcp\", \"delegation\");\n break;\n case \"subagent.start\":\n case \"subagent.end\":\n add(\"delegation\");\n break;\n case \"compaction.performed\":\n add(\"compaction\");\n break;\n case \"error.raised\":\n add(\"error\");\n break;\n }\n }\n return LOG_SIGNALS.filter((signal) => signals.has(signal));\n};\n\nconst severityFor = (event: CanonicalEvent): SeverityNumber => {\n switch (event.type) {\n case \"error.raised\":\n return event.severity === \"error\" ? SeverityNumber.ERROR : SeverityNumber.WARN;\n case \"session.end\":\n return event.reason === \"error\" || event.reason === \"timeout\"\n ? SeverityNumber.ERROR\n : event.reason === \"aborted\"\n ? SeverityNumber.WARN\n : SeverityNumber.INFO;\n case \"generation.end\":\n case \"tool.end\":\n case \"subagent.end\":\n return event.outcome === \"error\" || event.outcome === \"timeout\"\n ? SeverityNumber.ERROR\n : event.outcome === \"denied\" || event.outcome === \"cancelled\"\n ? SeverityNumber.WARN\n : SeverityNumber.INFO;\n default:\n return SeverityNumber.INFO;\n }\n};\n\nconst SEVERITY_TEXT: Readonly<Record<number, string>> = Object.freeze({\n [SeverityNumber.INFO]: \"INFO\",\n [SeverityNumber.WARN]: \"WARN\",\n [SeverityNumber.ERROR]: \"ERROR\",\n});\n\nconst identityAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n ids: { readonly traceId: string; readonly spanId: string; readonly parentSpanId?: string },\n): Attributes => exportIdentityAttributes(event, resource, ids);\n\n/**\n * Attributes describing the event itself, independent of any content it carries.\n *\n * Every attribute here is a closed vocabulary, an identifier this library\n * derived, a count, or a boolean — the same restriction the privacy service\n * applies everywhere else, so an attribute can never become a second disclosure\n * path alongside the body.\n */\nconst eventAttributes = (event: CanonicalEvent): Attributes => {\n switch (event.type) {\n case \"session.start\":\n return {\n [ATTR_OTELHOOK_SESSION_KIND]: event.sessionKind,\n ...(event.agentName === undefined ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: event.agentName }),\n ...(event.agentVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_AGENT_VERSION]: event.agentVersion }),\n ...(event.model === undefined\n ? {}\n : { [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId }),\n ...targetAttributes(event),\n };\n case \"session.end\":\n return {\n [ATTR_OTELHOOK_OUTCOME]: event.reason,\n ...usageAttributes(event.usage),\n };\n case \"prompt.submitted\":\n return {\n [ATTR_OTELHOOK_PROMPT_SOURCE]: event.promptSource,\n ...(event.turnIndex === undefined\n ? {}\n : { [ATTR_OTELHOOK_PROMPT_TURN_INDEX]: event.turnIndex }),\n ...targetAttributes(event),\n };\n case \"generation.start\":\n return {\n [ATTR_GEN_AI_OPERATION_NAME]: \"chat\",\n [ATTR_OTELHOOK_GENERATION_ID]: event.generationId,\n [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId,\n ...(event.model.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: event.model.vendor }),\n };\n case \"generation.end\":\n return {\n [ATTR_GEN_AI_OPERATION_NAME]: \"chat\",\n [ATTR_OTELHOOK_GENERATION_ID]: event.generationId,\n [ATTR_GEN_AI_RESPONSE_MODEL]: event.model.modelId,\n ...(event.model.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: event.model.vendor }),\n [ATTR_OTELHOOK_OUTCOME]: event.outcome,\n ...(event.stopReason === undefined ? {} : { [ATTR_OTELHOOK_STOP_REASON]: event.stopReason }),\n ...usageAttributes(event.usage),\n ...(event.usage === undefined || event.usagePartial === undefined\n ? {}\n : { [ATTR_OTELHOOK_USAGE_PARTIAL]: event.usagePartial }),\n };\n case \"tool.start\":\n return {\n [ATTR_GEN_AI_TOOL_NAME]: event.toolName,\n [ATTR_GEN_AI_TOOL_CALL_ID]: event.toolCallId,\n [ATTR_OTELHOOK_TOOL_KIND]: event.toolKind,\n ...(event.generationId === undefined\n ? {}\n : { [ATTR_OTELHOOK_GENERATION_ID]: event.generationId }),\n ...targetAttributes(event),\n };\n case \"tool.end\":\n return {\n [ATTR_GEN_AI_TOOL_NAME]: event.toolName,\n [ATTR_GEN_AI_TOOL_CALL_ID]: event.toolCallId,\n [ATTR_OTELHOOK_OUTCOME]: event.outcome,\n ...(event.permissionDecision === undefined\n ? {}\n : { [ATTR_OTELHOOK_TOOL_PERMISSION]: event.permissionDecision }),\n ...targetAttributes(event),\n };\n case \"subagent.start\":\n return {\n [ATTR_OTELHOOK_DELEGATION_DEPTH]: event.delegationDepth,\n ...(event.subagentType === undefined\n ? {}\n : { [ATTR_OTELHOOK_SUBAGENT_TYPE]: event.subagentType }),\n ...(event.model === undefined ? {} : { [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId }),\n };\n case \"subagent.end\":\n return {\n [ATTR_OTELHOOK_OUTCOME]: event.outcome,\n ...usageAttributes(event.usage),\n };\n case \"compaction.performed\":\n return {\n [ATTR_OTELHOOK_COMPACTION_TRIGGER]: event.trigger,\n ...(event.contextTokensBefore === undefined\n ? {}\n : { [ATTR_OTELHOOK_CONTEXT_TOKENS_BEFORE]: event.contextTokensBefore }),\n ...(event.contextTokensAfter === undefined\n ? {}\n : { [ATTR_OTELHOOK_CONTEXT_TOKENS_AFTER]: event.contextTokensAfter }),\n ...(event.droppedMessageCount === undefined\n ? {}\n : { [ATTR_OTELHOOK_DROPPED_MESSAGES]: event.droppedMessageCount }),\n ...usageAttributes(event.usage),\n };\n case \"error.raised\":\n return {\n [ATTR_ERROR_TYPE]: event.errorCode,\n [ATTR_OTELHOOK_ERROR_PHASE]: event.phase,\n [ATTR_OTELHOOK_ERROR_RETRYABLE]: event.retryable,\n [ATTR_OTELHOOK_ERROR_SEVERITY]: event.severity,\n };\n }\n};\n\nconst usageAttributes = (usage: CanonicalUsage | undefined): Attributes =>\n usage === undefined\n ? {}\n : {\n [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: usage.inputTokens,\n [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: usage.outputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: usage.cachedInputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: usage.cacheCreationInputTokens,\n ...usageTemporalityAttributes(usage),\n };\n\n/** Content facts an event carries, paired with the field they came from. */\nconst contentFactsOf = (event: CanonicalEvent): readonly ContentFact[] => {\n switch (event.type) {\n case \"prompt.submitted\":\n return event.content === undefined ? [] : [event.content];\n case \"generation.start\":\n return event.inputContent ?? [];\n case \"generation.end\":\n return event.outputContent ?? [];\n case \"tool.start\":\n return event.input === undefined ? [] : [event.input];\n case \"tool.end\":\n return event.output === undefined ? [] : [event.output];\n case \"error.raised\":\n return event.message === undefined ? [] : [event.message];\n default:\n return [];\n }\n};\n\ntype DisclosedBody =\n | { readonly text: string; readonly truncated: boolean }\n | { readonly withheld: ContentWithholdingReason }\n | { readonly metadataOnly: true };\n\nconst discloseBody = (fact: ContentFact, policy: LogContentPolicy): DisclosedBody => {\n if (fact.text === undefined && fact.characterLength === 0) {\n // The provider sent no text. Distinct from a privacy omit of real content:\n // there is nothing to withhold, and the record must say metadata_only.\n return { metadataOnly: true };\n }\n if (fact.text === undefined) {\n return { withheld: \"privacy-policy\" };\n }\n if (!policy.includeContent) {\n return { withheld: \"logs-content-disabled\" };\n }\n if (fact.disclosure === \"raw\" && !policy.allowRawContent) {\n // Belt to the privacy service's braces: `resolvePrivacyPolicy` already\n // downgrades `raw` without the opt-in, so reaching here means a fact was built\n // outside that path. Refusing rather than trusting it keeps the opt-in a\n // property of the wire, not of one code path.\n return { withheld: \"raw-not-permitted\" };\n }\n const length = codePointLength(fact.text);\n return length <= MAX_LOG_BODY_CHARACTERS\n ? { text: fact.text, truncated: false }\n : { text: sliceCodePoints(fact.text, MAX_LOG_BODY_CHARACTERS), truncated: true };\n};\n\nconst contentAttributes = (fact: ContentFact, body: DisclosedBody): Attributes => ({\n [ATTR_CONTENT_KIND]: fact.kind,\n ...(fact.role === undefined ? {} : { [ATTR_CONTENT_ROLE]: fact.role }),\n [ATTR_CONTENT_DISCLOSURE]: \"metadataOnly\" in body ? \"metadata_only\" : fact.disclosure,\n [ATTR_CONTENT_CHARACTER_LENGTH]: fact.characterLength,\n [ATTR_CONTENT_BYTE_LENGTH]: fact.byteLength,\n [ATTR_CONTENT_HASH]: fact.contentHash,\n [ATTR_CONTENT_TRUNCATED]: fact.truncated,\n [ATTR_CONTENT_SECRETS_REDACTED]: fact.secretsRedacted,\n ...(fact.label === undefined ? {} : { [ATTR_CONTENT_LABEL]: fact.label }),\n ...(\"withheld\" in body\n ? { [ATTR_CONTENT_WITHHELD]: body.withheld }\n : \"metadataOnly\" in body\n ? {}\n : { [ATTR_CONTENT_BODY_TRUNCATED]: body.truncated }),\n});\n\nexport type LogMappingOptions = {\n readonly resource: Resource;\n readonly instrumentationScope?: InstrumentationScope;\n /** Whether disclosed text may reach a body. Defaults to {@link NO_LOG_CONTENT}. */\n readonly content?: LogContentPolicy;\n /**\n * The same cross-process pairing facts the span mapping is given, so a record's\n * `spanContext` names the span id that batch actually exported.\n */\n readonly correlations?: readonly SpanCorrelation[];\n /** See `SemanticMappingOptions.correlationAvailable`. */\n readonly correlationAvailable?: boolean;\n};\n\nexport type LogMappingResult = {\n readonly records: readonly ReadableLogRecord[];\n /**\n * Content facts no record was produced for, because a bound was reached.\n *\n * Reported rather than truncated silently: a caller that logged \"N records\n * exported\" and nothing else would read a clipped batch as a complete one.\n */\n readonly droppedFacts: number;\n};\n\nconst buildRecord = (input: {\n readonly event: CanonicalEvent;\n readonly signal: LogSignal;\n readonly attributes: Attributes;\n readonly body?: string;\n readonly spanContext: SpanContext;\n readonly parentSpanId?: string;\n readonly resource: Resource;\n readonly scope: InstrumentationScope;\n}): ReadableLogRecord => {\n const severityNumber = severityFor(input.event);\n const hrTime = millisToHrTime(input.event.occurredAt);\n return {\n hrTime,\n // A hook observes an event that already happened, and this mapping is pure —\n // there is no clock here to read a real observation time from. Reporting the\n // occurrence time for both is the honest answer: it says \"this is when it\n // happened\" twice rather than inventing a second, wrong timestamp.\n hrTimeObserved: hrTime,\n spanContext: input.spanContext,\n severityNumber,\n severityText: SEVERITY_TEXT[severityNumber] ?? \"INFO\",\n ...(input.body === undefined ? {} : { body: input.body }),\n eventName: `otelhook.${input.event.type}`,\n resource: input.resource,\n instrumentationScope: input.scope,\n attributes: {\n ...identityAttributes(input.event, input.resource, {\n traceId: input.spanContext.traceId,\n spanId: input.spanContext.spanId,\n ...(input.parentSpanId === undefined ? {} : { parentSpanId: input.parentSpanId }),\n }),\n [ATTR_OTELHOOK_EVENT_TYPE]: input.event.type,\n [ATTR_OTELHOOK_EVENT_ID]: input.event.eventId,\n [ATTR_OTELHOOK_EVENT_SEQUENCE]: input.event.sequence,\n [ATTR_OTELHOOK_LOG_SIGNAL]: input.signal,\n [ATTR_OTELHOOK_LOG_MAPPING_VERSION]: LOG_MAPPING_VERSION,\n ...input.attributes,\n },\n droppedAttributesCount: 0,\n };\n};\n\n/**\n * Map one invocation's canonical event batch into OTLP-ready log records.\n *\n * One record per content fact, and one record per event that carries none, so an\n * event is never silently absent from the stream just because the provider\n * reported no text for it.\n */\nexport const canonicalEventsToLogRecords = (\n events: readonly CanonicalEvent[],\n options: LogMappingOptions,\n): LogMappingResult => {\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const content = options.content ?? NO_LOG_CONTENT;\n const identities = canonicalEventTraceIdentities(events, {\n ...(options.correlations === undefined ? {} : { correlations: options.correlations }),\n ...(options.correlationAvailable === undefined\n ? {}\n : { correlationAvailable: options.correlationAvailable }),\n });\n\n const records: ReadableLogRecord[] = [];\n let droppedFacts = 0;\n\n for (const event of events) {\n const identity = identities.get(event.eventId);\n if (identity === undefined) {\n // Unreachable: every event in the batch is given an identity above.\n continue;\n }\n const spanContext: SpanContext = {\n traceId: identity.traceId,\n spanId: identity.spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n };\n const shared = eventAttributes(event);\n const facts = contentFactsOf(event);\n\n if (facts.length === 0) {\n if (records.length >= MAX_LOG_RECORDS_PER_BATCH) {\n droppedFacts += 1;\n continue;\n }\n records.push(\n buildRecord({\n event,\n signal: logSignalOf(event),\n attributes:\n event.type === \"generation.end\"\n ? { ...shared, [ATTR_CONTENT_KIND]: \"response\", [ATTR_CONTENT_DISCLOSURE]: \"metadata_only\" }\n : shared,\n spanContext,\n ...(identity.parentSpanId === undefined ? {} : { parentSpanId: identity.parentSpanId }),\n resource: options.resource,\n scope,\n }),\n );\n continue;\n }\n\n let perEvent = 0;\n for (const fact of facts) {\n if (perEvent >= MAX_LOG_RECORDS_PER_EVENT || records.length >= MAX_LOG_RECORDS_PER_BATCH) {\n droppedFacts += 1;\n continue;\n }\n perEvent += 1;\n const body = discloseBody(fact, content);\n records.push(\n buildRecord({\n event,\n signal: logSignalOf(event, fact.kind),\n attributes: { ...shared, ...contentAttributes(fact, body) },\n ...(\"text\" in body ? { body: body.text } : {}),\n spanContext,\n ...(identity.parentSpanId === undefined ? {} : { parentSpanId: identity.parentSpanId }),\n resource: options.resource,\n scope,\n }),\n );\n }\n }\n\n return { records, droppedFacts };\n};\n","import { ValueType } from \"@opentelemetry/api\";\nimport { ExportResultCode, millisToHrTime, type ExportResult, type InstrumentationScope } from \"@opentelemetry/core\";\nimport { OTLPMetricExporter } from \"@opentelemetry/exporter-metrics-otlp-proto\";\nimport { resourceFromAttributes, type Resource } from \"@opentelemetry/resources\";\nimport {\n AggregationTemporality,\n DataPointType,\n type MetricData,\n type ResourceMetrics,\n} from \"@opentelemetry/sdk-metrics\";\n\nimport { siblingSignalEndpoint } from \"../config/otlp-endpoint.js\";\nimport type { ExporterPolicy } from \"../config/schema.js\";\nimport { createHealthTracker, type DeliveryHealthSnapshot } from \"../diagnostics/health.js\";\nimport { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { Clock, Logger } from \"../runtime/ports.js\";\nimport type { DurableMetricSpool, MetricSpoolBatch } from \"./durable-metric-spool.js\";\nimport { isPermanentExportFailure } from \"./export-failure.js\";\nimport { replayResource, resourceFromExporterPolicy, resourceWithContext } from \"./exporter-resource.js\";\nimport { METRIC_INSTRUMENTS, withoutAccountIdentity, type MetricPoint } from \"./metric-model.js\";\nimport { DEFAULT_INSTRUMENTATION_SCOPE } from \"./semconv.js\";\nimport type { SpoolSendOutcome } from \"./spool-queue.js\";\n\n/**\n * OTLP HTTP/protobuf sink for hook-derived metrics (issue #69).\n *\n * Unlike the trace and log sinks, it does not take canonical events: the points it\n * sends are already aggregated (see `metric-model.ts` and\n * `lifecycle/metric-series.ts`), because cumulative aggregation needs state the\n * telemetry layer must not own. This module only encodes, sends, spools what a\n * destination could not take, and replays the spool on flush.\n *\n * There is deliberately no `MeterProvider` and no periodic reader. A hook process\n * lives for one callback; a reader that collects on an interval would either never\n * fire or hold the process open. Points are exported once, right after the\n * callback's telemetry, inside the same bounded flush window.\n *\n * Fails open like the other sinks: every failure is a diagnostic, never a throw.\n */\n\nexport type MetricsEndpointResolution =\n | { readonly endpoint: string; readonly derived: boolean }\n | { readonly unresolvable: \"no-endpoint\" };\n\n/**\n * Where metric points are posted: `metrics.endpoint` as stated, else the traces\n * endpoint with `/v1/traces` swapped for `/v1/metrics` (or `/v1/metrics` appended\n * to a base URL).\n */\nexport const resolveMetricsEndpoint = (exporter: ExporterPolicy): MetricsEndpointResolution => {\n const stated = exporter.metrics?.endpoint;\n if (stated !== undefined) {\n return { endpoint: stated, derived: false };\n }\n if (exporter.endpoint === undefined) {\n return { unresolvable: \"no-endpoint\" };\n }\n return { endpoint: siblingSignalEndpoint(exporter.endpoint, \"metrics\"), derived: true };\n};\n\nexport type MetricsDeliverability =\n | { readonly status: \"configured\"; readonly endpoint: string; readonly derivedEndpoint: boolean }\n | {\n readonly status: \"disabled\";\n readonly reason:\n | \"metrics-disabled\"\n | \"exporter-disabled\"\n | \"protocol-none\"\n | \"protocol-unsupported\"\n | \"no-endpoint\";\n };\n\nexport const describeMetricsDeliverability = (exporter: ExporterPolicy): MetricsDeliverability => {\n if (exporter.metrics?.enabled !== true) {\n return { status: \"disabled\", reason: \"metrics-disabled\" };\n }\n if (!exporter.enabled) {\n return { status: \"disabled\", reason: \"exporter-disabled\" };\n }\n if (exporter.protocol === \"none\") {\n return { status: \"disabled\", reason: \"protocol-none\" };\n }\n if (exporter.protocol !== \"http/protobuf\") {\n return { status: \"disabled\", reason: \"protocol-unsupported\" };\n }\n const resolved = resolveMetricsEndpoint(exporter);\n if (\"unresolvable\" in resolved) {\n return { status: \"disabled\", reason: \"no-endpoint\" };\n }\n return { status: \"configured\", endpoint: resolved.endpoint, derivedEndpoint: resolved.derived };\n};\n\nconst DISABLED_DETAIL: Readonly<\n Record<Exclude<Extract<MetricsDeliverability, { status: \"disabled\" }>[\"reason\"], \"metrics-disabled\">, string>\n> = Object.freeze({\n \"exporter-disabled\": \"otlp metric sink disabled: the exporter is disabled\",\n \"protocol-none\": \"otlp metric sink disabled: protocol is none\",\n \"protocol-unsupported\": \"otlp metric sink disabled: protocol not supported by this build\",\n \"no-endpoint\": \"otlp metric sink disabled: no metrics endpoint configured and none could be derived\",\n});\n\nexport type MetricExportResult = {\n /** Points delivered or spooled. */\n readonly accepted: number;\n readonly rejected: number;\n readonly errors: readonly OtelHookErrorInfo[];\n};\n\nexport interface OtlpMetricTelemetrySink {\n /** Whether this sink sends anything. A disabled sink accepts nothing and reports nothing. */\n readonly enabled: boolean;\n /**\n * `context`: the session context the points' events agree on (see\n * `agreedContextAttributes`). It overrides the same keys on the Resource for\n * this export, as the trace and log sinks do; the points carry it already.\n */\n exportPoints(\n points: readonly MetricPoint[],\n context?: Readonly<Record<string, string | number | boolean>>,\n ): Promise<MetricExportResult>;\n /** Replays spooled batches; bounded, best-effort, never throws. */\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n health(): DeliveryHealthSnapshot;\n drainSpool(\n maxBatches?: number,\n ): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }>;\n}\n\nexport type OtlpMetricSinkOptions = {\n readonly exporter: ExporterPolicy;\n readonly headers?: Readonly<Record<string, string>>;\n readonly providerId: string;\n readonly installationId: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n readonly spool?: DurableMetricSpool;\n readonly instrumentationScope?: InstrumentationScope;\n /** Export destination this sink delivers to. */\n readonly destination?: string;\n};\n\nconst createDisabledMetricSink = (destination?: string): OtlpMetricTelemetrySink => {\n const health = createHealthTracker(\n \"telemetry-metric-sink\",\n destination === undefined ? {} : { destination },\n );\n return {\n enabled: false,\n exportPoints: (): Promise<MetricExportResult> => Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),\n flush: (): Promise<void> => Promise.resolve(),\n shutdown: (): Promise<void> => Promise.resolve(),\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool: (): Promise<{\n readonly drained: number;\n readonly remaining: number;\n readonly failed: number;\n }> => Promise.resolve({ drained: 0, remaining: 0, failed: 0 }),\n };\n};\n\n/** A sink for a destination that does not take metrics, or a build with metrics off. */\nexport const createDisabledOtlpMetricSink = createDisabledMetricSink;\n\nconst toMetricData = (points: readonly MetricPoint[]): MetricData[] => {\n const byInstrument = new Map<string, MetricPoint[]>();\n for (const point of points) {\n const key = `${point.instrument}|${point.temporality}`;\n const group = byInstrument.get(key) ?? [];\n group.push(point);\n byInstrument.set(key, group);\n }\n const metrics: MetricData[] = [];\n for (const group of byInstrument.values()) {\n const first = group[0];\n if (first === undefined) {\n continue;\n }\n const instrument = METRIC_INSTRUMENTS[first.instrument];\n const descriptor = {\n name: instrument.name,\n description: instrument.description,\n unit: instrument.unit,\n valueType: instrument.valueType === \"int\" ? ValueType.INT : ValueType.DOUBLE,\n };\n const aggregationTemporality =\n first.temporality === \"cumulative\" ? AggregationTemporality.CUMULATIVE : AggregationTemporality.DELTA;\n const times = (point: MetricPoint): { startTime: [number, number]; endTime: [number, number] } => ({\n startTime: millisToHrTime(point.startTimeMillis),\n endTime: millisToHrTime(point.timeMillis),\n });\n if (instrument.kind === \"counter\") {\n metrics.push({\n descriptor,\n aggregationTemporality,\n dataPointType: DataPointType.SUM,\n isMonotonic: true,\n dataPoints: group.map((point) => ({\n ...times(point),\n attributes: { ...point.attributes },\n value: point.value ?? 0,\n })),\n });\n continue;\n }\n metrics.push({\n descriptor,\n aggregationTemporality,\n dataPointType: DataPointType.HISTOGRAM,\n dataPoints: group.map((point) => {\n const histogram = point.histogram;\n return {\n ...times(point),\n attributes: { ...point.attributes },\n value: {\n buckets: {\n boundaries: [...(instrument.boundaries ?? [])],\n counts: [...(histogram?.bucketCounts ?? [])],\n },\n count: histogram?.count ?? 0,\n sum: histogram?.sum ?? 0,\n ...(histogram === undefined || histogram.count === 0\n ? {}\n : { min: histogram.min, max: histogram.max }),\n },\n };\n }),\n });\n }\n return metrics;\n};\n\nexport const createOtlpMetricSink = (options: OtlpMetricSinkOptions): OtlpMetricTelemetrySink => {\n const destinationFields =\n options.destination === undefined ? {} : { \"export.destination\": options.destination };\n const deliverability = describeMetricsDeliverability(options.exporter);\n if (deliverability.status === \"disabled\") {\n if (deliverability.reason !== \"metrics-disabled\") {\n options.logger?.warn(DISABLED_DETAIL[deliverability.reason], {\n \"exporter.protocol\": options.exporter.protocol,\n ...destinationFields,\n });\n }\n return createDisabledMetricSink(options.destination);\n }\n\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n // No account identity on any metric, even if an operator put it on the resource.\n const resource = resourceFromAttributes(\n withoutAccountIdentity(resourceFromExporterPolicy(options.exporter).attributes),\n );\n const health = createHealthTracker(\n \"telemetry-metric-sink\",\n options.destination === undefined ? {} : { destination: options.destination },\n );\n const exporter = new OTLPMetricExporter({\n url: deliverability.endpoint,\n headers: { ...options.headers },\n timeoutMillis: options.exporter.timeoutMillis,\n });\n let shutdownCompleted = false;\n\n const exportResourceMetrics = (\n points: readonly MetricPoint[],\n batchResource: Resource,\n batchScope: InstrumentationScope,\n ): Promise<ExportResult> =>\n new Promise((resolve) => {\n const payload: ResourceMetrics = {\n resource: batchResource,\n scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }],\n };\n try {\n exporter.export(payload, (result: ExportResult) => resolve(result));\n } catch (thrown) {\n resolve({\n code: ExportResultCode.FAILED,\n error: thrown instanceof Error ? thrown : new Error(\"export threw\"),\n });\n }\n });\n\n const toSpoolBatch = (points: readonly MetricPoint[], batchResource: Resource): MetricSpoolBatch => ({\n providerId: options.providerId,\n installationId: options.installationId,\n resourceAttributes: { ...batchResource.attributes },\n instrumentationScope: {\n name: scope.name,\n ...(scope.version === undefined ? {} : { version: scope.version }),\n },\n points: points.map((point) => ({ ...point })),\n enqueuedAt: options.clock.now(),\n });\n\n const sendSerializedBatch = async (batch: MetricSpoolBatch): Promise<SpoolSendOutcome> => {\n const batchResource = resourceFromAttributes(\n withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes),\n );\n const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);\n if (result.code === ExportResultCode.SUCCESS) {\n return true;\n }\n return isPermanentExportFailure(result) ? \"discard\" : false;\n };\n\n const exportPoints = async (\n points: readonly MetricPoint[],\n context?: Readonly<Record<string, string | number | boolean>>,\n ): Promise<MetricExportResult> => {\n if (points.length === 0) {\n return { accepted: 0, rejected: 0, errors: [] };\n }\n const batchResource = context === undefined ? resource : resourceWithContext(resource, context);\n const result = await exportResourceMetrics(points, batchResource, scope);\n if (result.code === ExportResultCode.SUCCESS) {\n health.recordSuccess(points.length, options.clock.now());\n return { accepted: points.length, rejected: 0, errors: [] };\n }\n health.recordFailure(\"telemetry-export-failure\", points.length, options.clock.now());\n const permanent = isPermanentExportFailure(result);\n if (options.spool !== undefined && !permanent) {\n const spooled = await options.spool.enqueue(toSpoolBatch(points, batchResource)).catch(() => ({\n spooled: false as const,\n reason: \"capacity-exceeded\" as const,\n }));\n if (spooled.spooled) {\n options.logger?.warn(\"metric batch not delivered; spooled for the next invocation\", {\n \"export.batch_size\": points.length,\n ...destinationFields,\n });\n return { accepted: points.length, rejected: 0, errors: [] };\n }\n }\n return {\n accepted: 0,\n rejected: points.length,\n errors: [\n createErrorInfo({\n code: \"telemetry-export-failure\",\n phase: \"export\",\n detail: permanent\n ? \"collector refused a metric batch with a non-retryable status\"\n : \"collector rejected or was unreachable for a metric batch\",\n details: {\n \"export.batch_size\": points.length,\n \"export.signal\": \"metrics\",\n ...destinationFields,\n },\n }),\n ],\n };\n };\n\n const drainSpool = async (\n maxBatches?: number,\n ): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }> => {\n if (options.spool === undefined) {\n return { drained: 0, remaining: 0, failed: 0 };\n }\n const result = await options.spool.drain(sendSerializedBatch, {\n ...(maxBatches === undefined ? {} : { maxBatches }),\n });\n if (result.drained > 0) {\n health.recordSuccess(result.drained, options.clock.now());\n }\n return result;\n };\n\n const flush = async (): Promise<void> => {\n try {\n await exporter.forceFlush();\n } catch {\n // Best-effort; reported through health.\n }\n await drainSpool().catch(() => undefined);\n };\n\n const shutdown = async (): Promise<void> => {\n if (shutdownCompleted) {\n return;\n }\n shutdownCompleted = true;\n await flush();\n try {\n await exporter.shutdown();\n } catch {\n // Idempotent and non-throwing.\n }\n };\n\n return {\n enabled: true,\n exportPoints,\n flush,\n shutdown,\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool,\n };\n};\n","import { ExportResultCode, type ExportResult } from \"@opentelemetry/core\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-proto\";\nimport type { InstrumentationScope } from \"@opentelemetry/core\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport type { ReadableSpan } from \"@opentelemetry/sdk-trace\";\n\nimport type { ExporterPolicy } from \"../config/schema.js\";\nimport { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport { createHealthTracker, type DeliveryHealthSnapshot } from \"../diagnostics/health.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { Clock, Logger, TelemetryEmitResult, TelemetrySink } from \"../runtime/ports.js\";\nimport type { DurableSpool, SerializedSpan, SpoolBatch } from \"./durable-spool.js\";\nimport { isPermanentExportFailure } from \"./export-failure.js\";\nimport type { SpoolSendOutcome } from \"./spool-queue.js\";\nimport {\n agreedContextAttributes,\n replayResource,\n resourceFromExporterPolicy,\n resourceWithContext,\n} from \"./exporter-resource.js\";\nimport {\n assembleReadableSpan,\n canonicalEventsToReadableSpans,\n DEFAULT_INSTRUMENTATION_SCOPE,\n type SpanCorrelation,\n type SpanCorrelationResolver,\n} from \"./semconv.js\";\n\nconst chunk = <T,>(items: readonly T[], size: number): readonly (readonly T[])[] => {\n if (size <= 0 || items.length <= size) {\n return [items];\n }\n const chunks: T[][] = [];\n for (let index = 0; index < items.length; index += size) {\n chunks.push(items.slice(index, index + size));\n }\n return chunks;\n};\n\nconst serializeSpan = (span: ReadableSpan): SerializedSpan => ({\n name: span.name,\n kind: span.kind,\n traceId: span.spanContext().traceId,\n spanId: span.spanContext().spanId,\n ...(span.parentSpanContext === undefined\n ? {}\n : { parentSpanId: span.parentSpanContext.spanId }),\n startMillis: span.startTime[0] * 1000 + Math.round(span.startTime[1] / 1e6),\n endMillis: span.endTime[0] * 1000 + Math.round(span.endTime[1] / 1e6),\n attributes: { ...span.attributes },\n statusCode: span.status.code,\n ...(span.status.message === undefined ? {} : { statusMessage: span.status.message }),\n});\n\nconst deserializeSpan = (\n serialized: SerializedSpan,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan =>\n assembleReadableSpan({\n name: serialized.name,\n kind: serialized.kind,\n startMillis: serialized.startMillis,\n endMillis: serialized.endMillis,\n attributes: serialized.attributes,\n status: { code: serialized.statusCode, ...(serialized.statusMessage === undefined ? {} : { message: serialized.statusMessage }) },\n traceId: serialized.traceId,\n spanId: serialized.spanId,\n ...(serialized.parentSpanId === undefined ? {} : { parentSpanId: serialized.parentSpanId }),\n resource,\n instrumentationScope: scope,\n });\n\nexport type OtlpTraceSinkOptions = {\n readonly exporter: ExporterPolicy;\n /** Header values, kept out of the resolved-config snapshot (ADR: config carries only header *names*). */\n readonly headers?: Readonly<Record<string, string>>;\n readonly providerId: string;\n readonly installationId: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Persists batches an unreachable collector rejected, for a later retry. */\n readonly spool?: DurableSpool;\n readonly instrumentationScope?: InstrumentationScope;\n /**\n * Supplies cross-process pairing for lifecycle spans, normally the\n * {@link SpanCorrelator}. Omitted, the sink pairs only within a batch.\n *\n * Injected as a plain function rather than as a correlator so the telemetry\n * layer keeps no dependency on lifecycle or on the state store (ADR 0006).\n */\n readonly correlate?: SpanCorrelationResolver;\n /**\n * Export destination this sink delivers to, when `exporter.destinations` is in\n * use. Labels health snapshots, diagnostics, and log lines; absent, all three are\n * exactly what a single-destination installation has always produced.\n */\n readonly destination?: string;\n};\n\nexport interface OtlpTelemetrySink extends TelemetrySink {\n health(): DeliveryHealthSnapshot;\n /** Attempts to resend previously spooled batches, bounded by `maxBatches`. */\n drainSpool(maxBatches?: number): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }>;\n}\n\n/** Sink that accepts every batch and does nothing else: exporter disabled or protocol `none`. */\nconst createDisabledSink = (destination?: string): OtlpTelemetrySink => {\n const health = createHealthTracker(\n \"telemetry-sink\",\n destination === undefined ? {} : { destination },\n );\n return {\n emit: (events): Promise<TelemetryEmitResult> => {\n health.recordSuccess(events.length);\n return Promise.resolve({ accepted: events.length, rejected: 0, errors: [] });\n },\n flush: (): Promise<void> => Promise.resolve(),\n shutdown: (): Promise<void> => Promise.resolve(),\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool: (): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }> =>\n Promise.resolve({ drained: 0, remaining: 0, failed: 0 }),\n };\n};\n\n/**\n * OTLP HTTP/protobuf {@link TelemetrySink}.\n *\n * Semantic mapping lives entirely in `semconv.ts`; this module only owns\n * batching, delivery, bounded flush/shutdown, health tracking, and — when a\n * spool is configured — persisting what a down collector rejected. Every\n * failure mode (disabled config, missing endpoint, export failure, timeout,\n * spool write failure, unreadable correlation state) degrades to a reported\n * diagnostic rather than a thrown error, preserving the hook's fail-open\n * contract.\n *\n * A disabled sink never calls `correlate`: with nothing being exported there is\n * no span to pair, and writing correlation state anyway would leave a disabled\n * installation quietly accumulating files.\n */\nexport const createOtlpTraceSink = (options: OtlpTraceSinkOptions): OtlpTelemetrySink => {\n const destinationFields =\n options.destination === undefined ? {} : { \"export.destination\": options.destination };\n if (!options.exporter.enabled || options.exporter.protocol === \"none\") {\n return createDisabledSink(options.destination);\n }\n if (options.exporter.endpoint === undefined) {\n options.logger?.warn(\"otlp sink disabled: no endpoint configured\", destinationFields);\n return createDisabledSink(options.destination);\n }\n if (options.exporter.protocol !== \"http/protobuf\") {\n options.logger?.warn(\"otlp sink: protocol not supported by this build, falling back to disabled\", {\n \"exporter.protocol\": options.exporter.protocol,\n ...destinationFields,\n });\n return createDisabledSink(options.destination);\n }\n\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const resource = resourceFromExporterPolicy(options.exporter);\n const health = createHealthTracker(\n \"telemetry-sink\",\n options.destination === undefined ? {} : { destination: options.destination },\n );\n const exporter = new OTLPTraceExporter({\n url: options.exporter.endpoint,\n headers: { ...options.headers },\n timeoutMillis: options.exporter.timeoutMillis,\n });\n let shutdownCompleted = false;\n\n const exportSpans = (spans: readonly ReadableSpan[]): Promise<ExportResult> =>\n new Promise((resolve) => {\n exporter.export([...spans], (result: ExportResult) => resolve(result));\n });\n\n const toSpoolBatch = (spans: readonly ReadableSpan[], batchResource: Resource): SpoolBatch => ({\n providerId: options.providerId,\n installationId: options.installationId,\n resourceAttributes: { ...batchResource.attributes },\n instrumentationScope: { name: scope.name, ...(scope.version === undefined ? {} : { version: scope.version }) },\n spans: spans.map(serializeSpan),\n enqueuedAt: options.clock.now(),\n });\n\n const sendSerializedBatch = async (batch: SpoolBatch): Promise<SpoolSendOutcome> => {\n const batchResource = replayResource(batch.resourceAttributes, options.exporter);\n const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));\n const result = await exportSpans(spans);\n if (result.code === ExportResultCode.SUCCESS) {\n return true;\n }\n return isPermanentExportFailure(result) ? \"discard\" : false;\n };\n\n /**\n * Cross-process pairing is an enrichment, never a precondition: if state is\n * unreadable the batch still exports, with each lifecycle span flagged\n * unpaired rather than dropped.\n *\n * `available` is reported separately from the (possibly empty) list because the\n * mapping needs the two apart. An empty list from a healthy correlator and an\n * empty list from a correlator that threw look identical, and only the first\n * means \"the state store is holding these starts\". Conflating them would drop an\n * unpaired start that nothing recorded, and the export would then report zero\n * rejections — so a caller would commit a callback whose telemetry went nowhere.\n */\n const resolveCorrelations = async (\n events: readonly CanonicalEvent[],\n ): Promise<{\n readonly correlations: readonly SpanCorrelation[];\n readonly available: boolean | undefined;\n }> => {\n if (options.correlate === undefined) {\n return { correlations: [], available: undefined };\n }\n try {\n return { correlations: await options.correlate(events), available: true };\n } catch {\n options.logger?.warn(\"span correlation unavailable; exporting unpaired spans\", {});\n return { correlations: [], available: false };\n }\n };\n\n const emit = async (events: Parameters<TelemetrySink[\"emit\"]>[0]): Promise<TelemetryEmitResult> => {\n if (events.length === 0) {\n return { accepted: 0, rejected: 0, errors: [] };\n }\n const resolved = await resolveCorrelations(events);\n // Session context overrides the same keys on the Resource for this batch, so\n // a backend reading the Resource sees what the records say.\n const batchResource = resourceWithContext(resource, agreedContextAttributes(events));\n const spans = canonicalEventsToReadableSpans(events, {\n resource: batchResource,\n instrumentationScope: scope,\n correlations: resolved.correlations,\n ...(resolved.available === undefined ? {} : { correlationAvailable: resolved.available }),\n });\n const errors: OtelHookErrorInfo[] = [];\n let accepted = 0;\n let rejected = 0;\n\n for (const batch of chunk(spans, options.exporter.maxBatchSize)) {\n if (batch.length === 0) {\n // A batch of only start edges maps to no span at all: a lone `*.start` is\n // held for its end rather than exported. Sending it anyway POSTed an\n // `ExportTraceServiceRequest` with no resource spans — an empty body at the\n // collector — and, against a down collector, spooled an empty batch that\n // the drain could only quarantine.\n continue;\n }\n let result: ExportResult;\n try {\n result = await exportSpans(batch);\n } catch (thrown) {\n result = { code: ExportResultCode.FAILED, error: thrown instanceof Error ? thrown : new Error(\"export threw\") };\n }\n if (result.code === ExportResultCode.SUCCESS) {\n accepted += batch.length;\n health.recordSuccess(batch.length, options.clock.now());\n continue;\n }\n\n health.recordFailure(\"telemetry-export-failure\", batch.length, options.clock.now());\n const permanent = isPermanentExportFailure(result);\n if (options.spool !== undefined && !permanent) {\n const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({\n spooled: false as const,\n reason: \"capacity-exceeded\" as const,\n }));\n if (spoolResult.spooled) {\n accepted += batch.length;\n options.logger?.warn(\"span batch not delivered; spooled for the next invocation\", {\n \"export.batch_size\": batch.length,\n ...destinationFields,\n });\n continue;\n }\n }\n rejected += batch.length;\n errors.push(\n createErrorInfo({\n code: \"telemetry-export-failure\",\n phase: \"export\",\n detail: permanent\n ? \"collector refused a span batch with a non-retryable status\"\n : \"collector rejected or was unreachable for a span batch\",\n details: { \"export.batch_size\": batch.length, ...destinationFields },\n }),\n );\n }\n\n return { accepted, rejected, errors };\n };\n\n const drainSpool = async (\n maxBatches?: number,\n ): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }> => {\n if (options.spool === undefined) {\n return { drained: 0, remaining: 0, failed: 0 };\n }\n const result = await options.spool.drain(sendSerializedBatch, { ...(maxBatches === undefined ? {} : { maxBatches }) });\n if (result.drained > 0) {\n health.recordSuccess(result.drained, options.clock.now());\n }\n return result;\n };\n\n const flush = async (): Promise<void> => {\n try {\n await exporter.forceFlush();\n } catch {\n // Best-effort: flush failures are reported through health, never thrown.\n }\n await drainSpool().catch(() => undefined);\n };\n\n const shutdown = async (): Promise<void> => {\n if (shutdownCompleted) {\n return;\n }\n shutdownCompleted = true;\n await flush();\n try {\n await exporter.shutdown();\n } catch {\n // Idempotent, non-throwing per the TelemetrySink contract.\n }\n };\n\n return {\n emit,\n flush,\n shutdown,\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool,\n };\n};\n","import 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 {\n DEFAULT_DESTINATION_NAME,\n effectiveSpoolPolicy,\n hasConfiguredDestinations,\n resolveDestinationHeaders,\n resolveExportDestinations,\n type ExportDestination,\n} from \"../config/destinations.js\";\nimport { siblingSignalEndpoint } from \"../config/otlp-endpoint.js\";\nimport { effectiveMetricsPolicy, type ExporterPolicy } from \"../config/schema.js\";\nimport type { DeliveryHealthSnapshot } from \"../diagnostics/health.js\";\nimport { createHealthTracker } from \"../diagnostics/health.js\";\nimport { errorInfoFromThrown, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { Clock, Logger, TelemetryEmitResult } from \"../runtime/ports.js\";\nimport { createFileDurableLogSpool, type DurableLogSpool } from \"./durable-log-spool.js\";\nimport { createFileDurableMetricSpool, type DurableMetricSpool } from \"./durable-metric-spool.js\";\nimport { createFileDurableSpool, type DurableSpool } from \"./durable-spool.js\";\nimport type { LogContentPolicy } from \"./log-records.js\";\nimport {\n createOtlpLogSink,\n resolveLogsEndpoint,\n type OtlpLogTelemetrySink,\n} from \"./otlp-log-sink.js\";\nimport {\n createDisabledOtlpMetricSink,\n createOtlpMetricSink,\n type OtlpMetricTelemetrySink,\n} from \"./otlp-metric-sink.js\";\nimport { createOtlpTraceSink, type OtlpTelemetrySink } from \"./otlp-sink.js\";\nimport type { SpanCorrelationResolver } from \"./semconv.js\";\nimport { createSignalFanout, type SignalFanoutSink } from \"./signal-fanout.js\";\n\n/**\n * Spool queue directories for one destination, below the identity namespace.\n *\n * `default` keeps the directories it has always had, so batches an earlier\n * version queued are still drained after an upgrade. Every other destination\n * queues under `destinations/<name>/`, so one destination's outage can never\n * consume another's budget or be drained by another's sender.\n */\nexport const spoolQueueNamesFor = (\n destination: string,\n): { readonly traces: string; readonly logs: string; readonly metrics: string } =>\n destination === DEFAULT_DESTINATION_NAME\n ? { traces: \"spool\", logs: \"spool-logs\", metrics: \"spool-metrics\" }\n : {\n traces: `destinations/${destination}/spool`,\n logs: `destinations/${destination}/spool-logs`,\n metrics: `destinations/${destination}/spool-metrics`,\n };\n\n/**\n * The exporter policy one destination's sinks are built from.\n *\n * Everything but where and how to send — timeout, batch sizes, service identity,\n * resource attributes, log content policy — is shared, so every destination\n * receives the same spans. The `default` destination gets the policy unchanged.\n */\nexport const exporterPolicyForDestination = (\n exporter: ExporterPolicy,\n destination: ExportDestination,\n): ExporterPolicy => {\n if (destination.source === \"exporter\") {\n return exporter;\n }\n const { destinations, endpoint, logs, ...shared } = exporter;\n void destinations;\n void endpoint;\n const tracesEndpoint = destination.tracesEndpoint ?? destination.endpoint;\n // An explicit logs URL wins; otherwise derive from `endpoint` (not from a\n // traces-only override), and failing that let the sink derive from the traces URL.\n const derivedLogs =\n destination.logsEndpoint ??\n (destination.endpoint === undefined\n ? undefined\n : (() => {\n const derived = resolveLogsEndpoint({\n ...exporter,\n endpoint: destination.endpoint,\n logs: { enabled: true, includeContent: false, maxBatchSize: logs.maxBatchSize },\n });\n return \"endpoint\" in derived ? derived.endpoint : undefined;\n })());\n const { metrics: sharedMetrics, ...rest } = shared;\n // Like logs: an explicit metrics URL wins; otherwise derive from `endpoint`, and\n // failing that let the sink derive from the traces URL.\n const derivedMetrics =\n destination.metricsEndpoint ??\n (destination.endpoint === undefined\n ? undefined\n : siblingSignalEndpoint(destination.endpoint, \"metrics\"));\n return {\n ...rest,\n protocol: destination.protocol,\n ...(tracesEndpoint === undefined ? {} : { endpoint: tracesEndpoint }),\n headerNames: Object.keys(destination.headers).sort(),\n logs: {\n ...logs,\n enabled: destination.signals.logs,\n ...(derivedLogs === undefined ? {} : { endpoint: derivedLogs }),\n },\n metrics: {\n ...effectiveMetricsPolicy({ ...exporter, metrics: sharedMetrics }),\n enabled: destination.signals.metrics,\n ...(derivedMetrics === undefined ? {} : { endpoint: derivedMetrics }),\n },\n };\n};\n\n/** The pair of sinks, and their spools, serving one destination. */\nexport type ExportDestinationSinks = {\n readonly name: string;\n readonly traces: OtlpTelemetrySink;\n readonly logs: OtlpLogTelemetrySink;\n readonly spool?: DurableSpool;\n readonly logSpool?: DurableLogSpool;\n /** Hook-derived metrics; a disabled sink unless this destination takes `metrics`. */\n readonly metrics: OtlpMetricTelemetrySink;\n readonly metricSpool?: DurableMetricSpool;\n};\n\n/** A destination left out of this invocation, and why — by name only. */\nexport type SkippedExportDestination = {\n readonly name: string;\n readonly reason: \"header-variable-missing\";\n /** Environment variable *names*; never a value. */\n readonly missingVariables: readonly string[];\n};\n\nexport type ExportDestinationsOptions = {\n readonly exporter: ExporterPolicy;\n /**\n * Header values for the `default` destination's traces: `--header` over\n * `OTEL_EXPORTER_OTLP_TRACES_HEADERS` over `OTEL_EXPORTER_OTLP_HEADERS`, as\n * resolved by `resolveOtlpHeaders`.\n */\n readonly defaultHeaders?: Readonly<Record<string, string>>;\n /**\n * Header values for the `default` destination's logs, when they differ from\n * its traces' (`OTEL_EXPORTER_OTLP_LOGS_HEADERS`). Defaults to {@link defaultHeaders}.\n */\n readonly defaultLogHeaders?: Readonly<Record<string, string>>;\n /**\n * The environment `env:` header references resolve against. Never read\n * implicitly; without it, a destination whose headers reference a variable is\n * skipped and reported.\n */\n readonly headerEnvironment?: Readonly<Record<string, string | undefined>>;\n readonly providerId: string;\n readonly installationId: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Root of the spool trees. Absent, nothing is spooled. */\n readonly spoolRootDir?: string;\n /** Whether the logs signal gets a spool at all; it is only built when logs are on. */\n readonly logContent: LogContentPolicy;\n readonly correlate?: SpanCorrelationResolver;\n};\n\n/**\n * A trace sink for a destination that does not take the traces signal.\n *\n * Contributes zero accepted and zero rejected — unlike a *disabled exporter*,\n * which accepts everything — because the counts decide commit-or-retry and a\n * signal that never tried must not make a real loss elsewhere look delivered.\n */\nconst createOptedOutTraceSink = (destination: string | undefined): OtlpTelemetrySink => {\n const health = createHealthTracker(\n \"telemetry-sink\",\n destination === undefined ? {} : { destination },\n );\n return {\n emit: (): Promise<TelemetryEmitResult> =>\n Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),\n flush: (): Promise<void> => Promise.resolve(),\n shutdown: (): Promise<void> => Promise.resolve(),\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool: (): Promise<{\n readonly drained: number;\n readonly remaining: number;\n readonly failed: number;\n }> => Promise.resolve({ drained: 0, remaining: 0, failed: 0 }),\n };\n};\n\n/**\n * Build one sink pair per enabled destination.\n *\n * With no `exporter.destinations`, this is exactly the single `default`\n * destination the runtime has always built: the same policy, the same header\n * values, the same spool directories.\n */\nexport const createExportDestinationSinks = (\n options: ExportDestinationsOptions,\n): {\n readonly destinations: readonly ExportDestinationSinks[];\n readonly skipped: readonly SkippedExportDestination[];\n} => {\n const labelled = hasConfiguredDestinations(options.exporter);\n const spoolPolicy = effectiveSpoolPolicy(options.exporter);\n const destinations: ExportDestinationSinks[] = [];\n const skipped: SkippedExportDestination[] = [];\n\n for (const destination of resolveExportDestinations(options.exporter)) {\n let headers: Readonly<Record<string, string>> | undefined;\n let logHeaders: Readonly<Record<string, string>> | undefined;\n if (destination.source === \"exporter\") {\n headers = options.defaultHeaders;\n logHeaders = options.defaultLogHeaders ?? options.defaultHeaders;\n } else {\n const resolved = resolveDestinationHeaders(destination.headers, options.headerEnvironment);\n if (resolved.missingVariables.length > 0) {\n // Sending without the header would be refused at best, and at worst\n // accepted into somebody else's unauthenticated tenant. So the destination\n // sits this invocation out, and says which variable it is waiting for.\n options.logger?.warn(\"export destination skipped: a header references an unset environment variable\", {\n \"export.destination\": destination.name,\n \"config.variables\": [...resolved.missingVariables],\n });\n skipped.push({\n name: destination.name,\n reason: \"header-variable-missing\",\n missingVariables: resolved.missingVariables,\n });\n continue;\n }\n headers = resolved.values;\n logHeaders = resolved.values;\n }\n\n const label = labelled ? destination.name : undefined;\n const policy = exporterPolicyForDestination(options.exporter, destination);\n const queues = spoolQueueNamesFor(destination.name);\n const bounds = {\n maxSpoolFiles: spoolPolicy.maxBatches,\n maxBytes: spoolPolicy.maxBytes,\n maxAgeMillis: spoolPolicy.maxAgeMillis,\n overflow: \"drop-oldest\" as const,\n };\n const shared = {\n providerId: options.providerId,\n installationId: options.installationId,\n clock: options.clock,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n };\n const spool =\n options.spoolRootDir === undefined || !destination.signals.traces\n ? undefined\n : createFileDurableSpool({\n rootDir: options.spoolRootDir,\n ...shared,\n ...bounds,\n queueName: queues.traces,\n });\n // Only built when logs are on: a default installation must not create a\n // directory for a signal it never emits.\n const logSpool =\n options.spoolRootDir === undefined || !destination.signals.logs\n ? undefined\n : createFileDurableLogSpool({\n rootDir: options.spoolRootDir,\n ...shared,\n ...bounds,\n queueName: queues.logs,\n });\n\n const metricSpool =\n options.spoolRootDir === undefined || !destination.signals.metrics\n ? undefined\n : createFileDurableMetricSpool({\n rootDir: options.spoolRootDir,\n ...shared,\n ...bounds,\n queueName: queues.metrics,\n });\n\n const sinkShared = {\n exporter: policy,\n ...shared,\n ...(options.correlate === undefined ? {} : { correlate: options.correlate }),\n ...(label === undefined ? {} : { destination: label }),\n };\n const traces = destination.signals.traces\n ? createOtlpTraceSink({\n ...sinkShared,\n ...(headers === undefined || Object.keys(headers).length === 0 ? {} : { headers }),\n ...(spool === undefined ? {} : { spool }),\n })\n : createOptedOutTraceSink(label);\n const logs = createOtlpLogSink({\n ...sinkShared,\n ...(logHeaders === undefined || Object.keys(logHeaders).length === 0\n ? {}\n : { headers: logHeaders }),\n ...(logSpool === undefined ? {} : { spool: logSpool }),\n content: options.logContent,\n });\n const metrics = destination.signals.metrics\n ? createOtlpMetricSink({\n exporter: policy,\n ...shared,\n ...(label === undefined ? {} : { destination: label }),\n ...(headers === undefined || Object.keys(headers).length === 0 ? {} : { headers }),\n ...(metricSpool === undefined ? {} : { spool: metricSpool }),\n })\n : createDisabledOtlpMetricSink(label);\n destinations.push({\n name: destination.name,\n traces,\n logs,\n metrics,\n ...(spool === undefined ? {} : { spool }),\n ...(logSpool === undefined ? {} : { logSpool }),\n ...(metricSpool === undefined ? {} : { metricSpool }),\n });\n }\n return { destinations, skipped };\n};\n\n/**\n * One canonical batch, every destination, in parallel.\n *\n * Each destination is its own {@link createSignalFanout} (traces then logs, which\n * must stay sequential so they share one correlation resolution); destinations run\n * concurrently, each bounded by the exporter's own timeout, so a slow or dead\n * destination costs at most that timeout and never another destination's delivery.\n * A destination that throws is contained to a rejection of its own share.\n *\n * Counts are summed across destinations, which gives the durability decision the\n * right inputs: everything delivered or spooled → `delivered`; nothing → `lost`\n * and safe to retry; some → `partial`, terminal, because retrying would re-export\n * to the destinations that already accepted.\n *\n * With one destination this returns that destination's fanout unchanged.\n */\nexport const createDestinationFanout = (\n destinations: readonly ExportDestinationSinks[],\n): SignalFanoutSink => {\n const fanouts = destinations.map((destination) => ({\n name: destination.name,\n sink: createSignalFanout({ traces: destination.traces, logs: destination.logs }),\n }));\n const only = fanouts.length === 1 ? fanouts[0] : undefined;\n if (only !== undefined) {\n return only.sink;\n }\n\n const emit = async (events: readonly CanonicalEvent[]): Promise<TelemetryEmitResult> => {\n const results = await Promise.all(\n fanouts.map((fanout) =>\n fanout.sink.emit(events).catch(\n (thrown: unknown): TelemetryEmitResult => ({\n accepted: 0,\n rejected: events.length,\n errors: [errorInfoFromThrown(thrown, { code: \"telemetry-export-failure\", phase: \"export\" })],\n }),\n ),\n ),\n );\n const errors: OtelHookErrorInfo[] = results.flatMap((result) => result.errors);\n return {\n accepted: results.reduce((sum, result) => sum + result.accepted, 0),\n rejected: results.reduce((sum, result) => sum + result.rejected, 0),\n errors,\n };\n };\n\n const settleAll = async (run: (sink: SignalFanoutSink) => Promise<void>): Promise<void> => {\n await Promise.all(fanouts.map((fanout) => run(fanout.sink).catch(() => undefined)));\n };\n\n return {\n emit,\n // Each destination drains its own spool in its flush; in parallel, so one\n // unreachable destination's drain cannot use up the others' flush window.\n flush: () => settleAll((sink) => sink.flush()),\n shutdown: () => settleAll((sink) => sink.shutdown()),\n health: (): readonly DeliveryHealthSnapshot[] => fanouts.flatMap((fanout) => fanout.sink.health()),\n };\n};\n","import { readsClaudeTranscriptUsage, sessionContextDir, 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 { createMetricSeriesStore, type MetricSeriesStore } from \"../lifecycle/metric-series.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 { createClaudeTranscriptUsageEnricher } from \"../providers/claude/transcript.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 {\n Clock,\n IdGenerator,\n Logger,\n PayloadEnricher,\n SessionContextReader,\n WorktreeLocator,\n} from \"../runtime/ports.js\";\nimport { createDirectorySessionContextReader } from \"../runtime/session-context.js\";\nimport { createAsyncLock } from \"../state/async-lock.js\";\nimport { createFilesystemStateStore, type FilesystemStateStore } from \"../state/filesystem-store.js\";\nimport type { DurableLogSpool } from \"../telemetry/durable-log-spool.js\";\nimport type { DurableSpool } from \"../telemetry/durable-spool.js\";\nimport {\n createDestinationFanout,\n createExportDestinationSinks,\n type ExportDestinationSinks,\n type SkippedExportDestination,\n} from \"../telemetry/export-destinations.js\";\nimport { effectiveMetricsPolicy } from \"../config/schema.js\";\nimport { agreedContextAttributes, resourceFromExporterPolicy } from \"../telemetry/exporter-resource.js\";\nimport {\n aggregateDeltaPoints,\n deriveMetricObservations,\n type GenerationStart,\n type MetricPoint,\n} from \"../telemetry/metric-model.js\";\nimport { createOtlpLogSink, type OtlpLogTelemetrySink } from \"../telemetry/otlp-log-sink.js\";\nimport { createOtlpTraceSink, type OtlpTelemetrySink } from \"../telemetry/otlp-sink.js\";\nimport {\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 /**\n * Hook-derived metrics for this callback (issue #69). Absent when no destination\n * takes metrics, or when nothing was recorded (a redelivery, a callback whose\n * telemetry was lost and will be retried, or a batch with nothing to measure).\n */\n readonly metrics?: MetricsReport;\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 MetricsReport = {\n /** Data points derived for this callback, before fan-out. */\n readonly points: number;\n /** Per destination taking metrics: points delivered or spooled, and refused. */\n readonly destinations: readonly {\n readonly name: string;\n readonly accepted: number;\n readonly rejected: number;\n }[];\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 /**\n * The traces signal of the primary destination — `default`, or the first entry\n * of `exporter.destinations` when there is no single-endpoint setting. Named\n * `sink` because it is the one every installation has.\n */\n readonly sink: OtlpTelemetrySink;\n /** The primary destination's 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 /** Every destination this runtime sends to, primary first. */\n readonly destinations: readonly ExportDestinationSinks[];\n /** Destinations left out of this invocation, by name, with the variables they lack. */\n readonly skippedDestinations: readonly SkippedExportDestination[];\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 /** Cumulative metric series state (issue #69). */\n readonly metricSeries: MetricSeriesStore;\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 /**\n * Header *values* for the `default` destination, deliberately absent from the\n * config snapshot.\n */\n readonly headers?: Readonly<Record<string, string>>;\n /**\n * Header values for the logs signal only, when they differ from the traces\n * signal's (`OTEL_EXPORTER_OTLP_LOGS_HEADERS`). Defaults to {@link headers}.\n */\n readonly logHeaders?: Readonly<Record<string, string>>;\n /**\n * Environment that `env:NAME` header references in `exporter.destinations`\n * resolve against. Never read implicitly; without it, a destination whose\n * headers reference a variable is skipped for the invocation and reported.\n */\n readonly headerEnvironment?: Readonly<Record<string, string | undefined>>;\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 * Payload enrichers run before the adapter parses (see `PayloadEnricher`).\n * When absent, the configuration decides: `providers.claudeCode.readTranscriptUsage`\n * adds the Claude Code transcript-usage enricher, and nothing else is added.\n * Pass `[]` to run none regardless of configuration.\n */\n readonly payloadEnrichers?: readonly PayloadEnricher[];\n /**\n * Reads session context files (`docs/session-context.md`). When absent, the\n * configuration decides: `sessionContext.dir` adds the directory reader, and\n * without it nothing is read. Pass `null` to read none regardless.\n */\n readonly sessionContextReader?: SessionContextReader | 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 spanCorrelator = createSpanCorrelator({\n stateStore,\n clock,\n maxStartAgeMillis: lifecycleMaxAge,\n });\n\n /**\n * One correlation resolution per batch, shared by every sink of every\n * destination.\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 signals (and the\n * destinations) pointing at different span ids for the same scope.\n */\n const correlate = shareCorrelationPerBatch((events) => spanCorrelator.correlateBatch(events));\n\n // One sink pair per export destination. Without `exporter.destinations` this is\n // the single `default` destination, built exactly as it always has been.\n const exportDestinations = createExportDestinationSinks({\n exporter: options.config.exporter,\n ...(options.headers === undefined ? {} : { defaultHeaders: options.headers }),\n ...(options.logHeaders === undefined ? {} : { defaultLogHeaders: options.logHeaders }),\n ...(options.headerEnvironment === undefined\n ? {}\n : { headerEnvironment: options.headerEnvironment }),\n providerId: options.providerNamespace,\n installationId: options.installationId,\n clock,\n logger,\n ...(options.enableSpool === false ? {} : { spoolRootDir: options.stateRootDir }),\n logContent: {\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 // The primary destination backs the single-destination accessors below: `default`\n // when it is configured, otherwise the first entry of the list.\n const primary = exportDestinations.destinations[0];\n const traceSink =\n primary?.traces ??\n createOtlpTraceSink({\n exporter: { ...options.config.exporter, enabled: false },\n providerId: options.providerNamespace,\n installationId: options.installationId,\n clock,\n });\n const logSink =\n primary?.logs ??\n createOtlpLogSink({\n exporter: { ...options.config.exporter, logs: { ...options.config.exporter.logs, enabled: false } },\n providerId: options.providerNamespace,\n installationId: options.installationId,\n clock,\n });\n const spool = primary?.spool;\n const logSpool = primary?.logSpool;\n\n const sink = createDestinationFanout(exportDestinations.destinations);\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 payloadEnrichers:\n options.payloadEnrichers ??\n (readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : []),\n ...(() => {\n if (options.sessionContextReader === null) {\n return {};\n }\n if (options.sessionContextReader !== undefined) {\n return { sessionContext: options.sessionContextReader };\n }\n const dir = sessionContextDir(options.config);\n return dir === undefined ? {} : { sessionContext: createDirectorySessionContextReader({ dir }) };\n })(),\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 metricSeries = createMetricSeriesStore({ stateStore, clock });\n const metricsPolicy = effectiveMetricsPolicy(options.config.exporter);\n const metricDestinations = exportDestinations.destinations.filter(\n (destination) => destination.metrics.enabled,\n );\n const metricResource = resourceFromExporterPolicy(options.config.exporter);\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 metricSeries,\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 * Start edges for generations whose `generation.start` was recorded by an earlier\n * process. Served from the batch's shared correlation, which the trace and log\n * sinks have already resolved for this exact batch, so this is normally a memo\n * hit rather than a second resolution.\n */\n const generationStartsFor = async (\n events: readonly CanonicalEvent[],\n ): Promise<((generationId: string) => GenerationStart | undefined) | undefined> => {\n const needed = events.some(\n (event) =>\n event.type === \"generation.end\" &&\n event.durationMillis === undefined &&\n !events.some(\n (other) => other.type === \"generation.start\" && other.generationId === event.generationId,\n ),\n );\n if (!needed) {\n return undefined;\n }\n try {\n const starts = new Map<string, GenerationStart>();\n for (const correlation of await correlate(events)) {\n if (correlation.ref.family !== \"generation\" || correlation.startMillis === undefined) {\n continue;\n }\n const requestModel = correlation.attributes?.[\"gen_ai.request.model\"];\n starts.set(correlation.ref.scopeKey, {\n startMillis: correlation.startMillis,\n ...(typeof requestModel === \"string\" ? { requestModel } : {}),\n });\n }\n return (generationId) => starts.get(generationId);\n } catch {\n return undefined;\n }\n };\n\n /**\n * Derive, aggregate, and send this callback's metrics (issue #69).\n *\n * Runs only for a callback whose accounting committed — the same condition the\n * usage deltas it reads were derived under — so a redelivery or a lost-and-retried\n * callback is measured exactly once. Fails open: a metrics failure is a\n * diagnostic, never a reason to retry the callback, whose traces are already out.\n */\n const recordMetrics = async (\n ingest: HookIngestOutcome,\n deliveryToken: string | undefined,\n diagnostics: OtelHookErrorInfo[],\n ): Promise<MetricsReport | undefined> => {\n if (metricDestinations.length === 0 || ingest.events.length === 0) {\n return undefined;\n }\n try {\n for (const event of ingest.events) {\n if (event.type === \"prompt.submitted\") {\n await metricSeries.recordTurnStart(event.sessionId, event.occurredAt);\n }\n }\n const generationStarts = await generationStartsFor(ingest.events);\n const turnStarts = new Map<string, number | undefined>();\n for (const event of ingest.events) {\n if (event.type === \"generation.end\" && !turnStarts.has(event.sessionId)) {\n turnStarts.set(event.sessionId, await metricSeries.readTurnStart(event.sessionId));\n }\n }\n const observations = deriveMetricObservations({\n events: ingest.events,\n usage: ingest.usageObservations,\n resource: metricResource,\n includeSessionId: metricsPolicy.includeSessionId,\n ...(generationStarts === undefined ? {} : { generationStarts }),\n turnStart: (sessionId) => turnStarts.get(sessionId),\n });\n if (observations.length === 0) {\n return undefined;\n }\n const points: readonly MetricPoint[] =\n metricsPolicy.temporality === \"delta\"\n ? aggregateDeltaPoints(observations, clock.now())\n : await metricSeries.recordCumulative(observations, {\n perSession: metricsPolicy.includeSessionId,\n ...(deliveryToken === undefined ? {} : { deliveryToken }),\n });\n const context = agreedContextAttributes(ingest.events);\n const results = await Promise.all(\n metricDestinations.map(async (destination) => {\n const result = await destination.metrics.exportPoints(points, context).catch(\n (thrown: unknown) => ({\n accepted: 0,\n rejected: points.length,\n errors: [\n errorInfoFromThrown(thrown, { code: \"telemetry-export-failure\", phase: \"export\" }),\n ],\n }),\n );\n diagnostics.push(...result.errors);\n return { name: destination.name, accepted: result.accepted, rejected: result.rejected };\n }),\n );\n return { points: points.length, destinations: results };\n } catch (thrown) {\n diagnostics.push(stateDiagnostic(thrown));\n logger.warn(\"hook-derived metrics could not be recorded for this callback\", {});\n return undefined;\n }\n };\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 const metrics =\n !duplicateDelivery && ingest.identity !== undefined && isCommittable(ingest.durability)\n ? await recordMetrics(\n ingest,\n identity === undefined ? undefined : rollupDeliveryToken(identity),\n diagnostics,\n )\n : undefined;\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 ...(metrics === undefined ? {} : { metrics }),\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[] => [\n ...sink.health(),\n ...metricDestinations.map((destination) => destination.metrics.health()),\n ];\n\n let shutdownReport: Promise<HookShutdownReport> | undefined;\n const shutdown = (): Promise<HookShutdownReport> => {\n shutdownReport ??= (async (): Promise<HookShutdownReport> => {\n const raced = await Promise.race([\n Promise.all([\n hook.shutdown(),\n // Metric sinks are not behind the hook's sink: they replay their own\n // spools here, inside the same bounded window.\n ...metricDestinations.map((destination) => destination.metrics.shutdown().catch(() => undefined)),\n ]).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 destinations: exportDestinations.destinations,\n skippedDestinations: exportDestinations.skipped,\n privacy,\n deduplicator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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,cAAc,mBAAmB;AAAA,IACjC,qBAAqB,mBAAmB;AAAA,IACxC;AAAA,IACA;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","z","z","z","z","z","z","z","sessionScope","owner","z","z","z","z","z","z","z","parsed","z","z","z","z","z","z","z","event","event","ATTR_SESSION_ID","ATTR_OTELHOOK_PROVIDER_ID","event","createHash","ATTR_ERROR_TYPE","ATTR_GEN_AI_OPERATION_NAME","ATTR_GEN_AI_REQUEST_MODEL","ATTR_GEN_AI_RESPONSE_MODEL","ATTR_GEN_AI_TOOL_NAME","ATTR_OTELHOOK_OUTCOME","createHash","event","ATTR_GEN_AI_REQUEST_MODEL","ATTR_GEN_AI_OPERATION_NAME","ATTR_GEN_AI_RESPONSE_MODEL","ATTR_GEN_AI_TOOL_NAME","ATTR_ERROR_TYPE","parent","result","event","usageKey","createHash","createHash","path","createHash","z","z","z","asRecord","resolve","createHash","asRecord","cursor","z","createHash","digest","createHash","z","z","path","event","resolve","open","path","z","z","event","open","resolve","z","event","batch","open","stat","path","readBounded","randomBytes","open","path","createHash","resolve","randomBytes","open","randomBytes","mkdir","readFile","readdir","rename","stat","unlink","writeFile","path","readFile","readdir","stat","isErrnoException","mkdir","randomBytes","writeFile","rename","unlink","isPlainObject","isFiniteNonNegative","isBoundedString","isPrimitiveAttribute","TRACE_ID_PATTERN","SPAN_ID_PATTERN","isFiniteNonNegative","isBoundedString","isPlainObject","TraceFlags","millisToHrTime","event","TraceFlags","millisToHrTime","ATTR_ERROR_TYPE","ATTR_GEN_AI_OPERATION_NAME","ATTR_GEN_AI_REQUEST_MODEL","ATTR_GEN_AI_RESPONSE_MODEL","ATTR_GEN_AI_SYSTEM","ATTR_GEN_AI_TOOL_CALL_ID","ATTR_GEN_AI_TOOL_NAME","ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS","ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS","ATTR_GEN_AI_USAGE_INPUT_TOKENS","ATTR_GEN_AI_USAGE_OUTPUT_TOKENS","ATTR_OTELHOOK_OUTCOME","ATTR_OTELHOOK_TOOL_KIND","ATTR_OTELHOOK_DELEGATION_DEPTH","ATTR_OTELHOOK_AGENT_NAME","ATTR_OTELHOOK_AGENT_VERSION","ATTR_OTELHOOK_SESSION_KIND","ATTR_OTELHOOK_GENERATION_ID","ATTR_OTELHOOK_COMPACTION_TRIGGER","codePointLength","sliceCodePoints","event","event","identityAttributes","ATTR_OTELHOOK_SESSION_KIND","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","millisToHrTime","TraceFlags","TraceFlags","millisToHrTime","resolve","ExportResultCode","millisToHrTime","resourceFromAttributes","DISABLED_DETAIL","millisToHrTime","resourceFromAttributes","resolve","ExportResultCode","ExportResultCode","chunk","createDisabledSink","resolve","ExportResultCode","DEFAULT_STALE_CLAIM_MILLIS","resolve","event","options"]}