@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/runtime/ports.ts","../src/model/events.ts","../src/errors/taxonomy.ts","../src/model/content.ts","../src/model/primitives.ts","../src/model/extensions.ts","../src/model/identity.ts","../src/model/target.ts","../src/model/usage.ts","../src/model/version.ts","../src/runtime/clock.ts","../src/runtime/ids.ts","../src/runtime/logger.ts","../src/errors/index.ts","../src/runtime/memory.ts","../src/runtime/delivery.ts","../src/runtime/hook.ts","../src/config/schema.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/privacy/service.ts","../src/providers/adapter.ts","../src/providers/registry.ts","../src/runtime/target-resolution.ts","../src/privacy/workspace.ts","../src/state/async-lock.ts","../src/state/store.ts","../src/runtime/session-context.ts","../src/runtime/git-worktree.ts"],"sourcesContent":["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 { z } from \"zod\";\n\nimport {\n errorPhaseSchema,\n errorSeveritySchema,\n otelHookErrorCodeSchema,\n} from \"../errors/taxonomy.js\";\nimport { contentFactSchema, contentFactsSchema } from \"./content.js\";\nimport { extensionsSchema, emptyExtensions } from \"./extensions.js\";\nimport { sourceProvenanceSchema, workspaceIdentitySchema } from \"./identity.js\";\nimport { subagentIdSchema, workspaceTargetSchema } from \"./target.js\";\nimport {\n durationMillisSchema,\n epochMillisSchema,\n eventIdSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n sequenceNumberSchema,\n sessionIdSchema,\n tokenCountSchema,\n} from \"./primitives.js\";\nimport { canonicalUsageSchema, type CanonicalUsage } from \"./usage.js\";\nimport { canonicalSchemaVersionSchema } from \"./version.js\";\n\n/** Model being invoked. Model identifiers are not treated as sensitive. */\nexport const modelDescriptorSchema = z.strictObject({\n modelId: nonEmptyStringSchema,\n /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */\n vendor: nonEmptyStringSchema.optional(),\n family: nonEmptyStringSchema.optional(),\n});\nexport type ModelDescriptor = z.infer<typeof modelDescriptorSchema>;\n\nexport const costFactsSchema = z.strictObject({\n /** ISO 4217 code. */\n currency: z.string().length(3),\n amount: z.number().min(0).finite(),\n source: z.enum([\"provider-reported\", \"computed\"]),\n});\nexport type CostFacts = z.infer<typeof costFactsSchema>;\n\nexport const canonicalEventTypeSchema = z.enum([\n \"session.start\",\n \"session.end\",\n \"prompt.submitted\",\n \"generation.start\",\n \"generation.end\",\n \"tool.start\",\n \"tool.end\",\n \"subagent.start\",\n \"subagent.end\",\n \"compaction.performed\",\n \"error.raised\",\n]);\nexport type CanonicalEventType = z.infer<typeof canonicalEventTypeSchema>;\n\nexport const CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;\n\nconst outcomeSchema = z.enum([\"ok\", \"error\", \"cancelled\", \"timeout\", \"denied\", \"unknown\"]);\nexport type EventOutcome = z.infer<typeof outcomeSchema>;\n\n/**\n * Fields present on every canonical event.\n *\n * Identity fields are duplicated onto each event rather than referenced through\n * shared state, so an event is self-describing once it leaves the process.\n */\nconst baseEventFields = {\n schemaVersion: canonicalSchemaVersionSchema,\n eventId: eventIdSchema,\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Per-invocation ordering key. Stable across replays of the same input. */\n sequence: sequenceNumberSchema,\n occurredAt: epochMillisSchema,\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n /**\n * The provider's own id for the subagent this event was emitted inside (e.g.\n * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event\n * factory, never by hand.\n */\n subagentId: subagentIdSchema.optional(),\n extensions: extensionsSchema.default(emptyExtensions),\n /**\n * Attributes of the session context segment in force when the event\n * occurred (`docs/session-context.md`), stamped by the core from a file a\n * harness wrote. Exported on every record of the event, over the same keys\n * from the Resource. Absent when no context applies. Set by the core only,\n * never by an adapter.\n */\n contextAttributes: z.record(z.string().min(1).max(255), z.union([z.string(), z.number(), z.boolean()])).optional(),\n} as const;\n\nconst event = <TShape extends z.ZodRawShape>(shape: TShape) =>\n z.strictObject({ ...baseEventFields, ...shape });\n\nexport const sessionStartEventSchema = event({\n type: z.literal(\"session.start\"),\n sessionKind: z.enum([\"interactive\", \"non-interactive\", \"unknown\"]),\n agentName: nonEmptyStringSchema.optional(),\n agentVersion: nonEmptyStringSchema.optional(),\n model: modelDescriptorSchema.optional(),\n /** The git worktree the session runs in, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const sessionEndEventSchema = event({\n type: z.literal(\"session.end\"),\n reason: z.enum([\"completed\", \"aborted\", \"error\", \"timeout\", \"unknown\"]),\n durationMillis: durationMillisSchema.optional(),\n /** Session totals, typically cumulative. */\n usage: canonicalUsageSchema.optional(),\n cost: costFactsSchema.optional(),\n});\n\nexport const promptSubmittedEventSchema = event({\n type: z.literal(\"prompt.submitted\"),\n promptSource: z.enum([\"user\", \"automation\", \"resumed\", \"unknown\"]),\n content: contentFactSchema.optional(),\n turnIndex: z.number().int().min(0).optional(),\n /** The git worktree the session runs in, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const generationStartEventSchema = event({\n type: z.literal(\"generation.start\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n requestedMaxOutputTokens: tokenCountSchema.optional(),\n inputContent: contentFactsSchema.optional(),\n});\n\nexport const generationEndEventSchema = event({\n type: z.literal(\"generation.end\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n outcome: outcomeSchema,\n stopReason: nonEmptyStringSchema.optional(),\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n /**\n * True when `usage` is known to cover only part of the generation (for\n * example the last model request of a multi-request turn); false when the\n * provider or harness said it is the whole. Absent: not stated. Meaningless\n * without `usage`.\n */\n usagePartial: z.boolean().optional(),\n cost: costFactsSchema.optional(),\n outputContent: contentFactsSchema.optional(),\n});\n\nexport const toolKindSchema = z.enum([\n \"read\",\n \"write\",\n \"execute\",\n \"search\",\n \"network\",\n \"delegate\",\n \"other\",\n \"unknown\",\n]);\nexport type ToolKind = z.infer<typeof toolKindSchema>;\n\nexport const toolStartEventSchema = event({\n type: z.literal(\"tool.start\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n toolKind: toolKindSchema,\n generationId: nonEmptyStringSchema.optional(),\n input: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const toolEndEventSchema = event({\n type: z.literal(\"tool.end\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n /** Present when the host asked for or recorded a permission decision. */\n permissionDecision: z.enum([\"allowed\", \"denied\", \"deferred\", \"not-required\"]).optional(),\n output: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const subagentStartEventSchema = event({\n type: z.literal(\"subagent.start\"),\n subagentInvocationId: invocationIdSchema,\n subagentType: nonEmptyStringSchema.optional(),\n /** 0 for the top-level agent; 1 for its direct children. */\n delegationDepth: z.number().int().min(0).max(64),\n model: modelDescriptorSchema.optional(),\n});\n\nexport const subagentEndEventSchema = event({\n type: z.literal(\"subagent.end\"),\n subagentInvocationId: invocationIdSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const compactionPerformedEventSchema = event({\n type: z.literal(\"compaction.performed\"),\n trigger: z.enum([\"automatic\", \"manual\", \"unknown\"]),\n /** Provider-reported context size before and after compaction, if known. */\n contextTokensBefore: tokenCountSchema.optional(),\n contextTokensAfter: tokenCountSchema.optional(),\n droppedMessageCount: z.number().int().min(0).optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const errorRaisedEventSchema = event({\n type: z.literal(\"error.raised\"),\n errorCode: otelHookErrorCodeSchema,\n severity: errorSeveritySchema,\n phase: errorPhaseSchema,\n retryable: z.boolean(),\n /** Error text is content: it is described, never embedded verbatim by default. */\n message: contentFactSchema.optional(),\n /** Non-sensitive, provider-agnostic short label. */\n detail: nonEmptyStringSchema.optional(),\n});\n\nexport const canonicalEventSchema = z.discriminatedUnion(\"type\", [\n sessionStartEventSchema,\n sessionEndEventSchema,\n promptSubmittedEventSchema,\n generationStartEventSchema,\n generationEndEventSchema,\n toolStartEventSchema,\n toolEndEventSchema,\n subagentStartEventSchema,\n subagentEndEventSchema,\n compactionPerformedEventSchema,\n errorRaisedEventSchema,\n]);\n\nexport type CanonicalEvent = z.infer<typeof canonicalEventSchema>;\nexport type CanonicalEventInput = z.input<typeof canonicalEventSchema>;\n\nexport type SessionStartEvent = z.infer<typeof sessionStartEventSchema>;\nexport type SessionEndEvent = z.infer<typeof sessionEndEventSchema>;\nexport type PromptSubmittedEvent = z.infer<typeof promptSubmittedEventSchema>;\nexport type GenerationStartEvent = z.infer<typeof generationStartEventSchema>;\nexport type GenerationEndEvent = z.infer<typeof generationEndEventSchema>;\nexport type ToolStartEvent = z.infer<typeof toolStartEventSchema>;\nexport type ToolEndEvent = z.infer<typeof toolEndEventSchema>;\nexport type SubagentStartEvent = z.infer<typeof subagentStartEventSchema>;\nexport type SubagentEndEvent = z.infer<typeof subagentEndEventSchema>;\nexport type CompactionPerformedEvent = z.infer<typeof compactionPerformedEventSchema>;\nexport type ErrorRaisedEvent = z.infer<typeof errorRaisedEventSchema>;\n\nexport type CanonicalEventOfType<TType extends CanonicalEventType> = Extract<\n CanonicalEvent,\n { type: TType }\n>;\n\n/**\n * The event types that may carry a resolved `target` (ADR 0008): a tool call\n * names the worktree it touched; a session start and a prompt name the one the\n * session runs in, so a consumer knows the session's place before its first\n * tool call.\n */\nexport const TARGETED_EVENT_TYPES = [\"session.start\", \"prompt.submitted\", \"tool.start\", \"tool.end\"] as const;\nexport type TargetedEventType = (typeof TARGETED_EVENT_TYPES)[number];\nexport type TargetedEvent = CanonicalEventOfType<TargetedEventType>;\n\nconst TARGETED: ReadonlySet<string> = new Set(TARGETED_EVENT_TYPES);\nexport const isTargetedEvent = (event: CanonicalEvent): event is TargetedEvent => TARGETED.has(event.type);\n\nexport type EventValidationResult =\n | { readonly status: \"ok\"; readonly event: CanonicalEvent }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nexport const validateCanonicalEvent = (value: unknown): EventValidationResult => {\n const parsed = canonicalEventSchema.safeParse(value);\n if (parsed.success) {\n return { status: \"ok\", event: parsed.data };\n }\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n};\n\n/** Parse or throw. Intended for fixtures and tests, not the hook path. */\nexport const parseCanonicalEvent = (value: unknown): CanonicalEvent =>\n canonicalEventSchema.parse(value);\n\n/** Usage carried by an event, if the event type can carry any. */\nexport const eventUsage = (event: CanonicalEvent): CanonicalUsage | undefined =>\n \"usage\" in event ? event.usage : undefined;\n\n/** Stable ordering: by sequence, then by timestamp, then by event id. */\nexport const compareEvents = (a: CanonicalEvent, b: CanonicalEvent): number =>\n a.sequence - b.sequence || a.occurredAt - b.occurredAt || a.eventId.localeCompare(b.eventId);\n","import { z } from \"zod\";\n\n/**\n * Closed set of error codes. Adding a code is a minor change; changing what a\n * code means is a breaking change.\n */\nexport const otelHookErrorCodeSchema = z.enum([\n /** Input was not usable at all (empty stdin, unparsable JSON). */\n \"invalid-input\",\n /** Input parsed but failed canonical schema validation. */\n \"schema-validation-failed\",\n /** No adapter claimed the input with sufficient confidence. */\n \"provider-unknown\",\n /** Several adapters claimed the input at the same confidence. */\n \"provider-detection-ambiguous\",\n /** An adapter threw or returned a malformed result. */\n \"provider-adapter-failure\",\n /** Two identity claims disagreed at equal confidence. */\n \"identity-conflict\",\n /** Required identity fields were absent. */\n \"identity-incomplete\",\n /** A usage report violated the canonical usage invariants. */\n \"usage-invalid\",\n /** The state store could not be read or written. */\n \"state-store-failure\",\n /** The telemetry sink rejected or could not deliver a batch. */\n \"telemetry-export-failure\",\n /** Content reached the sink boundary in a state the policy forbids. */\n \"privacy-policy-violation\",\n /** Configuration could not be resolved. */\n \"configuration-invalid\",\n /** A configured bound (events, batch size) dropped data. */\n \"limit-exceeded\",\n /**\n * No replay-stable delivery identifier was available for a callback while\n * deduplication was required.\n */\n \"delivery-identifier-unavailable\",\n \"delivery-claim-superseded\",\n /** Anything unanticipated. Always reported, never fatal to the host. */\n \"internal-error\",\n]);\nexport type OtelHookErrorCode = z.infer<typeof otelHookErrorCodeSchema>;\n\nexport const errorSeveritySchema = z.enum([\"warning\", \"error\"]);\nexport type ErrorSeverity = z.infer<typeof errorSeveritySchema>;\n\n/** Pipeline stage where a failure occurred. */\nexport const errorPhaseSchema = z.enum([\n \"configuration\",\n \"detection\",\n \"identity\",\n \"parsing\",\n \"normalization\",\n \"privacy\",\n \"state\",\n \"export\",\n \"shutdown\",\n]);\nexport type ErrorPhase = z.infer<typeof errorPhaseSchema>;\n\n/**\n * Which of the two safety postures a code participates in.\n *\n * - `fail-open`: the hook still reports success to the host agent. Telemetry may\n * be incomplete; the coding agent is never blocked.\n * - `fail-closed-attribution`: the observation is not attributed to a session or\n * provider. Data is dropped rather than labelled with a guess.\n */\nexport const failurePostureSchema = z.enum([\"fail-open\", \"fail-closed-attribution\"]);\nexport type FailurePosture = z.infer<typeof failurePostureSchema>;\n\nexport type ErrorCodeDescriptor = {\n readonly code: OtelHookErrorCode;\n readonly severity: ErrorSeverity;\n readonly posture: FailurePosture;\n /** Whether retrying the same input could succeed. */\n readonly retryable: boolean;\n readonly summary: string;\n};\n\nexport const ERROR_TAXONOMY: Readonly<Record<OtelHookErrorCode, ErrorCodeDescriptor>> =\n Object.freeze({\n \"invalid-input\": {\n code: \"invalid-input\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Input could not be read or decoded.\",\n },\n \"schema-validation-failed\": {\n code: \"schema-validation-failed\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"A canonical event failed schema validation and was dropped.\",\n },\n \"provider-unknown\": {\n code: \"provider-unknown\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"No adapter recognized the source provider; the input stays unattributed.\",\n },\n \"provider-detection-ambiguous\": {\n code: \"provider-detection-ambiguous\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Multiple adapters claimed the input at equal confidence.\",\n },\n \"provider-adapter-failure\": {\n code: \"provider-adapter-failure\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A provider adapter failed while parsing.\",\n },\n \"identity-conflict\": {\n code: \"identity-conflict\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Identity claims disagreed; attribution was declined.\",\n },\n \"identity-incomplete\": {\n code: \"identity-incomplete\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Required identity fields were missing; attribution was declined.\",\n },\n \"usage-invalid\": {\n code: \"usage-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A usage report violated the canonical usage invariants.\",\n },\n \"state-store-failure\": {\n code: \"state-store-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"State could not be read or written; derived values may be incomplete.\",\n },\n \"telemetry-export-failure\": {\n code: \"telemetry-export-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"The telemetry sink could not accept a batch.\",\n },\n \"privacy-policy-violation\": {\n code: \"privacy-policy-violation\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Content violated the resolved privacy policy and was dropped.\",\n },\n \"configuration-invalid\": {\n code: \"configuration-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Configuration could not be resolved; defaults apply.\",\n },\n \"limit-exceeded\": {\n code: \"limit-exceeded\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A configured bound was reached and data was dropped.\",\n },\n \"delivery-identifier-unavailable\": {\n code: \"delivery-identifier-unavailable\",\n severity: \"warning\",\n // Fail-open: the observation is still attributed and exported. Only the\n // at-most-once guarantee is missing, and refusing the telemetry to protect\n // a duplicate count would trade a certain loss for a possible one.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"No replay-stable delivery identifier was available; this callback was exported without deduplication.\",\n },\n \"delivery-claim-superseded\": {\n code: \"delivery-claim-superseded\",\n severity: \"warning\",\n // Fail-open, and specifically *not* silent. A peer reclaimed this callback's\n // claim while this process was still working on it, which means the\n // configured stale window is shorter than this installation's real worst\n // case. Both processes may now have exported the callback, so the\n // at-most-once guarantee did not hold for it — the only honest response is\n // to say so and let the operator raise the window.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"A delivery claim was reclaimed by another process before this one committed; the callback may have been exported twice.\",\n },\n \"internal-error\": {\n code: \"internal-error\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"An unexpected failure was contained.\",\n },\n });\n\nexport const describeErrorCode = (code: OtelHookErrorCode): ErrorCodeDescriptor =>\n ERROR_TAXONOMY[code];\n\n/** Outcome of attributing an observation to a provider and session. */\nexport const attributionOutcomeSchema = z.enum([\n /** Identity resolved; events carry provider and session identity. */\n \"attributed\",\n /** Identity could not be established safely; nothing was attributed. */\n \"declined\",\n /** Attribution was attempted and failed unexpectedly. */\n \"failed\",\n /** Input was recognized but intentionally carried no telemetry. */\n \"not-applicable\",\n]);\nexport type AttributionOutcome = z.infer<typeof attributionOutcomeSchema>;\n\nexport const attributionReasonSchema = z.enum([\n \"provider-unknown\",\n \"provider-detection-ambiguous\",\n \"identity-conflict\",\n \"identity-incomplete\",\n \"adapter-ignored-input\",\n \"adapter-failure\",\n \"invalid-input\",\n \"internal-error\",\n]);\nexport type AttributionReason = z.infer<typeof attributionReasonSchema>;\n","import { z } from \"zod\";\n\nimport { nonEmptyStringSchema } from \"./primitives.js\";\n\n/** What kind of conversational or tool content a fact describes. */\nexport const contentKindSchema = z.enum([\n \"prompt\",\n \"response\",\n \"reasoning\",\n \"tool-input\",\n \"tool-output\",\n \"error-message\",\n \"system-instruction\",\n \"attachment\",\n]);\nexport type ContentKind = z.infer<typeof contentKindSchema>;\n\nexport const contentRoleSchema = z.enum([\"user\", \"assistant\", \"system\", \"tool\", \"unknown\"]);\nexport type ContentRole = z.infer<typeof contentRoleSchema>;\n\n/**\n * How much of the original content this fact discloses.\n *\n * - `omitted`: no text at all (the default posture).\n * - `masked`: a shape-preserving mask; non-whitespace characters replaced.\n * - `redacted`: text with secret-looking spans replaced by a placeholder.\n * - `raw`: verbatim text. Only reachable through explicit opt-in.\n */\nexport const contentDisclosureSchema = z.enum([\"omitted\", \"masked\", \"redacted\", \"raw\"]);\nexport type ContentDisclosure = z.infer<typeof contentDisclosureSchema>;\n\nexport const CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;\n\n/**\n * A privacy-safe description of content.\n *\n * Lengths and a stable hash are always present so consumers can measure and\n * correlate volume without receiving the content itself. `text` is present only\n * when the resolved privacy policy allows disclosure, and is produced solely by\n * the central privacy service.\n */\nexport const contentFactSchema = z.strictObject({\n kind: contentKindSchema,\n role: contentRoleSchema.optional(),\n /** Unicode code point count of the original content. */\n characterLength: z.number().int().min(0),\n /** UTF-8 byte length of the original content. */\n byteLength: z.number().int().min(0),\n /** Stable salted digest of the original content. */\n contentHash: z.string().regex(CONTENT_HASH_PATTERN),\n disclosure: contentDisclosureSchema,\n /** Disclosed text, bounded by the privacy policy. Absent when omitted. */\n text: z.string().optional(),\n /** True when `text` was cut short by the configured string bound. */\n truncated: z.boolean(),\n /** Number of secret-looking spans replaced while producing `text`. */\n secretsRedacted: z.number().int().min(0),\n /** Optional non-sensitive label, e.g. a MIME type or tool name. */\n label: nonEmptyStringSchema.optional(),\n});\nexport type ContentFact = z.infer<typeof contentFactSchema>;\n\nexport const contentFactsSchema = z.array(contentFactSchema).max(64);\n\n/**\n * Guard used in tests and at the sink boundary: an omitted fact must not carry\n * text, and a disclosing fact must carry it.\n */\nexport const isContentFactConsistent = (fact: ContentFact): boolean =>\n fact.disclosure === \"omitted\" ? fact.text === undefined : fact.text !== undefined;\n\n/**\n * A fact for a content kind the event can carry when the provider sent no text.\n *\n * Always `omitted` with zero length, regardless of the installation's content\n * mode: there is nothing to mask, redact, or export.\n */\nexport const isUnavailableContentFact = (fact: ContentFact): boolean =>\n fact.disclosure === \"omitted\" &&\n fact.text === undefined &&\n fact.characterLength === 0 &&\n fact.byteLength === 0;\n","import { z } from \"zod\";\n\n/** Maximum length accepted for short identifier-like strings. */\nexport const MAX_IDENTIFIER_LENGTH = 256;\n\n/** Maximum length accepted for a single string attribute value. */\nexport const MAX_ATTRIBUTE_STRING_LENGTH = 4096;\n\n/** Maximum number of entries accepted in an attribute array value. */\nexport const MAX_ATTRIBUTE_ARRAY_LENGTH = 128;\n\nexport const nonEmptyStringSchema = z.string().min(1).max(MAX_IDENTIFIER_LENGTH);\n\n/** Wall-clock time as whole milliseconds since the Unix epoch. */\nexport const epochMillisSchema = z.number().int().min(0).max(8_640_000_000_000_000);\nexport type EpochMillis = z.infer<typeof epochMillisSchema>;\n\n/** Non-negative duration in milliseconds; may be fractional. */\nexport const durationMillisSchema = z.number().min(0).finite();\n\n/** Token counts are always non-negative integers. */\nexport const tokenCountSchema = z.number().int().min(0);\n\n/** Monotonically increasing per-invocation ordering key. */\nexport const sequenceNumberSchema = z.number().int().min(0);\n\nconst brandedIdSchema = (): z.ZodString => z.string().min(1).max(MAX_IDENTIFIER_LENGTH);\n\nexport const invocationIdSchema = brandedIdSchema().brand<\"InvocationId\">();\nexport type InvocationId = z.infer<typeof invocationIdSchema>;\n\nexport const sessionIdSchema = brandedIdSchema().brand<\"SessionId\">();\nexport type SessionId = z.infer<typeof sessionIdSchema>;\n\nexport const eventIdSchema = brandedIdSchema().brand<\"EventId\">();\nexport type EventId = z.infer<typeof eventIdSchema>;\n\n/**\n * Workspace identifiers are opaque, privacy-safe handles of the form\n * `<scheme>:<token>`. Filesystem paths cannot satisfy this pattern, which keeps\n * home directories and repository paths out of telemetry by construction.\n */\nexport const WORKSPACE_ID_PATTERN = /^[a-z][a-z0-9]{0,15}:[A-Za-z0-9_-]{8,128}$/;\nexport const workspaceIdSchema = z\n .string()\n .regex(WORKSPACE_ID_PATTERN, \"workspace id must be an opaque `<scheme>:<token>` handle\")\n .brand<\"WorkspaceId\">();\nexport type WorkspaceId = z.infer<typeof workspaceIdSchema>;\n\n/** Provider ids are lowercase, hyphenated, and stable across releases. */\nexport const PROVIDER_ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\nexport const providerIdSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(PROVIDER_ID_PATTERN, \"provider id must be lowercase and hyphenated\")\n .brand<\"ProviderId\">();\nexport type ProviderId = z.infer<typeof providerIdSchema>;\n\n/** Sentinel used whenever the source provider could not be established. */\nexport const UNKNOWN_PROVIDER_ID = \"unknown\" as const;\nexport type UnknownProviderId = typeof UNKNOWN_PROVIDER_ID;\n\nexport const resolvedProviderIdSchema = z.union([\n providerIdSchema,\n z.literal(UNKNOWN_PROVIDER_ID),\n]);\nexport type ResolvedProviderId = z.infer<typeof resolvedProviderIdSchema>;\n\nexport const isUnknownProvider = (value: ResolvedProviderId): value is UnknownProviderId =>\n value === UNKNOWN_PROVIDER_ID;\n\n/**\n * Attribute values are restricted to OpenTelemetry-compatible primitives.\n *\n * This restriction is a containment boundary, not a convenience: because no\n * nested object can be represented, a raw provider payload cannot be smuggled\n * out of an adapter through attributes or extensions.\n */\nexport const attributePrimitiveSchema = z.union([\n z.string().max(MAX_ATTRIBUTE_STRING_LENGTH),\n z.number().finite(),\n z.boolean(),\n]);\nexport type AttributePrimitive = z.infer<typeof attributePrimitiveSchema>;\n\nexport const attributeValueSchema = z.union([\n attributePrimitiveSchema,\n z.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH),\n]);\nexport type AttributeValue = z.infer<typeof attributeValueSchema>;\n\nexport const attributesSchema = z.record(z.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);\nexport type Attributes = z.infer<typeof attributesSchema>;\n\n/** Ordered confidence ladder for provider detection. */\nexport const detectionConfidenceSchema = z.enum([\"none\", \"weak\", \"strong\", \"exact\"]);\nexport type DetectionConfidence = z.infer<typeof detectionConfidenceSchema>;\n\nexport const DETECTION_CONFIDENCE_RANK: Readonly<Record<DetectionConfidence, number>> =\n Object.freeze({\n none: 0,\n weak: 1,\n strong: 2,\n exact: 3,\n });\n\nexport const compareDetectionConfidence = (a: DetectionConfidence, b: DetectionConfidence): number =>\n DETECTION_CONFIDENCE_RANK[a] - DETECTION_CONFIDENCE_RANK[b];\n\n/** How the observed data reached this process. */\nexport const sourceTransportSchema = z.enum([\n \"hook-stdin\",\n \"cli-argument\",\n \"library-call\",\n \"test-fixture\",\n]);\nexport type SourceTransport = z.infer<typeof sourceTransportSchema>;\n","import { z } from \"zod\";\n\nimport { attributeValueSchema, type AttributeValue } from \"./primitives.js\";\n\n/**\n * Extension keys must be namespaced: at least one dot-separated segment before\n * the leaf, e.g. `acme.deployment-tier`. Namespacing keeps provider- and\n * consumer-specific fields from colliding with core fields or each other.\n */\nexport const EXTENSION_KEY_PATTERN =\n /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;\n\n/** Namespaces owned by the core model; extensions may not use them. */\nexport const RESERVED_EXTENSION_NAMESPACES: readonly string[] = Object.freeze([\n \"otelhook\",\n \"otel\",\n \"telemetry\",\n]);\n\nexport const MAX_EXTENSION_ENTRIES = 64;\n\nexport const extensionKeyNamespace = (key: string): string => key.slice(0, key.indexOf(\".\"));\n\nexport const isReservedExtensionNamespace = (key: string): boolean =>\n RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));\n\nexport const isValidExtensionKey = (key: string): boolean =>\n EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);\n\n/**\n * Namespaced extension bag.\n *\n * Values are restricted to attribute primitives, so extensions cannot carry\n * nested provider payloads.\n */\nexport const extensionsSchema = z\n .record(z.string(), attributeValueSchema)\n .check((ctx) => {\n const keys = Object.keys(ctx.value);\n if (keys.length > MAX_EXTENSION_ENTRIES) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`,\n });\n }\n for (const key of keys) {\n if (!EXTENSION_KEY_PATTERN.test(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. \"acme.tier\"`,\n });\n continue;\n }\n if (isReservedExtensionNamespace(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`,\n });\n }\n }\n });\n\nexport type Extensions = Record<string, AttributeValue>;\n\nexport const EMPTY_EXTENSIONS: Extensions = Object.freeze({});\n\nexport const emptyExtensions = (): Extensions => ({});\n","import { z } from \"zod\";\n\nimport {\n attributesSchema,\n detectionConfidenceSchema,\n DETECTION_CONFIDENCE_RANK,\n epochMillisSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n resolvedProviderIdSchema,\n sessionIdSchema,\n sourceTransportSchema,\n workspaceIdSchema,\n type DetectionConfidence,\n type InvocationId,\n type SessionId,\n type WorkspaceId,\n} from \"./primitives.js\";\n\n/**\n * Where a workspace identifier came from.\n *\n * Ordered from most to least stable. The source is recorded so consumers can\n * tell a repository-scoped identity from a directory-scoped one instead of\n * assuming they are comparable.\n */\nexport const workspaceKeySourceSchema = z.enum([\n \"git-remote\",\n \"git-root\",\n \"working-directory\",\n \"explicit\",\n \"unknown\",\n]);\nexport type WorkspaceKeySource = z.infer<typeof workspaceKeySourceSchema>;\n\n/**\n * Privacy-safe workspace identity.\n *\n * Only opaque handles and explicitly allowed labels are modelled. There is no\n * field for a filesystem path, so paths cannot be exported through this type.\n */\nexport const workspaceIdentitySchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n keySource: workspaceKeySourceSchema,\n /** Repository name only; never an owner path or URL with credentials. */\n repositoryName: nonEmptyStringSchema.optional(),\n vcsBranchName: nonEmptyStringSchema.optional(),\n /** Opaque handle for the checked-out revision. */\n vcsRevisionId: nonEmptyStringSchema.optional(),\n })\n .readonly();\nexport type WorkspaceIdentity = z.infer<typeof workspaceIdentitySchema>;\n\nexport const UNKNOWN_WORKSPACE_ID = \"unknown:0000000000000000\" as WorkspaceId;\n\nexport const unknownWorkspaceIdentity = (): WorkspaceIdentity =>\n workspaceIdentitySchema.parse({\n workspaceId: UNKNOWN_WORKSPACE_ID,\n keySource: \"unknown\",\n });\n\n/**\n * Provenance of an observation: which provider produced it and which adapter\n * interpreted it, with the confidence of that attribution.\n */\nexport const sourceProvenanceSchema = z\n .strictObject({\n providerId: resolvedProviderIdSchema,\n providerVersion: nonEmptyStringSchema.optional(),\n adapterId: nonEmptyStringSchema,\n adapterVersion: nonEmptyStringSchema,\n detectionConfidence: detectionConfidenceSchema,\n /** The provider's own name for the source event, e.g. a hook event name. */\n sourceEventName: nonEmptyStringSchema.optional(),\n transport: sourceTransportSchema,\n })\n .readonly();\nexport type SourceProvenance = z.infer<typeof sourceProvenanceSchema>;\n\n/**\n * Opaque, immutable metadata supplied by the embedding consumer.\n *\n * The library never interprets these values; it only carries and exports them.\n */\nexport const consumerAttributesSchema = attributesSchema.readonly();\nexport type ConsumerAttributes = z.infer<typeof consumerAttributesSchema>;\n\n/**\n * Immutable identity of a single hook invocation.\n *\n * Frozen on parse. There is deliberately no setter, no builder that mutates in\n * place, and no module-level instance: identity is passed explicitly so two\n * concurrent invocations can never observe each other's fields.\n */\nexport const invocationIdentitySchema = z\n .strictObject({\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Set when this invocation runs beneath another agent invocation. */\n parentInvocationId: invocationIdSchema.optional(),\n /** Root of the session tree when the provider exposes one. */\n rootSessionId: sessionIdSchema.optional(),\n /** Stable handle for the agent process/instance, when available. */\n agentInstanceId: nonEmptyStringSchema.optional(),\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n startedAt: epochMillisSchema,\n consumerAttributes: consumerAttributesSchema,\n })\n .readonly();\nexport type InvocationIdentity = z.infer<typeof invocationIdentitySchema>;\n\n/** Fields an identity claim may contribute. */\nexport const identityClaimFieldsSchema = z.strictObject({\n invocationId: invocationIdSchema.optional(),\n sessionId: sessionIdSchema.optional(),\n parentInvocationId: invocationIdSchema.optional(),\n rootSessionId: sessionIdSchema.optional(),\n agentInstanceId: nonEmptyStringSchema.optional(),\n workspace: workspaceIdentitySchema.optional(),\n startedAt: epochMillisSchema.optional(),\n});\nexport type IdentityClaimFields = z.infer<typeof identityClaimFieldsSchema>;\n\n/**\n * A claim about invocation identity from one source.\n *\n * Claims are evidence, not truth. Resolution keeps the highest-confidence claim\n * per field and refuses to merge disagreeing peers.\n */\nexport const identityClaimSchema = z.strictObject({\n /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */\n source: nonEmptyStringSchema,\n confidence: detectionConfidenceSchema,\n fields: identityClaimFieldsSchema,\n});\nexport type IdentityClaim = z.infer<typeof identityClaimSchema>;\n\nexport type IdentityConflict = {\n readonly field: keyof IdentityClaimFields;\n readonly confidence: DetectionConfidence;\n /** Rendered, non-sensitive representations of the disagreeing values. */\n readonly values: readonly string[];\n readonly sources: readonly string[];\n};\n\nexport type IdentityResolution =\n | { readonly status: \"resolved\"; readonly identity: InvocationIdentity }\n | {\n readonly status: \"conflict\";\n readonly conflicts: readonly IdentityConflict[];\n }\n | {\n readonly status: \"incomplete\";\n readonly missing: readonly (keyof IdentityClaimFields)[];\n }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nconst CLAIM_FIELDS = [\n \"invocationId\",\n \"sessionId\",\n \"parentInvocationId\",\n \"rootSessionId\",\n \"agentInstanceId\",\n \"workspace\",\n \"startedAt\",\n] as const satisfies readonly (keyof IdentityClaimFields)[];\n\nconst renderClaimValue = (value: unknown): string => {\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (value !== null && typeof value === \"object\" && \"workspaceId\" in value) {\n const { workspaceId } = value;\n return typeof workspaceId === \"string\" ? workspaceId : \"<workspace>\";\n }\n return \"<opaque>\";\n};\n\nexport type ResolveIdentityInput = {\n readonly claims: readonly IdentityClaim[];\n readonly provenance: SourceProvenance;\n /** Used only for fields no claim provides and that have a safe default. */\n readonly fallback?: {\n readonly startedAt?: number;\n readonly workspace?: WorkspaceIdentity;\n };\n readonly consumerAttributes?: Readonly<Record<string, unknown>>;\n};\n\n/**\n * Resolve identity from claims, failing closed.\n *\n * Rules:\n * 1. For each field, only claims at the highest confidence that provided it are\n * considered. Lower-confidence claims never fill in or override.\n * 2. Two distinct values at that highest confidence produce a `conflict`. The\n * invocation is then not attributed at all — a mislabelled session is worse\n * than a missing one.\n * 3. `invocationId` and `sessionId` are mandatory. Missing either yields\n * `incomplete`; neither is invented here.\n * 4. `startedAt` and `workspace` may come from an explicit fallback, because a\n * clock reading and an `unknown` workspace handle assert nothing false.\n */\nexport const resolveInvocationIdentity = (input: ResolveIdentityInput): IdentityResolution => {\n const parsedClaims: IdentityClaim[] = [];\n const issues: string[] = [];\n for (const [index, claim] of input.claims.entries()) {\n const parsed = identityClaimSchema.safeParse(claim);\n if (parsed.success) {\n parsedClaims.push(parsed.data);\n } else {\n issues.push(\n `claim[${index}]: ${parsed.error.issues.map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`).join(\", \")}`,\n );\n }\n }\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const conflicts: IdentityConflict[] = [];\n const selected: Record<string, unknown> = {};\n\n for (const field of CLAIM_FIELDS) {\n const contributors = parsedClaims.filter((claim) => claim.fields[field] !== undefined);\n if (contributors.length === 0) {\n continue;\n }\n const bestRank = Math.max(\n ...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence]),\n );\n const best = contributors.filter(\n (claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank,\n );\n const rendered = new Map<string, string[]>();\n for (const claim of best) {\n const key = JSON.stringify(claim.fields[field]);\n const sources = rendered.get(key) ?? [];\n sources.push(claim.source);\n rendered.set(key, sources);\n }\n if (rendered.size > 1) {\n const [firstBest] = best;\n conflicts.push({\n field,\n confidence: firstBest?.confidence ?? \"none\",\n values: best.map((claim) => renderClaimValue(claim.fields[field])),\n sources: best.map((claim) => claim.source),\n });\n continue;\n }\n const [winner] = best;\n if (winner !== undefined) {\n selected[field] = winner.fields[field];\n }\n }\n\n if (conflicts.length > 0) {\n return { status: \"conflict\", conflicts };\n }\n\n const missing: (keyof IdentityClaimFields)[] = [];\n if (selected.invocationId === undefined) {\n missing.push(\"invocationId\");\n }\n if (selected.sessionId === undefined) {\n missing.push(\"sessionId\");\n }\n if (missing.length > 0) {\n return { status: \"incomplete\", missing };\n }\n\n const startedAt = (selected.startedAt as number | undefined) ?? input.fallback?.startedAt;\n if (startedAt === undefined) {\n return { status: \"incomplete\", missing: [\"startedAt\"] };\n }\n const workspace =\n (selected.workspace as WorkspaceIdentity | undefined) ??\n input.fallback?.workspace ??\n unknownWorkspaceIdentity();\n\n const candidate = {\n invocationId: selected.invocationId as InvocationId,\n sessionId: selected.sessionId as SessionId,\n ...(selected.parentInvocationId === undefined\n ? {}\n : { parentInvocationId: selected.parentInvocationId as InvocationId }),\n ...(selected.rootSessionId === undefined\n ? {}\n : { rootSessionId: selected.rootSessionId as SessionId }),\n ...(selected.agentInstanceId === undefined\n ? {}\n : { agentInstanceId: selected.agentInstanceId as string }),\n provenance: input.provenance,\n workspace,\n startedAt,\n consumerAttributes: input.consumerAttributes ?? {},\n };\n\n const parsed = invocationIdentitySchema.safeParse(candidate);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n }\n return { status: \"resolved\", identity: parsed.data };\n};\n","import { z } from \"zod\";\n\nimport { nonEmptyStringSchema, workspaceIdSchema } from \"./primitives.js\";\n\n/**\n * Per-event workspace targeting (ADR 0008).\n *\n * A session's `workspace` is where the agent was *started*. An agent routinely\n * works somewhere else — in a linked git worktree beside the checkout it was\n * launched from — and the session-level identity cannot show that. A tool event\n * can: the file it edited, or the directory its shell command ran in, names the\n * worktree it actually touched.\n *\n * Two values model that, and the split between them is the privacy boundary:\n *\n * - {@link TargetHint} is what an adapter observed — local paths. It is an\n * in-process value only: it is never part of a {@link CanonicalEvent}, never\n * persisted, never exported. The core resolves it and drops it.\n * - {@link WorkspaceTarget} is what the core resolved — salted handles of the\n * worktree and its repository, the worktree's kind, the checked-out branch, and\n * what the evidence was. It travels on the event.\n */\n\n/**\n * What a target was derived from, strongest evidence first.\n *\n * - `tool-path` — a path the tool call itself named (an edited or read file, a\n * patch header).\n * - `shell-cwd` — the working directory the provider reports a shell command ran in.\n * - `session-cwd` — only the session's own directory was known; the event may\n * have reached elsewhere (e.g. a shell `cd`) without the provider saying so.\n */\nexport const targetSourceSchema = z.enum([\"tool-path\", \"shell-cwd\", \"session-cwd\"]);\nexport type TargetSource = z.infer<typeof targetSourceSchema>;\n\n/** Most paths one hint may name; a bound, not a sampling rule (all must agree). */\nexport const MAX_TARGET_HINT_PATHS = 8;\n\n/** Longest local path a hint may carry. Longer input is dropped, never truncated. */\nexport const MAX_TARGET_PATH_LENGTH = 4096;\n\nconst localPathSchema = z\n .string()\n .min(1)\n .max(MAX_TARGET_PATH_LENGTH)\n .refine((value) => !value.includes(\"\\u0000\"), \"path must not contain NUL\");\n\n/**\n * An adapter's observation of where a tool event pointed. **Carries local paths**\n * — in-process only, see the module note.\n *\n * Every path in one hint must resolve to the same worktree, or the event gets no\n * target at all: a patch touching two worktrees did not target either of them.\n */\nexport const targetHintSchema = z\n .strictObject({\n source: targetSourceSchema,\n paths: z.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),\n /** Absolute directory that relative `paths` resolve against. */\n baseDirectory: localPathSchema.optional(),\n })\n .readonly();\nexport type TargetHint = z.infer<typeof targetHintSchema>;\n\n/**\n * The weakest hint: the session's own directory. Every adapter gives it to a\n * session start and a prompt, and to a tool call that names no path.\n */\nexport const sessionCwdHint = (cwd: string | undefined): TargetHint | undefined =>\n cwd === undefined || cwd.length === 0 ? undefined : { source: \"session-cwd\", paths: [cwd] };\n\n/**\n * Whether a worktree is its repository's main checkout (`main`) or one added\n * beside it with `git worktree add` (`linked`).\n */\nexport const worktreeKindSchema = z.enum([\"main\", \"linked\"]);\nexport type WorktreeKind = z.infer<typeof worktreeKindSchema>;\n\n/**\n * The git worktree a tool event targeted. Exported; carries no path.\n *\n * `workspaceId` is derived exactly like a `git-root` workspace identity, so a\n * consumer holding the same salt can match it against one it derived itself.\n * `repositoryId` is the same derivation applied to the repository's main\n * worktree, so every worktree of one repository shares it — and for a main\n * worktree it equals `workspaceId`.\n */\nexport const workspaceTargetSchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n /** Branch checked out in that worktree; absent on a detached HEAD. */\n vcsBranchName: nonEmptyStringSchema.optional(),\n source: targetSourceSchema,\n /** `git-root` handle of the repository's main worktree; absent when there is none to name. */\n repositoryId: workspaceIdSchema.optional(),\n worktreeKind: worktreeKindSchema.optional(),\n })\n .readonly();\nexport type WorkspaceTarget = z.infer<typeof workspaceTargetSchema>;\n\n/**\n * Shape a provider's own subagent identifier must have to be exported.\n *\n * Identifier-shaped on purpose — no whitespace, no path separators — so a\n * malformed payload field cannot carry prose or a path onto the wire under an id\n * attribute. A value that does not fit is dropped, not repaired.\n */\nexport const SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;\nexport const subagentIdSchema = z.string().regex(SUBAGENT_ID_PATTERN);\nexport type SubagentId = z.infer<typeof subagentIdSchema>;\n","import { z } from \"zod\";\n\nimport { tokenCountSchema } from \"./primitives.js\";\n\n/**\n * Whether an observation reports the change since the previous observation\n * (`delta`) or the running total for the session/generation (`cumulative`).\n *\n * The canonical model keeps temporality explicit rather than assuming one:\n * summing cumulative observations double-counts, and diffing delta observations\n * silently loses tokens.\n */\nexport const usageTemporalitySchema = z.enum([\"delta\", \"cumulative\"]);\nexport type UsageTemporality = z.infer<typeof usageTemporalitySchema>;\n\n/**\n * Whether the provider counts cache-creation tokens inside its input total or\n * reports them as a disjoint bucket.\n *\n * - `included-in-input`: `cacheCreationInputTokens` is a subset of `inputTokens`.\n * - `disjoint-from-input`: cache-creation tokens are billed in addition to\n * `inputTokens` and must be added when computing a total.\n * - `not-reported`: the provider exposes no cache-creation counter; the field is\n * pinned to zero.\n */\nexport const cacheCreationAccountingSchema = z.enum([\n \"included-in-input\",\n \"disjoint-from-input\",\n \"not-reported\",\n]);\nexport type CacheCreationAccounting = z.infer<typeof cacheCreationAccountingSchema>;\n\n/** Whether a provider-reported total agrees with the canonical computation. */\nexport const providerTotalAgreementSchema = z.enum([\"unreported\", \"agrees\", \"disagrees\"]);\nexport type ProviderTotalAgreement = z.infer<typeof providerTotalAgreementSchema>;\n\n/**\n * What an adapter reports, before normalization.\n *\n * `inputTokens` is *inclusive*: it counts every input token the provider\n * attributes to the call, including cache reads (and cache creation when the\n * provider folds it in). `outputTokens` is likewise inclusive of reasoning\n * output. Subset fields describe portions of those totals, never additions.\n */\nexport const usageReportSchema = z.strictObject({\n temporality: usageTemporalitySchema,\n /** Inclusive input tokens. */\n inputTokens: tokenCountSchema.optional(),\n /** Subset of `inputTokens` served from a prompt cache. */\n cachedInputTokens: tokenCountSchema.optional(),\n /** Tokens written to a prompt cache. */\n cacheCreationInputTokens: tokenCountSchema.optional(),\n /** Required when `cacheCreationInputTokens` is present and non-zero. */\n cacheCreationAccounting: cacheCreationAccountingSchema.optional(),\n /** Inclusive output tokens. */\n outputTokens: tokenCountSchema.optional(),\n /** Subset of `outputTokens` spent on reasoning. */\n reasoningOutputTokens: tokenCountSchema.optional(),\n /** Total exactly as the provider reported it, if it reported one. */\n providerTotalTokens: tokenCountSchema.optional(),\n});\nexport type UsageReport = z.infer<typeof usageReportSchema>;\n\n/**\n * Fully normalized usage.\n *\n * Derived fields (`uncachedInputTokens`, `totalTokens`,\n * `providerTotalAgreement`) are part of the schema and are re-checked on parse,\n * so an inconsistent object cannot exist. Construct values with\n * {@link normalizeUsage} rather than by hand.\n */\nexport const canonicalUsageSchema = z\n .strictObject({\n temporality: usageTemporalitySchema,\n inputTokens: tokenCountSchema,\n cachedInputTokens: tokenCountSchema,\n cacheCreationInputTokens: tokenCountSchema,\n cacheCreationAccounting: cacheCreationAccountingSchema,\n outputTokens: tokenCountSchema,\n reasoningOutputTokens: tokenCountSchema,\n /** Derived: input tokens that were neither cache reads nor cache writes. */\n uncachedInputTokens: tokenCountSchema,\n /** Derived: canonical billable total. */\n totalTokens: tokenCountSchema,\n providerTotalTokens: tokenCountSchema.optional(),\n providerTotalAgreement: providerTotalAgreementSchema,\n })\n .check((ctx) => {\n const usage = ctx.value;\n const push = (message: string): void => {\n ctx.issues.push({ code: \"custom\", input: usage, message });\n };\n\n if (usage.cachedInputTokens > usage.inputTokens) {\n push(\"cachedInputTokens must not exceed inputTokens (it is a subset)\");\n }\n if (usage.reasoningOutputTokens > usage.outputTokens) {\n push(\"reasoningOutputTokens must not exceed outputTokens (it is a subset)\");\n }\n if (usage.cacheCreationAccounting === \"not-reported\" && usage.cacheCreationInputTokens !== 0) {\n push(\"cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported\");\n }\n const creationInsideInput =\n usage.cacheCreationAccounting === \"included-in-input\" ? usage.cacheCreationInputTokens : 0;\n if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {\n push(\n \"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input\",\n );\n }\n const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;\n if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {\n push(`uncachedInputTokens must equal ${expectedUncached}`);\n }\n const creationOutsideInput =\n usage.cacheCreationAccounting === \"disjoint-from-input\" ? usage.cacheCreationInputTokens : 0;\n const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;\n if (usage.totalTokens !== expectedTotal) {\n push(`totalTokens must equal ${expectedTotal}`);\n }\n const expectedAgreement: ProviderTotalAgreement =\n usage.providerTotalTokens === undefined\n ? \"unreported\"\n : usage.providerTotalTokens === expectedTotal\n ? \"agrees\"\n : \"disagrees\";\n if (usage.providerTotalAgreement !== expectedAgreement) {\n push(`providerTotalAgreement must be ${expectedAgreement}`);\n }\n });\nexport type CanonicalUsage = z.infer<typeof canonicalUsageSchema>;\n\nexport type UsageNormalizationIssue = {\n readonly code:\n | \"invalid-report\"\n | \"cached-exceeds-input\"\n | \"reasoning-exceeds-output\"\n | \"cache-creation-exceeds-input\"\n | \"cache-creation-accounting-missing\";\n readonly message: string;\n};\n\nexport type UsageNormalizationResult =\n | { readonly status: \"ok\"; readonly usage: CanonicalUsage; readonly notes: readonly string[] }\n | { readonly status: \"invalid\"; readonly issues: readonly UsageNormalizationIssue[] };\n\n/**\n * Normalize a provider usage report into canonical usage.\n *\n * Deterministic rules:\n * 1. Absent counters default to `0`; `providerTotalTokens` stays absent.\n * 2. Non-integer, negative, or non-finite counters are rejected.\n * 3. A subset exceeding its total is rejected — never clamped — because\n * clamping would silently invent a billing story.\n * 4. `cacheCreationAccounting` defaults to `not-reported` when no cache-creation\n * tokens are reported, and is *required* when they are: guessing whether the\n * bucket is disjoint would mis-total every downstream cost calculation.\n * 5. A provider total that disagrees with the canonical total is preserved as\n * reported and flagged `disagrees`. Both numbers survive; neither is edited.\n */\nexport const normalizeUsage = (report: unknown): UsageNormalizationResult => {\n const parsed = usageReportSchema.safeParse(report);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map((issue) => ({\n code: \"invalid-report\" as const,\n message: `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n })),\n };\n }\n\n const input = parsed.data;\n const issues: UsageNormalizationIssue[] = [];\n const notes: string[] = [];\n\n const inputTokens = input.inputTokens ?? 0;\n const cachedInputTokens = input.cachedInputTokens ?? 0;\n const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;\n const outputTokens = input.outputTokens ?? 0;\n const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;\n\n let accounting: CacheCreationAccounting;\n if (cacheCreationInputTokens === 0) {\n accounting = input.cacheCreationAccounting ?? \"not-reported\";\n if (accounting !== \"not-reported\") {\n notes.push(\n `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`,\n );\n }\n } else if (input.cacheCreationAccounting === undefined) {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message:\n \"cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred\",\n });\n accounting = \"not-reported\";\n } else if (input.cacheCreationAccounting === \"not-reported\") {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message: \"cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens\",\n });\n accounting = \"not-reported\";\n } else {\n accounting = input.cacheCreationAccounting;\n }\n\n if (cachedInputTokens > inputTokens) {\n issues.push({\n code: \"cached-exceeds-input\",\n message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n if (reasoningOutputTokens > outputTokens) {\n issues.push({\n code: \"reasoning-exceeds-output\",\n message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`,\n });\n }\n\n const creationInsideInput = accounting === \"included-in-input\" ? cacheCreationInputTokens : 0;\n if (cachedInputTokens + creationInsideInput > inputTokens) {\n issues.push({\n code: \"cache-creation-exceeds-input\",\n message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const creationOutsideInput = accounting === \"disjoint-from-input\" ? cacheCreationInputTokens : 0;\n const totalTokens = inputTokens + creationOutsideInput + outputTokens;\n const providerTotalAgreement: ProviderTotalAgreement =\n input.providerTotalTokens === undefined\n ? \"unreported\"\n : input.providerTotalTokens === totalTokens\n ? \"agrees\"\n : \"disagrees\";\n\n if (providerTotalAgreement === \"disagrees\") {\n notes.push(\n `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`,\n );\n }\n\n const usage: CanonicalUsage = {\n temporality: input.temporality,\n inputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens,\n reasoningOutputTokens,\n uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,\n totalTokens,\n ...(input.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: input.providerTotalTokens }),\n providerTotalAgreement,\n };\n\n return { status: \"ok\", usage, notes };\n};\n\nexport class UsageNormalizationError extends Error {\n public readonly issues: readonly UsageNormalizationIssue[];\n\n public constructor(issues: readonly UsageNormalizationIssue[]) {\n super(`invalid usage report: ${issues.map((issue) => issue.message).join(\"; \")}`);\n this.name = \"UsageNormalizationError\";\n this.issues = issues;\n }\n}\n\n/** Convenience wrapper for call sites that treat invalid usage as a bug. */\nexport const normalizeUsageOrThrow = (report: unknown): CanonicalUsage => {\n const result = normalizeUsage(report);\n if (result.status === \"invalid\") {\n throw new UsageNormalizationError(result.issues);\n }\n return result.usage;\n};\n\nexport const EMPTY_DELTA_USAGE: CanonicalUsage = Object.freeze(\n normalizeUsageOrThrow({ temporality: \"delta\" }),\n);\n\nexport type UsageDeltaResult = {\n readonly usage: CanonicalUsage;\n /**\n * True when the current snapshot is smaller than the previous one on any\n * counter. That means the cumulative series restarted (new session, replayed\n * transcript, provider reset), so the current snapshot is emitted as the delta\n * instead of a negative difference.\n */\n readonly resetDetected: boolean;\n};\n\nconst requireCumulative = (usage: CanonicalUsage, label: string): void => {\n if (usage.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: `${label} must have cumulative temporality` },\n ]);\n }\n};\n\n/**\n * Convert two cumulative snapshots into a delta observation.\n *\n * Replay safety: re-processing the same snapshot yields an all-zero delta, and a\n * decreasing series is reported as a reset rather than a negative delta.\n * Accounting mode must match; mixing modes would make the subtraction meaningless.\n */\nexport const cumulativeToDelta = (\n previous: CanonicalUsage,\n current: CanonicalUsage,\n): UsageDeltaResult => {\n requireCumulative(previous, \"previous usage\");\n requireCumulative(current, \"current usage\");\n\n if (\n previous.cacheCreationAccounting !== current.cacheCreationAccounting &&\n previous.cacheCreationInputTokens !== 0 &&\n current.cacheCreationInputTokens !== 0\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot diff cumulative usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const resetDetected =\n current.inputTokens < previous.inputTokens ||\n current.cachedInputTokens < previous.cachedInputTokens ||\n current.cacheCreationInputTokens < previous.cacheCreationInputTokens ||\n current.outputTokens < previous.outputTokens ||\n current.reasoningOutputTokens < previous.reasoningOutputTokens;\n\n if (resetDetected) {\n return {\n usage: normalizeUsageOrThrow({ ...toReport(current), temporality: \"delta\" }),\n resetDetected: true,\n };\n }\n\n const usage = normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: current.inputTokens - previous.inputTokens,\n cachedInputTokens: current.cachedInputTokens - previous.cachedInputTokens,\n cacheCreationInputTokens:\n current.cacheCreationInputTokens - previous.cacheCreationInputTokens,\n cacheCreationAccounting: current.cacheCreationAccounting,\n outputTokens: current.outputTokens - previous.outputTokens,\n reasoningOutputTokens: current.reasoningOutputTokens - previous.reasoningOutputTokens,\n });\n\n return { usage, resetDetected: false };\n};\n\n/** Project canonical usage back onto the reported shape. */\nexport const toReport = (usage: CanonicalUsage): UsageReport => ({\n temporality: usage.temporality,\n inputTokens: usage.inputTokens,\n cachedInputTokens: usage.cachedInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n cacheCreationAccounting: usage.cacheCreationAccounting,\n outputTokens: usage.outputTokens,\n reasoningOutputTokens: usage.reasoningOutputTokens,\n ...(usage.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: usage.providerTotalTokens }),\n});\n\n/**\n * Add two delta observations. Cumulative usage is never summed, because two\n * running totals do not compose.\n */\nexport const addUsage = (a: CanonicalUsage, b: CanonicalUsage): CanonicalUsage => {\n if (a.temporality !== \"delta\" || b.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"only delta usage may be summed\" },\n ]);\n }\n const accounting =\n a.cacheCreationInputTokens === 0 && a.cacheCreationAccounting === \"not-reported\"\n ? b.cacheCreationAccounting\n : b.cacheCreationInputTokens === 0 && b.cacheCreationAccounting === \"not-reported\"\n ? a.cacheCreationAccounting\n : a.cacheCreationAccounting;\n\n if (\n a.cacheCreationInputTokens !== 0 &&\n b.cacheCreationInputTokens !== 0 &&\n a.cacheCreationAccounting !== b.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot sum usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n a.providerTotalTokens === undefined && b.providerTotalTokens === undefined\n ? undefined\n : (a.providerTotalTokens ?? 0) + (b.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: a.inputTokens + b.inputTokens,\n cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,\n cacheCreationInputTokens: a.cacheCreationInputTokens + b.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: a.outputTokens + b.outputTokens,\n reasoningOutputTokens: a.reasoningOutputTokens + b.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n","import { z } from \"zod\";\n\n/**\n * Version of the canonical event model.\n *\n * Every emitted event carries this value. Consumers must treat an unknown\n * version as unreadable rather than guessing field semantics.\n *\n * Compatibility rules:\n * - Additive optional fields do not change the version.\n * - Renaming, removing, or re-interpreting a field increments the version.\n */\nexport const CANONICAL_SCHEMA_VERSION = 1 as const;\n\nexport type CanonicalSchemaVersion = typeof CANONICAL_SCHEMA_VERSION;\n\nexport const canonicalSchemaVersionSchema = z.literal(CANONICAL_SCHEMA_VERSION);\n","import { 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 { 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 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 { 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 { createErrorInfo } from \"../errors/index.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { Attributes } from \"../model/primitives.js\";\nimport type { Clock, Logger, LogLevel, StateRecord, StateStore, StateValue, TelemetryEmitResult, TelemetrySink } from \"./ports.js\";\nimport { stateRecordSchema } from \"./ports.js\";\nimport { LOG_LEVEL_RANK } from \"./ports.js\";\n\nexport type InMemoryStateStoreOptions = {\n readonly clock: Clock;\n /**\n * Fail the next N operations. Used to prove the pipeline degrades instead of\n * throwing when state is unavailable.\n */\n readonly failOperations?: number;\n};\n\nexport interface InMemoryStateStore extends StateStore {\n /** Direct view of stored records, for assertions. */\n snapshot(): ReadonlyMap<string, StateRecord>;\n /** Make the next `count` operations reject. */\n failNext(count: number): void;\n clear(): void;\n}\n\nexport const createInMemoryStateStore = (\n options: InMemoryStateStoreOptions,\n): InMemoryStateStore => {\n const records = new Map<string, StateRecord>();\n let failures = options.failOperations ?? 0;\n\n const guard = (operation: string): void => {\n if (failures > 0) {\n failures -= 1;\n throw new Error(`in-memory state store failure injected during ${operation}`);\n }\n };\n\n return {\n read: (key: string): Promise<StateRecord | undefined> => {\n guard(\"read\");\n return Promise.resolve(records.get(key));\n },\n write: (key: string, value: StateValue): Promise<StateRecord> => {\n guard(\"write\");\n const previous = records.get(key);\n const record = stateRecordSchema.parse({\n revision: (previous?.revision ?? 0) + 1,\n updatedAt: options.clock.now(),\n value,\n });\n records.set(key, record);\n return Promise.resolve(record);\n },\n delete: (key: string): Promise<void> => {\n guard(\"delete\");\n records.delete(key);\n return Promise.resolve();\n },\n keys: (prefix: string): Promise<readonly string[]> => {\n guard(\"keys\");\n return Promise.resolve([...records.keys()].filter((key) => key.startsWith(prefix)).sort());\n },\n snapshot: (): ReadonlyMap<string, StateRecord> => new Map(records),\n failNext: (count: number): void => {\n failures += count;\n },\n clear: (): void => {\n records.clear();\n },\n };\n};\n\nexport type RecordingTelemetrySinkOptions = {\n /** Reject the next N batches, reporting an export failure. */\n readonly failBatches?: number;\n};\n\nexport interface RecordingTelemetrySink extends TelemetrySink {\n /** Batches in emit order. */\n batches(): readonly (readonly CanonicalEvent[])[];\n /** All events, flattened. */\n events(): readonly CanonicalEvent[];\n flushCount(): number;\n shutdownCount(): number;\n failNext(count: number): void;\n clear(): void;\n}\n\nexport const createRecordingTelemetrySink = (\n options: RecordingTelemetrySinkOptions = {},\n): RecordingTelemetrySink => {\n const batches: (readonly CanonicalEvent[])[] = [];\n let failures = options.failBatches ?? 0;\n let flushes = 0;\n let shutdowns = 0;\n\n return {\n emit: (events: readonly CanonicalEvent[]): Promise<TelemetryEmitResult> => {\n if (failures > 0) {\n failures -= 1;\n return Promise.resolve({\n accepted: 0,\n rejected: events.length,\n errors: [\n createErrorInfo({\n code: \"telemetry-export-failure\",\n phase: \"export\",\n detail: \"recording sink rejected the batch\",\n details: { \"export.batch_size\": events.length },\n }),\n ],\n });\n }\n batches.push([...events]);\n return Promise.resolve({ accepted: events.length, rejected: 0, errors: [] });\n },\n flush: (): Promise<void> => {\n flushes += 1;\n return Promise.resolve();\n },\n shutdown: (): Promise<void> => {\n shutdowns += 1;\n return Promise.resolve();\n },\n batches: (): readonly (readonly CanonicalEvent[])[] => batches.map((batch) => [...batch]),\n events: (): readonly CanonicalEvent[] => batches.flat(),\n flushCount: (): number => flushes,\n shutdownCount: (): number => shutdowns,\n failNext: (count: number): void => {\n failures += count;\n },\n clear: (): void => {\n batches.length = 0;\n },\n };\n};\n\n/** Sink that accepts and discards everything. */\nexport const createNullTelemetrySink = (): TelemetrySink => ({\n emit: (events: readonly CanonicalEvent[]): Promise<TelemetryEmitResult> =>\n Promise.resolve({ accepted: events.length, rejected: 0, errors: [] }),\n flush: (): Promise<void> => Promise.resolve(),\n shutdown: (): Promise<void> => Promise.resolve(),\n});\n\nexport type LogRecord = {\n readonly level: Exclude<LogLevel, \"silent\">;\n readonly message: string;\n readonly fields?: Attributes;\n};\n\nexport interface RecordingLogger extends Logger {\n records(): readonly LogRecord[];\n clear(): void;\n}\n\nexport const createRecordingLogger = (level: LogLevel = \"debug\"): RecordingLogger => {\n const records: LogRecord[] = [];\n const threshold = LOG_LEVEL_RANK[level];\n const push = (\n entryLevel: Exclude<LogLevel, \"silent\">,\n message: string,\n fields?: Attributes,\n ): void => {\n if (threshold === 0 || LOG_LEVEL_RANK[entryLevel] > threshold) {\n return;\n }\n records.push({ level: entryLevel, message, ...(fields === undefined ? {} : { fields }) });\n };\n\n return {\n error: (message: string, fields?: Attributes): void => {\n push(\"error\", message, fields);\n },\n warn: (message: string, fields?: Attributes): void => {\n push(\"warn\", message, fields);\n },\n info: (message: string, fields?: Attributes): void => {\n push(\"info\", message, fields);\n },\n debug: (message: string, fields?: Attributes): void => {\n push(\"debug\", message, fields);\n },\n records: (): readonly LogRecord[] => [...records],\n clear: (): void => {\n records.length = 0;\n },\n };\n};\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 { 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 { 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\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 { createHash } from \"node:crypto\";\n\nimport type { ContentFact, ContentKind, ContentRole } from \"../model/content.js\";\nimport { isValidExtensionKey } from \"../model/extensions.js\";\nimport {\n attributeValueSchema,\n MAX_ATTRIBUTE_ARRAY_LENGTH,\n MAX_ATTRIBUTE_STRING_LENGTH,\n type AttributePrimitive,\n type Attributes,\n type AttributeValue,\n} from \"../model/primitives.js\";\nimport {\n CONTENT_MODE_DISCLOSURE,\n resolvePrivacyPolicy,\n type PrivacyLimits,\n type PrivacyPolicy,\n} from \"./policy.js\";\n\nexport type SanitizedValue =\n | string\n | number\n | boolean\n | null\n | readonly SanitizedValue[]\n | { readonly [key: string]: SanitizedValue };\n\nexport type SanitizeStats = {\n readonly truncatedStrings: number;\n readonly truncatedArrays: number;\n readonly truncatedObjects: number;\n readonly redactedKeys: number;\n readonly depthExceeded: number;\n readonly droppedValues: number;\n readonly circularReferences: number;\n};\n\nexport type SanitizeResult = {\n readonly value: SanitizedValue;\n readonly stats: SanitizeStats;\n};\n\nexport type DescribeContentInput = {\n readonly kind: ContentKind;\n readonly text: string;\n readonly role?: ContentRole;\n readonly label?: string;\n};\n\nexport type DescribeStructuredInput = {\n readonly kind: ContentKind;\n readonly value: unknown;\n readonly role?: ContentRole;\n readonly label?: string;\n};\n\nexport type SanitizeExtensionsResult = {\n readonly extensions: Record<string, AttributeValue>;\n readonly droppedKeys: readonly string[];\n};\n\n/**\n * Single point through which every piece of potentially sensitive data passes.\n *\n * Provider adapters receive this service and are expected to describe content\n * with it rather than copying text into events themselves. That keeps the\n * disclosure decision in one auditable place.\n */\nexport interface PrivacyService {\n readonly policy: PrivacyPolicy;\n /** Notes about deterministic policy downgrades applied at construction. */\n readonly policyNotes: readonly string[];\n /** Stable salted digest, formatted `sha256:<hex>`. */\n hash(value: string): string;\n /** Opaque namespaced handle suitable for a workspace or resource id. */\n deriveOpaqueId(namespace: string, value: string): string;\n describeContent(input: DescribeContentInput): ContentFact;\n /**\n * A content fact for a kind the event can carry when the provider sent no\n * text. Distinct from describing an empty string: there is nothing to\n * disclose under any content mode, so the fact is always omitted.\n */\n describeUnavailableContent(input: Omit<DescribeContentInput, \"text\">): ContentFact;\n describeStructured(input: DescribeStructuredInput): ContentFact;\n isSecretKey(key: string): boolean;\n sanitizeStructured(value: unknown): SanitizeResult;\n /** Attribute-safe projection of a sanitized value, with dotted paths. */\n flattenToAttributes(value: SanitizedValue, prefix: string): Attributes;\n sanitizeAttributes(value: Readonly<Record<string, unknown>>): Attributes;\n sanitizeExtensions(value: Readonly<Record<string, unknown>>): SanitizeExtensionsResult;\n /** Bound a string to the policy limit, reporting whether it was cut. */\n boundString(value: string): { readonly text: string; readonly truncated: boolean };\n}\n\nconst compilePatterns = (sources: readonly string[], flags: string): readonly RegExp[] => {\n const compiled: RegExp[] = [];\n for (const source of sources) {\n try {\n compiled.push(new RegExp(source, flags));\n } catch {\n // An unusable pattern must not disable the whole privacy service; the\n // remaining patterns still apply. Skipping is the conservative choice for\n // key patterns only because a bad pattern would otherwise match nothing\n // anyway.\n continue;\n }\n }\n return compiled;\n};\n\nconst codePointLength = (value: string): number => [...value].length;\n\nconst isSanitizedArray = (value: SanitizedValue): value is readonly SanitizedValue[] =>\n Array.isArray(value);\n\nconst sliceCodePoints = (value: string, max: number): string => {\n if (max <= 0) {\n return \"\";\n }\n let result = \"\";\n let count = 0;\n for (const char of value) {\n if (count >= max) {\n break;\n }\n result += char;\n count += 1;\n }\n return result;\n};\n\nconst stableStringify = (value: unknown): string => {\n const seen = new WeakSet<object>();\n const walk = (input: unknown): string => {\n if (input === null) {\n return \"null\";\n }\n if (typeof input === \"string\") {\n return JSON.stringify(input);\n }\n if (typeof input === \"number\") {\n return Number.isFinite(input) ? JSON.stringify(input) : \"null\";\n }\n if (typeof input === \"boolean\") {\n return input ? \"true\" : \"false\";\n }\n if (typeof input === \"bigint\") {\n return JSON.stringify(input.toString());\n }\n if (typeof input !== \"object\") {\n return \"null\";\n }\n if (seen.has(input)) {\n return '\"<circular>\"';\n }\n seen.add(input);\n if (Array.isArray(input)) {\n return `[${input.map((entry) => walk(entry)).join(\",\")}]`;\n }\n const record = input as Record<string, unknown>;\n const keys = Object.keys(record).sort();\n return `{${keys\n .map((key) => `${JSON.stringify(key)}:${walk(record[key])}`)\n .join(\",\")}}`;\n };\n return walk(value);\n};\n\ntype MutableStats = {\n truncatedStrings: number;\n truncatedArrays: number;\n truncatedObjects: number;\n redactedKeys: number;\n depthExceeded: number;\n droppedValues: number;\n circularReferences: number;\n};\n\nconst emptyStats = (): MutableStats => ({\n truncatedStrings: 0,\n truncatedArrays: 0,\n truncatedObjects: 0,\n redactedKeys: 0,\n depthExceeded: 0,\n droppedValues: 0,\n circularReferences: 0,\n});\n\nexport const createPrivacyService = (policyInput: PrivacyPolicy): PrivacyService => {\n const { policy, notes } = resolvePrivacyPolicy(policyInput);\n const limits: PrivacyLimits = policy.limits;\n const secretKeyPatterns = compilePatterns(policy.secretKeyPatterns, \"i\");\n const secretValuePatterns = compilePatterns(policy.secretValuePatterns, \"g\");\n\n const hash = (value: string): string =>\n `sha256:${createHash(\"sha256\").update(policy.hashSalt).update(\"\\0\").update(value, \"utf8\").digest(\"hex\")}`;\n\n const isSecretKey = (key: string): boolean =>\n secretKeyPatterns.some((pattern) => pattern.test(key));\n\n const boundString = (value: string): { text: string; truncated: boolean } => {\n const length = codePointLength(value);\n if (length <= limits.maxStringLength) {\n return { text: value, truncated: false };\n }\n return { text: sliceCodePoints(value, limits.maxStringLength), truncated: true };\n };\n\n const redactSecretSpans = (value: string): { text: string; count: number } => {\n let count = 0;\n let text = value;\n for (const pattern of secretValuePatterns) {\n text = text.replace(new RegExp(pattern.source, pattern.flags), () => {\n count += 1;\n return policy.redactionPlaceholder;\n });\n }\n return { text, count };\n };\n\n const maskText = (value: string): string =>\n Array.from(value, (char) => (/\\s/.test(char) ? char : policy.maskCharacter)).join(\"\");\n\n const disclose = (\n original: string,\n ): { text: string | undefined; truncated: boolean; secretsRedacted: number } => {\n switch (policy.contentMode) {\n case \"omit\":\n return { text: undefined, truncated: false, secretsRedacted: 0 };\n case \"mask\": {\n const bounded = boundString(original);\n return { text: maskText(bounded.text), truncated: bounded.truncated, secretsRedacted: 0 };\n }\n case \"redact\": {\n const redacted = redactSecretSpans(original);\n const bounded = boundString(redacted.text);\n return {\n text: bounded.text,\n truncated: bounded.truncated,\n secretsRedacted: redacted.count,\n };\n }\n case \"raw\": {\n const bounded = boundString(original);\n return { text: bounded.text, truncated: bounded.truncated, secretsRedacted: 0 };\n }\n }\n };\n\n const describeText = (input: DescribeContentInput): ContentFact => {\n const disclosed = disclose(input.text);\n return {\n kind: input.kind,\n ...(input.role === undefined ? {} : { role: input.role }),\n characterLength: codePointLength(input.text),\n byteLength: Buffer.byteLength(input.text, \"utf8\"),\n contentHash: hash(input.text),\n disclosure: CONTENT_MODE_DISCLOSURE[policy.contentMode],\n ...(disclosed.text === undefined ? {} : { text: disclosed.text }),\n truncated: disclosed.truncated,\n secretsRedacted: disclosed.secretsRedacted,\n ...(input.label === undefined ? {} : { label: input.label }),\n };\n };\n\n const sanitizeValue = (value: unknown, depth: number, stats: MutableStats, seen: WeakSet<object>): SanitizedValue => {\n if (value === null) {\n return null;\n }\n switch (typeof value) {\n case \"string\": {\n const bounded = boundString(value);\n if (bounded.truncated) {\n stats.truncatedStrings += 1;\n }\n return bounded.text;\n }\n case \"number\":\n if (!Number.isFinite(value)) {\n stats.droppedValues += 1;\n return null;\n }\n return value;\n case \"boolean\":\n return value;\n case \"bigint\":\n return value.toString();\n case \"undefined\":\n case \"function\":\n case \"symbol\":\n stats.droppedValues += 1;\n return null;\n default:\n break;\n }\n\n if (depth >= limits.maxDepth) {\n stats.depthExceeded += 1;\n return \"<depth-exceeded>\";\n }\n if (seen.has(value)) {\n stats.circularReferences += 1;\n return \"<circular>\";\n }\n seen.add(value);\n\n if (Array.isArray(value)) {\n const entries = value.slice(0, limits.maxArrayLength);\n if (value.length > limits.maxArrayLength) {\n stats.truncatedArrays += 1;\n }\n return entries.map((entry) => sanitizeValue(entry, depth + 1, stats, seen));\n }\n\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const retained = keys.slice(0, limits.maxObjectKeys);\n if (keys.length > limits.maxObjectKeys) {\n stats.truncatedObjects += 1;\n }\n const result: Record<string, SanitizedValue> = {};\n for (const key of retained) {\n if (isSecretKey(key)) {\n stats.redactedKeys += 1;\n result[key] = policy.redactionPlaceholder;\n continue;\n }\n result[key] = sanitizeValue(record[key], depth + 1, stats, seen);\n }\n return result;\n };\n\n const sanitizeStructured = (value: unknown): SanitizeResult => {\n const stats = emptyStats();\n const sanitized = sanitizeValue(value, 0, stats, new WeakSet<object>());\n return { value: sanitized, stats };\n };\n\n const toAttributePrimitive = (value: SanitizedValue): AttributePrimitive | undefined => {\n if (typeof value === \"string\") {\n return value.slice(0, MAX_ATTRIBUTE_STRING_LENGTH);\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n return undefined;\n };\n\n const flattenToAttributes = (value: SanitizedValue, prefix: string): Attributes => {\n const attributes: Record<string, AttributeValue> = {};\n const walk = (current: SanitizedValue, path: string): void => {\n if (\n typeof current === \"string\" ||\n typeof current === \"number\" ||\n typeof current === \"boolean\"\n ) {\n const primitive = toAttributePrimitive(current);\n if (primitive !== undefined) {\n attributes[path] = primitive;\n }\n return;\n }\n if (current === null) {\n return;\n }\n if (isSanitizedArray(current)) {\n const primitives: AttributePrimitive[] = [];\n let uniform = true;\n for (const entry of current) {\n const entryPrimitive = toAttributePrimitive(entry);\n if (entryPrimitive === undefined) {\n uniform = false;\n break;\n }\n primitives.push(entryPrimitive);\n }\n if (uniform) {\n attributes[path] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);\n return;\n }\n for (const [index, entry] of current.entries()) {\n walk(entry, `${path}.${index}`);\n }\n return;\n }\n for (const [key, entry] of Object.entries(current)) {\n walk(entry, path === \"\" ? key : `${path}.${key}`);\n }\n };\n walk(value, prefix);\n return attributes;\n };\n\n const sanitizeAttributes = (value: Readonly<Record<string, unknown>>): Attributes => {\n const attributes: Record<string, AttributeValue> = {};\n for (const [key, entry] of Object.entries(value)) {\n if (isSecretKey(key)) {\n attributes[key] = policy.redactionPlaceholder;\n continue;\n }\n const sanitized = sanitizeStructured(entry).value;\n const primitive = toAttributePrimitive(sanitized);\n if (primitive !== undefined) {\n attributes[key] = primitive;\n continue;\n }\n const flattened = flattenToAttributes(sanitized, key);\n Object.assign(attributes, flattened);\n }\n return attributes;\n };\n\n const sanitizeExtensions = (\n value: Readonly<Record<string, unknown>>,\n ): SanitizeExtensionsResult => {\n const extensions: Record<string, AttributeValue> = {};\n const droppedKeys: string[] = [];\n for (const [key, entry] of Object.entries(value)) {\n if (!isValidExtensionKey(key)) {\n droppedKeys.push(key);\n continue;\n }\n if (isSecretKey(key)) {\n extensions[key] = policy.redactionPlaceholder;\n continue;\n }\n const sanitized = sanitizeStructured(entry).value;\n const candidate = attributeValueSchema.safeParse(sanitized);\n if (candidate.success) {\n extensions[key] = candidate.data;\n } else {\n droppedKeys.push(key);\n }\n }\n return { extensions, droppedKeys };\n };\n\n return {\n policy,\n policyNotes: notes,\n hash,\n deriveOpaqueId: (namespace: string, value: string): string =>\n hash(`${namespace}\\0${value}`),\n describeContent: describeText,\n describeUnavailableContent: (input: Omit<DescribeContentInput, \"text\">): ContentFact => ({\n kind: input.kind,\n ...(input.role === undefined ? {} : { role: input.role }),\n characterLength: 0,\n byteLength: 0,\n contentHash: hash(\"\"),\n disclosure: \"omitted\",\n truncated: false,\n secretsRedacted: 0,\n ...(input.label === undefined ? {} : { label: input.label }),\n }),\n describeStructured: (input: DescribeStructuredInput): ContentFact => {\n const serialized = stableStringify(input.value);\n const sanitized = sanitizeStructured(input.value);\n const base = describeText({\n kind: input.kind,\n text: serialized,\n ...(input.role === undefined ? {} : { role: input.role }),\n ...(input.label === undefined ? {} : { label: input.label }),\n });\n if (base.text === undefined) {\n return base;\n }\n // Disclose the sanitized projection rather than the raw serialization, so\n // secret-keyed values never appear even in `raw` mode.\n const disclosed = disclose(stableStringify(sanitized.value));\n return {\n ...base,\n ...(disclosed.text === undefined ? {} : { text: disclosed.text }),\n truncated: base.truncated || disclosed.truncated,\n secretsRedacted: disclosed.secretsRedacted + sanitized.stats.redactedKeys,\n };\n },\n isSecretKey,\n sanitizeStructured,\n flattenToAttributes,\n sanitizeAttributes,\n sanitizeExtensions,\n boundString,\n };\n};\n","import { z } from \"zod\";\n\nimport 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 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 * 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","/**\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","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"],"mappings":";AAAA,SAAS,KAAAA,WAAS;;;ACAlB,SAAS,KAAAC,UAAS;;;ACAlB,SAAS,SAAS;AAMX,IAAM,0BAA0B,EAAE,KAAK;AAAA;AAAA,EAE5C;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA,EACA;AAAA;AAAA,EAEA;AACF,CAAC;AAGM,IAAM,sBAAsB,EAAE,KAAK,CAAC,WAAW,OAAO,CAAC;AAIvD,IAAM,mBAAmB,EAAE,KAAK;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;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;AAC/D,cAAM,QAAQ,MAAM,YAAY,SAAS;AACzC,YAAI,MAAM,SAAS,YAAY;AAC7B,iBAAO,MAAM;AAAA,QACf;AACA,YAAI,MAAM,SAAS,WAAW;AAC5B,iBAAO;AAAA,QACT;AACA,cAAM,SAAc,cAAQ,SAAS;AACrC,YAAI,WAAW,WAAW;AACxB,iBAAO;AAAA,QACT;AACA,oBAAY;AAAA,MACd;AACA,aAAO;AAAA,IACT,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO,EAAE,OAAO;AAClB;","names":["z","z","z","z","z","z","z","z","z","z","z","parsed","z","z","z","z","z","z","z","event","z","z","z","z","z","z","z","z","z","z","z","createHash","createHash","path","z","z","event","resolve","path","z","z","event","resolve","z","event","batch","open","path","readBounded"]}
1
+ {"version":3,"sources":["../src/runtime/ports.ts","../src/model/events.ts","../src/errors/taxonomy.ts","../src/model/content.ts","../src/model/primitives.ts","../src/model/extensions.ts","../src/model/identity.ts","../src/model/target.ts","../src/model/usage.ts","../src/model/version.ts","../src/runtime/clock.ts","../src/runtime/ids.ts","../src/runtime/logger.ts","../src/errors/index.ts","../src/runtime/memory.ts","../src/runtime/delivery.ts","../src/runtime/hook.ts","../src/config/schema.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/privacy/service.ts","../src/providers/adapter.ts","../src/providers/registry.ts","../src/runtime/target-resolution.ts","../src/privacy/workspace.ts","../src/state/async-lock.ts","../src/state/store.ts","../src/runtime/session-context.ts","../src/runtime/git-worktree.ts"],"sourcesContent":["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 { z } from \"zod\";\n\nimport {\n errorPhaseSchema,\n errorSeveritySchema,\n otelHookErrorCodeSchema,\n} from \"../errors/taxonomy.js\";\nimport { contentFactSchema, contentFactsSchema } from \"./content.js\";\nimport { extensionsSchema, emptyExtensions } from \"./extensions.js\";\nimport { sourceProvenanceSchema, workspaceIdentitySchema } from \"./identity.js\";\nimport { subagentIdSchema, workspaceTargetSchema } from \"./target.js\";\nimport {\n durationMillisSchema,\n epochMillisSchema,\n eventIdSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n sequenceNumberSchema,\n sessionIdSchema,\n tokenCountSchema,\n} from \"./primitives.js\";\nimport { canonicalUsageSchema, type CanonicalUsage } from \"./usage.js\";\nimport { canonicalSchemaVersionSchema } from \"./version.js\";\n\n/** Model being invoked. Model identifiers are not treated as sensitive. */\nexport const modelDescriptorSchema = z.strictObject({\n modelId: nonEmptyStringSchema,\n /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */\n vendor: nonEmptyStringSchema.optional(),\n family: nonEmptyStringSchema.optional(),\n});\nexport type ModelDescriptor = z.infer<typeof modelDescriptorSchema>;\n\nexport const costFactsSchema = z.strictObject({\n /** ISO 4217 code. */\n currency: z.string().length(3),\n amount: z.number().min(0).finite(),\n source: z.enum([\"provider-reported\", \"computed\"]),\n});\nexport type CostFacts = z.infer<typeof costFactsSchema>;\n\nexport const canonicalEventTypeSchema = z.enum([\n \"session.start\",\n \"session.end\",\n \"prompt.submitted\",\n \"generation.start\",\n \"generation.end\",\n \"tool.start\",\n \"tool.end\",\n \"subagent.start\",\n \"subagent.end\",\n \"compaction.performed\",\n \"error.raised\",\n]);\nexport type CanonicalEventType = z.infer<typeof canonicalEventTypeSchema>;\n\nexport const CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;\n\nconst outcomeSchema = z.enum([\"ok\", \"error\", \"cancelled\", \"timeout\", \"denied\", \"unknown\"]);\nexport type EventOutcome = z.infer<typeof outcomeSchema>;\n\n/**\n * Fields present on every canonical event.\n *\n * Identity fields are duplicated onto each event rather than referenced through\n * shared state, so an event is self-describing once it leaves the process.\n */\nconst baseEventFields = {\n schemaVersion: canonicalSchemaVersionSchema,\n eventId: eventIdSchema,\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Per-invocation ordering key. Stable across replays of the same input. */\n sequence: sequenceNumberSchema,\n occurredAt: epochMillisSchema,\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n /**\n * The provider's own id for the subagent this event was emitted inside (e.g.\n * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event\n * factory, never by hand.\n */\n subagentId: subagentIdSchema.optional(),\n extensions: extensionsSchema.default(emptyExtensions),\n /**\n * Attributes of the session context segment in force when the event\n * occurred (`docs/session-context.md`), stamped by the core from a file a\n * harness wrote. Exported on every record of the event, over the same keys\n * from the Resource. Absent when no context applies. Set by the core only,\n * never by an adapter.\n */\n contextAttributes: z.record(z.string().min(1).max(255), z.union([z.string(), z.number(), z.boolean()])).optional(),\n} as const;\n\nconst event = <TShape extends z.ZodRawShape>(shape: TShape) =>\n z.strictObject({ ...baseEventFields, ...shape });\n\nexport const sessionStartEventSchema = event({\n type: z.literal(\"session.start\"),\n sessionKind: z.enum([\"interactive\", \"non-interactive\", \"unknown\"]),\n agentName: nonEmptyStringSchema.optional(),\n agentVersion: nonEmptyStringSchema.optional(),\n model: modelDescriptorSchema.optional(),\n /** The git worktree the session runs in, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const sessionEndEventSchema = event({\n type: z.literal(\"session.end\"),\n reason: z.enum([\"completed\", \"aborted\", \"error\", \"timeout\", \"unknown\"]),\n durationMillis: durationMillisSchema.optional(),\n /** Session totals, typically cumulative. */\n usage: canonicalUsageSchema.optional(),\n cost: costFactsSchema.optional(),\n});\n\nexport const promptSubmittedEventSchema = event({\n type: z.literal(\"prompt.submitted\"),\n promptSource: z.enum([\"user\", \"automation\", \"resumed\", \"unknown\"]),\n content: contentFactSchema.optional(),\n turnIndex: z.number().int().min(0).optional(),\n /** The git worktree the session runs in, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const generationStartEventSchema = event({\n type: z.literal(\"generation.start\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n requestedMaxOutputTokens: tokenCountSchema.optional(),\n inputContent: contentFactsSchema.optional(),\n});\n\nexport const generationEndEventSchema = event({\n type: z.literal(\"generation.end\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n outcome: outcomeSchema,\n stopReason: nonEmptyStringSchema.optional(),\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n /**\n * True when `usage` is known to cover only part of the generation (for\n * example the last model request of a multi-request turn); false when the\n * provider or harness said it is the whole. Absent: not stated. Meaningless\n * without `usage`.\n */\n usagePartial: z.boolean().optional(),\n cost: costFactsSchema.optional(),\n outputContent: contentFactsSchema.optional(),\n});\n\nexport const toolKindSchema = z.enum([\n \"read\",\n \"write\",\n \"execute\",\n \"search\",\n \"network\",\n \"delegate\",\n \"other\",\n \"unknown\",\n]);\nexport type ToolKind = z.infer<typeof toolKindSchema>;\n\nexport const toolStartEventSchema = event({\n type: z.literal(\"tool.start\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n toolKind: toolKindSchema,\n generationId: nonEmptyStringSchema.optional(),\n input: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const toolEndEventSchema = event({\n type: z.literal(\"tool.end\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n /** Present when the host asked for or recorded a permission decision. */\n permissionDecision: z.enum([\"allowed\", \"denied\", \"deferred\", \"not-required\"]).optional(),\n output: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const subagentStartEventSchema = event({\n type: z.literal(\"subagent.start\"),\n subagentInvocationId: invocationIdSchema,\n subagentType: nonEmptyStringSchema.optional(),\n /** 0 for the top-level agent; 1 for its direct children. */\n delegationDepth: z.number().int().min(0).max(64),\n model: modelDescriptorSchema.optional(),\n});\n\nexport const subagentEndEventSchema = event({\n type: z.literal(\"subagent.end\"),\n subagentInvocationId: invocationIdSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const compactionPerformedEventSchema = event({\n type: z.literal(\"compaction.performed\"),\n trigger: z.enum([\"automatic\", \"manual\", \"unknown\"]),\n /** Provider-reported context size before and after compaction, if known. */\n contextTokensBefore: tokenCountSchema.optional(),\n contextTokensAfter: tokenCountSchema.optional(),\n droppedMessageCount: z.number().int().min(0).optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const errorRaisedEventSchema = event({\n type: z.literal(\"error.raised\"),\n errorCode: otelHookErrorCodeSchema,\n severity: errorSeveritySchema,\n phase: errorPhaseSchema,\n retryable: z.boolean(),\n /** Error text is content: it is described, never embedded verbatim by default. */\n message: contentFactSchema.optional(),\n /** Non-sensitive, provider-agnostic short label. */\n detail: nonEmptyStringSchema.optional(),\n});\n\nexport const canonicalEventSchema = z.discriminatedUnion(\"type\", [\n sessionStartEventSchema,\n sessionEndEventSchema,\n promptSubmittedEventSchema,\n generationStartEventSchema,\n generationEndEventSchema,\n toolStartEventSchema,\n toolEndEventSchema,\n subagentStartEventSchema,\n subagentEndEventSchema,\n compactionPerformedEventSchema,\n errorRaisedEventSchema,\n]);\n\nexport type CanonicalEvent = z.infer<typeof canonicalEventSchema>;\nexport type CanonicalEventInput = z.input<typeof canonicalEventSchema>;\n\nexport type SessionStartEvent = z.infer<typeof sessionStartEventSchema>;\nexport type SessionEndEvent = z.infer<typeof sessionEndEventSchema>;\nexport type PromptSubmittedEvent = z.infer<typeof promptSubmittedEventSchema>;\nexport type GenerationStartEvent = z.infer<typeof generationStartEventSchema>;\nexport type GenerationEndEvent = z.infer<typeof generationEndEventSchema>;\nexport type ToolStartEvent = z.infer<typeof toolStartEventSchema>;\nexport type ToolEndEvent = z.infer<typeof toolEndEventSchema>;\nexport type SubagentStartEvent = z.infer<typeof subagentStartEventSchema>;\nexport type SubagentEndEvent = z.infer<typeof subagentEndEventSchema>;\nexport type CompactionPerformedEvent = z.infer<typeof compactionPerformedEventSchema>;\nexport type ErrorRaisedEvent = z.infer<typeof errorRaisedEventSchema>;\n\nexport type CanonicalEventOfType<TType extends CanonicalEventType> = Extract<\n CanonicalEvent,\n { type: TType }\n>;\n\n/**\n * The event types that may carry a resolved `target` (ADR 0008): a tool call\n * names the worktree it touched; a session start and a prompt name the one the\n * session runs in, so a consumer knows the session's place before its first\n * tool call.\n */\nexport const TARGETED_EVENT_TYPES = [\"session.start\", \"prompt.submitted\", \"tool.start\", \"tool.end\"] as const;\nexport type TargetedEventType = (typeof TARGETED_EVENT_TYPES)[number];\nexport type TargetedEvent = CanonicalEventOfType<TargetedEventType>;\n\nconst TARGETED: ReadonlySet<string> = new Set(TARGETED_EVENT_TYPES);\nexport const isTargetedEvent = (event: CanonicalEvent): event is TargetedEvent => TARGETED.has(event.type);\n\nexport type EventValidationResult =\n | { readonly status: \"ok\"; readonly event: CanonicalEvent }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nexport const validateCanonicalEvent = (value: unknown): EventValidationResult => {\n const parsed = canonicalEventSchema.safeParse(value);\n if (parsed.success) {\n return { status: \"ok\", event: parsed.data };\n }\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n};\n\n/** Parse or throw. Intended for fixtures and tests, not the hook path. */\nexport const parseCanonicalEvent = (value: unknown): CanonicalEvent =>\n canonicalEventSchema.parse(value);\n\n/** Usage carried by an event, if the event type can carry any. */\nexport const eventUsage = (event: CanonicalEvent): CanonicalUsage | undefined =>\n \"usage\" in event ? event.usage : undefined;\n\n/** Stable ordering: by sequence, then by timestamp, then by event id. */\nexport const compareEvents = (a: CanonicalEvent, b: CanonicalEvent): number =>\n a.sequence - b.sequence || a.occurredAt - b.occurredAt || a.eventId.localeCompare(b.eventId);\n","import { z } from \"zod\";\n\n/**\n * Closed set of error codes. Adding a code is a minor change; changing what a\n * code means is a breaking change.\n */\nexport const otelHookErrorCodeSchema = z.enum([\n /** Input was not usable at all (empty stdin, unparsable JSON). */\n \"invalid-input\",\n /** Input parsed but failed canonical schema validation. */\n \"schema-validation-failed\",\n /** No adapter claimed the input with sufficient confidence. */\n \"provider-unknown\",\n /** Several adapters claimed the input at the same confidence. */\n \"provider-detection-ambiguous\",\n /** An adapter threw or returned a malformed result. */\n \"provider-adapter-failure\",\n /** Two identity claims disagreed at equal confidence. */\n \"identity-conflict\",\n /** Required identity fields were absent. */\n \"identity-incomplete\",\n /** A usage report violated the canonical usage invariants. */\n \"usage-invalid\",\n /** The state store could not be read or written. */\n \"state-store-failure\",\n /** The telemetry sink rejected or could not deliver a batch. */\n \"telemetry-export-failure\",\n /** Content reached the sink boundary in a state the policy forbids. */\n \"privacy-policy-violation\",\n /** Configuration could not be resolved. */\n \"configuration-invalid\",\n /** A configured bound (events, batch size) dropped data. */\n \"limit-exceeded\",\n /**\n * No replay-stable delivery identifier was available for a callback while\n * deduplication was required.\n */\n \"delivery-identifier-unavailable\",\n \"delivery-claim-superseded\",\n /** Anything unanticipated. Always reported, never fatal to the host. */\n \"internal-error\",\n]);\nexport type OtelHookErrorCode = z.infer<typeof otelHookErrorCodeSchema>;\n\nexport const errorSeveritySchema = z.enum([\"warning\", \"error\"]);\nexport type ErrorSeverity = z.infer<typeof errorSeveritySchema>;\n\n/** Pipeline stage where a failure occurred. */\nexport const errorPhaseSchema = z.enum([\n \"configuration\",\n \"detection\",\n \"identity\",\n \"parsing\",\n \"normalization\",\n \"privacy\",\n \"state\",\n \"export\",\n \"shutdown\",\n]);\nexport type ErrorPhase = z.infer<typeof errorPhaseSchema>;\n\n/**\n * Which of the two safety postures a code participates in.\n *\n * - `fail-open`: the hook still reports success to the host agent. Telemetry may\n * be incomplete; the coding agent is never blocked.\n * - `fail-closed-attribution`: the observation is not attributed to a session or\n * provider. Data is dropped rather than labelled with a guess.\n */\nexport const failurePostureSchema = z.enum([\"fail-open\", \"fail-closed-attribution\"]);\nexport type FailurePosture = z.infer<typeof failurePostureSchema>;\n\nexport type ErrorCodeDescriptor = {\n readonly code: OtelHookErrorCode;\n readonly severity: ErrorSeverity;\n readonly posture: FailurePosture;\n /** Whether retrying the same input could succeed. */\n readonly retryable: boolean;\n readonly summary: string;\n};\n\nexport const ERROR_TAXONOMY: Readonly<Record<OtelHookErrorCode, ErrorCodeDescriptor>> =\n Object.freeze({\n \"invalid-input\": {\n code: \"invalid-input\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Input could not be read or decoded.\",\n },\n \"schema-validation-failed\": {\n code: \"schema-validation-failed\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"A canonical event failed schema validation and was dropped.\",\n },\n \"provider-unknown\": {\n code: \"provider-unknown\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"No adapter recognized the source provider; the input stays unattributed.\",\n },\n \"provider-detection-ambiguous\": {\n code: \"provider-detection-ambiguous\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Multiple adapters claimed the input at equal confidence.\",\n },\n \"provider-adapter-failure\": {\n code: \"provider-adapter-failure\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A provider adapter failed while parsing.\",\n },\n \"identity-conflict\": {\n code: \"identity-conflict\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Identity claims disagreed; attribution was declined.\",\n },\n \"identity-incomplete\": {\n code: \"identity-incomplete\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Required identity fields were missing; attribution was declined.\",\n },\n \"usage-invalid\": {\n code: \"usage-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A usage report violated the canonical usage invariants.\",\n },\n \"state-store-failure\": {\n code: \"state-store-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"State could not be read or written; derived values may be incomplete.\",\n },\n \"telemetry-export-failure\": {\n code: \"telemetry-export-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"The telemetry sink could not accept a batch.\",\n },\n \"privacy-policy-violation\": {\n code: \"privacy-policy-violation\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Content violated the resolved privacy policy and was dropped.\",\n },\n \"configuration-invalid\": {\n code: \"configuration-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Configuration could not be resolved; defaults apply.\",\n },\n \"limit-exceeded\": {\n code: \"limit-exceeded\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A configured bound was reached and data was dropped.\",\n },\n \"delivery-identifier-unavailable\": {\n code: \"delivery-identifier-unavailable\",\n severity: \"warning\",\n // Fail-open: the observation is still attributed and exported. Only the\n // at-most-once guarantee is missing, and refusing the telemetry to protect\n // a duplicate count would trade a certain loss for a possible one.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"No replay-stable delivery identifier was available; this callback was exported without deduplication.\",\n },\n \"delivery-claim-superseded\": {\n code: \"delivery-claim-superseded\",\n severity: \"warning\",\n // Fail-open, and specifically *not* silent. A peer reclaimed this callback's\n // claim while this process was still working on it, which means the\n // configured stale window is shorter than this installation's real worst\n // case. Both processes may now have exported the callback, so the\n // at-most-once guarantee did not hold for it — the only honest response is\n // to say so and let the operator raise the window.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"A delivery claim was reclaimed by another process before this one committed; the callback may have been exported twice.\",\n },\n \"internal-error\": {\n code: \"internal-error\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"An unexpected failure was contained.\",\n },\n });\n\nexport const describeErrorCode = (code: OtelHookErrorCode): ErrorCodeDescriptor =>\n ERROR_TAXONOMY[code];\n\n/** Outcome of attributing an observation to a provider and session. */\nexport const attributionOutcomeSchema = z.enum([\n /** Identity resolved; events carry provider and session identity. */\n \"attributed\",\n /** Identity could not be established safely; nothing was attributed. */\n \"declined\",\n /** Attribution was attempted and failed unexpectedly. */\n \"failed\",\n /** Input was recognized but intentionally carried no telemetry. */\n \"not-applicable\",\n]);\nexport type AttributionOutcome = z.infer<typeof attributionOutcomeSchema>;\n\nexport const attributionReasonSchema = z.enum([\n \"provider-unknown\",\n \"provider-detection-ambiguous\",\n \"identity-conflict\",\n \"identity-incomplete\",\n \"adapter-ignored-input\",\n \"adapter-failure\",\n \"invalid-input\",\n \"internal-error\",\n]);\nexport type AttributionReason = z.infer<typeof attributionReasonSchema>;\n","import { z } from \"zod\";\n\nimport { nonEmptyStringSchema } from \"./primitives.js\";\n\n/** What kind of conversational or tool content a fact describes. */\nexport const contentKindSchema = z.enum([\n \"prompt\",\n \"response\",\n \"reasoning\",\n \"tool-input\",\n \"tool-output\",\n \"error-message\",\n \"system-instruction\",\n \"attachment\",\n]);\nexport type ContentKind = z.infer<typeof contentKindSchema>;\n\nexport const contentRoleSchema = z.enum([\"user\", \"assistant\", \"system\", \"tool\", \"unknown\"]);\nexport type ContentRole = z.infer<typeof contentRoleSchema>;\n\n/**\n * How much of the original content this fact discloses.\n *\n * - `omitted`: no text at all (the default posture).\n * - `masked`: a shape-preserving mask; non-whitespace characters replaced.\n * - `redacted`: text with secret-looking spans replaced by a placeholder.\n * - `raw`: verbatim text. Only reachable through explicit opt-in.\n */\nexport const contentDisclosureSchema = z.enum([\"omitted\", \"masked\", \"redacted\", \"raw\"]);\nexport type ContentDisclosure = z.infer<typeof contentDisclosureSchema>;\n\nexport const CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;\n\n/**\n * A privacy-safe description of content.\n *\n * Lengths and a stable hash are always present so consumers can measure and\n * correlate volume without receiving the content itself. `text` is present only\n * when the resolved privacy policy allows disclosure, and is produced solely by\n * the central privacy service.\n */\nexport const contentFactSchema = z.strictObject({\n kind: contentKindSchema,\n role: contentRoleSchema.optional(),\n /** Unicode code point count of the original content. */\n characterLength: z.number().int().min(0),\n /** UTF-8 byte length of the original content. */\n byteLength: z.number().int().min(0),\n /** Stable salted digest of the original content. */\n contentHash: z.string().regex(CONTENT_HASH_PATTERN),\n disclosure: contentDisclosureSchema,\n /** Disclosed text, bounded by the privacy policy. Absent when omitted. */\n text: z.string().optional(),\n /** True when `text` was cut short by the configured string bound. */\n truncated: z.boolean(),\n /** Number of secret-looking spans replaced while producing `text`. */\n secretsRedacted: z.number().int().min(0),\n /** Optional non-sensitive label, e.g. a MIME type or tool name. */\n label: nonEmptyStringSchema.optional(),\n});\nexport type ContentFact = z.infer<typeof contentFactSchema>;\n\nexport const contentFactsSchema = z.array(contentFactSchema).max(64);\n\n/**\n * Guard used in tests and at the sink boundary: an omitted fact must not carry\n * text, and a disclosing fact must carry it.\n */\nexport const isContentFactConsistent = (fact: ContentFact): boolean =>\n fact.disclosure === \"omitted\" ? fact.text === undefined : fact.text !== undefined;\n\n/**\n * A fact for a content kind the event can carry when the provider sent no text.\n *\n * Always `omitted` with zero length, regardless of the installation's content\n * mode: there is nothing to mask, redact, or export.\n */\nexport const isUnavailableContentFact = (fact: ContentFact): boolean =>\n fact.disclosure === \"omitted\" &&\n fact.text === undefined &&\n fact.characterLength === 0 &&\n fact.byteLength === 0;\n","import { z } from \"zod\";\n\n/** Maximum length accepted for short identifier-like strings. */\nexport const MAX_IDENTIFIER_LENGTH = 256;\n\n/** Maximum length accepted for a single string attribute value. */\nexport const MAX_ATTRIBUTE_STRING_LENGTH = 4096;\n\n/** Maximum number of entries accepted in an attribute array value. */\nexport const MAX_ATTRIBUTE_ARRAY_LENGTH = 128;\n\nexport const nonEmptyStringSchema = z.string().min(1).max(MAX_IDENTIFIER_LENGTH);\n\n/** Wall-clock time as whole milliseconds since the Unix epoch. */\nexport const epochMillisSchema = z.number().int().min(0).max(8_640_000_000_000_000);\nexport type EpochMillis = z.infer<typeof epochMillisSchema>;\n\n/** Non-negative duration in milliseconds; may be fractional. */\nexport const durationMillisSchema = z.number().min(0).finite();\n\n/** Token counts are always non-negative integers. */\nexport const tokenCountSchema = z.number().int().min(0);\n\n/** Monotonically increasing per-invocation ordering key. */\nexport const sequenceNumberSchema = z.number().int().min(0);\n\nconst brandedIdSchema = (): z.ZodString => z.string().min(1).max(MAX_IDENTIFIER_LENGTH);\n\nexport const invocationIdSchema = brandedIdSchema().brand<\"InvocationId\">();\nexport type InvocationId = z.infer<typeof invocationIdSchema>;\n\nexport const sessionIdSchema = brandedIdSchema().brand<\"SessionId\">();\nexport type SessionId = z.infer<typeof sessionIdSchema>;\n\nexport const eventIdSchema = brandedIdSchema().brand<\"EventId\">();\nexport type EventId = z.infer<typeof eventIdSchema>;\n\n/**\n * Workspace identifiers are opaque, privacy-safe handles of the form\n * `<scheme>:<token>`. Filesystem paths cannot satisfy this pattern, which keeps\n * home directories and repository paths out of telemetry by construction.\n */\nexport const WORKSPACE_ID_PATTERN = /^[a-z][a-z0-9]{0,15}:[A-Za-z0-9_-]{8,128}$/;\nexport const workspaceIdSchema = z\n .string()\n .regex(WORKSPACE_ID_PATTERN, \"workspace id must be an opaque `<scheme>:<token>` handle\")\n .brand<\"WorkspaceId\">();\nexport type WorkspaceId = z.infer<typeof workspaceIdSchema>;\n\n/** Provider ids are lowercase, hyphenated, and stable across releases. */\nexport const PROVIDER_ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\nexport const providerIdSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(PROVIDER_ID_PATTERN, \"provider id must be lowercase and hyphenated\")\n .brand<\"ProviderId\">();\nexport type ProviderId = z.infer<typeof providerIdSchema>;\n\n/** Sentinel used whenever the source provider could not be established. */\nexport const UNKNOWN_PROVIDER_ID = \"unknown\" as const;\nexport type UnknownProviderId = typeof UNKNOWN_PROVIDER_ID;\n\nexport const resolvedProviderIdSchema = z.union([\n providerIdSchema,\n z.literal(UNKNOWN_PROVIDER_ID),\n]);\nexport type ResolvedProviderId = z.infer<typeof resolvedProviderIdSchema>;\n\nexport const isUnknownProvider = (value: ResolvedProviderId): value is UnknownProviderId =>\n value === UNKNOWN_PROVIDER_ID;\n\n/**\n * Attribute values are restricted to OpenTelemetry-compatible primitives.\n *\n * This restriction is a containment boundary, not a convenience: because no\n * nested object can be represented, a raw provider payload cannot be smuggled\n * out of an adapter through attributes or extensions.\n */\nexport const attributePrimitiveSchema = z.union([\n z.string().max(MAX_ATTRIBUTE_STRING_LENGTH),\n z.number().finite(),\n z.boolean(),\n]);\nexport type AttributePrimitive = z.infer<typeof attributePrimitiveSchema>;\n\nexport const attributeValueSchema = z.union([\n attributePrimitiveSchema,\n z.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH),\n]);\nexport type AttributeValue = z.infer<typeof attributeValueSchema>;\n\nexport const attributesSchema = z.record(z.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);\nexport type Attributes = z.infer<typeof attributesSchema>;\n\n/** Ordered confidence ladder for provider detection. */\nexport const detectionConfidenceSchema = z.enum([\"none\", \"weak\", \"strong\", \"exact\"]);\nexport type DetectionConfidence = z.infer<typeof detectionConfidenceSchema>;\n\nexport const DETECTION_CONFIDENCE_RANK: Readonly<Record<DetectionConfidence, number>> =\n Object.freeze({\n none: 0,\n weak: 1,\n strong: 2,\n exact: 3,\n });\n\nexport const compareDetectionConfidence = (a: DetectionConfidence, b: DetectionConfidence): number =>\n DETECTION_CONFIDENCE_RANK[a] - DETECTION_CONFIDENCE_RANK[b];\n\n/** How the observed data reached this process. */\nexport const sourceTransportSchema = z.enum([\n \"hook-stdin\",\n \"cli-argument\",\n \"library-call\",\n \"test-fixture\",\n]);\nexport type SourceTransport = z.infer<typeof sourceTransportSchema>;\n","import { z } from \"zod\";\n\nimport { attributeValueSchema, type AttributeValue } from \"./primitives.js\";\n\n/**\n * Extension keys must be namespaced: at least one dot-separated segment before\n * the leaf, e.g. `acme.deployment-tier`. Namespacing keeps provider- and\n * consumer-specific fields from colliding with core fields or each other.\n */\nexport const EXTENSION_KEY_PATTERN =\n /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;\n\n/** Namespaces owned by the core model; extensions may not use them. */\nexport const RESERVED_EXTENSION_NAMESPACES: readonly string[] = Object.freeze([\n \"otelhook\",\n \"otel\",\n \"telemetry\",\n]);\n\nexport const MAX_EXTENSION_ENTRIES = 64;\n\nexport const extensionKeyNamespace = (key: string): string => key.slice(0, key.indexOf(\".\"));\n\nexport const isReservedExtensionNamespace = (key: string): boolean =>\n RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));\n\nexport const isValidExtensionKey = (key: string): boolean =>\n EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);\n\n/**\n * Namespaced extension bag.\n *\n * Values are restricted to attribute primitives, so extensions cannot carry\n * nested provider payloads.\n */\nexport const extensionsSchema = z\n .record(z.string(), attributeValueSchema)\n .check((ctx) => {\n const keys = Object.keys(ctx.value);\n if (keys.length > MAX_EXTENSION_ENTRIES) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`,\n });\n }\n for (const key of keys) {\n if (!EXTENSION_KEY_PATTERN.test(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. \"acme.tier\"`,\n });\n continue;\n }\n if (isReservedExtensionNamespace(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`,\n });\n }\n }\n });\n\nexport type Extensions = Record<string, AttributeValue>;\n\nexport const EMPTY_EXTENSIONS: Extensions = Object.freeze({});\n\nexport const emptyExtensions = (): Extensions => ({});\n","import { z } from \"zod\";\n\nimport {\n attributesSchema,\n detectionConfidenceSchema,\n DETECTION_CONFIDENCE_RANK,\n epochMillisSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n resolvedProviderIdSchema,\n sessionIdSchema,\n sourceTransportSchema,\n workspaceIdSchema,\n type DetectionConfidence,\n type InvocationId,\n type SessionId,\n type WorkspaceId,\n} from \"./primitives.js\";\n\n/**\n * Where a workspace identifier came from.\n *\n * Ordered from most to least stable. The source is recorded so consumers can\n * tell a repository-scoped identity from a directory-scoped one instead of\n * assuming they are comparable.\n */\nexport const workspaceKeySourceSchema = z.enum([\n \"git-remote\",\n \"git-root\",\n \"working-directory\",\n \"explicit\",\n \"unknown\",\n]);\nexport type WorkspaceKeySource = z.infer<typeof workspaceKeySourceSchema>;\n\n/**\n * Privacy-safe workspace identity.\n *\n * Only opaque handles and explicitly allowed labels are modelled. There is no\n * field for a filesystem path, so paths cannot be exported through this type.\n */\nexport const workspaceIdentitySchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n keySource: workspaceKeySourceSchema,\n /** Repository name only; never an owner path or URL with credentials. */\n repositoryName: nonEmptyStringSchema.optional(),\n vcsBranchName: nonEmptyStringSchema.optional(),\n /** Opaque handle for the checked-out revision. */\n vcsRevisionId: nonEmptyStringSchema.optional(),\n })\n .readonly();\nexport type WorkspaceIdentity = z.infer<typeof workspaceIdentitySchema>;\n\nexport const UNKNOWN_WORKSPACE_ID = \"unknown:0000000000000000\" as WorkspaceId;\n\nexport const unknownWorkspaceIdentity = (): WorkspaceIdentity =>\n workspaceIdentitySchema.parse({\n workspaceId: UNKNOWN_WORKSPACE_ID,\n keySource: \"unknown\",\n });\n\n/**\n * Provenance of an observation: which provider produced it and which adapter\n * interpreted it, with the confidence of that attribution.\n */\nexport const sourceProvenanceSchema = z\n .strictObject({\n providerId: resolvedProviderIdSchema,\n providerVersion: nonEmptyStringSchema.optional(),\n adapterId: nonEmptyStringSchema,\n adapterVersion: nonEmptyStringSchema,\n detectionConfidence: detectionConfidenceSchema,\n /** The provider's own name for the source event, e.g. a hook event name. */\n sourceEventName: nonEmptyStringSchema.optional(),\n transport: sourceTransportSchema,\n })\n .readonly();\nexport type SourceProvenance = z.infer<typeof sourceProvenanceSchema>;\n\n/**\n * Opaque, immutable metadata supplied by the embedding consumer.\n *\n * The library never interprets these values; it only carries and exports them.\n */\nexport const consumerAttributesSchema = attributesSchema.readonly();\nexport type ConsumerAttributes = z.infer<typeof consumerAttributesSchema>;\n\n/**\n * Immutable identity of a single hook invocation.\n *\n * Frozen on parse. There is deliberately no setter, no builder that mutates in\n * place, and no module-level instance: identity is passed explicitly so two\n * concurrent invocations can never observe each other's fields.\n */\nexport const invocationIdentitySchema = z\n .strictObject({\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Set when this invocation runs beneath another agent invocation. */\n parentInvocationId: invocationIdSchema.optional(),\n /** Root of the session tree when the provider exposes one. */\n rootSessionId: sessionIdSchema.optional(),\n /** Stable handle for the agent process/instance, when available. */\n agentInstanceId: nonEmptyStringSchema.optional(),\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n startedAt: epochMillisSchema,\n consumerAttributes: consumerAttributesSchema,\n })\n .readonly();\nexport type InvocationIdentity = z.infer<typeof invocationIdentitySchema>;\n\n/** Fields an identity claim may contribute. */\nexport const identityClaimFieldsSchema = z.strictObject({\n invocationId: invocationIdSchema.optional(),\n sessionId: sessionIdSchema.optional(),\n parentInvocationId: invocationIdSchema.optional(),\n rootSessionId: sessionIdSchema.optional(),\n agentInstanceId: nonEmptyStringSchema.optional(),\n workspace: workspaceIdentitySchema.optional(),\n startedAt: epochMillisSchema.optional(),\n});\nexport type IdentityClaimFields = z.infer<typeof identityClaimFieldsSchema>;\n\n/**\n * A claim about invocation identity from one source.\n *\n * Claims are evidence, not truth. Resolution keeps the highest-confidence claim\n * per field and refuses to merge disagreeing peers.\n */\nexport const identityClaimSchema = z.strictObject({\n /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */\n source: nonEmptyStringSchema,\n confidence: detectionConfidenceSchema,\n fields: identityClaimFieldsSchema,\n});\nexport type IdentityClaim = z.infer<typeof identityClaimSchema>;\n\nexport type IdentityConflict = {\n readonly field: keyof IdentityClaimFields;\n readonly confidence: DetectionConfidence;\n /** Rendered, non-sensitive representations of the disagreeing values. */\n readonly values: readonly string[];\n readonly sources: readonly string[];\n};\n\nexport type IdentityResolution =\n | { readonly status: \"resolved\"; readonly identity: InvocationIdentity }\n | {\n readonly status: \"conflict\";\n readonly conflicts: readonly IdentityConflict[];\n }\n | {\n readonly status: \"incomplete\";\n readonly missing: readonly (keyof IdentityClaimFields)[];\n }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nconst CLAIM_FIELDS = [\n \"invocationId\",\n \"sessionId\",\n \"parentInvocationId\",\n \"rootSessionId\",\n \"agentInstanceId\",\n \"workspace\",\n \"startedAt\",\n] as const satisfies readonly (keyof IdentityClaimFields)[];\n\nconst renderClaimValue = (value: unknown): string => {\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (value !== null && typeof value === \"object\" && \"workspaceId\" in value) {\n const { workspaceId } = value;\n return typeof workspaceId === \"string\" ? workspaceId : \"<workspace>\";\n }\n return \"<opaque>\";\n};\n\nexport type ResolveIdentityInput = {\n readonly claims: readonly IdentityClaim[];\n readonly provenance: SourceProvenance;\n /** Used only for fields no claim provides and that have a safe default. */\n readonly fallback?: {\n readonly startedAt?: number;\n readonly workspace?: WorkspaceIdentity;\n };\n readonly consumerAttributes?: Readonly<Record<string, unknown>>;\n};\n\n/**\n * Resolve identity from claims, failing closed.\n *\n * Rules:\n * 1. For each field, only claims at the highest confidence that provided it are\n * considered. Lower-confidence claims never fill in or override.\n * 2. Two distinct values at that highest confidence produce a `conflict`. The\n * invocation is then not attributed at all — a mislabelled session is worse\n * than a missing one.\n * 3. `invocationId` and `sessionId` are mandatory. Missing either yields\n * `incomplete`; neither is invented here.\n * 4. `startedAt` and `workspace` may come from an explicit fallback, because a\n * clock reading and an `unknown` workspace handle assert nothing false.\n */\nexport const resolveInvocationIdentity = (input: ResolveIdentityInput): IdentityResolution => {\n const parsedClaims: IdentityClaim[] = [];\n const issues: string[] = [];\n for (const [index, claim] of input.claims.entries()) {\n const parsed = identityClaimSchema.safeParse(claim);\n if (parsed.success) {\n parsedClaims.push(parsed.data);\n } else {\n issues.push(\n `claim[${index}]: ${parsed.error.issues.map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`).join(\", \")}`,\n );\n }\n }\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const conflicts: IdentityConflict[] = [];\n const selected: Record<string, unknown> = {};\n\n for (const field of CLAIM_FIELDS) {\n const contributors = parsedClaims.filter((claim) => claim.fields[field] !== undefined);\n if (contributors.length === 0) {\n continue;\n }\n const bestRank = Math.max(\n ...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence]),\n );\n const best = contributors.filter(\n (claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank,\n );\n const rendered = new Map<string, string[]>();\n for (const claim of best) {\n const key = JSON.stringify(claim.fields[field]);\n const sources = rendered.get(key) ?? [];\n sources.push(claim.source);\n rendered.set(key, sources);\n }\n if (rendered.size > 1) {\n const [firstBest] = best;\n conflicts.push({\n field,\n confidence: firstBest?.confidence ?? \"none\",\n values: best.map((claim) => renderClaimValue(claim.fields[field])),\n sources: best.map((claim) => claim.source),\n });\n continue;\n }\n const [winner] = best;\n if (winner !== undefined) {\n selected[field] = winner.fields[field];\n }\n }\n\n if (conflicts.length > 0) {\n return { status: \"conflict\", conflicts };\n }\n\n const missing: (keyof IdentityClaimFields)[] = [];\n if (selected.invocationId === undefined) {\n missing.push(\"invocationId\");\n }\n if (selected.sessionId === undefined) {\n missing.push(\"sessionId\");\n }\n if (missing.length > 0) {\n return { status: \"incomplete\", missing };\n }\n\n const startedAt = (selected.startedAt as number | undefined) ?? input.fallback?.startedAt;\n if (startedAt === undefined) {\n return { status: \"incomplete\", missing: [\"startedAt\"] };\n }\n const workspace =\n (selected.workspace as WorkspaceIdentity | undefined) ??\n input.fallback?.workspace ??\n unknownWorkspaceIdentity();\n\n const candidate = {\n invocationId: selected.invocationId as InvocationId,\n sessionId: selected.sessionId as SessionId,\n ...(selected.parentInvocationId === undefined\n ? {}\n : { parentInvocationId: selected.parentInvocationId as InvocationId }),\n ...(selected.rootSessionId === undefined\n ? {}\n : { rootSessionId: selected.rootSessionId as SessionId }),\n ...(selected.agentInstanceId === undefined\n ? {}\n : { agentInstanceId: selected.agentInstanceId as string }),\n provenance: input.provenance,\n workspace,\n startedAt,\n consumerAttributes: input.consumerAttributes ?? {},\n };\n\n const parsed = invocationIdentitySchema.safeParse(candidate);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n }\n return { status: \"resolved\", identity: parsed.data };\n};\n","import { z } from \"zod\";\n\nimport { nonEmptyStringSchema, workspaceIdSchema } from \"./primitives.js\";\n\n/**\n * Per-event workspace targeting (ADR 0008).\n *\n * A session's `workspace` is where the agent was *started*. An agent routinely\n * works somewhere else — in a linked git worktree beside the checkout it was\n * launched from — and the session-level identity cannot show that. A tool event\n * can: the file it edited, or the directory its shell command ran in, names the\n * worktree it actually touched.\n *\n * Two values model that, and the split between them is the privacy boundary:\n *\n * - {@link TargetHint} is what an adapter observed — local paths. It is an\n * in-process value only: it is never part of a {@link CanonicalEvent}, never\n * persisted, never exported. The core resolves it and drops it.\n * - {@link WorkspaceTarget} is what the core resolved — salted handles of the\n * worktree and its repository, the worktree's kind, the checked-out branch, and\n * what the evidence was. It travels on the event.\n */\n\n/**\n * What a target was derived from, strongest evidence first.\n *\n * - `tool-path` — a path the tool call itself named (an edited or read file, a\n * patch header).\n * - `shell-cwd` — the working directory the provider reports a shell command ran in.\n * - `session-cwd` — only the session's own directory was known; the event may\n * have reached elsewhere (e.g. a shell `cd`) without the provider saying so.\n */\nexport const targetSourceSchema = z.enum([\"tool-path\", \"shell-cwd\", \"session-cwd\"]);\nexport type TargetSource = z.infer<typeof targetSourceSchema>;\n\n/** Most paths one hint may name; a bound, not a sampling rule (all must agree). */\nexport const MAX_TARGET_HINT_PATHS = 8;\n\n/** Longest local path a hint may carry. Longer input is dropped, never truncated. */\nexport const MAX_TARGET_PATH_LENGTH = 4096;\n\nconst localPathSchema = z\n .string()\n .min(1)\n .max(MAX_TARGET_PATH_LENGTH)\n .refine((value) => !value.includes(\"\\u0000\"), \"path must not contain NUL\");\n\n/**\n * An adapter's observation of where a tool event pointed. **Carries local paths**\n * — in-process only, see the module note.\n *\n * Every path in one hint must resolve to the same worktree, or the event gets no\n * target at all: a patch touching two worktrees did not target either of them.\n */\nexport const targetHintSchema = z\n .strictObject({\n source: targetSourceSchema,\n paths: z.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),\n /** Absolute directory that relative `paths` resolve against. */\n baseDirectory: localPathSchema.optional(),\n })\n .readonly();\nexport type TargetHint = z.infer<typeof targetHintSchema>;\n\n/**\n * The weakest hint: the session's own directory. Every adapter gives it to a\n * session start and a prompt, and to a tool call that names no path.\n */\nexport const sessionCwdHint = (cwd: string | undefined): TargetHint | undefined =>\n cwd === undefined || cwd.length === 0 ? undefined : { source: \"session-cwd\", paths: [cwd] };\n\n/**\n * Whether a worktree is its repository's main checkout (`main`) or one added\n * beside it with `git worktree add` (`linked`).\n */\nexport const worktreeKindSchema = z.enum([\"main\", \"linked\"]);\nexport type WorktreeKind = z.infer<typeof worktreeKindSchema>;\n\n/**\n * The git worktree a tool event targeted. Exported; carries no path.\n *\n * `workspaceId` is derived exactly like a `git-root` workspace identity, so a\n * consumer holding the same salt can match it against one it derived itself.\n * `repositoryId` is the same derivation applied to the repository's main\n * worktree, so every worktree of one repository shares it — and for a main\n * worktree it equals `workspaceId`.\n */\nexport const workspaceTargetSchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n /** Branch checked out in that worktree; absent on a detached HEAD. */\n vcsBranchName: nonEmptyStringSchema.optional(),\n source: targetSourceSchema,\n /** `git-root` handle of the repository's main worktree; absent when there is none to name. */\n repositoryId: workspaceIdSchema.optional(),\n worktreeKind: worktreeKindSchema.optional(),\n })\n .readonly();\nexport type WorkspaceTarget = z.infer<typeof workspaceTargetSchema>;\n\n/**\n * Shape a provider's own subagent identifier must have to be exported.\n *\n * Identifier-shaped on purpose — no whitespace, no path separators — so a\n * malformed payload field cannot carry prose or a path onto the wire under an id\n * attribute. A value that does not fit is dropped, not repaired.\n */\nexport const SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;\nexport const subagentIdSchema = z.string().regex(SUBAGENT_ID_PATTERN);\nexport type SubagentId = z.infer<typeof subagentIdSchema>;\n","import { z } from \"zod\";\n\nimport { tokenCountSchema } from \"./primitives.js\";\n\n/**\n * Whether an observation reports the change since the previous observation\n * (`delta`) or the running total for the session/generation (`cumulative`).\n *\n * The canonical model keeps temporality explicit rather than assuming one:\n * summing cumulative observations double-counts, and diffing delta observations\n * silently loses tokens.\n */\nexport const usageTemporalitySchema = z.enum([\"delta\", \"cumulative\"]);\nexport type UsageTemporality = z.infer<typeof usageTemporalitySchema>;\n\n/**\n * Whether the provider counts cache-creation tokens inside its input total or\n * reports them as a disjoint bucket.\n *\n * - `included-in-input`: `cacheCreationInputTokens` is a subset of `inputTokens`.\n * - `disjoint-from-input`: cache-creation tokens are billed in addition to\n * `inputTokens` and must be added when computing a total.\n * - `not-reported`: the provider exposes no cache-creation counter; the field is\n * pinned to zero.\n */\nexport const cacheCreationAccountingSchema = z.enum([\n \"included-in-input\",\n \"disjoint-from-input\",\n \"not-reported\",\n]);\nexport type CacheCreationAccounting = z.infer<typeof cacheCreationAccountingSchema>;\n\n/** Whether a provider-reported total agrees with the canonical computation. */\nexport const providerTotalAgreementSchema = z.enum([\"unreported\", \"agrees\", \"disagrees\"]);\nexport type ProviderTotalAgreement = z.infer<typeof providerTotalAgreementSchema>;\n\n/**\n * What an adapter reports, before normalization.\n *\n * `inputTokens` is *inclusive*: it counts every input token the provider\n * attributes to the call, including cache reads (and cache creation when the\n * provider folds it in). `outputTokens` is likewise inclusive of reasoning\n * output. Subset fields describe portions of those totals, never additions.\n */\nexport const usageReportSchema = z.strictObject({\n temporality: usageTemporalitySchema,\n /** Inclusive input tokens. */\n inputTokens: tokenCountSchema.optional(),\n /** Subset of `inputTokens` served from a prompt cache. */\n cachedInputTokens: tokenCountSchema.optional(),\n /** Tokens written to a prompt cache. */\n cacheCreationInputTokens: tokenCountSchema.optional(),\n /** Required when `cacheCreationInputTokens` is present and non-zero. */\n cacheCreationAccounting: cacheCreationAccountingSchema.optional(),\n /** Inclusive output tokens. */\n outputTokens: tokenCountSchema.optional(),\n /** Subset of `outputTokens` spent on reasoning. */\n reasoningOutputTokens: tokenCountSchema.optional(),\n /** Total exactly as the provider reported it, if it reported one. */\n providerTotalTokens: tokenCountSchema.optional(),\n});\nexport type UsageReport = z.infer<typeof usageReportSchema>;\n\n/**\n * Fully normalized usage.\n *\n * Derived fields (`uncachedInputTokens`, `totalTokens`,\n * `providerTotalAgreement`) are part of the schema and are re-checked on parse,\n * so an inconsistent object cannot exist. Construct values with\n * {@link normalizeUsage} rather than by hand.\n */\nexport const canonicalUsageSchema = z\n .strictObject({\n temporality: usageTemporalitySchema,\n inputTokens: tokenCountSchema,\n cachedInputTokens: tokenCountSchema,\n cacheCreationInputTokens: tokenCountSchema,\n cacheCreationAccounting: cacheCreationAccountingSchema,\n outputTokens: tokenCountSchema,\n reasoningOutputTokens: tokenCountSchema,\n /** Derived: input tokens that were neither cache reads nor cache writes. */\n uncachedInputTokens: tokenCountSchema,\n /** Derived: canonical billable total. */\n totalTokens: tokenCountSchema,\n providerTotalTokens: tokenCountSchema.optional(),\n providerTotalAgreement: providerTotalAgreementSchema,\n })\n .check((ctx) => {\n const usage = ctx.value;\n const push = (message: string): void => {\n ctx.issues.push({ code: \"custom\", input: usage, message });\n };\n\n if (usage.cachedInputTokens > usage.inputTokens) {\n push(\"cachedInputTokens must not exceed inputTokens (it is a subset)\");\n }\n if (usage.reasoningOutputTokens > usage.outputTokens) {\n push(\"reasoningOutputTokens must not exceed outputTokens (it is a subset)\");\n }\n if (usage.cacheCreationAccounting === \"not-reported\" && usage.cacheCreationInputTokens !== 0) {\n push(\"cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported\");\n }\n const creationInsideInput =\n usage.cacheCreationAccounting === \"included-in-input\" ? usage.cacheCreationInputTokens : 0;\n if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {\n push(\n \"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input\",\n );\n }\n const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;\n if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {\n push(`uncachedInputTokens must equal ${expectedUncached}`);\n }\n const creationOutsideInput =\n usage.cacheCreationAccounting === \"disjoint-from-input\" ? usage.cacheCreationInputTokens : 0;\n const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;\n if (usage.totalTokens !== expectedTotal) {\n push(`totalTokens must equal ${expectedTotal}`);\n }\n const expectedAgreement: ProviderTotalAgreement =\n usage.providerTotalTokens === undefined\n ? \"unreported\"\n : usage.providerTotalTokens === expectedTotal\n ? \"agrees\"\n : \"disagrees\";\n if (usage.providerTotalAgreement !== expectedAgreement) {\n push(`providerTotalAgreement must be ${expectedAgreement}`);\n }\n });\nexport type CanonicalUsage = z.infer<typeof canonicalUsageSchema>;\n\nexport type UsageNormalizationIssue = {\n readonly code:\n | \"invalid-report\"\n | \"cached-exceeds-input\"\n | \"reasoning-exceeds-output\"\n | \"cache-creation-exceeds-input\"\n | \"cache-creation-accounting-missing\";\n readonly message: string;\n};\n\nexport type UsageNormalizationResult =\n | { readonly status: \"ok\"; readonly usage: CanonicalUsage; readonly notes: readonly string[] }\n | { readonly status: \"invalid\"; readonly issues: readonly UsageNormalizationIssue[] };\n\n/**\n * Normalize a provider usage report into canonical usage.\n *\n * Deterministic rules:\n * 1. Absent counters default to `0`; `providerTotalTokens` stays absent.\n * 2. Non-integer, negative, or non-finite counters are rejected.\n * 3. A subset exceeding its total is rejected — never clamped — because\n * clamping would silently invent a billing story.\n * 4. `cacheCreationAccounting` defaults to `not-reported` when no cache-creation\n * tokens are reported, and is *required* when they are: guessing whether the\n * bucket is disjoint would mis-total every downstream cost calculation.\n * 5. A provider total that disagrees with the canonical total is preserved as\n * reported and flagged `disagrees`. Both numbers survive; neither is edited.\n */\nexport const normalizeUsage = (report: unknown): UsageNormalizationResult => {\n const parsed = usageReportSchema.safeParse(report);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map((issue) => ({\n code: \"invalid-report\" as const,\n message: `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n })),\n };\n }\n\n const input = parsed.data;\n const issues: UsageNormalizationIssue[] = [];\n const notes: string[] = [];\n\n const inputTokens = input.inputTokens ?? 0;\n const cachedInputTokens = input.cachedInputTokens ?? 0;\n const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;\n const outputTokens = input.outputTokens ?? 0;\n const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;\n\n let accounting: CacheCreationAccounting;\n if (cacheCreationInputTokens === 0) {\n accounting = input.cacheCreationAccounting ?? \"not-reported\";\n if (accounting !== \"not-reported\") {\n notes.push(\n `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`,\n );\n }\n } else if (input.cacheCreationAccounting === undefined) {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message:\n \"cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred\",\n });\n accounting = \"not-reported\";\n } else if (input.cacheCreationAccounting === \"not-reported\") {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message: \"cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens\",\n });\n accounting = \"not-reported\";\n } else {\n accounting = input.cacheCreationAccounting;\n }\n\n if (cachedInputTokens > inputTokens) {\n issues.push({\n code: \"cached-exceeds-input\",\n message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n if (reasoningOutputTokens > outputTokens) {\n issues.push({\n code: \"reasoning-exceeds-output\",\n message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`,\n });\n }\n\n const creationInsideInput = accounting === \"included-in-input\" ? cacheCreationInputTokens : 0;\n if (cachedInputTokens + creationInsideInput > inputTokens) {\n issues.push({\n code: \"cache-creation-exceeds-input\",\n message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const creationOutsideInput = accounting === \"disjoint-from-input\" ? cacheCreationInputTokens : 0;\n const totalTokens = inputTokens + creationOutsideInput + outputTokens;\n const providerTotalAgreement: ProviderTotalAgreement =\n input.providerTotalTokens === undefined\n ? \"unreported\"\n : input.providerTotalTokens === totalTokens\n ? \"agrees\"\n : \"disagrees\";\n\n if (providerTotalAgreement === \"disagrees\") {\n notes.push(\n `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`,\n );\n }\n\n const usage: CanonicalUsage = {\n temporality: input.temporality,\n inputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens,\n reasoningOutputTokens,\n uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,\n totalTokens,\n ...(input.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: input.providerTotalTokens }),\n providerTotalAgreement,\n };\n\n return { status: \"ok\", usage, notes };\n};\n\nexport class UsageNormalizationError extends Error {\n public readonly issues: readonly UsageNormalizationIssue[];\n\n public constructor(issues: readonly UsageNormalizationIssue[]) {\n super(`invalid usage report: ${issues.map((issue) => issue.message).join(\"; \")}`);\n this.name = \"UsageNormalizationError\";\n this.issues = issues;\n }\n}\n\n/** Convenience wrapper for call sites that treat invalid usage as a bug. */\nexport const normalizeUsageOrThrow = (report: unknown): CanonicalUsage => {\n const result = normalizeUsage(report);\n if (result.status === \"invalid\") {\n throw new UsageNormalizationError(result.issues);\n }\n return result.usage;\n};\n\nexport const EMPTY_DELTA_USAGE: CanonicalUsage = Object.freeze(\n normalizeUsageOrThrow({ temporality: \"delta\" }),\n);\n\nexport type UsageDeltaResult = {\n readonly usage: CanonicalUsage;\n /**\n * True when the current snapshot is smaller than the previous one on any\n * counter. That means the cumulative series restarted (new session, replayed\n * transcript, provider reset), so the current snapshot is emitted as the delta\n * instead of a negative difference.\n */\n readonly resetDetected: boolean;\n};\n\nconst requireCumulative = (usage: CanonicalUsage, label: string): void => {\n if (usage.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: `${label} must have cumulative temporality` },\n ]);\n }\n};\n\n/**\n * Convert two cumulative snapshots into a delta observation.\n *\n * Replay safety: re-processing the same snapshot yields an all-zero delta, and a\n * decreasing series is reported as a reset rather than a negative delta.\n * Accounting mode must match; mixing modes would make the subtraction meaningless.\n */\nexport const cumulativeToDelta = (\n previous: CanonicalUsage,\n current: CanonicalUsage,\n): UsageDeltaResult => {\n requireCumulative(previous, \"previous usage\");\n requireCumulative(current, \"current usage\");\n\n if (\n previous.cacheCreationAccounting !== current.cacheCreationAccounting &&\n previous.cacheCreationInputTokens !== 0 &&\n current.cacheCreationInputTokens !== 0\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot diff cumulative usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const resetDetected =\n current.inputTokens < previous.inputTokens ||\n current.cachedInputTokens < previous.cachedInputTokens ||\n current.cacheCreationInputTokens < previous.cacheCreationInputTokens ||\n current.outputTokens < previous.outputTokens ||\n current.reasoningOutputTokens < previous.reasoningOutputTokens;\n\n if (resetDetected) {\n return {\n usage: normalizeUsageOrThrow({ ...toReport(current), temporality: \"delta\" }),\n resetDetected: true,\n };\n }\n\n const usage = normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: current.inputTokens - previous.inputTokens,\n cachedInputTokens: current.cachedInputTokens - previous.cachedInputTokens,\n cacheCreationInputTokens:\n current.cacheCreationInputTokens - previous.cacheCreationInputTokens,\n cacheCreationAccounting: current.cacheCreationAccounting,\n outputTokens: current.outputTokens - previous.outputTokens,\n reasoningOutputTokens: current.reasoningOutputTokens - previous.reasoningOutputTokens,\n });\n\n return { usage, resetDetected: false };\n};\n\n/** Project canonical usage back onto the reported shape. */\nexport const toReport = (usage: CanonicalUsage): UsageReport => ({\n temporality: usage.temporality,\n inputTokens: usage.inputTokens,\n cachedInputTokens: usage.cachedInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n cacheCreationAccounting: usage.cacheCreationAccounting,\n outputTokens: usage.outputTokens,\n reasoningOutputTokens: usage.reasoningOutputTokens,\n ...(usage.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: usage.providerTotalTokens }),\n});\n\n/**\n * Add two delta observations. Cumulative usage is never summed, because two\n * running totals do not compose.\n */\nexport const addUsage = (a: CanonicalUsage, b: CanonicalUsage): CanonicalUsage => {\n if (a.temporality !== \"delta\" || b.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"only delta usage may be summed\" },\n ]);\n }\n const accounting =\n a.cacheCreationInputTokens === 0 && a.cacheCreationAccounting === \"not-reported\"\n ? b.cacheCreationAccounting\n : b.cacheCreationInputTokens === 0 && b.cacheCreationAccounting === \"not-reported\"\n ? a.cacheCreationAccounting\n : a.cacheCreationAccounting;\n\n if (\n a.cacheCreationInputTokens !== 0 &&\n b.cacheCreationInputTokens !== 0 &&\n a.cacheCreationAccounting !== b.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot sum usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n a.providerTotalTokens === undefined && b.providerTotalTokens === undefined\n ? undefined\n : (a.providerTotalTokens ?? 0) + (b.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: a.inputTokens + b.inputTokens,\n cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,\n cacheCreationInputTokens: a.cacheCreationInputTokens + b.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: a.outputTokens + b.outputTokens,\n reasoningOutputTokens: a.reasoningOutputTokens + b.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n","import { z } from \"zod\";\n\n/**\n * Version of the canonical event model.\n *\n * Every emitted event carries this value. Consumers must treat an unknown\n * version as unreadable rather than guessing field semantics.\n *\n * Compatibility rules:\n * - Additive optional fields do not change the version.\n * - Renaming, removing, or re-interpreting a field increments the version.\n */\nexport const CANONICAL_SCHEMA_VERSION = 1 as const;\n\nexport type CanonicalSchemaVersion = typeof CANONICAL_SCHEMA_VERSION;\n\nexport const canonicalSchemaVersionSchema = z.literal(CANONICAL_SCHEMA_VERSION);\n","import { 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 { 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 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 { 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 { createErrorInfo } from \"../errors/index.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { Attributes } from \"../model/primitives.js\";\nimport type { Clock, Logger, LogLevel, StateRecord, StateStore, StateValue, TelemetryEmitResult, TelemetrySink } from \"./ports.js\";\nimport { stateRecordSchema } from \"./ports.js\";\nimport { LOG_LEVEL_RANK } from \"./ports.js\";\n\nexport type InMemoryStateStoreOptions = {\n readonly clock: Clock;\n /**\n * Fail the next N operations. Used to prove the pipeline degrades instead of\n * throwing when state is unavailable.\n */\n readonly failOperations?: number;\n};\n\nexport interface InMemoryStateStore extends StateStore {\n /** Direct view of stored records, for assertions. */\n snapshot(): ReadonlyMap<string, StateRecord>;\n /** Make the next `count` operations reject. */\n failNext(count: number): void;\n clear(): void;\n}\n\nexport const createInMemoryStateStore = (\n options: InMemoryStateStoreOptions,\n): InMemoryStateStore => {\n const records = new Map<string, StateRecord>();\n let failures = options.failOperations ?? 0;\n\n const guard = (operation: string): void => {\n if (failures > 0) {\n failures -= 1;\n throw new Error(`in-memory state store failure injected during ${operation}`);\n }\n };\n\n return {\n read: (key: string): Promise<StateRecord | undefined> => {\n guard(\"read\");\n return Promise.resolve(records.get(key));\n },\n write: (key: string, value: StateValue): Promise<StateRecord> => {\n guard(\"write\");\n const previous = records.get(key);\n const record = stateRecordSchema.parse({\n revision: (previous?.revision ?? 0) + 1,\n updatedAt: options.clock.now(),\n value,\n });\n records.set(key, record);\n return Promise.resolve(record);\n },\n delete: (key: string): Promise<void> => {\n guard(\"delete\");\n records.delete(key);\n return Promise.resolve();\n },\n keys: (prefix: string): Promise<readonly string[]> => {\n guard(\"keys\");\n return Promise.resolve([...records.keys()].filter((key) => key.startsWith(prefix)).sort());\n },\n snapshot: (): ReadonlyMap<string, StateRecord> => new Map(records),\n failNext: (count: number): void => {\n failures += count;\n },\n clear: (): void => {\n records.clear();\n },\n };\n};\n\nexport type RecordingTelemetrySinkOptions = {\n /** Reject the next N batches, reporting an export failure. */\n readonly failBatches?: number;\n};\n\nexport interface RecordingTelemetrySink extends TelemetrySink {\n /** Batches in emit order. */\n batches(): readonly (readonly CanonicalEvent[])[];\n /** All events, flattened. */\n events(): readonly CanonicalEvent[];\n flushCount(): number;\n shutdownCount(): number;\n failNext(count: number): void;\n clear(): void;\n}\n\nexport const createRecordingTelemetrySink = (\n options: RecordingTelemetrySinkOptions = {},\n): RecordingTelemetrySink => {\n const batches: (readonly CanonicalEvent[])[] = [];\n let failures = options.failBatches ?? 0;\n let flushes = 0;\n let shutdowns = 0;\n\n return {\n emit: (events: readonly CanonicalEvent[]): Promise<TelemetryEmitResult> => {\n if (failures > 0) {\n failures -= 1;\n return Promise.resolve({\n accepted: 0,\n rejected: events.length,\n errors: [\n createErrorInfo({\n code: \"telemetry-export-failure\",\n phase: \"export\",\n detail: \"recording sink rejected the batch\",\n details: { \"export.batch_size\": events.length },\n }),\n ],\n });\n }\n batches.push([...events]);\n return Promise.resolve({ accepted: events.length, rejected: 0, errors: [] });\n },\n flush: (): Promise<void> => {\n flushes += 1;\n return Promise.resolve();\n },\n shutdown: (): Promise<void> => {\n shutdowns += 1;\n return Promise.resolve();\n },\n batches: (): readonly (readonly CanonicalEvent[])[] => batches.map((batch) => [...batch]),\n events: (): readonly CanonicalEvent[] => batches.flat(),\n flushCount: (): number => flushes,\n shutdownCount: (): number => shutdowns,\n failNext: (count: number): void => {\n failures += count;\n },\n clear: (): void => {\n batches.length = 0;\n },\n };\n};\n\n/** Sink that accepts and discards everything. */\nexport const createNullTelemetrySink = (): TelemetrySink => ({\n emit: (events: readonly CanonicalEvent[]): Promise<TelemetryEmitResult> =>\n Promise.resolve({ accepted: events.length, rejected: 0, errors: [] }),\n flush: (): Promise<void> => Promise.resolve(),\n shutdown: (): Promise<void> => Promise.resolve(),\n});\n\nexport type LogRecord = {\n readonly level: Exclude<LogLevel, \"silent\">;\n readonly message: string;\n readonly fields?: Attributes;\n};\n\nexport interface RecordingLogger extends Logger {\n records(): readonly LogRecord[];\n clear(): void;\n}\n\nexport const createRecordingLogger = (level: LogLevel = \"debug\"): RecordingLogger => {\n const records: LogRecord[] = [];\n const threshold = LOG_LEVEL_RANK[level];\n const push = (\n entryLevel: Exclude<LogLevel, \"silent\">,\n message: string,\n fields?: Attributes,\n ): void => {\n if (threshold === 0 || LOG_LEVEL_RANK[entryLevel] > threshold) {\n return;\n }\n records.push({ level: entryLevel, message, ...(fields === undefined ? {} : { fields }) });\n };\n\n return {\n error: (message: string, fields?: Attributes): void => {\n push(\"error\", message, fields);\n },\n warn: (message: string, fields?: Attributes): void => {\n push(\"warn\", message, fields);\n },\n info: (message: string, fields?: Attributes): void => {\n push(\"info\", message, fields);\n },\n debug: (message: string, fields?: Attributes): void => {\n push(\"debug\", message, fields);\n },\n records: (): readonly LogRecord[] => [...records],\n clear: (): void => {\n records.length = 0;\n },\n };\n};\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 { 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 { 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\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 { createHash } from \"node:crypto\";\n\nimport type { ContentFact, ContentKind, ContentRole } from \"../model/content.js\";\nimport { isValidExtensionKey } from \"../model/extensions.js\";\nimport {\n attributeValueSchema,\n MAX_ATTRIBUTE_ARRAY_LENGTH,\n MAX_ATTRIBUTE_STRING_LENGTH,\n type AttributePrimitive,\n type Attributes,\n type AttributeValue,\n} from \"../model/primitives.js\";\nimport {\n CONTENT_MODE_DISCLOSURE,\n resolvePrivacyPolicy,\n type PrivacyLimits,\n type PrivacyPolicy,\n} from \"./policy.js\";\n\nexport type SanitizedValue =\n | string\n | number\n | boolean\n | null\n | readonly SanitizedValue[]\n | { readonly [key: string]: SanitizedValue };\n\nexport type SanitizeStats = {\n readonly truncatedStrings: number;\n readonly truncatedArrays: number;\n readonly truncatedObjects: number;\n readonly redactedKeys: number;\n readonly depthExceeded: number;\n readonly droppedValues: number;\n readonly circularReferences: number;\n};\n\nexport type SanitizeResult = {\n readonly value: SanitizedValue;\n readonly stats: SanitizeStats;\n};\n\nexport type DescribeContentInput = {\n readonly kind: ContentKind;\n readonly text: string;\n readonly role?: ContentRole;\n readonly label?: string;\n};\n\nexport type DescribeStructuredInput = {\n readonly kind: ContentKind;\n readonly value: unknown;\n readonly role?: ContentRole;\n readonly label?: string;\n};\n\nexport type SanitizeExtensionsResult = {\n readonly extensions: Record<string, AttributeValue>;\n readonly droppedKeys: readonly string[];\n};\n\n/**\n * Single point through which every piece of potentially sensitive data passes.\n *\n * Provider adapters receive this service and are expected to describe content\n * with it rather than copying text into events themselves. That keeps the\n * disclosure decision in one auditable place.\n */\nexport interface PrivacyService {\n readonly policy: PrivacyPolicy;\n /** Notes about deterministic policy downgrades applied at construction. */\n readonly policyNotes: readonly string[];\n /** Stable salted digest, formatted `sha256:<hex>`. */\n hash(value: string): string;\n /** Opaque namespaced handle suitable for a workspace or resource id. */\n deriveOpaqueId(namespace: string, value: string): string;\n describeContent(input: DescribeContentInput): ContentFact;\n /**\n * A content fact for a kind the event can carry when the provider sent no\n * text. Distinct from describing an empty string: there is nothing to\n * disclose under any content mode, so the fact is always omitted.\n */\n describeUnavailableContent(input: Omit<DescribeContentInput, \"text\">): ContentFact;\n describeStructured(input: DescribeStructuredInput): ContentFact;\n isSecretKey(key: string): boolean;\n sanitizeStructured(value: unknown): SanitizeResult;\n /** Attribute-safe projection of a sanitized value, with dotted paths. */\n flattenToAttributes(value: SanitizedValue, prefix: string): Attributes;\n sanitizeAttributes(value: Readonly<Record<string, unknown>>): Attributes;\n sanitizeExtensions(value: Readonly<Record<string, unknown>>): SanitizeExtensionsResult;\n /** Bound a string to the policy limit, reporting whether it was cut. */\n boundString(value: string): { readonly text: string; readonly truncated: boolean };\n}\n\nconst compilePatterns = (sources: readonly string[], flags: string): readonly RegExp[] => {\n const compiled: RegExp[] = [];\n for (const source of sources) {\n try {\n compiled.push(new RegExp(source, flags));\n } catch {\n // An unusable pattern must not disable the whole privacy service; the\n // remaining patterns still apply. Skipping is the conservative choice for\n // key patterns only because a bad pattern would otherwise match nothing\n // anyway.\n continue;\n }\n }\n return compiled;\n};\n\nconst codePointLength = (value: string): number => [...value].length;\n\nconst isSanitizedArray = (value: SanitizedValue): value is readonly SanitizedValue[] =>\n Array.isArray(value);\n\nconst sliceCodePoints = (value: string, max: number): string => {\n if (max <= 0) {\n return \"\";\n }\n let result = \"\";\n let count = 0;\n for (const char of value) {\n if (count >= max) {\n break;\n }\n result += char;\n count += 1;\n }\n return result;\n};\n\nconst stableStringify = (value: unknown): string => {\n const seen = new WeakSet<object>();\n const walk = (input: unknown): string => {\n if (input === null) {\n return \"null\";\n }\n if (typeof input === \"string\") {\n return JSON.stringify(input);\n }\n if (typeof input === \"number\") {\n return Number.isFinite(input) ? JSON.stringify(input) : \"null\";\n }\n if (typeof input === \"boolean\") {\n return input ? \"true\" : \"false\";\n }\n if (typeof input === \"bigint\") {\n return JSON.stringify(input.toString());\n }\n if (typeof input !== \"object\") {\n return \"null\";\n }\n if (seen.has(input)) {\n return '\"<circular>\"';\n }\n seen.add(input);\n if (Array.isArray(input)) {\n return `[${input.map((entry) => walk(entry)).join(\",\")}]`;\n }\n const record = input as Record<string, unknown>;\n const keys = Object.keys(record).sort();\n return `{${keys\n .map((key) => `${JSON.stringify(key)}:${walk(record[key])}`)\n .join(\",\")}}`;\n };\n return walk(value);\n};\n\ntype MutableStats = {\n truncatedStrings: number;\n truncatedArrays: number;\n truncatedObjects: number;\n redactedKeys: number;\n depthExceeded: number;\n droppedValues: number;\n circularReferences: number;\n};\n\nconst emptyStats = (): MutableStats => ({\n truncatedStrings: 0,\n truncatedArrays: 0,\n truncatedObjects: 0,\n redactedKeys: 0,\n depthExceeded: 0,\n droppedValues: 0,\n circularReferences: 0,\n});\n\nexport const createPrivacyService = (policyInput: PrivacyPolicy): PrivacyService => {\n const { policy, notes } = resolvePrivacyPolicy(policyInput);\n const limits: PrivacyLimits = policy.limits;\n const secretKeyPatterns = compilePatterns(policy.secretKeyPatterns, \"i\");\n const secretValuePatterns = compilePatterns(policy.secretValuePatterns, \"g\");\n\n const hash = (value: string): string =>\n `sha256:${createHash(\"sha256\").update(policy.hashSalt).update(\"\\0\").update(value, \"utf8\").digest(\"hex\")}`;\n\n const isSecretKey = (key: string): boolean =>\n secretKeyPatterns.some((pattern) => pattern.test(key));\n\n const boundString = (value: string): { text: string; truncated: boolean } => {\n const length = codePointLength(value);\n if (length <= limits.maxStringLength) {\n return { text: value, truncated: false };\n }\n return { text: sliceCodePoints(value, limits.maxStringLength), truncated: true };\n };\n\n const redactSecretSpans = (value: string): { text: string; count: number } => {\n let count = 0;\n let text = value;\n for (const pattern of secretValuePatterns) {\n text = text.replace(new RegExp(pattern.source, pattern.flags), () => {\n count += 1;\n return policy.redactionPlaceholder;\n });\n }\n return { text, count };\n };\n\n const maskText = (value: string): string =>\n Array.from(value, (char) => (/\\s/.test(char) ? char : policy.maskCharacter)).join(\"\");\n\n const disclose = (\n original: string,\n ): { text: string | undefined; truncated: boolean; secretsRedacted: number } => {\n switch (policy.contentMode) {\n case \"omit\":\n return { text: undefined, truncated: false, secretsRedacted: 0 };\n case \"mask\": {\n const bounded = boundString(original);\n return { text: maskText(bounded.text), truncated: bounded.truncated, secretsRedacted: 0 };\n }\n case \"redact\": {\n const redacted = redactSecretSpans(original);\n const bounded = boundString(redacted.text);\n return {\n text: bounded.text,\n truncated: bounded.truncated,\n secretsRedacted: redacted.count,\n };\n }\n case \"raw\": {\n const bounded = boundString(original);\n return { text: bounded.text, truncated: bounded.truncated, secretsRedacted: 0 };\n }\n }\n };\n\n const describeText = (input: DescribeContentInput): ContentFact => {\n const disclosed = disclose(input.text);\n return {\n kind: input.kind,\n ...(input.role === undefined ? {} : { role: input.role }),\n characterLength: codePointLength(input.text),\n byteLength: Buffer.byteLength(input.text, \"utf8\"),\n contentHash: hash(input.text),\n disclosure: CONTENT_MODE_DISCLOSURE[policy.contentMode],\n ...(disclosed.text === undefined ? {} : { text: disclosed.text }),\n truncated: disclosed.truncated,\n secretsRedacted: disclosed.secretsRedacted,\n ...(input.label === undefined ? {} : { label: input.label }),\n };\n };\n\n const sanitizeValue = (value: unknown, depth: number, stats: MutableStats, seen: WeakSet<object>): SanitizedValue => {\n if (value === null) {\n return null;\n }\n switch (typeof value) {\n case \"string\": {\n const bounded = boundString(value);\n if (bounded.truncated) {\n stats.truncatedStrings += 1;\n }\n return bounded.text;\n }\n case \"number\":\n if (!Number.isFinite(value)) {\n stats.droppedValues += 1;\n return null;\n }\n return value;\n case \"boolean\":\n return value;\n case \"bigint\":\n return value.toString();\n case \"undefined\":\n case \"function\":\n case \"symbol\":\n stats.droppedValues += 1;\n return null;\n default:\n break;\n }\n\n if (depth >= limits.maxDepth) {\n stats.depthExceeded += 1;\n return \"<depth-exceeded>\";\n }\n if (seen.has(value)) {\n stats.circularReferences += 1;\n return \"<circular>\";\n }\n seen.add(value);\n\n if (Array.isArray(value)) {\n const entries = value.slice(0, limits.maxArrayLength);\n if (value.length > limits.maxArrayLength) {\n stats.truncatedArrays += 1;\n }\n return entries.map((entry) => sanitizeValue(entry, depth + 1, stats, seen));\n }\n\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const retained = keys.slice(0, limits.maxObjectKeys);\n if (keys.length > limits.maxObjectKeys) {\n stats.truncatedObjects += 1;\n }\n const result: Record<string, SanitizedValue> = {};\n for (const key of retained) {\n if (isSecretKey(key)) {\n stats.redactedKeys += 1;\n result[key] = policy.redactionPlaceholder;\n continue;\n }\n result[key] = sanitizeValue(record[key], depth + 1, stats, seen);\n }\n return result;\n };\n\n const sanitizeStructured = (value: unknown): SanitizeResult => {\n const stats = emptyStats();\n const sanitized = sanitizeValue(value, 0, stats, new WeakSet<object>());\n return { value: sanitized, stats };\n };\n\n const toAttributePrimitive = (value: SanitizedValue): AttributePrimitive | undefined => {\n if (typeof value === \"string\") {\n return value.slice(0, MAX_ATTRIBUTE_STRING_LENGTH);\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n return undefined;\n };\n\n const flattenToAttributes = (value: SanitizedValue, prefix: string): Attributes => {\n const attributes: Record<string, AttributeValue> = {};\n const walk = (current: SanitizedValue, path: string): void => {\n if (\n typeof current === \"string\" ||\n typeof current === \"number\" ||\n typeof current === \"boolean\"\n ) {\n const primitive = toAttributePrimitive(current);\n if (primitive !== undefined) {\n attributes[path] = primitive;\n }\n return;\n }\n if (current === null) {\n return;\n }\n if (isSanitizedArray(current)) {\n const primitives: AttributePrimitive[] = [];\n let uniform = true;\n for (const entry of current) {\n const entryPrimitive = toAttributePrimitive(entry);\n if (entryPrimitive === undefined) {\n uniform = false;\n break;\n }\n primitives.push(entryPrimitive);\n }\n if (uniform) {\n attributes[path] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);\n return;\n }\n for (const [index, entry] of current.entries()) {\n walk(entry, `${path}.${index}`);\n }\n return;\n }\n for (const [key, entry] of Object.entries(current)) {\n walk(entry, path === \"\" ? key : `${path}.${key}`);\n }\n };\n walk(value, prefix);\n return attributes;\n };\n\n const sanitizeAttributes = (value: Readonly<Record<string, unknown>>): Attributes => {\n const attributes: Record<string, AttributeValue> = {};\n for (const [key, entry] of Object.entries(value)) {\n if (isSecretKey(key)) {\n attributes[key] = policy.redactionPlaceholder;\n continue;\n }\n const sanitized = sanitizeStructured(entry).value;\n const primitive = toAttributePrimitive(sanitized);\n if (primitive !== undefined) {\n attributes[key] = primitive;\n continue;\n }\n const flattened = flattenToAttributes(sanitized, key);\n Object.assign(attributes, flattened);\n }\n return attributes;\n };\n\n const sanitizeExtensions = (\n value: Readonly<Record<string, unknown>>,\n ): SanitizeExtensionsResult => {\n const extensions: Record<string, AttributeValue> = {};\n const droppedKeys: string[] = [];\n for (const [key, entry] of Object.entries(value)) {\n if (!isValidExtensionKey(key)) {\n droppedKeys.push(key);\n continue;\n }\n if (isSecretKey(key)) {\n extensions[key] = policy.redactionPlaceholder;\n continue;\n }\n const sanitized = sanitizeStructured(entry).value;\n const candidate = attributeValueSchema.safeParse(sanitized);\n if (candidate.success) {\n extensions[key] = candidate.data;\n } else {\n droppedKeys.push(key);\n }\n }\n return { extensions, droppedKeys };\n };\n\n return {\n policy,\n policyNotes: notes,\n hash,\n deriveOpaqueId: (namespace: string, value: string): string =>\n hash(`${namespace}\\0${value}`),\n describeContent: describeText,\n describeUnavailableContent: (input: Omit<DescribeContentInput, \"text\">): ContentFact => ({\n kind: input.kind,\n ...(input.role === undefined ? {} : { role: input.role }),\n characterLength: 0,\n byteLength: 0,\n contentHash: hash(\"\"),\n disclosure: \"omitted\",\n truncated: false,\n secretsRedacted: 0,\n ...(input.label === undefined ? {} : { label: input.label }),\n }),\n describeStructured: (input: DescribeStructuredInput): ContentFact => {\n const serialized = stableStringify(input.value);\n const sanitized = sanitizeStructured(input.value);\n const base = describeText({\n kind: input.kind,\n text: serialized,\n ...(input.role === undefined ? {} : { role: input.role }),\n ...(input.label === undefined ? {} : { label: input.label }),\n });\n if (base.text === undefined) {\n return base;\n }\n // Disclose the sanitized projection rather than the raw serialization, so\n // secret-keyed values never appear even in `raw` mode.\n const disclosed = disclose(stableStringify(sanitized.value));\n return {\n ...base,\n ...(disclosed.text === undefined ? {} : { text: disclosed.text }),\n truncated: base.truncated || disclosed.truncated,\n secretsRedacted: disclosed.secretsRedacted + sanitized.stats.redactedKeys,\n };\n },\n isSecretKey,\n sanitizeStructured,\n flattenToAttributes,\n sanitizeAttributes,\n sanitizeExtensions,\n boundString,\n };\n};\n","import { z } from \"zod\";\n\nimport 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 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 * 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","/**\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","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"],"mappings":";AAAA,SAAS,KAAAA,WAAS;;;ACAlB,SAAS,KAAAC,UAAS;;;ACAlB,SAAS,SAAS;AAMX,IAAM,0BAA0B,EAAE,KAAK;AAAA;AAAA,EAE5C;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA,EACA;AAAA;AAAA,EAEA;AACF,CAAC;AAGM,IAAM,sBAAsB,EAAE,KAAK,CAAC,WAAW,OAAO,CAAC;AAIvD,IAAM,mBAAmB,EAAE,KAAK;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAWM,IAAM,uBAAuB,EAAE,KAAK,CAAC,aAAa,yBAAyB,CAAC;AAY5E,IAAM,iBACX,OAAO,OAAO;AAAA,EACZ,iBAAiB;AAAA,IACf,MAAM;AAAA,IACN,UAAU;AAAA,IACV,SAAS;AAAA,IACT,WAAW;AAAA,IACX,SAAS;AAAA,EACX;AAAA,EACA,4BAA4B;AAAA,IAC1B,MAAM;AAAA,IACN,UAAU;AAAA,IACV,SAAS;AAAA,IACT,WAAW;AAAA,IACX,SAAS;AAAA,EACX;AAAA,EACA,oBAAoB;AAAA,IAClB,MAAM;AAAA,IACN,UAAU;AAAA,IACV,SAAS;AAAA,IACT,WAAW;AAAA,IACX,SAAS;AAAA,EACX;AAAA,EACA,gCAAgC;AAAA,IAC9B,MAAM;A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AA,MACd;AACA,aAAO;AAAA,IACT,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO,EAAE,OAAO;AAClB;","names":["z","z","z","z","z","z","z","z","z","z","z","parsed","z","z","z","z","z","z","z","event","z","z","z","z","z","z","z","z","z","z","z","createHash","createHash","path","z","z","event","resolve","path","z","z","event","resolve","z","event","batch","open","path","readBounded"]}