@osfactory/otel-hook 0.10.0 → 0.11.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 (43) hide show
  1. package/README.md +82 -3
  2. package/dist/{adapter-B9RwW6TO.d.ts → adapter-DiLknaTF.d.ts} +1 -1
  3. package/dist/cli.js +1131 -77
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +11 -4
  6. package/dist/config.js +100 -18
  7. package/dist/config.js.map +1 -1
  8. package/dist/{destinations-DWOkVxV1.d.ts → destinations-BIl3gGzx.d.ts} +12 -2
  9. package/dist/diagnostics.d.ts +1 -1
  10. package/dist/diagnostics.js.map +1 -1
  11. package/dist/{export-destinations-lORbe25J.d.ts → export-destinations-QWKGGEjk.d.ts} +130 -5
  12. package/dist/{filesystem-store-DX3dGIgu.d.ts → filesystem-store-D3SCNmbX.d.ts} +1 -1
  13. package/dist/{hook-BAxXoKsp.d.ts → hook-BOecWGSz.d.ts} +4 -4
  14. package/dist/index.d.ts +14 -14
  15. package/dist/index.js +1114 -90
  16. package/dist/index.js.map +1 -1
  17. package/dist/install.d.ts +3 -3
  18. package/dist/integration.d.ts +29 -11
  19. package/dist/integration.js +1117 -154
  20. package/dist/integration.js.map +1 -1
  21. package/dist/lifecycle.d.ts +54 -3
  22. package/dist/lifecycle.js +270 -4
  23. package/dist/lifecycle.js.map +1 -1
  24. package/dist/{memory-aJilVG4R.d.ts → memory-Cs51jyRk.d.ts} +1 -1
  25. package/dist/{semconv-Dw7gcQcg.d.ts → metric-model-DDnWxL9d.d.ts} +154 -2
  26. package/dist/{payload-D7gc0-WQ.d.ts → payload-ChtrEX6A.d.ts} +1 -1
  27. package/dist/{ports-plO5MKrY.d.ts → ports-CeqLq31i.d.ts} +24 -0
  28. package/dist/providers.d.ts +8 -8
  29. package/dist/{registry-C7XO4DzD.d.ts → registry-CcJNF3WY.d.ts} +2 -2
  30. package/dist/runtime.d.ts +7 -7
  31. package/dist/runtime.js +55 -9
  32. package/dist/runtime.js.map +1 -1
  33. package/dist/{schema-CHb3GU1r.d.ts → schema-DMnoU1V_.d.ts} +64 -1
  34. package/dist/state.d.ts +3 -3
  35. package/dist/state.js +23 -0
  36. package/dist/state.js.map +1 -1
  37. package/dist/telemetry.d.ts +5 -5
  38. package/dist/telemetry.js +860 -17
  39. package/dist/telemetry.js.map +1 -1
  40. package/dist/testing.d.ts +8 -8
  41. package/dist/testing.js +55 -9
  42. package/dist/testing.js.map +1 -1
  43. package/package.json +3 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lifecycle/dedup.ts","../src/state/store.ts","../src/lifecycle/keys.ts","../src/model/primitives.ts","../src/telemetry/semconv.ts","../src/version.ts","../src/telemetry/export-identity.ts","../src/model/events.ts","../src/errors/taxonomy.ts","../src/model/content.ts","../src/model/extensions.ts","../src/model/identity.ts","../src/model/target.ts","../src/model/usage.ts","../src/model/version.ts","../src/lifecycle/span-correlator.ts","../src/lifecycle/usage-accumulator.ts","../src/lifecycle/janitor.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\n\nimport type { Attributes } from \"../model/primitives.js\";\nimport type { Clock, StateRecord, StateStore } from \"../runtime/ports.js\";\nimport { withOptionalSessionLock } from \"../state/store.js\";\nimport { dedupKey, dedupScanPrefix, dedupScopeOf } from \"./keys.js\";\n\nexport type DedupCheckResult = {\n /** True when `callbackId` was already marked seen for this scope. */\n readonly duplicate: boolean;\n};\n\nexport type DedupCleanupResult = {\n readonly removed: number;\n readonly scanned: number;\n /**\n * Aged-out records the sweep deliberately kept because they are uncommitted\n * claims younger than the stale-claim window — a live process may still be\n * working on them.\n *\n * Reported rather than merely not-removed, because the two are indistinguishable\n * in `removed` and only one of them means \"retention is configured shorter than\n * this installation's own export budget\". Absent when nothing was retained.\n */\n readonly retainedInFlight?: number;\n};\n\n/**\n * What happened when a delivery tried to take ownership of a callback id.\n *\n * - `fresh`: nothing had this id. The caller owns it and must `commit`.\n * - `duplicate`: a previous delivery ran this callback to completion.\n * - `in-flight`: another delivery holds the id right now — a concurrent process,\n * or one that has not committed yet. Treated as a duplicate.\n * - `reclaimed`: a claim was abandoned long enough ago to be assumed dead, and\n * this delivery has taken it over. The caller owns it and must `commit`.\n */\nexport type DeliveryClaimOutcome = \"fresh\" | \"duplicate\" | \"in-flight\" | \"reclaimed\";\n\nexport type DeliveryClaimResult = {\n readonly outcome: DeliveryClaimOutcome;\n /** True for `duplicate` and `in-flight`: the caller must not export or account. */\n readonly duplicate: boolean;\n /** True for `fresh` and `reclaimed`: the caller owns the id and should commit. */\n readonly owned: boolean;\n /** How many deliveries have claimed this id, including this one. */\n readonly attempt: number;\n /** Age of the claim that was taken over. Present only for `reclaimed`. */\n readonly abandonedForMillis?: number;\n /**\n * Opaque proof that *this* delivery owns the claim. Present when `owned`.\n *\n * No floor computation can be proven exact, so the stale window may still be too\n * short for some real installation. Passing this back to {@link\n * CallbackDeduplicator.commit} turns that from a silent double-count into a\n * detected, reported condition: if a peer reclaimed the id in the meantime the\n * record carries a different token, and the commit refuses rather than\n * overwriting the peer's in-flight work.\n */\n readonly owner?: string;\n};\n\n/** Whether a commit actually took effect. */\nexport type DeliveryCommitResult = {\n readonly status: \"committed\" | \"superseded\";\n /** The attempt number recorded, for diagnostics. */\n readonly attempt: number;\n};\n\nexport type DeliveryClaimOptions = {\n /**\n * How long an uncommitted claim is respected before it is assumed to belong to\n * a process that died mid-flight. Default 60,000ms.\n */\n readonly staleClaimMillis?: number;\n};\n\n/**\n * Delivery guard: suppresses a redelivered callback while local state is intact.\n *\n * Deliberately not described as \"exactly-once\". This records intent and completion\n * in a local store; the collector it protects is a separate system with no shared\n * transaction, so a process killed between an accepted export and `commit` leaves a\n * callback that will be exported again. What this guarantees is that a redelivery\n * seen by a *live* store is suppressed, and that a crash is recoverable rather than\n * either silently lost or permanently blocked.\n *\n * Coding-agent hosts redeliver callbacks — a retried hook invocation, a\n * duplicated event, a replayed transcript — and a deterministic identity makes\n * the replay recomputable, but something still has to remember which identities\n * have already been handled. This is that memory: a bounded, TTL-swept set of\n * seen ids per scope, independent of what the id actually names.\n *\n * Ownership is two-phase on purpose. `claim` records an intent before the caller\n * exports anything and `commit` records completion afterwards, so the window\n * where a crash could produce a double export does not exist: a second delivery\n * arriving in that window sees `in-flight` and stands down. The cost of that\n * choice is that a process killed between the two leaves an uncommitted claim,\n * which is why an old one is reclaimable rather than permanent — permanent would\n * turn every crash into silently lost telemetry.\n */\nexport interface CallbackDeduplicator {\n /**\n * Single-phase check: marks the id complete immediately and reports whether it\n * had been seen. Retained for callers that have nothing to protect between the\n * check and the side effect; `claim`/`commit` is the stronger guarantee.\n */\n checkAndMark(scope: string, callbackId: string): Promise<DedupCheckResult>;\n /** Take ownership of a callback id before acting on it. */\n claim(\n scope: string,\n callbackId: string,\n options?: DeliveryClaimOptions,\n ): Promise<DeliveryClaimResult>;\n /**\n * Record that a claimed callback ran to completion.\n *\n * `owner` is the token {@link DeliveryClaimResult.owner} handed out. Supplied and\n * matching, the claim completes. Supplied and *not* matching, the claim has been\n * reclaimed by a peer while this delivery was still working, and the commit is\n * refused — reported as `\"superseded\"` so the caller can say so instead of\n * silently marking a callback handled that somebody else is mid-flight on.\n */\n commit(scope: string, callbackId: string, owner?: string): Promise<DeliveryCommitResult>;\n /**\n * Give up a claim without completing it, so the next delivery of the same\n * callback is treated as fresh instead of waiting out the stale window.\n */\n release(scope: string, callbackId: string): Promise<void>;\n /**\n * Drop dedup records older than `maxAgeMillis`.\n *\n * An uncommitted claim is held back until it is also older than\n * `staleClaimMillis`, whatever the retention says. Retention is an operator's\n * answer to \"how long should a handled callback stay recognizable\"; the stale\n * window is a statement about how long one process's own work can take. Deleting\n * a claim inside that window would hand the callback to a concurrent delivery as\n * *fresh* while the holder is still exporting it — a retention setting silently\n * converting suppression into a double export, which is the opposite of what\n * tightening retention looks like it does.\n */\n cleanup(\n maxAgeMillis: number,\n options?: {\n readonly maxEntries?: number;\n readonly sessionId?: string;\n /** Floor on how long an uncommitted claim survives. Default 60,000ms. */\n readonly staleClaimMillis?: number;\n },\n ): Promise<DedupCleanupResult>;\n}\n\nexport type CallbackDeduplicatorDependencies = {\n readonly stateStore: StateStore;\n readonly clock: Clock;\n};\n\nconst DEFAULT_STALE_CLAIM_MILLIS = 60_000;\n\ntype DedupState = \"claimed\" | \"completed\";\n\n/**\n * Read the recorded state of a dedup record.\n *\n * A record written by an older release carries only `seenAt`, which meant\n * \"handled\". Absent a `state` field it is therefore read as `completed`, so an\n * upgrade never resurrects a callback the previous version had already exported.\n */\nconst stateOf = (record: StateRecord | undefined): DedupState | undefined => {\n if (record?.value.kind !== \"attributes\") {\n return undefined;\n }\n const declared = record.value.attributes.state;\n if (declared === \"claimed\" || declared === \"completed\") {\n return declared;\n }\n return \"completed\";\n};\n\nconst attemptOf = (record: StateRecord | undefined): number => {\n if (record?.value.kind !== \"attributes\") {\n return 0;\n }\n const attempt = record.value.attributes.attempt;\n return typeof attempt === \"number\" && Number.isInteger(attempt) && attempt > 0 ? attempt : 1;\n};\n\nconst ownerOf = (record: StateRecord | undefined): string | undefined => {\n if (record?.value.kind !== \"attributes\") {\n return undefined;\n }\n const owner = record.value.attributes.owner;\n return typeof owner === \"string\" && owner.length > 0 ? owner : undefined;\n};\n\nconst newOwnerToken = (): string => randomBytes(12).toString(\"hex\");\n\nconst claimedAtOf = (record: StateRecord | undefined): number | undefined => {\n if (record?.value.kind !== \"attributes\") {\n return undefined;\n }\n const claimedAt = record.value.attributes.claimedAt;\n return typeof claimedAt === \"number\" ? claimedAt : record.updatedAt;\n};\n\nexport const createCallbackDeduplicator = (\n deps: CallbackDeduplicatorDependencies,\n): CallbackDeduplicator => {\n const { stateStore, clock } = deps;\n\n const write = (key: string, attributes: Attributes): Promise<unknown> =>\n stateStore.write(key, { kind: \"attributes\", attributes });\n\n const checkAndMark = (scope: string, callbackId: string): Promise<DedupCheckResult> =>\n withOptionalSessionLock(stateStore, scope, async (): Promise<DedupCheckResult> => {\n const key = dedupKey(scope, callbackId);\n const existing = await stateStore.read(key);\n if (existing?.value.kind === \"attributes\") {\n return { duplicate: true };\n }\n const now = clock.now();\n await write(key, {\n state: \"completed\",\n attempt: 1,\n claimedAt: now,\n seenAt: now,\n owner: newOwnerToken(),\n });\n return { duplicate: false };\n });\n\n const claim = (\n scope: string,\n callbackId: string,\n options?: DeliveryClaimOptions,\n ): Promise<DeliveryClaimResult> =>\n withOptionalSessionLock(stateStore, scope, async (): Promise<DeliveryClaimResult> => {\n const staleClaimMillis = options?.staleClaimMillis ?? DEFAULT_STALE_CLAIM_MILLIS;\n const key = dedupKey(scope, callbackId);\n const existing = await stateStore.read(key);\n const state = stateOf(existing);\n const now = clock.now();\n\n if (state === \"completed\") {\n return { outcome: \"duplicate\", duplicate: true, owned: false, attempt: attemptOf(existing) };\n }\n\n if (state === \"claimed\") {\n const claimedAt = claimedAtOf(existing) ?? now;\n const age = now - claimedAt;\n if (age <= staleClaimMillis) {\n return {\n outcome: \"in-flight\",\n duplicate: true,\n owned: false,\n attempt: attemptOf(existing),\n };\n }\n const attempt = attemptOf(existing) + 1;\n const owner = newOwnerToken();\n await write(key, { state: \"claimed\", attempt, claimedAt: now, owner });\n return {\n outcome: \"reclaimed\",\n duplicate: false,\n owned: true,\n attempt,\n abandonedForMillis: age,\n owner,\n };\n }\n\n const owner = newOwnerToken();\n await write(key, { state: \"claimed\", attempt: 1, claimedAt: now, owner });\n return { outcome: \"fresh\", duplicate: false, owned: true, attempt: 1, owner };\n });\n\n const commit = (\n scope: string,\n callbackId: string,\n owner?: string,\n ): Promise<DeliveryCommitResult> =>\n withOptionalSessionLock(stateStore, scope, async (): Promise<DeliveryCommitResult> => {\n const key = dedupKey(scope, callbackId);\n const existing = await stateStore.read(key);\n const now = clock.now();\n const attempt = Math.max(attemptOf(existing), 1);\n\n const recordedOwner = ownerOf(existing);\n if (owner !== undefined && recordedOwner !== undefined && recordedOwner !== owner) {\n // A peer reclaimed this id while we were still working, which means the\n // stale window was shorter than this installation's real worst case.\n // Completing it now would tell that peer's delivery to stand down after it\n // has already exported. Refusing is the honest answer, and being able to\n // say so is the point of the token: no floor computation can be proven\n // exact, so the failure has to be detectable rather than merely unlikely.\n return { status: \"superseded\", attempt };\n }\n\n await write(key, {\n state: \"completed\",\n attempt,\n claimedAt: claimedAtOf(existing) ?? now,\n completedAt: now,\n seenAt: now,\n ...(recordedOwner === undefined ? {} : { owner: recordedOwner }),\n });\n return { status: \"committed\", attempt };\n });\n\n const release = (scope: string, callbackId: string): Promise<void> =>\n withOptionalSessionLock(stateStore, scope, async (): Promise<void> => {\n const key = dedupKey(scope, callbackId);\n // Only an uncommitted claim is droppable: releasing a completed record\n // would re-open a callback whose telemetry has already been exported.\n if (stateOf(await stateStore.read(key)) === \"claimed\") {\n await stateStore.delete(key);\n }\n });\n\n const cleanup = async (\n maxAgeMillis: number,\n options?: {\n readonly maxEntries?: number;\n readonly sessionId?: string;\n readonly staleClaimMillis?: number;\n },\n ): Promise<DedupCleanupResult> => {\n const keys = await stateStore.keys(dedupScanPrefix(options?.sessionId));\n const cap = options?.maxEntries ?? 1_000;\n const staleClaimMillis = options?.staleClaimMillis ?? DEFAULT_STALE_CLAIM_MILLIS;\n const now = clock.now();\n let removed = 0;\n let scanned = 0;\n let retainedInFlight = 0;\n\n /** Whether this record may be dropped, counting a live claim as it goes. */\n const isDroppable = (record: StateRecord | undefined, count: boolean): boolean => {\n if (record === undefined || now - record.updatedAt <= maxAgeMillis) {\n return false;\n }\n if (stateOf(record) === \"claimed\") {\n const age = now - (claimedAtOf(record) ?? record.updatedAt);\n if (age <= staleClaimMillis) {\n if (count) {\n retainedInFlight += 1;\n }\n return false;\n }\n }\n return true;\n };\n\n for (const key of keys) {\n if (scanned >= cap) {\n break;\n }\n scanned += 1;\n\n // Unlocked first pass. It decides only whether this key is worth locking for,\n // which is what keeps a sweep of a mostly-live store from paying a lock\n // acquisition per record: the common answer is \"not aged out, leave it\".\n if (!isDroppable(await stateStore.read(key), true)) {\n continue;\n }\n\n const scope = dedupScopeOf(key);\n if (scope === undefined) {\n // A key from a previous layout version: unreachable by any current read, so\n // there is no claim to race and no scope to lock on.\n await stateStore.delete(key);\n removed += 1;\n continue;\n }\n\n // Locked second pass, because a peer's `claim` takes this same lock and may\n // have refreshed the record since the first read. Deciding once, outside the\n // lock, would let a sweep delete a claim written microseconds earlier — and the\n // concurrent redelivery would then read `fresh` and export a second time.\n await withOptionalSessionLock(stateStore, scope, async (): Promise<void> => {\n if (!isDroppable(await stateStore.read(key), false)) {\n return;\n }\n await stateStore.delete(key);\n removed += 1;\n });\n }\n\n return {\n removed,\n scanned,\n ...(retainedInFlight === 0 ? {} : { retainedInFlight }),\n };\n };\n\n return { checkAndMark, claim, commit, release, cleanup };\n};\n","import type { Clock, StateStore } from \"../runtime/ports.js\";\nimport { LockWaitTimeoutError } from \"./async-lock.js\";\n\n/**\n * A lock could not be acquired within its wait bound because somebody else holds\n * it.\n *\n * Distinct from \"the store is broken\" on purpose, and the distinction is\n * load-bearing for callers that guard a read-modify-write with it. Contention\n * means a peer is plausibly *inside* the critical section right now, so\n * proceeding unlocked would produce exactly the lost update the lock exists to\n * prevent. A store that cannot lock at all — an unwritable directory, a full\n * disk — protects nothing, because the state the lock guards is equally\n * unreachable; there proceeding is the fail-open answer and costs nothing.\n */\nexport class StateLockTimeoutError extends Error {\n public readonly lockKey: string;\n\n public constructor(key: string, timeoutMillis: number) {\n super(`state store lock wait for \"${key}\" exceeded ${String(timeoutMillis)}ms`);\n this.name = \"StateLockTimeoutError\";\n this.lockKey = key;\n }\n}\n\n/**\n * Whether a thrown value means \"somebody else holds the lock\".\n *\n * Also true for {@link LockWaitTimeoutError}, the in-process variant, which\n * carries a second warning for callers: a timed-out wait does not cancel the\n * queued critical section, so it may still run afterwards. A caller that treats\n * contention as \"retry unlocked\" would therefore risk running the section twice.\n */\nexport const isStateLockContention = (thrown: unknown): boolean =>\n thrown instanceof StateLockTimeoutError || thrown instanceof LockWaitTimeoutError;\n\n/**\n * Optional capability beyond the frozen {@link StateStore} contract: a\n * session-scoped lock a caller can use to make a multi-step read-modify-write\n * atomic across an entire session, not just a single key.\n *\n * Deliberately keyed by an explicit `sessionId` the caller already knows,\n * rather than derived by parsing the store's own keys, so a store never has\n * to understand any particular key scheme.\n */\nexport interface LockingStateStore extends StateStore {\n withSessionLock<T>(\n sessionId: string,\n fn: () => Promise<T>,\n options?: { readonly timeoutMillis?: number },\n ): Promise<T>;\n}\n\nexport const isLockingStateStore = (store: StateStore): store is LockingStateStore =>\n typeof (store as Partial<LockingStateStore>).withSessionLock === \"function\";\n\n/** Runs `fn` under the store's session lock when it has one; otherwise runs it directly. */\nexport const withOptionalSessionLock = async <T>(\n store: StateStore,\n sessionId: string,\n fn: () => Promise<T>,\n options?: { readonly timeoutMillis?: number },\n): Promise<T> => {\n if (isLockingStateStore(store)) {\n return store.withSessionLock(sessionId, fn, options);\n }\n return fn();\n};\n\nexport type StateStoreDependencies = {\n readonly clock: Clock;\n};\n","/**\n * State key namespaces for lifecycle bookkeeping.\n *\n * Prefixed with `lifecycle:` so these keys can never collide with the\n * orchestrator's own `sequence:<sessionId>` and `usage:<sessionId>:...` keys\n * in the same {@link StateStore}, even though both share the store.\n *\n * Two properties are load-bearing here, because the store hashes a *whole\n * logical key* into one record: keys must be unambiguous, and a key space whose\n * layout changes must not be readable under its old meaning.\n */\nexport const LIFECYCLE_PREFIX = \"lifecycle\";\n\n/**\n * Layout version of the span key space.\n *\n * Bumped when the *segments* change, not when a record's contents do — that is\n * {@link SPAN_RECORD_VERSION}'s job. Version 2 inserted the provider segment,\n * so a v1 key must never be reachable: reading one would pair a span across\n * providers, which is exactly the attribution guess this library refuses.\n */\nexport const SPAN_KEY_VERSION = 2;\n\n/**\n * Layout version of the dedup key space.\n *\n * Version 2 re-scoped these keys from a session id to a delivery scope. The two\n * spaces are not interchangeable — a v1 key found under a v2 read would suppress\n * an unrelated callback — so the version segment keeps them disjoint.\n */\nexport const DEDUP_KEY_VERSION = 2;\n\n/**\n * Make a variable segment unambiguous within a `:`-delimited key.\n *\n * Without this, `dedupKey(\"a:b\", \"c\")` and `dedupKey(\"a\", \"b:c\")` produce the\n * identical logical key, and the store hashes both to one record — so one\n * delivery silently suppresses an unrelated one. That is reachable input, not a\n * theoretical one: `--callback-scope` is host-supplied, and a provider's session\n * or tool-call id is not required to avoid a colon.\n *\n * `%` is escaped first so the encoding stays injective, which makes this a true\n * bijection on segments rather than a lossy scrub. A segment containing neither\n * character encodes to itself, so keys already on disk keep their identity and\n * no cumulative baseline is reset by adopting this.\n */\nconst encodeSegment = (segment: string): string =>\n segment.replaceAll(\"%\", \"%25\").replaceAll(\":\", \"%3A\");\n\n/**\n * Session first, then provider: the janitor sweeps a whole session by prefix,\n * so the session segment has to lead. The provider segment below it is what\n * makes cross-provider pairing impossible by construction rather than only by\n * the runtime check in the span correlator.\n */\nexport const spanKey = (\n sessionId: string,\n providerId: string,\n scope: string,\n scopeKey: string,\n): string =>\n `${spanScanPrefix(sessionId)}${encodeSegment(providerId)}:${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;\n\n/**\n * The session-scoped prefix names one layout version; the bare prefix names\n * every one of them. That asymmetry is deliberate: a sweep must be able to\n * reclaim records written by a previous version, which a versioned prefix could\n * never match, while a *read* must never reach across a layout change.\n */\nexport const spanScanPrefix = (sessionId?: string): string =>\n sessionId === undefined\n ? `${LIFECYCLE_PREFIX}:span:`\n : `${LIFECYCLE_PREFIX}:span:v${String(SPAN_KEY_VERSION)}:${encodeSegment(sessionId)}:`;\n\n/**\n * Dedup keys are scoped by a *delivery scope*, not by a session id.\n *\n * A host-supplied delivery id carries its own namespace, and a provider-derived\n * one is scoped by a digest of provider, installation, and session — so neither\n * is a session id, and neither can be found by scanning for one.\n */\nexport const dedupKey = (scope: string, callbackId: string): string =>\n `${dedupScanPrefix(scope)}${encodeSegment(callbackId)}`;\n\nexport const dedupScanPrefix = (scope?: string): string =>\n scope === undefined\n ? `${LIFECYCLE_PREFIX}:dedup:`\n : `${LIFECYCLE_PREFIX}:dedup:v${String(DEDUP_KEY_VERSION)}:${encodeSegment(scope)}:`;\n\nconst decodeSegment = (segment: string): string =>\n segment.replaceAll(\"%3A\", \":\").replaceAll(\"%25\", \"%\");\n\n/**\n * Recover the delivery scope a dedup key belongs to.\n *\n * Needed by the sweep and nothing else. A sweep enumerates keys rather than being\n * handed a scope, but deleting a dedup record is a read-modify-write against the\n * same record a concurrent `claim` is deciding on — so the sweep has to take the\n * same per-scope lock, and to take it, it has to know the scope. Recovering it\n * from the key is safe precisely because {@link encodeSegment} is injective.\n *\n * Returns `undefined` for a key from a previous layout version, which no lock\n * protects because no current read can reach it.\n */\nexport const dedupScopeOf = (key: string): string | undefined => {\n const prefix = `${LIFECYCLE_PREFIX}:dedup:v${String(DEDUP_KEY_VERSION)}:`;\n if (!key.startsWith(prefix)) {\n return undefined;\n }\n // Exactly two segments follow the prefix, and neither can contain a raw `:`,\n // so the first `:` after the prefix is unambiguously the boundary.\n const rest = key.slice(prefix.length);\n const boundary = rest.indexOf(\":\");\n return boundary <= 0 ? undefined : decodeSegment(rest.slice(0, boundary));\n};\n\n/**\n * Usage rollup keys are escaped but deliberately *not* versioned: their layout\n * has not changed, and a version segment would orphan every cumulative token\n * baseline on disk — resetting usage accounting to fix a bug that escaping\n * already fixes.\n */\nexport const rollupUsageKey = (sessionId: string, scope: string, scopeKey: string): string =>\n `${rollupScanPrefix(sessionId)}${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;\n\nexport const rollupEpochKey = (sessionId: string, scope: string, scopeKey: string): string =>\n `${rollupEpochScanPrefix(sessionId)}${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;\n\nexport const rollupScanPrefix = (sessionId?: string): string =>\n sessionId === undefined\n ? `${LIFECYCLE_PREFIX}:usage:`\n : `${LIFECYCLE_PREFIX}:usage:${encodeSegment(sessionId)}:`;\n\nexport const rollupEpochScanPrefix = (sessionId?: string): string =>\n sessionId === undefined\n ? `${LIFECYCLE_PREFIX}:epoch:`\n : `${LIFECYCLE_PREFIX}:epoch:${encodeSegment(sessionId)}:`;\n","import { 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 { createHash } from \"node:crypto\";\n\nimport { SpanKind, SpanStatusCode, TraceFlags, type Attributes, type SpanContext, type SpanStatus } from \"@opentelemetry/api\";\nimport { millisToHrTime } from \"@opentelemetry/core\";\nimport type { InstrumentationScope } from \"@opentelemetry/core\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport type { ReadableSpan } from \"@opentelemetry/sdk-trace\";\nimport {\n ATTR_ERROR_TYPE,\n ATTR_GEN_AI_OPERATION_NAME,\n ATTR_GEN_AI_REQUEST_MODEL,\n ATTR_GEN_AI_RESPONSE_MODEL,\n ATTR_GEN_AI_SYSTEM,\n ATTR_GEN_AI_TOOL_CALL_ID,\n ATTR_GEN_AI_TOOL_NAME,\n ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n} from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport type { CanonicalEvent, CanonicalEventType } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\nimport { VERSION } from \"../version.js\";\nimport {\n ATTR_OTELHOOK_TARGET_REPOSITORY_ID,\n ATTR_OTELHOOK_TARGET_SOURCE,\n ATTR_OTELHOOK_TARGET_WORKSPACE_ID,\n ATTR_OTELHOOK_TARGET_WORKTREE_KIND,\n ATTR_VCS_REF_HEAD_NAME,\n exportIdentityAttributes,\n passthroughResourceAttributes,\n targetAttributes,\n usageTemporalityAttributes,\n} from \"./export-identity.js\";\n\nconst SCOPE_NAME = \"@osfactory/otel-hook\";\n\nexport const DEFAULT_INSTRUMENTATION_SCOPE: InstrumentationScope = Object.freeze({\n name: SCOPE_NAME,\n version: VERSION,\n});\n\nconst ATTR_OTELHOOK_SPAN_PAIRED = \"otelhook.span.paired\";\nconst ATTR_OTELHOOK_SPAN_PAIRING = \"otelhook.span.pairing\";\nconst ATTR_OTELHOOK_SPAN_ORPHAN = \"otelhook.span.orphan\";\nconst ATTR_OTELHOOK_OUTCOME = \"otelhook.outcome\";\nconst ATTR_OTELHOOK_RESET_DETECTED = \"otelhook.usage.reset_detected\";\n/** True when a generation's usage covers only part of it; see `generation.end.usagePartial`. */\nexport const ATTR_OTELHOOK_USAGE_PARTIAL = \"otelhook.usage.partial\";\nconst ATTR_OTELHOOK_TOOL_KIND = \"otelhook.tool.kind\";\nconst ATTR_OTELHOOK_DELEGATION_DEPTH = \"otelhook.delegation_depth\";\nconst ATTR_OTELHOOK_COMPACTION_TRIGGER = \"otelhook.compaction.trigger\";\nconst ATTR_OTELHOOK_AGENT_NAME = \"otelhook.agent.name\";\nconst ATTR_OTELHOOK_AGENT_VERSION = \"otelhook.agent.version\";\nconst ATTR_OTELHOOK_GENERATION_ID = \"otelhook.generation.id\";\n\n/**\n * Pure, stateless canonical-event-to-span mapping.\n *\n * Isolated in one module so every other piece of the telemetry pipeline\n * — batching, retry, spooling — can change without touching what an attribute\n * means. Two edges of the same lifecycle scope are merged into one span when\n * they appear in the same batch; when they arrive in *different* short-lived\n * hook processes they are merged through a {@link SpanCorrelation} the caller\n * resolved from persisted state. Either way the mapping itself stays a pure\n * function: state is read by the correlator, never by this module.\n *\n * ## Identity of a span\n *\n * Trace and span ids are derived, never random, so two processes that never\n * meet still agree on them:\n *\n * - `traceId = H(providerId, sessionId)` — one trace per session per provider.\n * Deriving it from the session rather than the invocation is what lets a\n * `tool.end` emitted minutes later land in the same trace as its `tool.start`;\n * including the provider is what stops two providers that happen to reuse a\n * session id from being stitched into one trace.\n * - `spanId = H(providerId, sessionId, family, scopeKey)` — stable across\n * processes and idempotent under redelivery, so a collector that sees a\n * start-only span and later the completed span treats them as one span\n * rather than two.\n */\n// NUL, so joined parts cannot collide across a different split: no identifier\n// this library accepts can contain one, which a printable separator cannot\n// promise. Never emitted — only hashed, or used as an in-memory map key.\nconst FIELD_SEPARATOR = \"\\u0000\";\n\nconst digestHex = (parts: readonly string[], length: number): string =>\n createHash(\"sha256\").update(parts.join(FIELD_SEPARATOR)).digest(\"hex\").slice(0, length);\n\n/** Lifecycle scopes that pair a `*.start` edge with a later `*.end` edge. */\nexport type SpanFamily = \"session\" | \"generation\" | \"tool\" | \"subagent\";\n\n/** Identifies one lifecycle span within a session. */\nexport type SpanScopeRef = {\n readonly family: SpanFamily;\n readonly scopeKey: string;\n};\n\n/**\n * Why a lifecycle span is, or is not, a complete pair.\n *\n * Deliberately explicit rather than a bare boolean: \"we never saw the start\",\n * \"we saw it but it aged out of state\", and \"state could not be read at all\"\n * are different operational facts, and a dashboard that cannot tell them apart\n * cannot tell a broken host from a broken exporter.\n */\nexport type SpanOrphanClassification =\n /** Both edges are known — from this batch, or from persisted state. */\n | \"none\"\n /** The start is known; its end has not arrived yet. */\n | \"missing-end\"\n /** An end arrived and no start was ever recorded for this scope. */\n | \"missing-start\"\n /** A start was recorded but aged past the retention window before the end arrived. */\n | \"expired-start\"\n /** A start exists but was recorded by a different provider; pairing it would be a guess. */\n | \"provider-mismatch\"\n /** A second, distinct end arrived for a scope that was already closed. */\n | \"already-closed\"\n /** The persisted record was written by an incompatible version and was discarded. */\n | \"state-incompatible\"\n /** The persisted record could not be understood. */\n | \"state-corrupt\"\n /** State could not be consulted at all; the mapping degraded rather than failing. */\n | \"state-unavailable\";\n\nexport type SpanPairing =\n /** Both edges were present in this batch. */\n | \"in-batch\"\n /** The other edge came from state written by an earlier process. */\n | \"cross-process\"\n | \"unpaired\";\n\n/**\n * Whether this scope should produce an OTLP record now.\n *\n * OTLP has no notion of updating a span: a span is exported once, when it ends,\n * and a second record carrying the same trace and span id is not a revision of\n * the first — it is a duplicate that backends variously drop, keep the older of,\n * or display twice. Since every lifecycle span id here is *derived* from\n * `(provider, session, family, scopeKey)`, a `*.start` edge and its later `*.end`\n * edge compute the identical id, so exporting on both is precisely that\n * duplicate.\n *\n * `defer` is therefore the answer for a start whose end has not arrived: the\n * start is durable in the state store, and the end edge exports the one complete\n * span using the times recovered from it. Nothing is lost by waiting, and what is\n * gained is that the record a collector receives has a real duration.\n */\nexport type SpanDisposition =\n /** Export a record for this scope now. */\n | \"emit\"\n /** Hold: the start is recorded, and the end edge will export the complete span. */\n | \"defer\";\n\n/**\n * One scope's correlation facts, resolved from persisted state by the caller.\n *\n * Plain data on purpose: the telemetry layer must not reach into the state\n * store itself (ADR 0006), so it declares what it needs and the lifecycle layer\n * supplies it.\n */\nexport type SpanCorrelation = {\n readonly providerId: string;\n readonly sessionId: string;\n readonly ref: SpanScopeRef;\n readonly pairing: SpanPairing;\n readonly orphan: SpanOrphanClassification;\n /**\n * Whether to export a record for this scope now. Defaults to `emit` when a\n * correlation is supplied without one.\n */\n readonly disposition?: SpanDisposition;\n /**\n * Extra component mixed into the derived span id.\n *\n * Set only when this record is a genuinely *additional* observation of a scope\n * that has already been exported once — a second, distinct end for a scope that\n * was already closed. Both records are real, so neither is dropped, and the\n * discriminator keeps them from claiming the same span id.\n */\n readonly spanIdDiscriminator?: string;\n /** Start recovered from state; authoritative over the batch's own start edge. */\n readonly startMillis?: number;\n /** End recovered from state; authoritative so a redelivered end re-exports an identical span. */\n readonly endMillis?: number;\n /** Parent recorded at start time, so an end-only process hangs the span in the same place. */\n readonly parent?: SpanScopeRef;\n /** Attributes only the start edge could supply, recovered for an end-only span. */\n readonly attributes?: Attributes;\n};\n\n/**\n * Resolves persisted correlation for one batch.\n *\n * Must never reject: a state failure is a degraded span, never a lost export.\n */\nexport type SpanCorrelationResolver = (\n events: readonly CanonicalEvent[],\n) => Promise<readonly SpanCorrelation[]>;\n\n/**\n * Upper bound on how many start-edge attributes the correlator may carry\n * forward, so persisted state cannot grow with provider-controlled input.\n */\nexport const MAX_RECOVERED_START_ATTRIBUTES = 16;\n\nconst familyOf = (type: CanonicalEventType): SpanFamily | undefined => {\n switch (type) {\n case \"session.start\":\n case \"session.end\":\n return \"session\";\n case \"generation.start\":\n case \"generation.end\":\n return \"generation\";\n case \"tool.start\":\n case \"tool.end\":\n return \"tool\";\n case \"subagent.start\":\n case \"subagent.end\":\n return \"subagent\";\n default:\n return undefined;\n }\n};\n\n/** The lifecycle span an event is an edge of, or undefined for a point-in-time event. */\nexport const spanScopeRefOf = (event: CanonicalEvent): SpanScopeRef | undefined => {\n const family = familyOf(event.type);\n if (family === undefined) {\n return undefined;\n }\n switch (event.type) {\n case \"session.start\":\n case \"session.end\":\n return { family, scopeKey: event.sessionId };\n case \"generation.start\":\n case \"generation.end\":\n return { family, scopeKey: event.generationId };\n case \"tool.start\":\n case \"tool.end\":\n return { family, scopeKey: event.toolCallId };\n case \"subagent.start\":\n case \"subagent.end\":\n return { family, scopeKey: event.subagentInvocationId };\n default:\n return undefined;\n }\n};\n\n/**\n * Where a span hangs in the trace, judged from this event alone.\n *\n * Everything in a session descends from the session span. A tool call names its\n * generation only on `tool.start`, which is exactly why the correlator persists\n * the parent: the `tool.end` process would otherwise reparent the same span to\n * the session and produce a tree whose shape depends on which edge happened to\n * be exported last.\n */\nexport const parentScopeRefOf = (event: CanonicalEvent): SpanScopeRef | undefined => {\n if (event.type === \"session.start\" || event.type === \"session.end\") {\n return undefined;\n }\n if (event.type === \"tool.start\" && event.generationId !== undefined) {\n return { family: \"generation\", scopeKey: event.generationId };\n }\n return { family: \"session\", scopeKey: event.sessionId };\n};\n\n/**\n * Span attributes that only a `*.start` edge can supply.\n *\n * The correlator persists these verbatim so an end-only span in a later process\n * still carries the tool kind, requested model, delegation depth, or agent name\n * the start process saw. An allowlist, and bounded, so persisted state can\n * never become a second route for provider payload content to escape.\n */\nexport const startOnlySpanAttributes = (event: CanonicalEvent): Attributes => {\n switch (event.type) {\n // The session's own worktree is carried forward like a tool's target, so\n // the session span a later `session.end` process exports still names it.\n case \"session.start\":\n return {\n ...(event.agentName === undefined ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: event.agentName }),\n ...(event.agentVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_AGENT_VERSION]: event.agentVersion }),\n ...targetAttributes(event),\n };\n case \"generation.start\":\n return {\n [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId,\n ...(event.model.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: event.model.vendor }),\n };\n // `toolName` and `toolCallId` are on both tool edges, so they are not\n // start-only and persisting them would just pad every record.\n // The target is carried forward too: an end-only process may see a payload\n // with less to go on (no tool input), and the start's evidence still holds.\n case \"tool.start\":\n return { [ATTR_OTELHOOK_TOOL_KIND]: event.toolKind, ...targetAttributes(event) };\n case \"subagent.start\":\n return { [ATTR_OTELHOOK_DELEGATION_DEPTH]: event.delegationDepth };\n default:\n return {};\n }\n};\n\nconst deriveTraceId = (providerId: string, sessionId: string): string =>\n digestHex([\"otelhook/trace\", providerId, sessionId], 32);\n\nconst deriveSpanId = (providerId: string, sessionId: string, ref: SpanScopeRef): string =>\n digestHex([\"otelhook/span\", providerId, sessionId, ref.family, ref.scopeKey], 16);\n\nconst deriveStandaloneSpanId = (\n providerId: string,\n sessionId: string,\n eventType: string,\n eventId: string,\n): string => digestHex([\"otelhook/span\", providerId, sessionId, \"event\", eventType, eventId], 16);\n\nconst correlationKey = (providerId: string, sessionId: string, ref: SpanScopeRef): string =>\n [providerId, sessionId, ref.family, ref.scopeKey].join(FIELD_SEPARATOR);\n\nconst outcomeStatus = (outcome: string | undefined): SpanStatus => {\n if (outcome === undefined || outcome === \"ok\" || outcome === \"unknown\") {\n return { code: SpanStatusCode.UNSET };\n }\n if (outcome === \"cancelled\") {\n return { code: SpanStatusCode.UNSET };\n }\n return { code: SpanStatusCode.ERROR, message: outcome };\n};\n\nconst identityAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n ids: { readonly traceId: string; readonly spanId: string; readonly parentSpanId?: string },\n): Attributes => exportIdentityAttributes(event, resource, ids);\n\nconst usageAttributes = (usage: CanonicalUsage | undefined, resetDetected: boolean): Attributes => {\n if (usage === undefined) {\n return {};\n }\n return {\n [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: usage.inputTokens,\n [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: usage.outputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: usage.cachedInputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: usage.cacheCreationInputTokens,\n [ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]: usage.reasoningOutputTokens,\n ...usageTemporalityAttributes(usage),\n ...(resetDetected ? { [ATTR_OTELHOOK_RESET_DETECTED]: true } : {}),\n };\n};\n\n/** Evidence strength of a target source; see `targetSourceSchema`. */\nconst TARGET_SOURCE_RANK: Readonly<Record<string, number>> = Object.freeze({\n \"tool-path\": 3,\n \"shell-cwd\": 2,\n \"session-cwd\": 1,\n});\n\nconst TARGET_KEYS = [\n ATTR_OTELHOOK_TARGET_WORKSPACE_ID,\n ATTR_OTELHOOK_TARGET_SOURCE,\n ATTR_VCS_REF_HEAD_NAME,\n ATTR_OTELHOOK_TARGET_REPOSITORY_ID,\n ATTR_OTELHOOK_TARGET_WORKTREE_KIND,\n] as const;\n\nconst pickTarget = (attributes: Attributes): Attributes => {\n const picked: Attributes = {};\n for (const key of TARGET_KEYS) {\n if (attributes[key] !== undefined) {\n picked[key] = attributes[key];\n }\n }\n return picked;\n};\n\n/**\n * Drop the target keys so they can be re-chosen as one unit, keeping only what\n * the launcher put on the Resource (a `vcs.ref.head.name` passed through by\n * `exportIdentityAttributes`) as the fallback beneath the chosen target.\n */\nconst withoutTarget = (attributes: Attributes, resource: Resource): Attributes => {\n const rest: Attributes = { ...attributes };\n for (const key of TARGET_KEYS) {\n delete rest[key];\n }\n return { ...rest, ...pickTarget(passthroughResourceAttributes(resource)) };\n};\n\nconst rankOf = (candidate: Attributes): number => {\n const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];\n return typeof source === \"string\" && Object.hasOwn(TARGET_SOURCE_RANK, source)\n ? (TARGET_SOURCE_RANK[source] ?? 0)\n : 0;\n};\n\n/**\n * One span, one target: the strongest evidence among the recovered start,\n * the live start, and the live end — later wins a tie. A Cursor shell call's\n * start knows its `cwd` and its end does not; the span must keep the former,\n * not be downgraded to the workspace root by whichever edge exported last.\n */\nconst strongestTarget = (candidates: readonly Attributes[]): Attributes => {\n let best: Attributes = {};\n let bestRank = 0;\n for (const candidate of candidates) {\n const rank = rankOf(candidate);\n if (rank > 0 && rank >= bestRank) {\n best = candidate;\n bestRank = rank;\n }\n }\n return best;\n};\n\ntype SpanGroup = {\n readonly ref: SpanScopeRef;\n start?: CanonicalEvent;\n end?: CanonicalEvent;\n};\n\nconst buildSpanContext = (traceId: string, spanId: string): SpanContext => ({\n traceId,\n spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n});\n\nexport type ReadableSpanInput = {\n readonly name: string;\n readonly kind: SpanKind;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly attributes: Attributes;\n readonly status: SpanStatus;\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n};\n\n/** Reconstructs a {@link ReadableSpan} from plain, serializable fields. Used by the durable spool to replay a span it persisted earlier. */\nexport const assembleReadableSpan = (input: ReadableSpanInput): ReadableSpan => toReadableSpan(input);\n\nconst toReadableSpan = (input: ReadableSpanInput): ReadableSpan => {\n const startTime = millisToHrTime(input.startMillis);\n const endTime = millisToHrTime(Math.max(input.startMillis, input.endMillis));\n const duration = millisToHrTime(Math.max(0, input.endMillis - input.startMillis));\n return {\n name: input.name,\n kind: input.kind,\n spanContext: (): SpanContext => buildSpanContext(input.traceId, input.spanId),\n ...(input.parentSpanId === undefined\n ? {}\n : { parentSpanContext: buildSpanContext(input.traceId, input.parentSpanId) }),\n startTime,\n endTime,\n status: input.status,\n attributes: input.attributes,\n links: [],\n events: [],\n duration,\n ended: true,\n resource: input.resource,\n instrumentationScope: input.instrumentationScope,\n droppedAttributesCount: 0,\n droppedEventsCount: 0,\n droppedLinksCount: 0,\n };\n};\n\ntype ResolvedPairing = {\n readonly pairing: SpanPairing;\n readonly orphan: SpanOrphanClassification;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly parent: SpanScopeRef | undefined;\n readonly recovered: Attributes;\n};\n\nconst resolvePairing = (\n group: SpanGroup,\n anchor: CanonicalEvent,\n correlation: SpanCorrelation | undefined,\n): ResolvedPairing => {\n const inBatch = group.start !== undefined && group.end !== undefined;\n const batchStart = group.start?.occurredAt ?? anchor.occurredAt;\n const batchEnd = group.end?.occurredAt ?? anchor.occurredAt;\n\n if (correlation === undefined) {\n return {\n pairing: inBatch ? \"in-batch\" : \"unpaired\",\n orphan: inBatch ? \"none\" : group.start === undefined ? \"missing-start\" : \"missing-end\",\n startMillis: batchStart,\n endMillis: inBatch ? batchEnd : batchStart,\n parent: parentScopeRefOf(anchor),\n recovered: {},\n };\n }\n\n // A correlation that reports no start (an orphaned end) must not fabricate\n // one: the span collapses onto the end instant rather than claiming a\n // duration measured from an event nobody ever saw.\n const startMillis = correlation.startMillis ?? (inBatch ? batchStart : batchEnd);\n const endMillis = correlation.endMillis ?? (group.end === undefined ? startMillis : batchEnd);\n return {\n pairing: correlation.pairing,\n orphan: correlation.orphan,\n startMillis,\n endMillis,\n parent: correlation.parent ?? parentScopeRefOf(anchor),\n recovered: correlation.attributes ?? {},\n };\n};\n\nconst buildLifecycleSpan = (\n plan: GroupPlan,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan => {\n const group = plan.group;\n const anchor = plan.anchor;\n const correlation = plan.correlation;\n const providerId = anchor.provenance.providerId;\n const sessionId = anchor.sessionId;\n const resolved = resolvePairing(group, anchor, correlation);\n const traceId = plan.traceId;\n const spanId = plan.spanId;\n const parentSpanId =\n resolved.parent === undefined ? undefined : deriveSpanId(providerId, sessionId, resolved.parent);\n\n let name: string = group.ref.family;\n let kind: SpanKind = SpanKind.INTERNAL;\n let status: SpanStatus = { code: SpanStatusCode.UNSET };\n // Attributes recovered from the start process sit *beneath* whatever this\n // batch observed: a live edge always wins over a remembered one.\n let attributes: Attributes = {\n ...identityAttributes(anchor, resource, {\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n }),\n ...resolved.recovered,\n [ATTR_OTELHOOK_SPAN_PAIRED]: resolved.pairing !== \"unpaired\",\n [ATTR_OTELHOOK_SPAN_PAIRING]: resolved.pairing,\n [ATTR_OTELHOOK_SPAN_ORPHAN]: resolved.orphan,\n };\n\n switch (group.ref.family) {\n case \"session\": {\n const end = group.end?.type === \"session.end\" ? group.end : undefined;\n const start = group.start?.type === \"session.start\" ? group.start : undefined;\n name = \"session\";\n kind = SpanKind.INTERNAL;\n attributes = {\n ...withoutTarget(attributes, resource),\n ...strongestTarget([pickTarget(resolved.recovered), start === undefined ? {} : targetAttributes(start)]),\n ...(start?.agentName === undefined ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName }),\n ...(start?.agentVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion }),\n ...(end === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.reason }),\n ...usageAttributes(end?.usage, false),\n };\n if (end?.reason === \"error\" || end?.reason === \"timeout\") {\n status = { code: SpanStatusCode.ERROR, message: end.reason };\n }\n break;\n }\n case \"generation\": {\n const start = group.start?.type === \"generation.start\" ? group.start : undefined;\n const end = group.end?.type === \"generation.end\" ? group.end : undefined;\n const model = end?.model ?? start?.model;\n name = model === undefined ? \"generation\" : `generation ${model.modelId}`;\n kind = SpanKind.CLIENT;\n attributes = {\n ...attributes,\n [ATTR_GEN_AI_OPERATION_NAME]: \"chat\",\n ...(model?.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: model.vendor }),\n ...(start?.model?.modelId === undefined ? {} : { [ATTR_GEN_AI_REQUEST_MODEL]: start.model.modelId }),\n ...(end?.model?.modelId === undefined ? {} : { [ATTR_GEN_AI_RESPONSE_MODEL]: end.model.modelId }),\n // The provider's own id for this unit of work (Cursor generation,\n // Codex turn): the key a consumer stores a usage observation under.\n [ATTR_OTELHOOK_GENERATION_ID]: group.ref.scopeKey,\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...usageAttributes(end?.usage, false),\n ...(end?.usage === undefined || end.usagePartial === undefined\n ? {}\n : { [ATTR_OTELHOOK_USAGE_PARTIAL]: end.usagePartial }),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n case \"tool\": {\n const start = group.start?.type === \"tool.start\" ? group.start : undefined;\n const end = group.end?.type === \"tool.end\" ? group.end : undefined;\n const toolName = start?.toolName ?? end?.toolName ?? \"unknown\";\n name = `tool ${toolName}`;\n kind = SpanKind.CLIENT;\n attributes = {\n // Target keys are re-chosen below as one unit, never mixed across edges.\n ...withoutTarget(attributes, resource),\n [ATTR_GEN_AI_TOOL_NAME]: toolName,\n [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,\n ...(start?.toolKind === undefined ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind }),\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...strongestTarget([\n pickTarget(resolved.recovered),\n start === undefined ? {} : targetAttributes(start),\n end === undefined ? {} : targetAttributes(end),\n ]),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n case \"subagent\": {\n const start = group.start?.type === \"subagent.start\" ? group.start : undefined;\n const end = group.end?.type === \"subagent.end\" ? group.end : undefined;\n name = \"subagent\";\n kind = SpanKind.INTERNAL;\n attributes = {\n ...attributes,\n ...(start?.delegationDepth === undefined\n ? {}\n : { [ATTR_OTELHOOK_DELEGATION_DEPTH]: start.delegationDepth }),\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...usageAttributes(end?.usage, false),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n }\n\n if (status.code === SpanStatusCode.ERROR) {\n attributes = { ...attributes, [ATTR_ERROR_TYPE]: status.message ?? \"error\" };\n }\n\n return toReadableSpan({\n name,\n kind,\n startMillis: resolved.startMillis,\n endMillis: resolved.endMillis,\n attributes,\n status,\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n resource,\n instrumentationScope: scope,\n });\n};\n\nconst buildStandaloneSpan = (\n event: CanonicalEvent,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan => {\n const providerId = event.provenance.providerId;\n const traceId = deriveTraceId(providerId, event.sessionId);\n const spanId = deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId);\n const parent = parentScopeRefOf(event);\n const parentSpanId =\n parent === undefined ? undefined : deriveSpanId(providerId, event.sessionId, parent);\n let attributes: Attributes = {\n ...identityAttributes(event, resource, {\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n }),\n [ATTR_OTELHOOK_SPAN_PAIRED]: true,\n };\n let status: SpanStatus = { code: SpanStatusCode.UNSET };\n let name: string = event.type;\n\n switch (event.type) {\n case \"prompt.submitted\":\n name = \"prompt\";\n attributes = { ...attributes, \"otelhook.prompt.source\": event.promptSource, ...targetAttributes(event) };\n break;\n case \"compaction.performed\":\n name = \"compaction\";\n attributes = {\n ...attributes,\n [ATTR_OTELHOOK_COMPACTION_TRIGGER]: event.trigger,\n ...usageAttributes(event.usage, false),\n };\n break;\n case \"error.raised\":\n name = \"error\";\n status = { code: SpanStatusCode.ERROR, message: event.errorCode };\n attributes = {\n ...attributes,\n [ATTR_ERROR_TYPE]: event.errorCode,\n \"otelhook.error.phase\": event.phase,\n \"otelhook.error.retryable\": event.retryable,\n };\n break;\n default:\n break;\n }\n\n return toReadableSpan({\n name,\n kind: SpanKind.INTERNAL,\n startMillis: event.occurredAt,\n endMillis: event.occurredAt,\n attributes,\n status,\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n resource,\n instrumentationScope: scope,\n });\n};\n\nexport type SemanticMappingOptions = {\n readonly resource: Resource;\n readonly instrumentationScope?: InstrumentationScope;\n /**\n * Cross-process pairing facts, at most one entry per lifecycle scope in\n * `events`. Omitted entirely, the mapping degrades to in-batch pairing only —\n * the behavior of a host that wired no state store.\n */\n readonly correlations?: readonly SpanCorrelation[];\n /**\n * Whether a correlator was consulted at all, and whether it answered.\n *\n * This is what separates \"the state store is holding this start, so the end edge\n * will publish it\" from \"nothing recorded this start\". Both look like an empty\n * `correlations` list, and only the first is safe to drop — dropping the second\n * would discard an observation that was neither persisted nor exported, while a\n * caller that saw zero rejections went on to mark the callback handled.\n *\n * - `true` — the correlator ran; an absent or non-`defer` entry means emit.\n * - `false` — the correlator failed; every unpaired start is emitted as an\n * explicitly labelled, uniquely identified fallback.\n * - omitted — no correlator is wired, so cross-process pairing was never on\n * offer and an unpaired start is deferred (the documented no-state-root\n * degradation).\n */\n readonly correlationAvailable?: boolean;\n};\n\n/**\n * Fill in a correlation for an unpaired start that nothing recorded.\n *\n * Reached when a correlator was consulted and either failed outright or reported\n * nothing for this scope. The synthesized entry says what is true — the state was\n * not consulted successfully, so this span is unpaired and no end can complete it\n * — and carries a discriminator so the record cannot claim the span id a later end\n * will publish for the same scope.\n */\nconst effectiveCorrelation = (\n group: SpanGroup,\n correlation: SpanCorrelation | undefined,\n): SpanCorrelation | undefined => {\n if (correlation !== undefined || group.end !== undefined || group.start === undefined) {\n return correlation;\n }\n return {\n providerId: group.start.provenance.providerId,\n sessionId: group.start.sessionId,\n ref: group.ref,\n pairing: \"unpaired\",\n orphan: \"state-unavailable\",\n disposition: \"emit\",\n spanIdDiscriminator: group.start.eventId,\n };\n};\n\n/** How one batch's events distribute over the lifecycle scopes they are edges of. */\ntype BatchLayout = {\n readonly groups: ReadonlyMap<string, SpanGroup>;\n readonly standalone: readonly CanonicalEvent[];\n /** Event id of each lifecycle edge, mapped to the group key it belongs to. */\n readonly groupOf: ReadonlyMap<string, string>;\n};\n\nconst layoutBatch = (events: readonly CanonicalEvent[]): BatchLayout => {\n const groups = new Map<string, SpanGroup>();\n const standalone: CanonicalEvent[] = [];\n const groupOf = new Map<string, string>();\n\n for (const event of events) {\n const ref = spanScopeRefOf(event);\n if (ref === undefined) {\n standalone.push(event);\n continue;\n }\n const groupKey = correlationKey(event.provenance.providerId, event.sessionId, ref);\n const group: SpanGroup = groups.get(groupKey) ?? { ref };\n if (event.type.endsWith(\".start\")) {\n group.start = event;\n } else {\n group.end = event;\n }\n groups.set(groupKey, group);\n groupOf.set(event.eventId, groupKey);\n }\n return { groups, standalone, groupOf };\n};\n\nconst indexCorrelations = (\n correlations: readonly SpanCorrelation[] | undefined,\n): ReadonlyMap<string, SpanCorrelation> => {\n const indexed = new Map<string, SpanCorrelation>();\n for (const correlation of correlations ?? []) {\n indexed.set(\n correlationKey(correlation.providerId, correlation.sessionId, correlation.ref),\n correlation,\n );\n }\n return indexed;\n};\n\n/**\n * What this batch does with one lifecycle scope, decided once.\n *\n * Both the span mapping and the log mapping need the *same* answer to \"which\n * span id identifies this scope, and is a record for it going out now?\" — a log\n * record whose `spanContext` names a span id the exporter never published would\n * dangle at the collector. Computing it in one place is what keeps the two\n * signals pointing at the same span rather than at two plausible derivations of\n * it.\n */\ntype GroupPlan = {\n readonly group: SpanGroup;\n /** The event the span's identity and provenance are read from. */\n readonly anchor: CanonicalEvent;\n /**\n * False when the start is deferred: the state store is holding it and the end\n * edge will publish the one complete span, so nothing is exported for it now.\n */\n readonly emits: boolean;\n readonly correlation: SpanCorrelation | undefined;\n readonly traceId: string;\n readonly spanId: string;\n};\n\nconst planGroup = (\n group: SpanGroup,\n correlation: SpanCorrelation | undefined,\n correlationAvailable: boolean | undefined,\n): GroupPlan | undefined => {\n const anchor = group.start ?? group.end;\n if (anchor === undefined) {\n // Unreachable: a group exists only because an event was filed into it.\n return undefined;\n }\n const providerId = anchor.provenance.providerId;\n const sessionId = anchor.sessionId;\n\n // A start with no end in this batch is dropped **only** when something states\n // that it is durably recorded, because its span id is a pure function of the\n // scope: emitting here and again at the end edge would put two records with one\n // id on the wire, and OTLP has no update operation.\n //\n // `defer` is that statement, and it is the correlator's to make — it just wrote\n // the record. Anything else means nothing is holding this start, so dropping it\n // would lose an observation that was neither persisted nor exported, while the\n // caller saw zero rejections and marked the callback handled. Those are exported\n // under a discriminated span id instead.\n const durablyRecorded =\n group.end === undefined &&\n (correlation?.disposition === \"defer\" ||\n // No correlator wired at all: cross-process pairing was never on offer, so\n // this is the documented no-state-root degradation rather than a failure to\n // persist something that should have been persisted.\n (correlation === undefined && correlationAvailable === undefined));\n\n // A deferred start keeps the scope's *plain* span id, because that is the id the\n // end edge will publish. Only a record actually going out now may claim a\n // discriminated one.\n const effective = durablyRecorded ? correlation : effectiveCorrelation(group, correlation);\n const discriminator = durablyRecorded ? undefined : effective?.spanIdDiscriminator;\n\n return {\n group,\n anchor,\n emits: !durablyRecorded,\n correlation: effective,\n traceId: deriveTraceId(providerId, sessionId),\n spanId:\n discriminator === undefined\n ? deriveSpanId(providerId, sessionId, group.ref)\n : digestHex(\n [\n \"otelhook/span\",\n providerId,\n sessionId,\n group.ref.family,\n group.ref.scopeKey,\n discriminator,\n ],\n 16,\n ),\n };\n};\n\n/** Trace and span a record derived from one canonical event belongs to. */\nexport type EventTraceIdentity = {\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n};\n\n/**\n * Resolve the trace and span identity of every event in one batch.\n *\n * Exposed for signals other than traces — a log record correlates by carrying\n * the *same* derived ids the span mapping would compute, including the deferred\n * and discriminated cases. Whole batch at once because a start's identity\n * depends on whether its end is in the same batch.\n *\n * Both ids come from the event's own `(providerId, sessionId)`, never from a\n * batch-level or module-level value, which is what makes cross-session\n * contamination structurally impossible: two sessions in one batch derive two\n * different trace ids.\n */\nexport const canonicalEventTraceIdentities = (\n events: readonly CanonicalEvent[],\n options: {\n readonly correlations?: readonly SpanCorrelation[];\n readonly correlationAvailable?: boolean;\n } = {},\n): ReadonlyMap<string, EventTraceIdentity> => {\n const layout = layoutBatch(events);\n const correlations = indexCorrelations(options.correlations);\n const plans = new Map<string, GroupPlan>();\n for (const [groupKey, group] of layout.groups) {\n const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);\n if (plan !== undefined) {\n plans.set(groupKey, plan);\n }\n }\n\n const identities = new Map<string, EventTraceIdentity>();\n for (const event of events) {\n const providerId = event.provenance.providerId;\n const groupKey = layout.groupOf.get(event.eventId);\n const plan = groupKey === undefined ? undefined : plans.get(groupKey);\n if (plan === undefined) {\n const parent = parentScopeRefOf(event);\n identities.set(event.eventId, {\n traceId: deriveTraceId(providerId, event.sessionId),\n spanId: deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId),\n ...(parent === undefined\n ? {}\n : { parentSpanId: deriveSpanId(providerId, event.sessionId, parent) }),\n });\n continue;\n }\n const parent = plan.correlation?.parent ?? parentScopeRefOf(event);\n identities.set(event.eventId, {\n traceId: plan.traceId,\n spanId: plan.spanId,\n ...(parent === undefined\n ? {}\n : { parentSpanId: deriveSpanId(providerId, event.sessionId, parent) }),\n });\n }\n return identities;\n};\n\n/** Maps one invocation's canonical event batch into OTLP-ready spans. */\nexport const canonicalEventsToReadableSpans = (\n events: readonly CanonicalEvent[],\n options: SemanticMappingOptions,\n): readonly ReadableSpan[] => {\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const layout = layoutBatch(events);\n const correlations = indexCorrelations(options.correlations);\n\n const spans: ReadableSpan[] = [];\n for (const [groupKey, group] of layout.groups) {\n const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);\n if (plan === undefined || !plan.emits) {\n continue;\n }\n spans.push(buildLifecycleSpan(plan, options.resource, scope));\n }\n for (const event of layout.standalone) {\n spans.push(buildStandaloneSpan(event, options.resource, scope));\n }\n return spans;\n};\n","/**\n * Package version, kept in its own module so the CLI can report it without\n * importing the whole library barrel (and every provider adapter with it).\n *\n * Updated by `scripts/release/sync-version.mjs` during semantic-release.\n */\nexport const VERSION = \"0.10.0\";\n","import type { Attributes } from \"@opentelemetry/api\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport { ATTR_SESSION_ID } from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport { isTargetedEvent, type CanonicalEvent } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\n\n/**\n * W3C hex identity attributes on every log and span.\n *\n * Mission Control (and any consumer that decodes OTLP protobuf with a JSON\n * `toObject` that stringifies bytes as UTF-8) cannot recover a usable id from\n * the protobuf `trace_id` / `span_id` fields. These attributes are already hex\n * in the OpenTelemetry JS API; they are copied onto the attribute map so a\n * consumer never has to stringify binary ids.\n */\nexport const ATTR_TRACE_ID = \"trace_id\";\nexport const ATTR_SPAN_ID = \"span_id\";\nexport const ATTR_PARENT_SPAN_ID = \"parent_span_id\";\n\n/** Provider session id, kept when `session.id` is an externally supplied key. */\nexport const ATTR_OTELHOOK_SESSION_ID = \"otelhook.session.id\";\n/** Same provider session id under the gen_ai conversation attribute. */\nexport const ATTR_GEN_AI_CONVERSATION_ID = \"gen_ai.conversation.id\";\n\nexport const TRACE_ID_HEX_PATTERN = /^[0-9a-f]{32}$/;\nexport const SPAN_ID_HEX_PATTERN = /^[0-9a-f]{16}$/;\n\nconst ATTR_OTELHOOK_INVOCATION_ID = \"otelhook.invocation.id\";\nconst ATTR_OTELHOOK_PROVIDER_ID = \"otelhook.provider.id\";\nconst ATTR_OTELHOOK_PROVIDER_VERSION = \"otelhook.provider.version\";\nconst ATTR_OTELHOOK_WORKSPACE_ID = \"otelhook.workspace.id\";\n\n/**\n * Resource attributes a launcher may set to supply the session key, in\n * preference order: the OpenTelemetry semantic-convention `session.id`, then the\n * legacy `har.session_key` that earlier launchers still send.\n */\nexport const EXTERNAL_SESSION_KEY_ATTRIBUTES: readonly string[] = Object.freeze([\n ATTR_SESSION_ID,\n \"har.session_key\",\n]);\n\n/**\n * The provider's own subagent id (Claude Code `agent_id`), on every record of an\n * event emitted inside a subagent. Same class as `session.id`: a provider-minted\n * opaque identifier, exported verbatim so a consumer can join it to the\n * provider's own per-subagent records.\n */\nexport const ATTR_OTELHOOK_SUBAGENT_ID = \"otelhook.subagent.id\";\n\n/**\n * Worktree an event targeted (ADR 0008): the one a tool call touched, or the one\n * a session runs in on its start and prompts. Branch under the OTel VCS\n * attribute; the worktree root, and its repository's main worktree root, only\n * as salted `git-root` handles.\n */\nexport const ATTR_VCS_REF_HEAD_NAME = \"vcs.ref.head.name\";\nexport const ATTR_OTELHOOK_TARGET_WORKSPACE_ID = \"otelhook.target.workspace.id\";\nexport const ATTR_OTELHOOK_TARGET_SOURCE = \"otelhook.target.source\";\nexport const ATTR_OTELHOOK_TARGET_REPOSITORY_ID = \"otelhook.target.repository.id\";\nexport const ATTR_OTELHOOK_TARGET_WORKTREE_KIND = \"otelhook.target.worktree.kind\";\n\n/** Whether `gen_ai.usage.*` on this record is a delta or a running total. */\nexport const ATTR_OTELHOOK_USAGE_TEMPORALITY = \"otelhook.usage.temporality\";\n\n/** Target attributes for a targeted event; empty when the core resolved none. */\nexport const targetAttributes = (event: CanonicalEvent): Attributes => {\n if (!isTargetedEvent(event) || event.target === undefined) {\n return {};\n }\n const { target } = event;\n return {\n [ATTR_OTELHOOK_TARGET_WORKSPACE_ID]: target.workspaceId,\n [ATTR_OTELHOOK_TARGET_SOURCE]: target.source,\n ...(target.vcsBranchName === undefined ? {} : { [ATTR_VCS_REF_HEAD_NAME]: target.vcsBranchName }),\n ...(target.repositoryId === undefined\n ? {}\n : { [ATTR_OTELHOOK_TARGET_REPOSITORY_ID]: target.repositoryId }),\n ...(target.worktreeKind === undefined\n ? {}\n : { [ATTR_OTELHOOK_TARGET_WORKTREE_KIND]: target.worktreeKind }),\n };\n};\n\n/** Temporality of reported usage, so a consumer never sums running totals. */\nexport const usageTemporalityAttributes = (usage: CanonicalUsage | undefined): Attributes =>\n usage === undefined ? {} : { [ATTR_OTELHOOK_USAGE_TEMPORALITY]: usage.temporality };\n\nconst isPrimitiveAttribute = (value: unknown): value is string | number | boolean =>\n typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\";\n\n/**\n * Resource attribute namespaces a launcher puts on the process that are also\n * copied onto every span and log record.\n *\n * Many backends index only record attributes (filters, search, dashboards), so a\n * value that exists only on the Resource is invisible there. Copied:\n *\n * - `har.*` — attributes earlier launchers send;\n * - `factory.*` — the Factory Commits telemetry profile (work unit, slot, …),\n * **except** `factory.local.*`, which the profile defines as local-only: it\n * stays on the Resource and never reaches a record;\n * - `vcs.*` — OpenTelemetry VCS attributes. An event's own resolved target\n * (ADR 0008) still wins for the keys it sets, such as `vcs.ref.head.name`.\n *\n * `session.id` is not copied: it is resolved separately (see\n * `resolveExportedSessionId`), so a resource value cannot overwrite the\n * trimmed, resolved one.\n */\nexport const PASSTHROUGH_RESOURCE_PREFIXES: readonly string[] = Object.freeze([\"har.\", \"factory.\", \"vcs.\"]);\n/** Local-only profile namespace: never copied from the Resource onto records. */\nexport const LOCAL_ONLY_RESOURCE_PREFIX = \"factory.local.\";\n\nconst isPassthroughKey = (key: string): boolean =>\n PASSTHROUGH_RESOURCE_PREFIXES.some((prefix) => key.startsWith(prefix)) &&\n !key.startsWith(LOCAL_ONLY_RESOURCE_PREFIX) &&\n key !== \"factory.local\";\n\n/**\n * Primitive resource attributes to copy onto every log and span record.\n *\n * Only the namespaces in `PASSTHROUGH_RESOURCE_PREFIXES` are forwarded, minus\n * `factory.local.*`; nothing is invented when they are absent.\n */\nexport const passthroughResourceAttributes = (resource: Resource): Attributes => {\n const attributes: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(resource.attributes)) {\n if (isPassthroughKey(key) && isPrimitiveAttribute(value)) {\n attributes[key] = value;\n }\n }\n return attributes;\n};\n\n/**\n * Session id to put on `session.id`, preferring an externally supplied key.\n *\n * A launcher supplies the key as a resource attribute (usually through\n * `OTEL_RESOURCE_ATTRIBUTES`): `session.id` first, then the legacy\n * `har.session_key`, then the provider's own session id. The provider's id is\n * never discarded: it is returned separately so callers can emit it as\n * `otelhook.session.id` / `gen_ai.conversation.id`.\n */\nexport const resolveExportedSessionId = (\n eventSessionId: string,\n resource: Resource,\n): { readonly sessionId: string; readonly providerSessionId: string } => {\n for (const key of EXTERNAL_SESSION_KEY_ATTRIBUTES) {\n const supplied = resource.attributes[key];\n if (typeof supplied === \"string\") {\n const trimmed = supplied.trim();\n if (trimmed.length > 0) {\n return { sessionId: trimmed, providerSessionId: eventSessionId };\n }\n }\n }\n return { sessionId: eventSessionId, providerSessionId: eventSessionId };\n};\n\nexport type ExportedTraceIds = {\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n};\n\n/**\n * Hex-only trace/span attributes. A value that is not W3C hex is omitted\n * rather than stringified — binary blobs must never appear in id fields.\n */\nexport const hexTraceAttributes = (ids: ExportedTraceIds): Attributes => ({\n ...(TRACE_ID_HEX_PATTERN.test(ids.traceId) ? { [ATTR_TRACE_ID]: ids.traceId } : {}),\n ...(SPAN_ID_HEX_PATTERN.test(ids.spanId) ? { [ATTR_SPAN_ID]: ids.spanId } : {}),\n ...(ids.parentSpanId !== undefined && SPAN_ID_HEX_PATTERN.test(ids.parentSpanId)\n ? { [ATTR_PARENT_SPAN_ID]: ids.parentSpanId }\n : {}),\n});\n\n/**\n * Identity attributes shared by the log and span mappings.\n *\n * `session.id` is the externally supplied session key when the resource carries\n * one (`session.id`, then `har.session_key`), otherwise the provider session id.\n * The provider id is always also emitted under `otelhook.session.id` and\n * `gen_ai.conversation.id`. Profile resource attributes are copied on too (see\n * `passthroughResourceAttributes`).\n */\nexport const exportIdentityAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n ids: ExportedTraceIds,\n): Attributes => {\n const { sessionId, providerSessionId } = resolveExportedSessionId(event.sessionId, resource);\n return {\n [ATTR_SESSION_ID]: sessionId,\n [ATTR_OTELHOOK_SESSION_ID]: providerSessionId,\n [ATTR_GEN_AI_CONVERSATION_ID]: providerSessionId,\n [ATTR_OTELHOOK_INVOCATION_ID]: event.invocationId,\n [ATTR_OTELHOOK_PROVIDER_ID]: event.provenance.providerId,\n ...(event.provenance.providerVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event.provenance.providerVersion }),\n [ATTR_OTELHOOK_WORKSPACE_ID]: event.workspace.workspaceId,\n ...(event.subagentId === undefined ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event.subagentId }),\n ...passthroughResourceAttributes(resource),\n ...hexTraceAttributes(ids),\n };\n};\n","import { z } from \"zod\";\n\nimport {\n errorPhaseSchema,\n errorSeveritySchema,\n otelHookErrorCodeSchema,\n} from \"../errors/taxonomy.js\";\nimport { contentFactSchema, contentFactsSchema } from \"./content.js\";\nimport { extensionsSchema, emptyExtensions } from \"./extensions.js\";\nimport { sourceProvenanceSchema, workspaceIdentitySchema } from \"./identity.js\";\nimport { subagentIdSchema, workspaceTargetSchema } from \"./target.js\";\nimport {\n durationMillisSchema,\n epochMillisSchema,\n eventIdSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n sequenceNumberSchema,\n sessionIdSchema,\n tokenCountSchema,\n} from \"./primitives.js\";\nimport { canonicalUsageSchema, type CanonicalUsage } from \"./usage.js\";\nimport { canonicalSchemaVersionSchema } from \"./version.js\";\n\n/** Model being invoked. Model identifiers are not treated as sensitive. */\nexport const modelDescriptorSchema = z.strictObject({\n modelId: nonEmptyStringSchema,\n /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */\n vendor: nonEmptyStringSchema.optional(),\n family: nonEmptyStringSchema.optional(),\n});\nexport type ModelDescriptor = z.infer<typeof modelDescriptorSchema>;\n\nexport const costFactsSchema = z.strictObject({\n /** ISO 4217 code. */\n currency: z.string().length(3),\n amount: z.number().min(0).finite(),\n source: z.enum([\"provider-reported\", \"computed\"]),\n});\nexport type CostFacts = z.infer<typeof costFactsSchema>;\n\nexport const canonicalEventTypeSchema = z.enum([\n \"session.start\",\n \"session.end\",\n \"prompt.submitted\",\n \"generation.start\",\n \"generation.end\",\n \"tool.start\",\n \"tool.end\",\n \"subagent.start\",\n \"subagent.end\",\n \"compaction.performed\",\n \"error.raised\",\n]);\nexport type CanonicalEventType = z.infer<typeof canonicalEventTypeSchema>;\n\nexport const CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;\n\nconst outcomeSchema = z.enum([\"ok\", \"error\", \"cancelled\", \"timeout\", \"denied\", \"unknown\"]);\nexport type EventOutcome = z.infer<typeof outcomeSchema>;\n\n/**\n * Fields present on every canonical event.\n *\n * Identity fields are duplicated onto each event rather than referenced through\n * shared state, so an event is self-describing once it leaves the process.\n */\nconst baseEventFields = {\n schemaVersion: canonicalSchemaVersionSchema,\n eventId: eventIdSchema,\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Per-invocation ordering key. Stable across replays of the same input. */\n sequence: sequenceNumberSchema,\n occurredAt: epochMillisSchema,\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n /**\n * The provider's own id for the subagent this event was emitted inside (e.g.\n * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event\n * factory, never by hand.\n */\n subagentId: subagentIdSchema.optional(),\n extensions: extensionsSchema.default(emptyExtensions),\n} 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\nimport { attributeValueSchema, type AttributeValue } from \"./primitives.js\";\n\n/**\n * Extension keys must be namespaced: at least one dot-separated segment before\n * the leaf, e.g. `acme.deployment-tier`. Namespacing keeps provider- and\n * consumer-specific fields from colliding with core fields or each other.\n */\nexport const EXTENSION_KEY_PATTERN =\n /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;\n\n/** Namespaces owned by the core model; extensions may not use them. */\nexport const RESERVED_EXTENSION_NAMESPACES: readonly string[] = Object.freeze([\n \"otelhook\",\n \"otel\",\n \"telemetry\",\n]);\n\nexport const MAX_EXTENSION_ENTRIES = 64;\n\nexport const extensionKeyNamespace = (key: string): string => key.slice(0, key.indexOf(\".\"));\n\nexport const isReservedExtensionNamespace = (key: string): boolean =>\n RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));\n\nexport const isValidExtensionKey = (key: string): boolean =>\n EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);\n\n/**\n * Namespaced extension bag.\n *\n * Values are restricted to attribute primitives, so extensions cannot carry\n * nested provider payloads.\n */\nexport const extensionsSchema = z\n .record(z.string(), attributeValueSchema)\n .check((ctx) => {\n const keys = Object.keys(ctx.value);\n if (keys.length > MAX_EXTENSION_ENTRIES) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`,\n });\n }\n for (const key of keys) {\n if (!EXTENSION_KEY_PATTERN.test(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. \"acme.tier\"`,\n });\n continue;\n }\n if (isReservedExtensionNamespace(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`,\n });\n }\n }\n });\n\nexport type Extensions = Record<string, AttributeValue>;\n\nexport const EMPTY_EXTENSIONS: Extensions = Object.freeze({});\n\nexport const emptyExtensions = (): Extensions => ({});\n","import { z } from \"zod\";\n\nimport {\n attributesSchema,\n detectionConfidenceSchema,\n DETECTION_CONFIDENCE_RANK,\n epochMillisSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n resolvedProviderIdSchema,\n sessionIdSchema,\n sourceTransportSchema,\n workspaceIdSchema,\n type DetectionConfidence,\n type InvocationId,\n type SessionId,\n type WorkspaceId,\n} from \"./primitives.js\";\n\n/**\n * Where a workspace identifier came from.\n *\n * Ordered from most to least stable. The source is recorded so consumers can\n * tell a repository-scoped identity from a directory-scoped one instead of\n * assuming they are comparable.\n */\nexport const workspaceKeySourceSchema = z.enum([\n \"git-remote\",\n \"git-root\",\n \"working-directory\",\n \"explicit\",\n \"unknown\",\n]);\nexport type WorkspaceKeySource = z.infer<typeof workspaceKeySourceSchema>;\n\n/**\n * Privacy-safe workspace identity.\n *\n * Only opaque handles and explicitly allowed labels are modelled. There is no\n * field for a filesystem path, so paths cannot be exported through this type.\n */\nexport const workspaceIdentitySchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n keySource: workspaceKeySourceSchema,\n /** Repository name only; never an owner path or URL with credentials. */\n repositoryName: nonEmptyStringSchema.optional(),\n vcsBranchName: nonEmptyStringSchema.optional(),\n /** Opaque handle for the checked-out revision. */\n vcsRevisionId: nonEmptyStringSchema.optional(),\n })\n .readonly();\nexport type WorkspaceIdentity = z.infer<typeof workspaceIdentitySchema>;\n\nexport const UNKNOWN_WORKSPACE_ID = \"unknown:0000000000000000\" as WorkspaceId;\n\nexport const unknownWorkspaceIdentity = (): WorkspaceIdentity =>\n workspaceIdentitySchema.parse({\n workspaceId: UNKNOWN_WORKSPACE_ID,\n keySource: \"unknown\",\n });\n\n/**\n * Provenance of an observation: which provider produced it and which adapter\n * interpreted it, with the confidence of that attribution.\n */\nexport const sourceProvenanceSchema = z\n .strictObject({\n providerId: resolvedProviderIdSchema,\n providerVersion: nonEmptyStringSchema.optional(),\n adapterId: nonEmptyStringSchema,\n adapterVersion: nonEmptyStringSchema,\n detectionConfidence: detectionConfidenceSchema,\n /** The provider's own name for the source event, e.g. a hook event name. */\n sourceEventName: nonEmptyStringSchema.optional(),\n transport: sourceTransportSchema,\n })\n .readonly();\nexport type SourceProvenance = z.infer<typeof sourceProvenanceSchema>;\n\n/**\n * Opaque, immutable metadata supplied by the embedding consumer.\n *\n * The library never interprets these values; it only carries and exports them.\n */\nexport const consumerAttributesSchema = attributesSchema.readonly();\nexport type ConsumerAttributes = z.infer<typeof consumerAttributesSchema>;\n\n/**\n * Immutable identity of a single hook invocation.\n *\n * Frozen on parse. There is deliberately no setter, no builder that mutates in\n * place, and no module-level instance: identity is passed explicitly so two\n * concurrent invocations can never observe each other's fields.\n */\nexport const invocationIdentitySchema = z\n .strictObject({\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Set when this invocation runs beneath another agent invocation. */\n parentInvocationId: invocationIdSchema.optional(),\n /** Root of the session tree when the provider exposes one. */\n rootSessionId: sessionIdSchema.optional(),\n /** Stable handle for the agent process/instance, when available. */\n agentInstanceId: nonEmptyStringSchema.optional(),\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n startedAt: epochMillisSchema,\n consumerAttributes: consumerAttributesSchema,\n })\n .readonly();\nexport type InvocationIdentity = z.infer<typeof invocationIdentitySchema>;\n\n/** Fields an identity claim may contribute. */\nexport const identityClaimFieldsSchema = z.strictObject({\n invocationId: invocationIdSchema.optional(),\n sessionId: sessionIdSchema.optional(),\n parentInvocationId: invocationIdSchema.optional(),\n rootSessionId: sessionIdSchema.optional(),\n agentInstanceId: nonEmptyStringSchema.optional(),\n workspace: workspaceIdentitySchema.optional(),\n startedAt: epochMillisSchema.optional(),\n});\nexport type IdentityClaimFields = z.infer<typeof identityClaimFieldsSchema>;\n\n/**\n * A claim about invocation identity from one source.\n *\n * Claims are evidence, not truth. Resolution keeps the highest-confidence claim\n * per field and refuses to merge disagreeing peers.\n */\nexport const identityClaimSchema = z.strictObject({\n /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */\n source: nonEmptyStringSchema,\n confidence: detectionConfidenceSchema,\n fields: identityClaimFieldsSchema,\n});\nexport type IdentityClaim = z.infer<typeof identityClaimSchema>;\n\nexport type IdentityConflict = {\n readonly field: keyof IdentityClaimFields;\n readonly confidence: DetectionConfidence;\n /** Rendered, non-sensitive representations of the disagreeing values. */\n readonly values: readonly string[];\n readonly sources: readonly string[];\n};\n\nexport type IdentityResolution =\n | { readonly status: \"resolved\"; readonly identity: InvocationIdentity }\n | {\n readonly status: \"conflict\";\n readonly conflicts: readonly IdentityConflict[];\n }\n | {\n readonly status: \"incomplete\";\n readonly missing: readonly (keyof IdentityClaimFields)[];\n }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nconst CLAIM_FIELDS = [\n \"invocationId\",\n \"sessionId\",\n \"parentInvocationId\",\n \"rootSessionId\",\n \"agentInstanceId\",\n \"workspace\",\n \"startedAt\",\n] as const satisfies readonly (keyof IdentityClaimFields)[];\n\nconst renderClaimValue = (value: unknown): string => {\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (value !== null && typeof value === \"object\" && \"workspaceId\" in value) {\n const { workspaceId } = value;\n return typeof workspaceId === \"string\" ? workspaceId : \"<workspace>\";\n }\n return \"<opaque>\";\n};\n\nexport type ResolveIdentityInput = {\n readonly claims: readonly IdentityClaim[];\n readonly provenance: SourceProvenance;\n /** Used only for fields no claim provides and that have a safe default. */\n readonly fallback?: {\n readonly startedAt?: number;\n readonly workspace?: WorkspaceIdentity;\n };\n readonly consumerAttributes?: Readonly<Record<string, unknown>>;\n};\n\n/**\n * Resolve identity from claims, failing closed.\n *\n * Rules:\n * 1. For each field, only claims at the highest confidence that provided it are\n * considered. Lower-confidence claims never fill in or override.\n * 2. Two distinct values at that highest confidence produce a `conflict`. The\n * invocation is then not attributed at all — a mislabelled session is worse\n * than a missing one.\n * 3. `invocationId` and `sessionId` are mandatory. Missing either yields\n * `incomplete`; neither is invented here.\n * 4. `startedAt` and `workspace` may come from an explicit fallback, because a\n * clock reading and an `unknown` workspace handle assert nothing false.\n */\nexport const resolveInvocationIdentity = (input: ResolveIdentityInput): IdentityResolution => {\n const parsedClaims: IdentityClaim[] = [];\n const issues: string[] = [];\n for (const [index, claim] of input.claims.entries()) {\n const parsed = identityClaimSchema.safeParse(claim);\n if (parsed.success) {\n parsedClaims.push(parsed.data);\n } else {\n issues.push(\n `claim[${index}]: ${parsed.error.issues.map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`).join(\", \")}`,\n );\n }\n }\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const conflicts: IdentityConflict[] = [];\n const selected: Record<string, unknown> = {};\n\n for (const field of CLAIM_FIELDS) {\n const contributors = parsedClaims.filter((claim) => claim.fields[field] !== undefined);\n if (contributors.length === 0) {\n continue;\n }\n const bestRank = Math.max(\n ...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence]),\n );\n const best = contributors.filter(\n (claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank,\n );\n const rendered = new Map<string, string[]>();\n for (const claim of best) {\n const key = JSON.stringify(claim.fields[field]);\n const sources = rendered.get(key) ?? [];\n sources.push(claim.source);\n rendered.set(key, sources);\n }\n if (rendered.size > 1) {\n const [firstBest] = best;\n conflicts.push({\n field,\n confidence: firstBest?.confidence ?? \"none\",\n values: best.map((claim) => renderClaimValue(claim.fields[field])),\n sources: best.map((claim) => claim.source),\n });\n continue;\n }\n const [winner] = best;\n if (winner !== undefined) {\n selected[field] = winner.fields[field];\n }\n }\n\n if (conflicts.length > 0) {\n return { status: \"conflict\", conflicts };\n }\n\n const missing: (keyof IdentityClaimFields)[] = [];\n if (selected.invocationId === undefined) {\n missing.push(\"invocationId\");\n }\n if (selected.sessionId === undefined) {\n missing.push(\"sessionId\");\n }\n if (missing.length > 0) {\n return { status: \"incomplete\", missing };\n }\n\n const startedAt = (selected.startedAt as number | undefined) ?? input.fallback?.startedAt;\n if (startedAt === undefined) {\n return { status: \"incomplete\", missing: [\"startedAt\"] };\n }\n const workspace =\n (selected.workspace as WorkspaceIdentity | undefined) ??\n input.fallback?.workspace ??\n unknownWorkspaceIdentity();\n\n const candidate = {\n invocationId: selected.invocationId as InvocationId,\n sessionId: selected.sessionId as SessionId,\n ...(selected.parentInvocationId === undefined\n ? {}\n : { parentInvocationId: selected.parentInvocationId as InvocationId }),\n ...(selected.rootSessionId === undefined\n ? {}\n : { rootSessionId: selected.rootSessionId as SessionId }),\n ...(selected.agentInstanceId === undefined\n ? {}\n : { agentInstanceId: selected.agentInstanceId as string }),\n provenance: input.provenance,\n workspace,\n startedAt,\n consumerAttributes: input.consumerAttributes ?? {},\n };\n\n const parsed = invocationIdentitySchema.safeParse(candidate);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n }\n return { status: \"resolved\", identity: parsed.data };\n};\n","import { z } from \"zod\";\n\nimport { nonEmptyStringSchema, workspaceIdSchema } from \"./primitives.js\";\n\n/**\n * Per-event workspace targeting (ADR 0008).\n *\n * A session's `workspace` is where the agent was *started*. An agent routinely\n * works somewhere else — in a linked git worktree beside the checkout it was\n * launched from — and the session-level identity cannot show that. A tool event\n * can: the file it edited, or the directory its shell command ran in, names the\n * worktree it actually touched.\n *\n * Two values model that, and the split between them is the privacy boundary:\n *\n * - {@link TargetHint} is what an adapter observed — local paths. It is an\n * in-process value only: it is never part of a {@link CanonicalEvent}, never\n * persisted, never exported. The core resolves it and drops it.\n * - {@link WorkspaceTarget} is what the core resolved — salted handles of the\n * worktree and its repository, the worktree's kind, the checked-out branch, and\n * what the evidence was. It travels on the event.\n */\n\n/**\n * What a target was derived from, strongest evidence first.\n *\n * - `tool-path` — a path the tool call itself named (an edited or read file, a\n * patch header).\n * - `shell-cwd` — the working directory the provider reports a shell command ran in.\n * - `session-cwd` — only the session's own directory was known; the event may\n * have reached elsewhere (e.g. a shell `cd`) without the provider saying so.\n */\nexport const targetSourceSchema = z.enum([\"tool-path\", \"shell-cwd\", \"session-cwd\"]);\nexport type TargetSource = z.infer<typeof targetSourceSchema>;\n\n/** Most paths one hint may name; a bound, not a sampling rule (all must agree). */\nexport const MAX_TARGET_HINT_PATHS = 8;\n\n/** Longest local path a hint may carry. Longer input is dropped, never truncated. */\nexport const MAX_TARGET_PATH_LENGTH = 4096;\n\nconst localPathSchema = z\n .string()\n .min(1)\n .max(MAX_TARGET_PATH_LENGTH)\n .refine((value) => !value.includes(\"\\u0000\"), \"path must not contain NUL\");\n\n/**\n * An adapter's observation of where a tool event pointed. **Carries local paths**\n * — in-process only, see the module note.\n *\n * Every path in one hint must resolve to the same worktree, or the event gets no\n * target at all: a patch touching two worktrees did not target either of them.\n */\nexport const targetHintSchema = z\n .strictObject({\n source: targetSourceSchema,\n paths: z.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),\n /** Absolute directory that relative `paths` resolve against. */\n baseDirectory: localPathSchema.optional(),\n })\n .readonly();\nexport type TargetHint = z.infer<typeof targetHintSchema>;\n\n/**\n * The weakest hint: the session's own directory. Every adapter gives it to a\n * session start and a prompt, and to a tool call that names no path.\n */\nexport const sessionCwdHint = (cwd: string | undefined): TargetHint | undefined =>\n cwd === undefined || cwd.length === 0 ? undefined : { source: \"session-cwd\", paths: [cwd] };\n\n/**\n * Whether a worktree is its repository's main checkout (`main`) or one added\n * beside it with `git worktree add` (`linked`).\n */\nexport const worktreeKindSchema = z.enum([\"main\", \"linked\"]);\nexport type WorktreeKind = z.infer<typeof worktreeKindSchema>;\n\n/**\n * The git worktree a tool event targeted. Exported; carries no path.\n *\n * `workspaceId` is derived exactly like a `git-root` workspace identity, so a\n * consumer holding the same salt can match it against one it derived itself.\n * `repositoryId` is the same derivation applied to the repository's main\n * worktree, so every worktree of one repository shares it — and for a main\n * worktree it equals `workspaceId`.\n */\nexport const workspaceTargetSchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n /** Branch checked out in that worktree; absent on a detached HEAD. */\n vcsBranchName: nonEmptyStringSchema.optional(),\n source: targetSourceSchema,\n /** `git-root` handle of the repository's main worktree; absent when there is none to name. */\n repositoryId: workspaceIdSchema.optional(),\n worktreeKind: worktreeKindSchema.optional(),\n })\n .readonly();\nexport type WorkspaceTarget = z.infer<typeof workspaceTargetSchema>;\n\n/**\n * Shape a provider's own subagent identifier must have to be exported.\n *\n * Identifier-shaped on purpose — no whitespace, no path separators — so a\n * malformed payload field cannot carry prose or a path onto the wire under an id\n * attribute. A value that does not fit is dropped, not repaired.\n */\nexport const SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;\nexport const subagentIdSchema = z.string().regex(SUBAGENT_ID_PATTERN);\nexport type SubagentId = z.infer<typeof subagentIdSchema>;\n","import { z } from \"zod\";\n\nimport { tokenCountSchema } from \"./primitives.js\";\n\n/**\n * Whether an observation reports the change since the previous observation\n * (`delta`) or the running total for the session/generation (`cumulative`).\n *\n * The canonical model keeps temporality explicit rather than assuming one:\n * summing cumulative observations double-counts, and diffing delta observations\n * silently loses tokens.\n */\nexport const usageTemporalitySchema = z.enum([\"delta\", \"cumulative\"]);\nexport type UsageTemporality = z.infer<typeof usageTemporalitySchema>;\n\n/**\n * Whether the provider counts cache-creation tokens inside its input total or\n * reports them as a disjoint bucket.\n *\n * - `included-in-input`: `cacheCreationInputTokens` is a subset of `inputTokens`.\n * - `disjoint-from-input`: cache-creation tokens are billed in addition to\n * `inputTokens` and must be added when computing a total.\n * - `not-reported`: the provider exposes no cache-creation counter; the field is\n * pinned to zero.\n */\nexport const cacheCreationAccountingSchema = z.enum([\n \"included-in-input\",\n \"disjoint-from-input\",\n \"not-reported\",\n]);\nexport type CacheCreationAccounting = z.infer<typeof cacheCreationAccountingSchema>;\n\n/** Whether a provider-reported total agrees with the canonical computation. */\nexport const providerTotalAgreementSchema = z.enum([\"unreported\", \"agrees\", \"disagrees\"]);\nexport type ProviderTotalAgreement = z.infer<typeof providerTotalAgreementSchema>;\n\n/**\n * What an adapter reports, before normalization.\n *\n * `inputTokens` is *inclusive*: it counts every input token the provider\n * attributes to the call, including cache reads (and cache creation when the\n * provider folds it in). `outputTokens` is likewise inclusive of reasoning\n * output. Subset fields describe portions of those totals, never additions.\n */\nexport const usageReportSchema = z.strictObject({\n temporality: usageTemporalitySchema,\n /** Inclusive input tokens. */\n inputTokens: tokenCountSchema.optional(),\n /** Subset of `inputTokens` served from a prompt cache. */\n cachedInputTokens: tokenCountSchema.optional(),\n /** Tokens written to a prompt cache. */\n cacheCreationInputTokens: tokenCountSchema.optional(),\n /** Required when `cacheCreationInputTokens` is present and non-zero. */\n cacheCreationAccounting: cacheCreationAccountingSchema.optional(),\n /** Inclusive output tokens. */\n outputTokens: tokenCountSchema.optional(),\n /** Subset of `outputTokens` spent on reasoning. */\n reasoningOutputTokens: tokenCountSchema.optional(),\n /** Total exactly as the provider reported it, if it reported one. */\n providerTotalTokens: tokenCountSchema.optional(),\n});\nexport type UsageReport = z.infer<typeof usageReportSchema>;\n\n/**\n * Fully normalized usage.\n *\n * Derived fields (`uncachedInputTokens`, `totalTokens`,\n * `providerTotalAgreement`) are part of the schema and are re-checked on parse,\n * so an inconsistent object cannot exist. Construct values with\n * {@link normalizeUsage} rather than by hand.\n */\nexport const canonicalUsageSchema = z\n .strictObject({\n temporality: usageTemporalitySchema,\n inputTokens: tokenCountSchema,\n cachedInputTokens: tokenCountSchema,\n cacheCreationInputTokens: tokenCountSchema,\n cacheCreationAccounting: cacheCreationAccountingSchema,\n outputTokens: tokenCountSchema,\n reasoningOutputTokens: tokenCountSchema,\n /** Derived: input tokens that were neither cache reads nor cache writes. */\n uncachedInputTokens: tokenCountSchema,\n /** Derived: canonical billable total. */\n totalTokens: tokenCountSchema,\n providerTotalTokens: tokenCountSchema.optional(),\n providerTotalAgreement: providerTotalAgreementSchema,\n })\n .check((ctx) => {\n const usage = ctx.value;\n const push = (message: string): void => {\n ctx.issues.push({ code: \"custom\", input: usage, message });\n };\n\n if (usage.cachedInputTokens > usage.inputTokens) {\n push(\"cachedInputTokens must not exceed inputTokens (it is a subset)\");\n }\n if (usage.reasoningOutputTokens > usage.outputTokens) {\n push(\"reasoningOutputTokens must not exceed outputTokens (it is a subset)\");\n }\n if (usage.cacheCreationAccounting === \"not-reported\" && usage.cacheCreationInputTokens !== 0) {\n push(\"cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported\");\n }\n const creationInsideInput =\n usage.cacheCreationAccounting === \"included-in-input\" ? usage.cacheCreationInputTokens : 0;\n if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {\n push(\n \"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input\",\n );\n }\n const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;\n if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {\n push(`uncachedInputTokens must equal ${expectedUncached}`);\n }\n const creationOutsideInput =\n usage.cacheCreationAccounting === \"disjoint-from-input\" ? usage.cacheCreationInputTokens : 0;\n const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;\n if (usage.totalTokens !== expectedTotal) {\n push(`totalTokens must equal ${expectedTotal}`);\n }\n const expectedAgreement: ProviderTotalAgreement =\n usage.providerTotalTokens === undefined\n ? \"unreported\"\n : usage.providerTotalTokens === expectedTotal\n ? \"agrees\"\n : \"disagrees\";\n if (usage.providerTotalAgreement !== expectedAgreement) {\n push(`providerTotalAgreement must be ${expectedAgreement}`);\n }\n });\nexport type CanonicalUsage = z.infer<typeof canonicalUsageSchema>;\n\nexport type UsageNormalizationIssue = {\n readonly code:\n | \"invalid-report\"\n | \"cached-exceeds-input\"\n | \"reasoning-exceeds-output\"\n | \"cache-creation-exceeds-input\"\n | \"cache-creation-accounting-missing\";\n readonly message: string;\n};\n\nexport type UsageNormalizationResult =\n | { readonly status: \"ok\"; readonly usage: CanonicalUsage; readonly notes: readonly string[] }\n | { readonly status: \"invalid\"; readonly issues: readonly UsageNormalizationIssue[] };\n\n/**\n * Normalize a provider usage report into canonical usage.\n *\n * Deterministic rules:\n * 1. Absent counters default to `0`; `providerTotalTokens` stays absent.\n * 2. Non-integer, negative, or non-finite counters are rejected.\n * 3. A subset exceeding its total is rejected — never clamped — because\n * clamping would silently invent a billing story.\n * 4. `cacheCreationAccounting` defaults to `not-reported` when no cache-creation\n * tokens are reported, and is *required* when they are: guessing whether the\n * bucket is disjoint would mis-total every downstream cost calculation.\n * 5. A provider total that disagrees with the canonical total is preserved as\n * reported and flagged `disagrees`. Both numbers survive; neither is edited.\n */\nexport const normalizeUsage = (report: unknown): UsageNormalizationResult => {\n const parsed = usageReportSchema.safeParse(report);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map((issue) => ({\n code: \"invalid-report\" as const,\n message: `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n })),\n };\n }\n\n const input = parsed.data;\n const issues: UsageNormalizationIssue[] = [];\n const notes: string[] = [];\n\n const inputTokens = input.inputTokens ?? 0;\n const cachedInputTokens = input.cachedInputTokens ?? 0;\n const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;\n const outputTokens = input.outputTokens ?? 0;\n const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;\n\n let accounting: CacheCreationAccounting;\n if (cacheCreationInputTokens === 0) {\n accounting = input.cacheCreationAccounting ?? \"not-reported\";\n if (accounting !== \"not-reported\") {\n notes.push(\n `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`,\n );\n }\n } else if (input.cacheCreationAccounting === undefined) {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message:\n \"cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred\",\n });\n accounting = \"not-reported\";\n } else if (input.cacheCreationAccounting === \"not-reported\") {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message: \"cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens\",\n });\n accounting = \"not-reported\";\n } else {\n accounting = input.cacheCreationAccounting;\n }\n\n if (cachedInputTokens > inputTokens) {\n issues.push({\n code: \"cached-exceeds-input\",\n message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n if (reasoningOutputTokens > outputTokens) {\n issues.push({\n code: \"reasoning-exceeds-output\",\n message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`,\n });\n }\n\n const creationInsideInput = accounting === \"included-in-input\" ? cacheCreationInputTokens : 0;\n if (cachedInputTokens + creationInsideInput > inputTokens) {\n issues.push({\n code: \"cache-creation-exceeds-input\",\n message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const creationOutsideInput = accounting === \"disjoint-from-input\" ? cacheCreationInputTokens : 0;\n const totalTokens = inputTokens + creationOutsideInput + outputTokens;\n const providerTotalAgreement: ProviderTotalAgreement =\n input.providerTotalTokens === undefined\n ? \"unreported\"\n : input.providerTotalTokens === totalTokens\n ? \"agrees\"\n : \"disagrees\";\n\n if (providerTotalAgreement === \"disagrees\") {\n notes.push(\n `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`,\n );\n }\n\n const usage: CanonicalUsage = {\n temporality: input.temporality,\n inputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens,\n reasoningOutputTokens,\n uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,\n totalTokens,\n ...(input.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: input.providerTotalTokens }),\n providerTotalAgreement,\n };\n\n return { status: \"ok\", usage, notes };\n};\n\nexport class UsageNormalizationError extends Error {\n public readonly issues: readonly UsageNormalizationIssue[];\n\n public constructor(issues: readonly UsageNormalizationIssue[]) {\n super(`invalid usage report: ${issues.map((issue) => issue.message).join(\"; \")}`);\n this.name = \"UsageNormalizationError\";\n this.issues = issues;\n }\n}\n\n/** Convenience wrapper for call sites that treat invalid usage as a bug. */\nexport const normalizeUsageOrThrow = (report: unknown): CanonicalUsage => {\n const result = normalizeUsage(report);\n if (result.status === \"invalid\") {\n throw new UsageNormalizationError(result.issues);\n }\n return result.usage;\n};\n\nexport const EMPTY_DELTA_USAGE: CanonicalUsage = Object.freeze(\n normalizeUsageOrThrow({ temporality: \"delta\" }),\n);\n\nexport type UsageDeltaResult = {\n readonly usage: CanonicalUsage;\n /**\n * True when the current snapshot is smaller than the previous one on any\n * counter. That means the cumulative series restarted (new session, replayed\n * transcript, provider reset), so the current snapshot is emitted as the delta\n * instead of a negative difference.\n */\n readonly resetDetected: boolean;\n};\n\nconst requireCumulative = (usage: CanonicalUsage, label: string): void => {\n if (usage.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: `${label} must have cumulative temporality` },\n ]);\n }\n};\n\n/**\n * Convert two cumulative snapshots into a delta observation.\n *\n * Replay safety: re-processing the same snapshot yields an all-zero delta, and a\n * decreasing series is reported as a reset rather than a negative delta.\n * Accounting mode must match; mixing modes would make the subtraction meaningless.\n */\nexport const cumulativeToDelta = (\n previous: CanonicalUsage,\n current: CanonicalUsage,\n): UsageDeltaResult => {\n requireCumulative(previous, \"previous usage\");\n requireCumulative(current, \"current usage\");\n\n if (\n previous.cacheCreationAccounting !== current.cacheCreationAccounting &&\n previous.cacheCreationInputTokens !== 0 &&\n current.cacheCreationInputTokens !== 0\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot diff cumulative usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const resetDetected =\n current.inputTokens < previous.inputTokens ||\n current.cachedInputTokens < previous.cachedInputTokens ||\n current.cacheCreationInputTokens < previous.cacheCreationInputTokens ||\n current.outputTokens < previous.outputTokens ||\n current.reasoningOutputTokens < previous.reasoningOutputTokens;\n\n if (resetDetected) {\n return {\n usage: normalizeUsageOrThrow({ ...toReport(current), temporality: \"delta\" }),\n resetDetected: true,\n };\n }\n\n const usage = normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: current.inputTokens - previous.inputTokens,\n cachedInputTokens: current.cachedInputTokens - previous.cachedInputTokens,\n cacheCreationInputTokens:\n current.cacheCreationInputTokens - previous.cacheCreationInputTokens,\n cacheCreationAccounting: current.cacheCreationAccounting,\n outputTokens: current.outputTokens - previous.outputTokens,\n reasoningOutputTokens: current.reasoningOutputTokens - previous.reasoningOutputTokens,\n });\n\n return { usage, resetDetected: false };\n};\n\n/** Project canonical usage back onto the reported shape. */\nexport const toReport = (usage: CanonicalUsage): UsageReport => ({\n temporality: usage.temporality,\n inputTokens: usage.inputTokens,\n cachedInputTokens: usage.cachedInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n cacheCreationAccounting: usage.cacheCreationAccounting,\n outputTokens: usage.outputTokens,\n reasoningOutputTokens: usage.reasoningOutputTokens,\n ...(usage.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: usage.providerTotalTokens }),\n});\n\n/**\n * Add two delta observations. Cumulative usage is never summed, because two\n * running totals do not compose.\n */\nexport const addUsage = (a: CanonicalUsage, b: CanonicalUsage): CanonicalUsage => {\n if (a.temporality !== \"delta\" || b.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"only delta usage may be summed\" },\n ]);\n }\n const accounting =\n a.cacheCreationInputTokens === 0 && a.cacheCreationAccounting === \"not-reported\"\n ? b.cacheCreationAccounting\n : b.cacheCreationInputTokens === 0 && b.cacheCreationAccounting === \"not-reported\"\n ? a.cacheCreationAccounting\n : a.cacheCreationAccounting;\n\n if (\n a.cacheCreationInputTokens !== 0 &&\n b.cacheCreationInputTokens !== 0 &&\n a.cacheCreationAccounting !== b.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot sum usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n a.providerTotalTokens === undefined && b.providerTotalTokens === undefined\n ? undefined\n : (a.providerTotalTokens ?? 0) + (b.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: a.inputTokens + b.inputTokens,\n cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,\n cacheCreationInputTokens: a.cacheCreationInputTokens + b.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: a.outputTokens + b.outputTokens,\n reasoningOutputTokens: a.reasoningOutputTokens + b.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n","import { z } from \"zod\";\n\n/**\n * Version of the canonical event model.\n *\n * Every emitted event carries this value. Consumers must treat an unknown\n * version as unreadable rather than guessing field semantics.\n *\n * Compatibility rules:\n * - Additive optional fields do not change the version.\n * - Renaming, removing, or re-interpreting a field increments the version.\n */\nexport const CANONICAL_SCHEMA_VERSION = 1 as const;\n\nexport type CanonicalSchemaVersion = typeof CANONICAL_SCHEMA_VERSION;\n\nexport const canonicalSchemaVersionSchema = z.literal(CANONICAL_SCHEMA_VERSION);\n","import type { Attributes as SpanAttributes } from \"@opentelemetry/api\";\n\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport {\n MAX_ATTRIBUTE_STRING_LENGTH,\n MAX_IDENTIFIER_LENGTH,\n type Attributes,\n} from \"../model/primitives.js\";\nimport type { Clock, StateStore, StateValue } from \"../runtime/ports.js\";\nimport { withOptionalSessionLock } from \"../state/store.js\";\nimport {\n MAX_RECOVERED_START_ATTRIBUTES,\n parentScopeRefOf,\n spanScopeRefOf,\n startOnlySpanAttributes,\n type SpanCorrelation,\n type SpanFamily,\n type SpanOrphanClassification,\n type SpanScopeRef,\n} from \"../telemetry/semconv.js\";\nimport { spanKey, spanScanPrefix } from \"./keys.js\";\n\n/** Correlation scopes that pair a `*.start` event with a later `*.end` event. */\nexport type LifecycleScope = SpanFamily;\n\n/**\n * Shape version of a persisted span record.\n *\n * A record written under a different version is discarded on read rather than\n * interpreted: guessing at an older layout is exactly the kind of silent\n * mis-attribution this library refuses to do. See `docs/state-retention.md`.\n */\nexport const SPAN_RECORD_VERSION = 2;\n\n/** Facts about a span recovered from, or written to, persisted state. */\nexport type SpanCorrelationFacts = {\n readonly startedAt?: number;\n readonly endedAt?: number;\n readonly parent?: SpanScopeRef;\n readonly attributes?: SpanAttributes;\n};\n\nexport type SpanStartInput = {\n readonly sessionId: string;\n /** Attribution boundary: a scope recorded by one provider never pairs with another's. */\n readonly providerId: string;\n readonly scope: LifecycleScope;\n readonly scopeKey: string;\n /** The canonical event id of the start event; used to detect redelivery. */\n readonly eventId: string;\n readonly occurredAt: number;\n /** Where this span hangs, so an end-only process reparents it identically. */\n readonly parent?: SpanScopeRef;\n /** Attributes only the start edge knows; carried forward to the end-side span. */\n readonly attributes?: SpanAttributes;\n};\n\nexport type SpanEndInput = {\n readonly sessionId: string;\n readonly providerId: string;\n readonly scope: LifecycleScope;\n readonly scopeKey: string;\n readonly eventId: string;\n readonly occurredAt: number;\n};\n\nexport type SpanStartResult =\n | { readonly status: \"recorded\"; readonly facts: SpanCorrelationFacts }\n /** The same start (by event id) was already recorded; state is unchanged. */\n | { readonly status: \"duplicate\"; readonly facts: SpanCorrelationFacts }\n /**\n * The record was completed, but an OTLP record for this scope has already been\n * published under its span id — so this edge must not export one.\n */\n | { readonly status: \"published\"; readonly facts: SpanCorrelationFacts }\n /** A different provider owns this scope key in this session; nothing was written. */\n | { readonly status: \"conflict\"; readonly reason: \"provider-mismatch\" };\n\n/** Why an end could not be paired with a recorded start. */\nexport type SpanEndOrphanReason =\n | \"no-start-recorded\"\n | \"start-expired\"\n | \"already-closed\"\n | \"provider-mismatch\"\n | \"state-incompatible\"\n | \"state-corrupt\";\n\nexport type SpanEndResult =\n | {\n readonly status: \"matched\";\n readonly startedAt: number;\n readonly durationMillis: number;\n readonly facts: SpanCorrelationFacts;\n }\n /** This exact end (by event id) was already applied; the same facts are replayed. */\n | { readonly status: \"duplicate\"; readonly facts: SpanCorrelationFacts }\n | {\n readonly status: \"orphaned\";\n readonly reason: SpanEndOrphanReason;\n readonly facts: SpanCorrelationFacts;\n };\n\nexport type SpanCleanupResult = {\n readonly removed: number;\n readonly scanned: number;\n /**\n * Records dropped that held a start and never received an end.\n *\n * These are the spans that will never be exported at all: the end edge is what\n * emits a lifecycle span, so a scope whose end never arrives — a session the\n * host killed, a tool call that outlived the retention window — produces no\n * OTLP record. That is the standard OpenTelemetry outcome for a span that never\n * ends, and it is deliberately not papered over with a synthetic end time,\n * because a fabricated duration is a wrong measurement rather than a missing\n * one. Counting them keeps the cost visible: a non-zero number here means real\n * activity went unreported, which is a signal about the host or the retention\n * window rather than noise. See `docs/state-retention.md`.\n */\n readonly expiredOpen: number;\n};\n\n/**\n * Cross-invocation start/end correlation for session, generation, tool, and\n * subagent scopes.\n *\n * A coding-agent hook fires once per lifecycle edge, usually as a separate\n * short-lived process for the start and for the end. This records an open span\n * in the shared state store so the end side can report a real start time,\n * duration, parent, and start-only attributes even though its process has no\n * memory of the start — and so a redelivered start or end (an at-least-once\n * host retry) re-exports an identical span instead of being double-counted.\n *\n * ## What it refuses to do\n *\n * - **Pair across sessions.** The state key is session-scoped, so two sessions\n * cannot see each other's open spans.\n * - **Pair across providers.** The key is provider-scoped *and* the record\n * carries the provider that wrote it, so a mismatch is reported rather than\n * guessed at — the same defense in depth the durable spool uses.\n * - **Trust a stale start.** A start older than `maxStartAgeMillis` when its end\n * arrives is dropped and classified `start-expired`, rather than reporting a\n * duration that really measures a machine suspend or a reused id.\n * - **Interpret a record it does not understand.** A corrupt or wrong-version\n * record is deleted and classified, never partially read.\n */\nexport interface SpanCorrelator {\n recordStart(input: SpanStartInput): Promise<SpanStartResult>;\n recordEnd(input: SpanEndInput): Promise<SpanEndResult>;\n /**\n * Records every lifecycle edge in a batch and reports what the exported spans\n * should say. Never rejects: a state failure degrades one scope to\n * `state-unavailable` rather than losing the batch (fail-open telemetry).\n */\n correlateBatch(events: readonly CanonicalEvent[]): Promise<readonly SpanCorrelation[]>;\n /** Bounded sweep: drops spans untouched for longer than `maxAgeMillis`. */\n cleanup(\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<SpanCleanupResult>;\n}\n\nexport type SpanCorrelatorDependencies = {\n readonly stateStore: StateStore;\n readonly clock: Clock;\n /**\n * A recorded start older than this when its end arrives is not trusted.\n * Default 24 hours, matching the janitor's retention window.\n */\n readonly maxStartAgeMillis?: number;\n};\n\nconst DEFAULT_MAX_START_AGE_MILLIS = 24 * 60 * 60 * 1000;\nconst ATTRIBUTE_PREFIX = \"a:\";\n\ntype SpanRecord = {\n readonly providerId: string;\n readonly startEventId?: string;\n readonly startedAt?: number;\n readonly endEventId?: string;\n readonly endedAt?: number;\n readonly parent?: SpanScopeRef;\n readonly attributes?: SpanAttributes;\n /**\n * True once an OTLP record has been produced for this scope under its derived\n * span id.\n *\n * Needed for the ordering nobody controls: the end edge can be mapped before\n * the start edge, and then the end has already exported an orphan carrying the\n * scope's canonical span id. Without this flag the late start would look like\n * the benign \"end raced ahead\" case and export a *second* record with that same\n * id — the duplicate the whole defer strategy exists to avoid. So the flag turns\n * \"was this scope already published?\" into a fact on disk rather than an\n * assumption about arrival order.\n */\n readonly exported?: boolean;\n};\n\ntype DecodedRecord =\n | { readonly kind: \"absent\" }\n | { readonly kind: \"incompatible\" }\n | { readonly kind: \"corrupt\" }\n | { readonly kind: \"present\"; readonly record: SpanRecord };\n\nconst SPAN_FAMILIES: readonly SpanFamily[] = [\"session\", \"generation\", \"tool\", \"subagent\"];\n\nconst isSpanFamily = (value: unknown): value is SpanFamily =>\n typeof value === \"string\" && (SPAN_FAMILIES as readonly string[]).includes(value);\n\nconst optionalNumber = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n\nconst optionalString = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 ? value : undefined;\n\n/**\n * Persisted attributes are flattened under a prefix rather than nested: the\n * state schema admits only flat primitives, which is what keeps a provider\n * payload from ever being smuggled through the state store.\n */\nconst encodeAttributes = (attributes: SpanAttributes | undefined): Attributes => {\n const encoded: Record<string, string | number | boolean> = {};\n let count = 0;\n for (const [key, value] of Object.entries(attributes ?? {})) {\n if (count >= MAX_RECOVERED_START_ATTRIBUTES) {\n break;\n }\n const encodedKey = `${ATTRIBUTE_PREFIX}${key}`;\n if (encodedKey.length > MAX_IDENTIFIER_LENGTH) {\n continue;\n }\n if (typeof value === \"string\") {\n encoded[encodedKey] = value.slice(0, MAX_ATTRIBUTE_STRING_LENGTH);\n } else if (typeof value === \"number\" && Number.isFinite(value)) {\n encoded[encodedKey] = value;\n } else if (typeof value === \"boolean\") {\n encoded[encodedKey] = value;\n } else {\n continue;\n }\n count += 1;\n }\n return encoded;\n};\n\nconst decodeAttributes = (attributes: Attributes): SpanAttributes | undefined => {\n const decoded: Record<string, string | number | boolean> = {};\n let count = 0;\n for (const [key, value] of Object.entries(attributes)) {\n if (!key.startsWith(ATTRIBUTE_PREFIX) || count >= MAX_RECOVERED_START_ATTRIBUTES) {\n continue;\n }\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n decoded[key.slice(ATTRIBUTE_PREFIX.length)] = value;\n count += 1;\n }\n }\n return count === 0 ? undefined : decoded;\n};\n\nconst encodeRecord = (record: SpanRecord): StateValue => ({\n kind: \"attributes\",\n attributes: {\n v: SPAN_RECORD_VERSION,\n providerId: record.providerId,\n ...(record.startEventId === undefined ? {} : { startEventId: record.startEventId }),\n ...(record.startedAt === undefined ? {} : { startedAt: record.startedAt }),\n ...(record.endEventId === undefined ? {} : { endEventId: record.endEventId }),\n ...(record.endedAt === undefined ? {} : { endedAt: record.endedAt }),\n ...(record.exported === true ? { exported: true } : {}),\n ...(record.parent === undefined\n ? {}\n : { parentFamily: record.parent.family, parentScopeKey: record.parent.scopeKey }),\n ...encodeAttributes(record.attributes),\n },\n});\n\nconst decodeRecord = (attributes: Attributes): DecodedRecord => {\n if (attributes[\"v\"] !== SPAN_RECORD_VERSION) {\n return { kind: \"incompatible\" };\n }\n const providerId = optionalString(attributes[\"providerId\"]);\n if (providerId === undefined) {\n return { kind: \"corrupt\" };\n }\n // A half-written edge (a timestamp with no event id, or the reverse) is not\n // an edge we can reason about; the record is refused rather than completed\n // with an invented half.\n const startedAt = optionalNumber(attributes[\"startedAt\"]);\n const startEventId = optionalString(attributes[\"startEventId\"]);\n if ((startedAt === undefined) !== (startEventId === undefined)) {\n return { kind: \"corrupt\" };\n }\n const endedAt = optionalNumber(attributes[\"endedAt\"]);\n const endEventId = optionalString(attributes[\"endEventId\"]);\n if ((endedAt === undefined) !== (endEventId === undefined)) {\n return { kind: \"corrupt\" };\n }\n const exported = attributes[\"exported\"] === true;\n const parentFamily = attributes[\"parentFamily\"];\n const parentScopeKey = optionalString(attributes[\"parentScopeKey\"]);\n const parent =\n isSpanFamily(parentFamily) && parentScopeKey !== undefined\n ? { family: parentFamily, scopeKey: parentScopeKey }\n : undefined;\n const decodedAttributes = decodeAttributes(attributes);\n return {\n kind: \"present\",\n record: {\n providerId,\n ...(startEventId === undefined ? {} : { startEventId }),\n ...(startedAt === undefined ? {} : { startedAt }),\n ...(endEventId === undefined ? {} : { endEventId }),\n ...(endedAt === undefined ? {} : { endedAt }),\n ...(parent === undefined ? {} : { parent }),\n ...(exported ? { exported: true } : {}),\n ...(decodedAttributes === undefined ? {} : { attributes: decodedAttributes }),\n },\n };\n};\n\nconst factsOf = (record: SpanRecord): SpanCorrelationFacts => ({\n ...(record.startedAt === undefined ? {} : { startedAt: record.startedAt }),\n ...(record.endedAt === undefined ? {} : { endedAt: record.endedAt }),\n ...(record.parent === undefined ? {} : { parent: record.parent }),\n ...(record.attributes === undefined ? {} : { attributes: record.attributes }),\n});\n\n/**\n * Persisted facts speak in event time (`startedAt`); a span speaks in the\n * milliseconds it is stamped with. Translated in one place so the two\n * vocabularies cannot silently drift apart.\n */\nconst correlationTimesOf = (\n facts: SpanCorrelationFacts,\n options: { readonly withStart: boolean } = { withStart: true },\n): Pick<SpanCorrelation, \"startMillis\" | \"endMillis\" | \"parent\" | \"attributes\"> => ({\n ...(facts.startedAt === undefined || !options.withStart ? {} : { startMillis: facts.startedAt }),\n ...(facts.endedAt === undefined ? {} : { endMillis: facts.endedAt }),\n ...(facts.parent === undefined ? {} : { parent: facts.parent }),\n ...(facts.attributes === undefined ? {} : { attributes: facts.attributes }),\n});\n\nconst orphanClassificationOf = (reason: SpanEndOrphanReason): SpanOrphanClassification => {\n switch (reason) {\n case \"no-start-recorded\":\n return \"missing-start\";\n case \"start-expired\":\n return \"expired-start\";\n case \"already-closed\":\n return \"already-closed\";\n case \"provider-mismatch\":\n return \"provider-mismatch\";\n case \"state-incompatible\":\n return \"state-incompatible\";\n case \"state-corrupt\":\n return \"state-corrupt\";\n }\n};\n\ntype BatchGroup = {\n readonly providerId: string;\n readonly sessionId: string;\n readonly ref: SpanScopeRef;\n start?: CanonicalEvent;\n end?: CanonicalEvent;\n};\n\nexport const createSpanCorrelator = (deps: SpanCorrelatorDependencies): SpanCorrelator => {\n const { stateStore, clock } = deps;\n const maxStartAgeMillis = deps.maxStartAgeMillis ?? DEFAULT_MAX_START_AGE_MILLIS;\n\n const keyFor = (input: {\n readonly sessionId: string;\n readonly providerId: string;\n readonly scope: LifecycleScope;\n readonly scopeKey: string;\n }): string => spanKey(input.sessionId, input.providerId, input.scope, input.scopeKey);\n\n /**\n * Reads and validates one record, deleting anything it refuses to interpret.\n * Self-healing on purpose: a single unreadable record must not make the same\n * scope unreadable forever.\n */\n const readRecord = async (key: string): Promise<DecodedRecord> => {\n const existing = await stateStore.read(key);\n if (existing === undefined) {\n return { kind: \"absent\" };\n }\n if (existing.value.kind !== \"attributes\") {\n await stateStore.delete(key);\n return { kind: \"corrupt\" };\n }\n const decoded = decodeRecord(existing.value.attributes);\n if (decoded.kind === \"corrupt\" || decoded.kind === \"incompatible\") {\n await stateStore.delete(key);\n }\n return decoded;\n };\n\n const recordStart = (input: SpanStartInput): Promise<SpanStartResult> =>\n withOptionalSessionLock(stateStore, input.sessionId, async (): Promise<SpanStartResult> => {\n const key = keyFor(input);\n const decoded = await readRecord(key);\n\n if (decoded.kind === \"present\") {\n const existing = decoded.record;\n if (existing.providerId !== input.providerId) {\n return { status: \"conflict\", reason: \"provider-mismatch\" };\n }\n if (existing.startEventId === input.eventId) {\n return { status: \"duplicate\", facts: factsOf(existing) };\n }\n if (existing.startEventId === undefined && existing.endEventId !== undefined) {\n // The end raced ahead of the start (two hook processes, no ordering\n // guarantee between them). Complete the record rather than treating\n // the late start as the beginning of a second span.\n //\n // If that end was already exported, the scope's canonical span id is\n // already on the wire and this start must stay silent: re-exporting a\n // now-complete span under the same id would be a duplicate, not a\n // correction, because OTLP has no update. The enrichment is lost and the\n // published record remains the orphan the end could honestly produce.\n const completed: SpanRecord = {\n ...existing,\n startEventId: input.eventId,\n startedAt: input.occurredAt,\n ...(input.parent === undefined ? {} : { parent: input.parent }),\n ...(input.attributes === undefined ? {} : { attributes: input.attributes }),\n };\n await stateStore.write(key, encodeRecord(completed));\n return existing.exported === true\n ? { status: \"published\", facts: factsOf(completed) }\n : { status: \"recorded\", facts: factsOf(completed) };\n }\n }\n\n // Either nothing was recorded, or a *different* start claims this scope\n // key: the previous span is superseded rather than merged into.\n const fresh: SpanRecord = {\n providerId: input.providerId,\n startEventId: input.eventId,\n startedAt: input.occurredAt,\n ...(input.parent === undefined ? {} : { parent: input.parent }),\n ...(input.attributes === undefined ? {} : { attributes: input.attributes }),\n };\n await stateStore.write(key, encodeRecord(fresh));\n return { status: \"recorded\", facts: factsOf(fresh) };\n });\n\n const recordEnd = (input: SpanEndInput): Promise<SpanEndResult> =>\n withOptionalSessionLock(stateStore, input.sessionId, async (): Promise<SpanEndResult> => {\n const key = keyFor(input);\n const decoded = await readRecord(key);\n\n if (decoded.kind === \"incompatible\" || decoded.kind === \"corrupt\") {\n const reason = decoded.kind === \"incompatible\" ? \"state-incompatible\" : \"state-corrupt\";\n return { status: \"orphaned\", reason, facts: { endedAt: input.occurredAt } };\n }\n if (decoded.kind === \"absent\") {\n // Remember the end anyway: a start that arrives late still deserves to\n // be paired rather than exported as a second orphan.\n const endOnly: SpanRecord = {\n providerId: input.providerId,\n endEventId: input.eventId,\n endedAt: input.occurredAt,\n // This end is about to be exported as an orphan under the scope's\n // canonical span id, so a start arriving later must not reuse it.\n exported: true,\n };\n await stateStore.write(key, encodeRecord(endOnly));\n return { status: \"orphaned\", reason: \"no-start-recorded\", facts: factsOf(endOnly) };\n }\n\n const existing = decoded.record;\n if (existing.providerId !== input.providerId) {\n return {\n status: \"orphaned\",\n reason: \"provider-mismatch\",\n facts: { endedAt: input.occurredAt },\n };\n }\n if (existing.endEventId === input.eventId) {\n // Idempotent replay: answer with the facts already on disk so the\n // re-exported span is byte-identical to the first one.\n return { status: \"duplicate\", facts: factsOf(existing) };\n }\n if (existing.endEventId !== undefined) {\n return {\n status: \"orphaned\",\n reason: \"already-closed\",\n facts: { endedAt: input.occurredAt },\n };\n }\n if (existing.startedAt === undefined) {\n const replaced: SpanRecord = {\n ...existing,\n endEventId: input.eventId,\n endedAt: input.occurredAt,\n exported: true,\n };\n await stateStore.write(key, encodeRecord(replaced));\n return { status: \"orphaned\", reason: \"no-start-recorded\", facts: factsOf(replaced) };\n }\n if (input.occurredAt - existing.startedAt > maxStartAgeMillis) {\n await stateStore.delete(key);\n return { status: \"orphaned\", reason: \"start-expired\", facts: { endedAt: input.occurredAt } };\n }\n\n const closed: SpanRecord = {\n ...existing,\n endEventId: input.eventId,\n endedAt: input.occurredAt,\n exported: true,\n };\n await stateStore.write(key, encodeRecord(closed));\n return {\n status: \"matched\",\n startedAt: existing.startedAt,\n durationMillis: Math.max(0, input.occurredAt - existing.startedAt),\n facts: factsOf(closed),\n };\n });\n\n const correlateGroup = async (group: BatchGroup): Promise<SpanCorrelation> => {\n const base = {\n providerId: group.providerId,\n sessionId: group.sessionId,\n ref: group.ref,\n } as const;\n const unpaired = (\n orphan: SpanOrphanClassification,\n facts: SpanCorrelationFacts,\n ): SpanCorrelation => ({\n ...base,\n pairing: \"unpaired\",\n orphan,\n // An unpaired span has no trustworthy start, so a start time is the one\n // fact it must not carry; everything else recovered is still true.\n ...correlationTimesOf(facts, { withStart: false }),\n });\n\n let startFacts: SpanCorrelationFacts | undefined;\n if (group.start !== undefined) {\n const parent = parentScopeRefOf(group.start);\n const result = await recordStart({\n sessionId: group.sessionId,\n providerId: group.providerId,\n scope: group.ref.family,\n scopeKey: group.ref.scopeKey,\n eventId: group.start.eventId,\n occurredAt: group.start.occurredAt,\n ...(parent === undefined ? {} : { parent }),\n attributes: startOnlySpanAttributes(group.start),\n });\n if (result.status === \"conflict\") {\n return unpaired(\"provider-mismatch\", {});\n }\n if (result.status === \"published\" && group.end === undefined) {\n // The end already exported this scope's span. Completing the record was\n // still worth doing (a redelivered end replays identical facts), but\n // emitting here would duplicate a span id already on the wire.\n return { ...unpaired(\"already-closed\", result.facts), disposition: \"defer\" };\n }\n startFacts = result.facts;\n }\n\n if (group.end === undefined) {\n const facts = startFacts ?? {};\n // A start whose end already landed (the racing-process case) closes a\n // complete span, even though only the start is in this batch.\n if (facts.endedAt !== undefined) {\n return {\n ...base,\n pairing: \"cross-process\",\n orphan: \"none\",\n disposition: \"emit\",\n ...correlationTimesOf(facts),\n };\n }\n // The end has not arrived. The start is durable now, so the end edge will\n // export one complete span under this scope's derived id; exporting a\n // zero-duration record here as well would put two records with that same id\n // on the wire, and OTLP cannot revise a span.\n return { ...unpaired(\"missing-end\", facts), disposition: \"defer\" };\n }\n\n const result = await recordEnd({\n sessionId: group.sessionId,\n providerId: group.providerId,\n scope: group.ref.family,\n scopeKey: group.ref.scopeKey,\n eventId: group.end.eventId,\n occurredAt: group.end.occurredAt,\n });\n\n if (result.status === \"orphaned\") {\n const orphan = orphanClassificationOf(result.reason);\n // `already-closed` means a *second, distinct* end for a scope whose first\n // end has already been exported under this scope's derived span id. Both\n // ends are real observations, so neither is dropped — but the second must\n // not reuse that id. Keying the discriminator on the end event id keeps a\n // redelivery of this same second end idempotent, since it recomputes the\n // same id rather than inventing a third.\n return orphan === \"already-closed\"\n ? {\n ...unpaired(orphan, result.facts),\n disposition: \"emit\",\n spanIdDiscriminator: group.end.eventId,\n }\n : { ...unpaired(orphan, result.facts), disposition: \"emit\" };\n }\n if (result.status === \"duplicate\" && result.facts.startedAt === undefined) {\n // A replayed end that never had a start is still an orphan.\n return { ...unpaired(\"missing-start\", result.facts), disposition: \"emit\" };\n }\n return {\n ...base,\n pairing: group.start === undefined ? \"cross-process\" : \"in-batch\",\n orphan: \"none\",\n disposition: \"emit\",\n ...correlationTimesOf(result.facts),\n };\n };\n\n const correlateBatch = async (\n events: readonly CanonicalEvent[],\n ): Promise<readonly SpanCorrelation[]> => {\n const groups = new Map<string, BatchGroup>();\n for (const event of events) {\n const ref = spanScopeRefOf(event);\n if (ref === undefined) {\n continue;\n }\n const providerId = event.provenance.providerId;\n const groupKey = [providerId, event.sessionId, ref.family, ref.scopeKey].join(\"\\u0000\");\n const group: BatchGroup = groups.get(groupKey) ?? {\n providerId,\n sessionId: event.sessionId,\n ref,\n };\n if (event.type.endsWith(\".start\")) {\n group.start = event;\n } else {\n group.end = event;\n }\n groups.set(groupKey, group);\n }\n\n const correlations: SpanCorrelation[] = [];\n for (const group of groups.values()) {\n try {\n correlations.push(await correlateGroup(group));\n } catch {\n // Fail open: an unreachable, locked, or unwritable state store costs a\n // span its pairing, never the whole export.\n //\n // A start whose record could not be written is the case that needs care.\n // It is *not* deferrable — deferring means \"the state store is holding\n // this, the end edge will publish it\", and here the state store is exactly\n // what failed. So it must be exported, and it must not use the scope's\n // canonical span id: nothing recorded this start, so a later end will\n // publish that id itself as an orphan, and reusing it would put two\n // records with one identity on the wire. Discriminating by the start's own\n // event id makes this record honest and collision-free.\n const unrecordedStart = group.start !== undefined && group.end === undefined;\n correlations.push({\n providerId: group.providerId,\n sessionId: group.sessionId,\n ref: group.ref,\n pairing: \"unpaired\",\n orphan: \"state-unavailable\",\n disposition: \"emit\",\n ...(unrecordedStart && group.start !== undefined\n ? { spanIdDiscriminator: group.start.eventId }\n : {}),\n });\n }\n }\n return correlations;\n };\n\n const cleanup = async (\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<SpanCleanupResult> => {\n const keys = await stateStore.keys(spanScanPrefix(options?.sessionId));\n const cap = options?.maxEntries ?? 1_000;\n const now = clock.now();\n let removed = 0;\n let scanned = 0;\n let expiredOpen = 0;\n for (const key of keys) {\n if (scanned >= cap) {\n break;\n }\n scanned += 1;\n const record = await stateStore.read(key);\n if (record !== undefined && now - record.updatedAt > maxAgeMillis) {\n // Classified before deletion: a record with a start and no end is a span\n // that will never be exported, which is worth counting rather than\n // discarding silently.\n if (record.value.kind === \"attributes\") {\n const decoded = decodeRecord(record.value.attributes);\n if (\n decoded.kind === \"present\" &&\n decoded.record.startedAt !== undefined &&\n decoded.record.endedAt === undefined\n ) {\n expiredOpen += 1;\n }\n }\n await stateStore.delete(key);\n removed += 1;\n }\n }\n return { removed, scanned, expiredOpen };\n };\n\n return { recordStart, recordEnd, correlateBatch, cleanup };\n};\n","import {\n UsageNormalizationError,\n normalizeUsageOrThrow,\n type CanonicalUsage,\n} from \"../model/usage.js\";\nimport type { Attributes } from \"../model/primitives.js\";\nimport type { Clock, StateStore } from \"../runtime/ports.js\";\nimport { withOptionalSessionLock } from \"../state/store.js\";\nimport { rollupEpochKey, rollupEpochScanPrefix, rollupScanPrefix, rollupUsageKey } from \"./keys.js\";\n\nexport type UsageAccumulatorKey = {\n readonly sessionId: string;\n readonly scope: string;\n readonly scopeKey: string;\n};\n\nexport type UsageAccumulatorSnapshot = {\n readonly total: CanonicalUsage;\n /** Increments every time {@link UsageAccumulator.recordReset} is called for this key. */\n readonly epoch: number;\n};\n\nexport type RollupCleanupResult = { readonly removed: number; readonly scanned: number };\n\n/**\n * Which delivery an accumulation belongs to, and which of its observations this is.\n *\n * Supplying it makes the accumulation idempotent for *that delivery*: a second\n * application of the same `(callbackId, ordinal)` is a no-op that returns the\n * current total. Omitting it keeps the old unconditional behaviour, which is right\n * for a caller that has no delivery identity to key on — there is nothing to\n * recognize a repeat by, and refusing to accumulate would lose a real observation.\n *\n * `callbackId` must be an opaque digest, not a raw host or provider id: it is\n * written into a state record.\n */\nexport type DeliveryStamp = {\n readonly callbackId: string;\n /** Zero-based index of this observation within the delivery, per rollup key. */\n readonly ordinal: number;\n};\n\nexport type AccumulateOptions = { readonly delivery?: DeliveryStamp };\n\n/**\n * Rolls a stream of `delta` usage observations up into a running `cumulative`\n * total per scope, independent of the orchestrator's own per-scope\n * cumulative-to-delta baseline (`docs/usage-semantics.md`) — that baseline\n * answers \"what changed since last time\"; this answers \"what is the running\n * total\", which a diagnostics view or a parent scope (tool -> generation ->\n * session) needs and the core does not compute.\n *\n * A provider counter can restart mid-session (a process restart, a replayed\n * transcript). Rather than let a smaller cumulative total silently deflate the\n * running rollup, {@link UsageAccumulator.recordReset} starts a new epoch: the\n * total resets to zero and the epoch number increments, so a downstream\n * consumer can tell \"the counter restarted\" from \"usage actually decreased\"\n * and never sums across the boundary as if it were one continuous series.\n */\nexport interface UsageAccumulator {\n /**\n * Fold `delta` into the running total for `key`.\n *\n * With `options.delivery`, folding is idempotent for that delivery: a redelivered\n * callback whose claim was reclaimed or superseded re-derives the same delta and\n * would otherwise count it twice. The marker lives in the same record as the total\n * it describes, so the check and the write are one atomic operation — which is the\n * only reason this is expressible without a multi-key transaction. What it does\n * *not* cover is a delivery whose marker a later, different delivery has since\n * overwritten: only the most recent delivery per rollup key is recognizable, which\n * is exactly the retry window and nothing beyond it.\n */\n accumulateDelta(\n key: UsageAccumulatorKey,\n delta: CanonicalUsage,\n options?: AccumulateOptions,\n ): Promise<UsageAccumulatorSnapshot>;\n /** Start a new epoch. Idempotent per delivery when `options.delivery` is given. */\n recordReset(key: UsageAccumulatorKey, options?: AccumulateOptions): Promise<{ readonly epoch: number }>;\n read(key: UsageAccumulatorKey): Promise<UsageAccumulatorSnapshot | undefined>;\n cleanup(\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<RollupCleanupResult>;\n}\n\nexport type UsageAccumulatorDependencies = {\n readonly stateStore: StateStore;\n readonly clock: Clock;\n};\n\nconst EMPTY_CUMULATIVE_USAGE: CanonicalUsage = normalizeUsageOrThrow({ temporality: \"cumulative\" });\n\nconst combineCumulativeWithDelta = (total: CanonicalUsage, delta: CanonicalUsage): CanonicalUsage => {\n if (total.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"usage rollup total must have cumulative temporality\" },\n ]);\n }\n if (delta.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"usage accumulator only accepts delta observations\" },\n ]);\n }\n\n const accounting =\n total.cacheCreationInputTokens === 0 && total.cacheCreationAccounting === \"not-reported\"\n ? delta.cacheCreationAccounting\n : delta.cacheCreationInputTokens === 0 && delta.cacheCreationAccounting === \"not-reported\"\n ? total.cacheCreationAccounting\n : total.cacheCreationAccounting;\n\n if (\n total.cacheCreationInputTokens !== 0 &&\n delta.cacheCreationInputTokens !== 0 &&\n total.cacheCreationAccounting !== delta.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot roll up usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n total.providerTotalTokens === undefined && delta.providerTotalTokens === undefined\n ? undefined\n : (total.providerTotalTokens ?? 0) + (delta.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"cumulative\",\n inputTokens: total.inputTokens + delta.inputTokens,\n cachedInputTokens: total.cachedInputTokens + delta.cachedInputTokens,\n cacheCreationInputTokens: total.cacheCreationInputTokens + delta.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: total.outputTokens + delta.outputTokens,\n reasoningOutputTokens: total.reasoningOutputTokens + delta.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n\nexport const createUsageAccumulator = (deps: UsageAccumulatorDependencies): UsageAccumulator => {\n const { stateStore, clock } = deps;\n\n /**\n * The epoch record's own delivery marker.\n *\n * Kept in the epoch record for the same reason the total's marker is kept in the\n * total: one write, so the counter and the statement about who moved it cannot\n * disagree. The epoch record is an `attributes` value, so the two fields are\n * flat rather than nested.\n */\n const readEpochMarker = (\n attributes: Attributes,\n ): { readonly callbackId: string; readonly applications: number } | undefined => {\n const callbackId = attributes.resetDelivery;\n const applications = attributes.resetApplications;\n if (\n typeof callbackId !== \"string\" ||\n callbackId.length === 0 ||\n typeof applications !== \"number\" ||\n !Number.isInteger(applications) ||\n applications < 1\n ) {\n return undefined;\n }\n return { callbackId, applications };\n };\n\n const readEpoch = async (key: UsageAccumulatorKey): Promise<number> => {\n const record = await stateStore.read(rollupEpochKey(key.sessionId, key.scope, key.scopeKey));\n if (record?.value.kind === \"attributes\" && typeof record.value.attributes.epoch === \"number\") {\n return record.value.attributes.epoch;\n }\n return 0;\n };\n\n /**\n * Whether this delivery's observation number `ordinal` is already folded in.\n *\n * The comparison is `<` rather than `===` because observations are applied in\n * order: `applications` is the count folded in so far, so any ordinal below it has\n * been seen. A marker naming a *different* delivery means this rollup has moved on\n * and nothing can be recognized.\n */\n const alreadyApplied = (\n marker: { readonly callbackId: string; readonly applications: number } | undefined,\n delivery: DeliveryStamp | undefined,\n ): boolean =>\n delivery !== undefined &&\n marker !== undefined &&\n marker.callbackId === delivery.callbackId &&\n delivery.ordinal < marker.applications;\n\n const markerFor = (\n delivery: DeliveryStamp | undefined,\n ): { readonly appliedDelivery?: { readonly callbackId: string; readonly applications: number } } =>\n delivery === undefined\n ? {}\n : {\n appliedDelivery: { callbackId: delivery.callbackId, applications: delivery.ordinal + 1 },\n };\n\n const accumulateDelta = (\n key: UsageAccumulatorKey,\n delta: CanonicalUsage,\n options?: AccumulateOptions,\n ): Promise<UsageAccumulatorSnapshot> =>\n withOptionalSessionLock(stateStore, key.sessionId, async (): Promise<UsageAccumulatorSnapshot> => {\n const usageKey = rollupUsageKey(key.sessionId, key.scope, key.scopeKey);\n const existing = await stateStore.read(usageKey);\n const previousTotal =\n existing?.value.kind === \"usage-cumulative\" ? existing.value.usage : EMPTY_CUMULATIVE_USAGE;\n\n if (\n existing?.value.kind === \"usage-cumulative\" &&\n alreadyApplied(existing.value.appliedDelivery, options?.delivery)\n ) {\n // This exact observation of this exact delivery is already in the total.\n // Reporting the total unchanged is the honest answer: the caller asked for\n // the running figure after its delta, and that is what this is.\n return { total: previousTotal, epoch: await readEpoch(key) };\n }\n\n const total = combineCumulativeWithDelta(previousTotal, delta);\n await stateStore.write(usageKey, {\n kind: \"usage-cumulative\",\n usage: total,\n ...markerFor(options?.delivery),\n });\n return { total, epoch: await readEpoch(key) };\n });\n\n const recordReset = (\n key: UsageAccumulatorKey,\n options?: AccumulateOptions,\n ): Promise<{ readonly epoch: number }> =>\n withOptionalSessionLock(stateStore, key.sessionId, async (): Promise<{ readonly epoch: number }> => {\n const epochKey = rollupEpochKey(key.sessionId, key.scope, key.scopeKey);\n const existingEpoch = await stateStore.read(epochKey);\n const marker =\n existingEpoch?.value.kind === \"attributes\"\n ? readEpochMarker(existingEpoch.value.attributes)\n : undefined;\n\n if (alreadyApplied(marker, options?.delivery)) {\n // A replayed reset must not open a second epoch: the epoch number is what a\n // consumer uses to refuse summing across a counter restart, and inflating it\n // twice for one restart makes a real series look like two.\n return { epoch: await readEpoch(key) };\n }\n\n const epoch = (await readEpoch(key)) + 1;\n const applied = markerFor(options?.delivery).appliedDelivery;\n await stateStore.write(epochKey, {\n kind: \"attributes\",\n attributes: {\n epoch,\n ...(applied === undefined\n ? {}\n : { resetDelivery: applied.callbackId, resetApplications: applied.applications }),\n },\n });\n await stateStore.delete(rollupUsageKey(key.sessionId, key.scope, key.scopeKey));\n return { epoch };\n });\n\n const read = async (key: UsageAccumulatorKey): Promise<UsageAccumulatorSnapshot | undefined> => {\n const record = await stateStore.read(rollupUsageKey(key.sessionId, key.scope, key.scopeKey));\n if (record?.value.kind !== \"usage-cumulative\") {\n return undefined;\n }\n return { total: record.value.usage, epoch: await readEpoch(key) };\n };\n\n const cleanup = async (\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<RollupCleanupResult> => {\n const cap = options?.maxEntries ?? 1_000;\n const now = clock.now();\n let removed = 0;\n let scanned = 0;\n\n const sweep = async (keys: readonly string[]): Promise<void> => {\n for (const key of keys) {\n if (scanned >= cap) {\n return;\n }\n scanned += 1;\n const record = await stateStore.read(key);\n if (record !== undefined && now - record.updatedAt > maxAgeMillis) {\n await stateStore.delete(key);\n removed += 1;\n }\n }\n };\n\n await sweep(await stateStore.keys(rollupScanPrefix(options?.sessionId)));\n await sweep(await stateStore.keys(rollupEpochScanPrefix(options?.sessionId)));\n return { removed, scanned };\n };\n\n return { accumulateDelta, recordReset, read, cleanup };\n};\n","import type { CallbackDeduplicator } from \"./dedup.js\";\nimport type { SpanCorrelator } from \"./span-correlator.js\";\nimport type { UsageAccumulator } from \"./usage-accumulator.js\";\n\nconst DEFAULT_MAX_AGE_MILLIS = 24 * 60 * 60 * 1000;\nconst DEFAULT_MAX_ENTRIES_PER_COMPONENT = 1_000;\n\nexport type LifecycleJanitorOptions = {\n readonly spanCorrelator?: SpanCorrelator;\n readonly deduplicator?: CallbackDeduplicator;\n readonly usageAccumulator?: UsageAccumulator;\n readonly spanMaxAgeMillis?: number;\n readonly dedupMaxAgeMillis?: number;\n /**\n * Floor on how long an uncommitted delivery claim survives the sweep, whatever\n * `dedupMaxAgeMillis` says.\n *\n * Passed through rather than left to the deduplicator's default so it can be the\n * *effective* window the runtime computed, which is raised from the requested one\n * to cover a process's whole export budget. A sweep using a smaller number than\n * the claim path uses would delete claims the claim path still considers live.\n */\n readonly dedupStaleClaimMillis?: number;\n readonly usageMaxAgeMillis?: number;\n /** Caps how many keys any single component scans per sweep. */\n readonly maxEntriesPerComponent?: number;\n};\n\nexport type LifecycleSweepStats = {\n readonly removed: number;\n readonly scanned: number;\n /**\n * Span records dropped with a start and no end — spans that were never\n * exported. Reported only by the span sweep; see `SpanCleanupResult`.\n */\n readonly expiredOpen?: number;\n /**\n * Aged-out records kept back because they are delivery claims a live process may\n * still hold. Reported only by the dedup sweep; see `DedupCleanupResult`.\n */\n readonly retainedInFlight?: number;\n};\n\nexport type LifecycleCleanupReport = {\n readonly span?: LifecycleSweepStats;\n readonly dedup?: LifecycleSweepStats;\n readonly usage?: LifecycleSweepStats;\n};\n\n/**\n * Fans a single bounded cleanup pass out across whichever lifecycle\n * components are configured.\n *\n * Each component already bounds its own sweep (`maxEntries`); this exists so\n * a caller — a CLI subcommand, a periodic timer, an opportunistic call at the\n * end of `flush()` — can run \"the\" cleanup without wiring each component by\n * hand, and so the bound is enforced uniformly rather than per call site.\n */\nexport interface LifecycleJanitor {\n runOnce(sessionId?: string): Promise<LifecycleCleanupReport>;\n}\n\nexport const createLifecycleJanitor = (options: LifecycleJanitorOptions): LifecycleJanitor => {\n const maxEntries = options.maxEntriesPerComponent ?? DEFAULT_MAX_ENTRIES_PER_COMPONENT;\n const spanMaxAge = options.spanMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;\n const dedupMaxAge = options.dedupMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;\n const usageMaxAge = options.usageMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;\n\n const runOnce = async (sessionId?: string): Promise<LifecycleCleanupReport> => {\n const scope = { maxEntries, ...(sessionId === undefined ? {} : { sessionId }) };\n const [span, dedup, usage] = await Promise.all([\n options.spanCorrelator?.cleanup(spanMaxAge, scope),\n // Deduplication is deliberately swept across every scope rather than the\n // ending session's: a delivery scope is a host-chosen namespace or a\n // digest of provider/installation/session, never a session id, so scoping\n // this sweep by `sessionId` would match nothing and let records accumulate\n // forever. The sweep is TTL-driven and still bounded by `maxEntries`.\n options.deduplicator?.cleanup(dedupMaxAge, {\n maxEntries,\n ...(options.dedupStaleClaimMillis === undefined\n ? {}\n : { staleClaimMillis: options.dedupStaleClaimMillis }),\n }),\n options.usageAccumulator?.cleanup(usageMaxAge, scope),\n ]);\n return {\n ...(span === undefined ? {} : { span }),\n ...(dedup === undefined ? {} : { dedup }),\n ...(usage === undefined ? {} : { usage }),\n };\n };\n\n return { runOnce };\n};\n"],"mappings":";AAAA,SAAS,mBAAmB;;;ACqDrB,IAAM,sBAAsB,CAAC,UAClC,OAAQ,MAAqC,oBAAoB;AAG5D,IAAM,0BAA0B,OACrC,OACA,WACA,IACA,YACe;AACf,MAAI,oBAAoB,KAAK,GAAG;AAC9B,WAAO,MAAM,gBAAgB,WAAW,IAAI,OAAO;AAAA,EACrD;AACA,SAAO,GAAG;AACZ;;;ACxDO,IAAM,mBAAmB;AAUzB,IAAM,mBAAmB;AASzB,IAAM,oBAAoB;AAgBjC,IAAM,gBAAgB,CAAC,YACrB,QAAQ,WAAW,KAAK,KAAK,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AM,QAAQ,IAAI;AAAA,MAC7C,QAAQ,gBAAgB,QAAQ,YAAY,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAMjD,QAAQ,cAAc,QAAQ,aAAa;AAAA,QACzC;AAAA,QACA,GAAI,QAAQ,0BAA0B,SAClC,CAAC,IACD,EAAE,kBAAkB,QAAQ,sBAAsB;AAAA,MACxD,CAAC;AAAA,MACD,QAAQ,kBAAkB,QAAQ,aAAa,KAAK;AAAA,IACtD,CAAC;AACD,WAAO;AAAA,MACL,GAAI,SAAS,SAAY,CAAC,IAAI,EAAE,KAAK;AAAA,MACrC,GAAI,UAAU,SAAY,CAAC,IAAI,EAAE,MAAM;AAAA,MACvC,GAAI,UAAU,SAAY,CAAC,IAAI,EAAE,MAAM;AAAA,IACzC;AAAA,EACF;AAEA,SAAO,EAAE,QAAQ;AACnB;","names":["owner","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","event","event","event","result","event"]}
1
+ {"version":3,"sources":["../src/lifecycle/dedup.ts","../src/state/store.ts","../src/lifecycle/keys.ts","../src/model/primitives.ts","../src/telemetry/semconv.ts","../src/version.ts","../src/telemetry/export-identity.ts","../src/model/events.ts","../src/errors/taxonomy.ts","../src/model/content.ts","../src/model/extensions.ts","../src/model/identity.ts","../src/model/target.ts","../src/model/usage.ts","../src/model/version.ts","../src/lifecycle/span-correlator.ts","../src/lifecycle/usage-accumulator.ts","../src/lifecycle/metric-series.ts","../src/telemetry/metric-model.ts","../src/lifecycle/janitor.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\n\nimport type { Attributes } from \"../model/primitives.js\";\nimport type { Clock, StateRecord, StateStore } from \"../runtime/ports.js\";\nimport { withOptionalSessionLock } from \"../state/store.js\";\nimport { dedupKey, dedupScanPrefix, dedupScopeOf } from \"./keys.js\";\n\nexport type DedupCheckResult = {\n /** True when `callbackId` was already marked seen for this scope. */\n readonly duplicate: boolean;\n};\n\nexport type DedupCleanupResult = {\n readonly removed: number;\n readonly scanned: number;\n /**\n * Aged-out records the sweep deliberately kept because they are uncommitted\n * claims younger than the stale-claim window — a live process may still be\n * working on them.\n *\n * Reported rather than merely not-removed, because the two are indistinguishable\n * in `removed` and only one of them means \"retention is configured shorter than\n * this installation's own export budget\". Absent when nothing was retained.\n */\n readonly retainedInFlight?: number;\n};\n\n/**\n * What happened when a delivery tried to take ownership of a callback id.\n *\n * - `fresh`: nothing had this id. The caller owns it and must `commit`.\n * - `duplicate`: a previous delivery ran this callback to completion.\n * - `in-flight`: another delivery holds the id right now — a concurrent process,\n * or one that has not committed yet. Treated as a duplicate.\n * - `reclaimed`: a claim was abandoned long enough ago to be assumed dead, and\n * this delivery has taken it over. The caller owns it and must `commit`.\n */\nexport type DeliveryClaimOutcome = \"fresh\" | \"duplicate\" | \"in-flight\" | \"reclaimed\";\n\nexport type DeliveryClaimResult = {\n readonly outcome: DeliveryClaimOutcome;\n /** True for `duplicate` and `in-flight`: the caller must not export or account. */\n readonly duplicate: boolean;\n /** True for `fresh` and `reclaimed`: the caller owns the id and should commit. */\n readonly owned: boolean;\n /** How many deliveries have claimed this id, including this one. */\n readonly attempt: number;\n /** Age of the claim that was taken over. Present only for `reclaimed`. */\n readonly abandonedForMillis?: number;\n /**\n * Opaque proof that *this* delivery owns the claim. Present when `owned`.\n *\n * No floor computation can be proven exact, so the stale window may still be too\n * short for some real installation. Passing this back to {@link\n * CallbackDeduplicator.commit} turns that from a silent double-count into a\n * detected, reported condition: if a peer reclaimed the id in the meantime the\n * record carries a different token, and the commit refuses rather than\n * overwriting the peer's in-flight work.\n */\n readonly owner?: string;\n};\n\n/** Whether a commit actually took effect. */\nexport type DeliveryCommitResult = {\n readonly status: \"committed\" | \"superseded\";\n /** The attempt number recorded, for diagnostics. */\n readonly attempt: number;\n};\n\nexport type DeliveryClaimOptions = {\n /**\n * How long an uncommitted claim is respected before it is assumed to belong to\n * a process that died mid-flight. Default 60,000ms.\n */\n readonly staleClaimMillis?: number;\n};\n\n/**\n * Delivery guard: suppresses a redelivered callback while local state is intact.\n *\n * Deliberately not described as \"exactly-once\". This records intent and completion\n * in a local store; the collector it protects is a separate system with no shared\n * transaction, so a process killed between an accepted export and `commit` leaves a\n * callback that will be exported again. What this guarantees is that a redelivery\n * seen by a *live* store is suppressed, and that a crash is recoverable rather than\n * either silently lost or permanently blocked.\n *\n * Coding-agent hosts redeliver callbacks — a retried hook invocation, a\n * duplicated event, a replayed transcript — and a deterministic identity makes\n * the replay recomputable, but something still has to remember which identities\n * have already been handled. This is that memory: a bounded, TTL-swept set of\n * seen ids per scope, independent of what the id actually names.\n *\n * Ownership is two-phase on purpose. `claim` records an intent before the caller\n * exports anything and `commit` records completion afterwards, so the window\n * where a crash could produce a double export does not exist: a second delivery\n * arriving in that window sees `in-flight` and stands down. The cost of that\n * choice is that a process killed between the two leaves an uncommitted claim,\n * which is why an old one is reclaimable rather than permanent — permanent would\n * turn every crash into silently lost telemetry.\n */\nexport interface CallbackDeduplicator {\n /**\n * Single-phase check: marks the id complete immediately and reports whether it\n * had been seen. Retained for callers that have nothing to protect between the\n * check and the side effect; `claim`/`commit` is the stronger guarantee.\n */\n checkAndMark(scope: string, callbackId: string): Promise<DedupCheckResult>;\n /** Take ownership of a callback id before acting on it. */\n claim(\n scope: string,\n callbackId: string,\n options?: DeliveryClaimOptions,\n ): Promise<DeliveryClaimResult>;\n /**\n * Record that a claimed callback ran to completion.\n *\n * `owner` is the token {@link DeliveryClaimResult.owner} handed out. Supplied and\n * matching, the claim completes. Supplied and *not* matching, the claim has been\n * reclaimed by a peer while this delivery was still working, and the commit is\n * refused — reported as `\"superseded\"` so the caller can say so instead of\n * silently marking a callback handled that somebody else is mid-flight on.\n */\n commit(scope: string, callbackId: string, owner?: string): Promise<DeliveryCommitResult>;\n /**\n * Give up a claim without completing it, so the next delivery of the same\n * callback is treated as fresh instead of waiting out the stale window.\n */\n release(scope: string, callbackId: string): Promise<void>;\n /**\n * Drop dedup records older than `maxAgeMillis`.\n *\n * An uncommitted claim is held back until it is also older than\n * `staleClaimMillis`, whatever the retention says. Retention is an operator's\n * answer to \"how long should a handled callback stay recognizable\"; the stale\n * window is a statement about how long one process's own work can take. Deleting\n * a claim inside that window would hand the callback to a concurrent delivery as\n * *fresh* while the holder is still exporting it — a retention setting silently\n * converting suppression into a double export, which is the opposite of what\n * tightening retention looks like it does.\n */\n cleanup(\n maxAgeMillis: number,\n options?: {\n readonly maxEntries?: number;\n readonly sessionId?: string;\n /** Floor on how long an uncommitted claim survives. Default 60,000ms. */\n readonly staleClaimMillis?: number;\n },\n ): Promise<DedupCleanupResult>;\n}\n\nexport type CallbackDeduplicatorDependencies = {\n readonly stateStore: StateStore;\n readonly clock: Clock;\n};\n\nconst DEFAULT_STALE_CLAIM_MILLIS = 60_000;\n\ntype DedupState = \"claimed\" | \"completed\";\n\n/**\n * Read the recorded state of a dedup record.\n *\n * A record written by an older release carries only `seenAt`, which meant\n * \"handled\". Absent a `state` field it is therefore read as `completed`, so an\n * upgrade never resurrects a callback the previous version had already exported.\n */\nconst stateOf = (record: StateRecord | undefined): DedupState | undefined => {\n if (record?.value.kind !== \"attributes\") {\n return undefined;\n }\n const declared = record.value.attributes.state;\n if (declared === \"claimed\" || declared === \"completed\") {\n return declared;\n }\n return \"completed\";\n};\n\nconst attemptOf = (record: StateRecord | undefined): number => {\n if (record?.value.kind !== \"attributes\") {\n return 0;\n }\n const attempt = record.value.attributes.attempt;\n return typeof attempt === \"number\" && Number.isInteger(attempt) && attempt > 0 ? attempt : 1;\n};\n\nconst ownerOf = (record: StateRecord | undefined): string | undefined => {\n if (record?.value.kind !== \"attributes\") {\n return undefined;\n }\n const owner = record.value.attributes.owner;\n return typeof owner === \"string\" && owner.length > 0 ? owner : undefined;\n};\n\nconst newOwnerToken = (): string => randomBytes(12).toString(\"hex\");\n\nconst claimedAtOf = (record: StateRecord | undefined): number | undefined => {\n if (record?.value.kind !== \"attributes\") {\n return undefined;\n }\n const claimedAt = record.value.attributes.claimedAt;\n return typeof claimedAt === \"number\" ? claimedAt : record.updatedAt;\n};\n\nexport const createCallbackDeduplicator = (\n deps: CallbackDeduplicatorDependencies,\n): CallbackDeduplicator => {\n const { stateStore, clock } = deps;\n\n const write = (key: string, attributes: Attributes): Promise<unknown> =>\n stateStore.write(key, { kind: \"attributes\", attributes });\n\n const checkAndMark = (scope: string, callbackId: string): Promise<DedupCheckResult> =>\n withOptionalSessionLock(stateStore, scope, async (): Promise<DedupCheckResult> => {\n const key = dedupKey(scope, callbackId);\n const existing = await stateStore.read(key);\n if (existing?.value.kind === \"attributes\") {\n return { duplicate: true };\n }\n const now = clock.now();\n await write(key, {\n state: \"completed\",\n attempt: 1,\n claimedAt: now,\n seenAt: now,\n owner: newOwnerToken(),\n });\n return { duplicate: false };\n });\n\n const claim = (\n scope: string,\n callbackId: string,\n options?: DeliveryClaimOptions,\n ): Promise<DeliveryClaimResult> =>\n withOptionalSessionLock(stateStore, scope, async (): Promise<DeliveryClaimResult> => {\n const staleClaimMillis = options?.staleClaimMillis ?? DEFAULT_STALE_CLAIM_MILLIS;\n const key = dedupKey(scope, callbackId);\n const existing = await stateStore.read(key);\n const state = stateOf(existing);\n const now = clock.now();\n\n if (state === \"completed\") {\n return { outcome: \"duplicate\", duplicate: true, owned: false, attempt: attemptOf(existing) };\n }\n\n if (state === \"claimed\") {\n const claimedAt = claimedAtOf(existing) ?? now;\n const age = now - claimedAt;\n if (age <= staleClaimMillis) {\n return {\n outcome: \"in-flight\",\n duplicate: true,\n owned: false,\n attempt: attemptOf(existing),\n };\n }\n const attempt = attemptOf(existing) + 1;\n const owner = newOwnerToken();\n await write(key, { state: \"claimed\", attempt, claimedAt: now, owner });\n return {\n outcome: \"reclaimed\",\n duplicate: false,\n owned: true,\n attempt,\n abandonedForMillis: age,\n owner,\n };\n }\n\n const owner = newOwnerToken();\n await write(key, { state: \"claimed\", attempt: 1, claimedAt: now, owner });\n return { outcome: \"fresh\", duplicate: false, owned: true, attempt: 1, owner };\n });\n\n const commit = (\n scope: string,\n callbackId: string,\n owner?: string,\n ): Promise<DeliveryCommitResult> =>\n withOptionalSessionLock(stateStore, scope, async (): Promise<DeliveryCommitResult> => {\n const key = dedupKey(scope, callbackId);\n const existing = await stateStore.read(key);\n const now = clock.now();\n const attempt = Math.max(attemptOf(existing), 1);\n\n const recordedOwner = ownerOf(existing);\n if (owner !== undefined && recordedOwner !== undefined && recordedOwner !== owner) {\n // A peer reclaimed this id while we were still working, which means the\n // stale window was shorter than this installation's real worst case.\n // Completing it now would tell that peer's delivery to stand down after it\n // has already exported. Refusing is the honest answer, and being able to\n // say so is the point of the token: no floor computation can be proven\n // exact, so the failure has to be detectable rather than merely unlikely.\n return { status: \"superseded\", attempt };\n }\n\n await write(key, {\n state: \"completed\",\n attempt,\n claimedAt: claimedAtOf(existing) ?? now,\n completedAt: now,\n seenAt: now,\n ...(recordedOwner === undefined ? {} : { owner: recordedOwner }),\n });\n return { status: \"committed\", attempt };\n });\n\n const release = (scope: string, callbackId: string): Promise<void> =>\n withOptionalSessionLock(stateStore, scope, async (): Promise<void> => {\n const key = dedupKey(scope, callbackId);\n // Only an uncommitted claim is droppable: releasing a completed record\n // would re-open a callback whose telemetry has already been exported.\n if (stateOf(await stateStore.read(key)) === \"claimed\") {\n await stateStore.delete(key);\n }\n });\n\n const cleanup = async (\n maxAgeMillis: number,\n options?: {\n readonly maxEntries?: number;\n readonly sessionId?: string;\n readonly staleClaimMillis?: number;\n },\n ): Promise<DedupCleanupResult> => {\n const keys = await stateStore.keys(dedupScanPrefix(options?.sessionId));\n const cap = options?.maxEntries ?? 1_000;\n const staleClaimMillis = options?.staleClaimMillis ?? DEFAULT_STALE_CLAIM_MILLIS;\n const now = clock.now();\n let removed = 0;\n let scanned = 0;\n let retainedInFlight = 0;\n\n /** Whether this record may be dropped, counting a live claim as it goes. */\n const isDroppable = (record: StateRecord | undefined, count: boolean): boolean => {\n if (record === undefined || now - record.updatedAt <= maxAgeMillis) {\n return false;\n }\n if (stateOf(record) === \"claimed\") {\n const age = now - (claimedAtOf(record) ?? record.updatedAt);\n if (age <= staleClaimMillis) {\n if (count) {\n retainedInFlight += 1;\n }\n return false;\n }\n }\n return true;\n };\n\n for (const key of keys) {\n if (scanned >= cap) {\n break;\n }\n scanned += 1;\n\n // Unlocked first pass. It decides only whether this key is worth locking for,\n // which is what keeps a sweep of a mostly-live store from paying a lock\n // acquisition per record: the common answer is \"not aged out, leave it\".\n if (!isDroppable(await stateStore.read(key), true)) {\n continue;\n }\n\n const scope = dedupScopeOf(key);\n if (scope === undefined) {\n // A key from a previous layout version: unreachable by any current read, so\n // there is no claim to race and no scope to lock on.\n await stateStore.delete(key);\n removed += 1;\n continue;\n }\n\n // Locked second pass, because a peer's `claim` takes this same lock and may\n // have refreshed the record since the first read. Deciding once, outside the\n // lock, would let a sweep delete a claim written microseconds earlier — and the\n // concurrent redelivery would then read `fresh` and export a second time.\n await withOptionalSessionLock(stateStore, scope, async (): Promise<void> => {\n if (!isDroppable(await stateStore.read(key), false)) {\n return;\n }\n await stateStore.delete(key);\n removed += 1;\n });\n }\n\n return {\n removed,\n scanned,\n ...(retainedInFlight === 0 ? {} : { retainedInFlight }),\n };\n };\n\n return { checkAndMark, claim, commit, release, cleanup };\n};\n","import type { Clock, StateStore } from \"../runtime/ports.js\";\nimport { LockWaitTimeoutError } from \"./async-lock.js\";\n\n/**\n * A lock could not be acquired within its wait bound because somebody else holds\n * it.\n *\n * Distinct from \"the store is broken\" on purpose, and the distinction is\n * load-bearing for callers that guard a read-modify-write with it. Contention\n * means a peer is plausibly *inside* the critical section right now, so\n * proceeding unlocked would produce exactly the lost update the lock exists to\n * prevent. A store that cannot lock at all — an unwritable directory, a full\n * disk — protects nothing, because the state the lock guards is equally\n * unreachable; there proceeding is the fail-open answer and costs nothing.\n */\nexport class StateLockTimeoutError extends Error {\n public readonly lockKey: string;\n\n public constructor(key: string, timeoutMillis: number) {\n super(`state store lock wait for \"${key}\" exceeded ${String(timeoutMillis)}ms`);\n this.name = \"StateLockTimeoutError\";\n this.lockKey = key;\n }\n}\n\n/**\n * Whether a thrown value means \"somebody else holds the lock\".\n *\n * Also true for {@link LockWaitTimeoutError}, the in-process variant, which\n * carries a second warning for callers: a timed-out wait does not cancel the\n * queued critical section, so it may still run afterwards. A caller that treats\n * contention as \"retry unlocked\" would therefore risk running the section twice.\n */\nexport const isStateLockContention = (thrown: unknown): boolean =>\n thrown instanceof StateLockTimeoutError || thrown instanceof LockWaitTimeoutError;\n\n/**\n * Optional capability beyond the frozen {@link StateStore} contract: a\n * session-scoped lock a caller can use to make a multi-step read-modify-write\n * atomic across an entire session, not just a single key.\n *\n * Deliberately keyed by an explicit `sessionId` the caller already knows,\n * rather than derived by parsing the store's own keys, so a store never has\n * to understand any particular key scheme.\n */\nexport interface LockingStateStore extends StateStore {\n withSessionLock<T>(\n sessionId: string,\n fn: () => Promise<T>,\n options?: { readonly timeoutMillis?: number },\n ): Promise<T>;\n}\n\nexport const isLockingStateStore = (store: StateStore): store is LockingStateStore =>\n typeof (store as Partial<LockingStateStore>).withSessionLock === \"function\";\n\n/** Runs `fn` under the store's session lock when it has one; otherwise runs it directly. */\nexport const withOptionalSessionLock = async <T>(\n store: StateStore,\n sessionId: string,\n fn: () => Promise<T>,\n options?: { readonly timeoutMillis?: number },\n): Promise<T> => {\n if (isLockingStateStore(store)) {\n return store.withSessionLock(sessionId, fn, options);\n }\n return fn();\n};\n\nexport type StateStoreDependencies = {\n readonly clock: Clock;\n};\n","/**\n * State key namespaces for lifecycle bookkeeping.\n *\n * Prefixed with `lifecycle:` so these keys can never collide with the\n * orchestrator's own `sequence:<sessionId>` and `usage:<sessionId>:...` keys\n * in the same {@link StateStore}, even though both share the store.\n *\n * Two properties are load-bearing here, because the store hashes a *whole\n * logical key* into one record: keys must be unambiguous, and a key space whose\n * layout changes must not be readable under its old meaning.\n */\nexport const LIFECYCLE_PREFIX = \"lifecycle\";\n\n/**\n * Layout version of the span key space.\n *\n * Bumped when the *segments* change, not when a record's contents do — that is\n * {@link SPAN_RECORD_VERSION}'s job. Version 2 inserted the provider segment,\n * so a v1 key must never be reachable: reading one would pair a span across\n * providers, which is exactly the attribution guess this library refuses.\n */\nexport const SPAN_KEY_VERSION = 2;\n\n/**\n * Layout version of the dedup key space.\n *\n * Version 2 re-scoped these keys from a session id to a delivery scope. The two\n * spaces are not interchangeable — a v1 key found under a v2 read would suppress\n * an unrelated callback — so the version segment keeps them disjoint.\n */\nexport const DEDUP_KEY_VERSION = 2;\n\n/**\n * Make a variable segment unambiguous within a `:`-delimited key.\n *\n * Without this, `dedupKey(\"a:b\", \"c\")` and `dedupKey(\"a\", \"b:c\")` produce the\n * identical logical key, and the store hashes both to one record — so one\n * delivery silently suppresses an unrelated one. That is reachable input, not a\n * theoretical one: `--callback-scope` is host-supplied, and a provider's session\n * or tool-call id is not required to avoid a colon.\n *\n * `%` is escaped first so the encoding stays injective, which makes this a true\n * bijection on segments rather than a lossy scrub. A segment containing neither\n * character encodes to itself, so keys already on disk keep their identity and\n * no cumulative baseline is reset by adopting this.\n */\nconst encodeSegment = (segment: string): string =>\n segment.replaceAll(\"%\", \"%25\").replaceAll(\":\", \"%3A\");\n\n/**\n * Session first, then provider: the janitor sweeps a whole session by prefix,\n * so the session segment has to lead. The provider segment below it is what\n * makes cross-provider pairing impossible by construction rather than only by\n * the runtime check in the span correlator.\n */\nexport const spanKey = (\n sessionId: string,\n providerId: string,\n scope: string,\n scopeKey: string,\n): string =>\n `${spanScanPrefix(sessionId)}${encodeSegment(providerId)}:${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;\n\n/**\n * The session-scoped prefix names one layout version; the bare prefix names\n * every one of them. That asymmetry is deliberate: a sweep must be able to\n * reclaim records written by a previous version, which a versioned prefix could\n * never match, while a *read* must never reach across a layout change.\n */\nexport const spanScanPrefix = (sessionId?: string): string =>\n sessionId === undefined\n ? `${LIFECYCLE_PREFIX}:span:`\n : `${LIFECYCLE_PREFIX}:span:v${String(SPAN_KEY_VERSION)}:${encodeSegment(sessionId)}:`;\n\n/**\n * Dedup keys are scoped by a *delivery scope*, not by a session id.\n *\n * A host-supplied delivery id carries its own namespace, and a provider-derived\n * one is scoped by a digest of provider, installation, and session — so neither\n * is a session id, and neither can be found by scanning for one.\n */\nexport const dedupKey = (scope: string, callbackId: string): string =>\n `${dedupScanPrefix(scope)}${encodeSegment(callbackId)}`;\n\nexport const dedupScanPrefix = (scope?: string): string =>\n scope === undefined\n ? `${LIFECYCLE_PREFIX}:dedup:`\n : `${LIFECYCLE_PREFIX}:dedup:v${String(DEDUP_KEY_VERSION)}:${encodeSegment(scope)}:`;\n\nconst decodeSegment = (segment: string): string =>\n segment.replaceAll(\"%3A\", \":\").replaceAll(\"%25\", \"%\");\n\n/**\n * Recover the delivery scope a dedup key belongs to.\n *\n * Needed by the sweep and nothing else. A sweep enumerates keys rather than being\n * handed a scope, but deleting a dedup record is a read-modify-write against the\n * same record a concurrent `claim` is deciding on — so the sweep has to take the\n * same per-scope lock, and to take it, it has to know the scope. Recovering it\n * from the key is safe precisely because {@link encodeSegment} is injective.\n *\n * Returns `undefined` for a key from a previous layout version, which no lock\n * protects because no current read can reach it.\n */\nexport const dedupScopeOf = (key: string): string | undefined => {\n const prefix = `${LIFECYCLE_PREFIX}:dedup:v${String(DEDUP_KEY_VERSION)}:`;\n if (!key.startsWith(prefix)) {\n return undefined;\n }\n // Exactly two segments follow the prefix, and neither can contain a raw `:`,\n // so the first `:` after the prefix is unambiguously the boundary.\n const rest = key.slice(prefix.length);\n const boundary = rest.indexOf(\":\");\n return boundary <= 0 ? undefined : decodeSegment(rest.slice(0, boundary));\n};\n\n/**\n * Usage rollup keys are escaped but deliberately *not* versioned: their layout\n * has not changed, and a version segment would orphan every cumulative token\n * baseline on disk — resetting usage accounting to fix a bug that escaping\n * already fixes.\n */\nexport const rollupUsageKey = (sessionId: string, scope: string, scopeKey: string): string =>\n `${rollupScanPrefix(sessionId)}${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;\n\nexport const rollupEpochKey = (sessionId: string, scope: string, scopeKey: string): string =>\n `${rollupEpochScanPrefix(sessionId)}${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;\n\nexport const rollupScanPrefix = (sessionId?: string): string =>\n sessionId === undefined\n ? `${LIFECYCLE_PREFIX}:usage:`\n : `${LIFECYCLE_PREFIX}:usage:${encodeSegment(sessionId)}:`;\n\nexport const rollupEpochScanPrefix = (sessionId?: string): string =>\n sessionId === undefined\n ? `${LIFECYCLE_PREFIX}:epoch:`\n : `${LIFECYCLE_PREFIX}:epoch:${encodeSegment(sessionId)}:`;\n\n/**\n * Metric series state (issue #69): one record per series, under the provider\n * session it belongs to so the janitor can sweep a session's series with the rest\n * of its state. The scope segment is `s=<sessionId>` for a per-session series and\n * `all` for one that spans sessions (`session.id` switched off); the `s=` prefix\n * keeps the two from ever colliding, whatever a provider names its sessions.\n *\n * `seriesDigest` is a digest of the instrument and its attributes, never the\n * attributes themselves.\n */\nexport const metricSeriesKey = (sessionScope: string, seriesDigest: string): string =>\n `${metricSeriesScanPrefix(sessionScope)}${encodeSegment(seriesDigest)}`;\n\nexport const metricSeriesScanPrefix = (sessionScope?: string): string =>\n sessionScope === undefined\n ? `${LIFECYCLE_PREFIX}:metric:v1:`\n : `${LIFECYCLE_PREFIX}:metric:v1:${encodeSegment(sessionScope)}:`;\n","import { 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 { createHash } from \"node:crypto\";\n\nimport { SpanKind, SpanStatusCode, TraceFlags, type Attributes, type SpanContext, type SpanStatus } from \"@opentelemetry/api\";\nimport { millisToHrTime } from \"@opentelemetry/core\";\nimport type { InstrumentationScope } from \"@opentelemetry/core\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport type { ReadableSpan } from \"@opentelemetry/sdk-trace\";\nimport {\n ATTR_ERROR_TYPE,\n ATTR_GEN_AI_OPERATION_NAME,\n ATTR_GEN_AI_REQUEST_MODEL,\n ATTR_GEN_AI_RESPONSE_MODEL,\n ATTR_GEN_AI_SYSTEM,\n ATTR_GEN_AI_TOOL_CALL_ID,\n ATTR_GEN_AI_TOOL_NAME,\n ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n} from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport type { CanonicalEvent, CanonicalEventType } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\nimport { VERSION } from \"../version.js\";\nimport {\n ATTR_OTELHOOK_TARGET_REPOSITORY_ID,\n ATTR_OTELHOOK_TARGET_SOURCE,\n ATTR_OTELHOOK_TARGET_WORKSPACE_ID,\n ATTR_OTELHOOK_TARGET_WORKTREE_KIND,\n ATTR_VCS_REF_HEAD_NAME,\n exportIdentityAttributes,\n passthroughResourceAttributes,\n targetAttributes,\n usageTemporalityAttributes,\n} from \"./export-identity.js\";\n\nconst SCOPE_NAME = \"@osfactory/otel-hook\";\n\nexport const DEFAULT_INSTRUMENTATION_SCOPE: InstrumentationScope = Object.freeze({\n name: SCOPE_NAME,\n version: VERSION,\n});\n\nconst ATTR_OTELHOOK_SPAN_PAIRED = \"otelhook.span.paired\";\nconst ATTR_OTELHOOK_SPAN_PAIRING = \"otelhook.span.pairing\";\nconst ATTR_OTELHOOK_SPAN_ORPHAN = \"otelhook.span.orphan\";\nconst ATTR_OTELHOOK_OUTCOME = \"otelhook.outcome\";\nconst ATTR_OTELHOOK_RESET_DETECTED = \"otelhook.usage.reset_detected\";\n/** True when a generation's usage covers only part of it; see `generation.end.usagePartial`. */\nexport const ATTR_OTELHOOK_USAGE_PARTIAL = \"otelhook.usage.partial\";\nconst ATTR_OTELHOOK_TOOL_KIND = \"otelhook.tool.kind\";\nconst ATTR_OTELHOOK_DELEGATION_DEPTH = \"otelhook.delegation_depth\";\nconst ATTR_OTELHOOK_COMPACTION_TRIGGER = \"otelhook.compaction.trigger\";\nconst ATTR_OTELHOOK_AGENT_NAME = \"otelhook.agent.name\";\nconst ATTR_OTELHOOK_AGENT_VERSION = \"otelhook.agent.version\";\nconst ATTR_OTELHOOK_GENERATION_ID = \"otelhook.generation.id\";\n\n/**\n * Pure, stateless canonical-event-to-span mapping.\n *\n * Isolated in one module so every other piece of the telemetry pipeline\n * — batching, retry, spooling — can change without touching what an attribute\n * means. Two edges of the same lifecycle scope are merged into one span when\n * they appear in the same batch; when they arrive in *different* short-lived\n * hook processes they are merged through a {@link SpanCorrelation} the caller\n * resolved from persisted state. Either way the mapping itself stays a pure\n * function: state is read by the correlator, never by this module.\n *\n * ## Identity of a span\n *\n * Trace and span ids are derived, never random, so two processes that never\n * meet still agree on them:\n *\n * - `traceId = H(providerId, sessionId)` — one trace per session per provider.\n * Deriving it from the session rather than the invocation is what lets a\n * `tool.end` emitted minutes later land in the same trace as its `tool.start`;\n * including the provider is what stops two providers that happen to reuse a\n * session id from being stitched into one trace.\n * - `spanId = H(providerId, sessionId, family, scopeKey)` — stable across\n * processes and idempotent under redelivery, so a collector that sees a\n * start-only span and later the completed span treats them as one span\n * rather than two.\n */\n// NUL, so joined parts cannot collide across a different split: no identifier\n// this library accepts can contain one, which a printable separator cannot\n// promise. Never emitted — only hashed, or used as an in-memory map key.\nconst FIELD_SEPARATOR = \"\\u0000\";\n\nconst digestHex = (parts: readonly string[], length: number): string =>\n createHash(\"sha256\").update(parts.join(FIELD_SEPARATOR)).digest(\"hex\").slice(0, length);\n\n/** Lifecycle scopes that pair a `*.start` edge with a later `*.end` edge. */\nexport type SpanFamily = \"session\" | \"generation\" | \"tool\" | \"subagent\";\n\n/** Identifies one lifecycle span within a session. */\nexport type SpanScopeRef = {\n readonly family: SpanFamily;\n readonly scopeKey: string;\n};\n\n/**\n * Why a lifecycle span is, or is not, a complete pair.\n *\n * Deliberately explicit rather than a bare boolean: \"we never saw the start\",\n * \"we saw it but it aged out of state\", and \"state could not be read at all\"\n * are different operational facts, and a dashboard that cannot tell them apart\n * cannot tell a broken host from a broken exporter.\n */\nexport type SpanOrphanClassification =\n /** Both edges are known — from this batch, or from persisted state. */\n | \"none\"\n /** The start is known; its end has not arrived yet. */\n | \"missing-end\"\n /** An end arrived and no start was ever recorded for this scope. */\n | \"missing-start\"\n /** A start was recorded but aged past the retention window before the end arrived. */\n | \"expired-start\"\n /** A start exists but was recorded by a different provider; pairing it would be a guess. */\n | \"provider-mismatch\"\n /** A second, distinct end arrived for a scope that was already closed. */\n | \"already-closed\"\n /** The persisted record was written by an incompatible version and was discarded. */\n | \"state-incompatible\"\n /** The persisted record could not be understood. */\n | \"state-corrupt\"\n /** State could not be consulted at all; the mapping degraded rather than failing. */\n | \"state-unavailable\";\n\nexport type SpanPairing =\n /** Both edges were present in this batch. */\n | \"in-batch\"\n /** The other edge came from state written by an earlier process. */\n | \"cross-process\"\n | \"unpaired\";\n\n/**\n * Whether this scope should produce an OTLP record now.\n *\n * OTLP has no notion of updating a span: a span is exported once, when it ends,\n * and a second record carrying the same trace and span id is not a revision of\n * the first — it is a duplicate that backends variously drop, keep the older of,\n * or display twice. Since every lifecycle span id here is *derived* from\n * `(provider, session, family, scopeKey)`, a `*.start` edge and its later `*.end`\n * edge compute the identical id, so exporting on both is precisely that\n * duplicate.\n *\n * `defer` is therefore the answer for a start whose end has not arrived: the\n * start is durable in the state store, and the end edge exports the one complete\n * span using the times recovered from it. Nothing is lost by waiting, and what is\n * gained is that the record a collector receives has a real duration.\n */\nexport type SpanDisposition =\n /** Export a record for this scope now. */\n | \"emit\"\n /** Hold: the start is recorded, and the end edge will export the complete span. */\n | \"defer\";\n\n/**\n * One scope's correlation facts, resolved from persisted state by the caller.\n *\n * Plain data on purpose: the telemetry layer must not reach into the state\n * store itself (ADR 0006), so it declares what it needs and the lifecycle layer\n * supplies it.\n */\nexport type SpanCorrelation = {\n readonly providerId: string;\n readonly sessionId: string;\n readonly ref: SpanScopeRef;\n readonly pairing: SpanPairing;\n readonly orphan: SpanOrphanClassification;\n /**\n * Whether to export a record for this scope now. Defaults to `emit` when a\n * correlation is supplied without one.\n */\n readonly disposition?: SpanDisposition;\n /**\n * Extra component mixed into the derived span id.\n *\n * Set only when this record is a genuinely *additional* observation of a scope\n * that has already been exported once — a second, distinct end for a scope that\n * was already closed. Both records are real, so neither is dropped, and the\n * discriminator keeps them from claiming the same span id.\n */\n readonly spanIdDiscriminator?: string;\n /** Start recovered from state; authoritative over the batch's own start edge. */\n readonly startMillis?: number;\n /** End recovered from state; authoritative so a redelivered end re-exports an identical span. */\n readonly endMillis?: number;\n /** Parent recorded at start time, so an end-only process hangs the span in the same place. */\n readonly parent?: SpanScopeRef;\n /** Attributes only the start edge could supply, recovered for an end-only span. */\n readonly attributes?: Attributes;\n};\n\n/**\n * Resolves persisted correlation for one batch.\n *\n * Must never reject: a state failure is a degraded span, never a lost export.\n */\nexport type SpanCorrelationResolver = (\n events: readonly CanonicalEvent[],\n) => Promise<readonly SpanCorrelation[]>;\n\n/**\n * Upper bound on how many start-edge attributes the correlator may carry\n * forward, so persisted state cannot grow with provider-controlled input.\n */\nexport const MAX_RECOVERED_START_ATTRIBUTES = 16;\n\nconst familyOf = (type: CanonicalEventType): SpanFamily | undefined => {\n switch (type) {\n case \"session.start\":\n case \"session.end\":\n return \"session\";\n case \"generation.start\":\n case \"generation.end\":\n return \"generation\";\n case \"tool.start\":\n case \"tool.end\":\n return \"tool\";\n case \"subagent.start\":\n case \"subagent.end\":\n return \"subagent\";\n default:\n return undefined;\n }\n};\n\n/** The lifecycle span an event is an edge of, or undefined for a point-in-time event. */\nexport const spanScopeRefOf = (event: CanonicalEvent): SpanScopeRef | undefined => {\n const family = familyOf(event.type);\n if (family === undefined) {\n return undefined;\n }\n switch (event.type) {\n case \"session.start\":\n case \"session.end\":\n return { family, scopeKey: event.sessionId };\n case \"generation.start\":\n case \"generation.end\":\n return { family, scopeKey: event.generationId };\n case \"tool.start\":\n case \"tool.end\":\n return { family, scopeKey: event.toolCallId };\n case \"subagent.start\":\n case \"subagent.end\":\n return { family, scopeKey: event.subagentInvocationId };\n default:\n return undefined;\n }\n};\n\n/**\n * Where a span hangs in the trace, judged from this event alone.\n *\n * Everything in a session descends from the session span. A tool call names its\n * generation only on `tool.start`, which is exactly why the correlator persists\n * the parent: the `tool.end` process would otherwise reparent the same span to\n * the session and produce a tree whose shape depends on which edge happened to\n * be exported last.\n */\nexport const parentScopeRefOf = (event: CanonicalEvent): SpanScopeRef | undefined => {\n if (event.type === \"session.start\" || event.type === \"session.end\") {\n return undefined;\n }\n if (event.type === \"tool.start\" && event.generationId !== undefined) {\n return { family: \"generation\", scopeKey: event.generationId };\n }\n return { family: \"session\", scopeKey: event.sessionId };\n};\n\n/**\n * Span attributes that only a `*.start` edge can supply.\n *\n * The correlator persists these verbatim so an end-only span in a later process\n * still carries the tool kind, requested model, delegation depth, or agent name\n * the start process saw. An allowlist, and bounded, so persisted state can\n * never become a second route for provider payload content to escape.\n */\nexport const startOnlySpanAttributes = (event: CanonicalEvent): Attributes => {\n switch (event.type) {\n // The session's own worktree is carried forward like a tool's target, so\n // the session span a later `session.end` process exports still names it.\n case \"session.start\":\n return {\n ...(event.agentName === undefined ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: event.agentName }),\n ...(event.agentVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_AGENT_VERSION]: event.agentVersion }),\n ...targetAttributes(event),\n };\n case \"generation.start\":\n return {\n [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId,\n ...(event.model.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: event.model.vendor }),\n };\n // `toolName` and `toolCallId` are on both tool edges, so they are not\n // start-only and persisting them would just pad every record.\n // The target is carried forward too: an end-only process may see a payload\n // with less to go on (no tool input), and the start's evidence still holds.\n case \"tool.start\":\n return { [ATTR_OTELHOOK_TOOL_KIND]: event.toolKind, ...targetAttributes(event) };\n case \"subagent.start\":\n return { [ATTR_OTELHOOK_DELEGATION_DEPTH]: event.delegationDepth };\n default:\n return {};\n }\n};\n\nconst deriveTraceId = (providerId: string, sessionId: string): string =>\n digestHex([\"otelhook/trace\", providerId, sessionId], 32);\n\nconst deriveSpanId = (providerId: string, sessionId: string, ref: SpanScopeRef): string =>\n digestHex([\"otelhook/span\", providerId, sessionId, ref.family, ref.scopeKey], 16);\n\nconst deriveStandaloneSpanId = (\n providerId: string,\n sessionId: string,\n eventType: string,\n eventId: string,\n): string => digestHex([\"otelhook/span\", providerId, sessionId, \"event\", eventType, eventId], 16);\n\nconst correlationKey = (providerId: string, sessionId: string, ref: SpanScopeRef): string =>\n [providerId, sessionId, ref.family, ref.scopeKey].join(FIELD_SEPARATOR);\n\nconst outcomeStatus = (outcome: string | undefined): SpanStatus => {\n if (outcome === undefined || outcome === \"ok\" || outcome === \"unknown\") {\n return { code: SpanStatusCode.UNSET };\n }\n if (outcome === \"cancelled\") {\n return { code: SpanStatusCode.UNSET };\n }\n return { code: SpanStatusCode.ERROR, message: outcome };\n};\n\nconst identityAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n ids: { readonly traceId: string; readonly spanId: string; readonly parentSpanId?: string },\n): Attributes => exportIdentityAttributes(event, resource, ids);\n\nconst usageAttributes = (usage: CanonicalUsage | undefined, resetDetected: boolean): Attributes => {\n if (usage === undefined) {\n return {};\n }\n return {\n [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: usage.inputTokens,\n [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: usage.outputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: usage.cachedInputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: usage.cacheCreationInputTokens,\n [ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]: usage.reasoningOutputTokens,\n ...usageTemporalityAttributes(usage),\n ...(resetDetected ? { [ATTR_OTELHOOK_RESET_DETECTED]: true } : {}),\n };\n};\n\n/** Evidence strength of a target source; see `targetSourceSchema`. */\nconst TARGET_SOURCE_RANK: Readonly<Record<string, number>> = Object.freeze({\n \"tool-path\": 3,\n \"shell-cwd\": 2,\n \"session-cwd\": 1,\n});\n\nconst TARGET_KEYS = [\n ATTR_OTELHOOK_TARGET_WORKSPACE_ID,\n ATTR_OTELHOOK_TARGET_SOURCE,\n ATTR_VCS_REF_HEAD_NAME,\n ATTR_OTELHOOK_TARGET_REPOSITORY_ID,\n ATTR_OTELHOOK_TARGET_WORKTREE_KIND,\n] as const;\n\nconst pickTarget = (attributes: Attributes): Attributes => {\n const picked: Attributes = {};\n for (const key of TARGET_KEYS) {\n if (attributes[key] !== undefined) {\n picked[key] = attributes[key];\n }\n }\n return picked;\n};\n\n/**\n * Drop the target keys so they can be re-chosen as one unit, keeping only what\n * the launcher put on the Resource (a `vcs.ref.head.name` passed through by\n * `exportIdentityAttributes`) as the fallback beneath the chosen target.\n */\nconst withoutTarget = (attributes: Attributes, resource: Resource): Attributes => {\n const rest: Attributes = { ...attributes };\n for (const key of TARGET_KEYS) {\n delete rest[key];\n }\n return { ...rest, ...pickTarget(passthroughResourceAttributes(resource)) };\n};\n\nconst rankOf = (candidate: Attributes): number => {\n const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];\n return typeof source === \"string\" && Object.hasOwn(TARGET_SOURCE_RANK, source)\n ? (TARGET_SOURCE_RANK[source] ?? 0)\n : 0;\n};\n\n/**\n * One span, one target: the strongest evidence among the recovered start,\n * the live start, and the live end — later wins a tie. A Cursor shell call's\n * start knows its `cwd` and its end does not; the span must keep the former,\n * not be downgraded to the workspace root by whichever edge exported last.\n */\nconst strongestTarget = (candidates: readonly Attributes[]): Attributes => {\n let best: Attributes = {};\n let bestRank = 0;\n for (const candidate of candidates) {\n const rank = rankOf(candidate);\n if (rank > 0 && rank >= bestRank) {\n best = candidate;\n bestRank = rank;\n }\n }\n return best;\n};\n\ntype SpanGroup = {\n readonly ref: SpanScopeRef;\n start?: CanonicalEvent;\n end?: CanonicalEvent;\n};\n\nconst buildSpanContext = (traceId: string, spanId: string): SpanContext => ({\n traceId,\n spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n});\n\nexport type ReadableSpanInput = {\n readonly name: string;\n readonly kind: SpanKind;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly attributes: Attributes;\n readonly status: SpanStatus;\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n};\n\n/** Reconstructs a {@link ReadableSpan} from plain, serializable fields. Used by the durable spool to replay a span it persisted earlier. */\nexport const assembleReadableSpan = (input: ReadableSpanInput): ReadableSpan => toReadableSpan(input);\n\nconst toReadableSpan = (input: ReadableSpanInput): ReadableSpan => {\n const startTime = millisToHrTime(input.startMillis);\n const endTime = millisToHrTime(Math.max(input.startMillis, input.endMillis));\n const duration = millisToHrTime(Math.max(0, input.endMillis - input.startMillis));\n return {\n name: input.name,\n kind: input.kind,\n spanContext: (): SpanContext => buildSpanContext(input.traceId, input.spanId),\n ...(input.parentSpanId === undefined\n ? {}\n : { parentSpanContext: buildSpanContext(input.traceId, input.parentSpanId) }),\n startTime,\n endTime,\n status: input.status,\n attributes: input.attributes,\n links: [],\n events: [],\n duration,\n ended: true,\n resource: input.resource,\n instrumentationScope: input.instrumentationScope,\n droppedAttributesCount: 0,\n droppedEventsCount: 0,\n droppedLinksCount: 0,\n };\n};\n\ntype ResolvedPairing = {\n readonly pairing: SpanPairing;\n readonly orphan: SpanOrphanClassification;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly parent: SpanScopeRef | undefined;\n readonly recovered: Attributes;\n};\n\nconst resolvePairing = (\n group: SpanGroup,\n anchor: CanonicalEvent,\n correlation: SpanCorrelation | undefined,\n): ResolvedPairing => {\n const inBatch = group.start !== undefined && group.end !== undefined;\n const batchStart = group.start?.occurredAt ?? anchor.occurredAt;\n const batchEnd = group.end?.occurredAt ?? anchor.occurredAt;\n\n if (correlation === undefined) {\n return {\n pairing: inBatch ? \"in-batch\" : \"unpaired\",\n orphan: inBatch ? \"none\" : group.start === undefined ? \"missing-start\" : \"missing-end\",\n startMillis: batchStart,\n endMillis: inBatch ? batchEnd : batchStart,\n parent: parentScopeRefOf(anchor),\n recovered: {},\n };\n }\n\n // A correlation that reports no start (an orphaned end) must not fabricate\n // one: the span collapses onto the end instant rather than claiming a\n // duration measured from an event nobody ever saw.\n const startMillis = correlation.startMillis ?? (inBatch ? batchStart : batchEnd);\n const endMillis = correlation.endMillis ?? (group.end === undefined ? startMillis : batchEnd);\n return {\n pairing: correlation.pairing,\n orphan: correlation.orphan,\n startMillis,\n endMillis,\n parent: correlation.parent ?? parentScopeRefOf(anchor),\n recovered: correlation.attributes ?? {},\n };\n};\n\nconst buildLifecycleSpan = (\n plan: GroupPlan,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan => {\n const group = plan.group;\n const anchor = plan.anchor;\n const correlation = plan.correlation;\n const providerId = anchor.provenance.providerId;\n const sessionId = anchor.sessionId;\n const resolved = resolvePairing(group, anchor, correlation);\n const traceId = plan.traceId;\n const spanId = plan.spanId;\n const parentSpanId =\n resolved.parent === undefined ? undefined : deriveSpanId(providerId, sessionId, resolved.parent);\n\n let name: string = group.ref.family;\n let kind: SpanKind = SpanKind.INTERNAL;\n let status: SpanStatus = { code: SpanStatusCode.UNSET };\n // Attributes recovered from the start process sit *beneath* whatever this\n // batch observed: a live edge always wins over a remembered one.\n let attributes: Attributes = {\n ...identityAttributes(anchor, resource, {\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n }),\n ...resolved.recovered,\n [ATTR_OTELHOOK_SPAN_PAIRED]: resolved.pairing !== \"unpaired\",\n [ATTR_OTELHOOK_SPAN_PAIRING]: resolved.pairing,\n [ATTR_OTELHOOK_SPAN_ORPHAN]: resolved.orphan,\n };\n\n switch (group.ref.family) {\n case \"session\": {\n const end = group.end?.type === \"session.end\" ? group.end : undefined;\n const start = group.start?.type === \"session.start\" ? group.start : undefined;\n name = \"session\";\n kind = SpanKind.INTERNAL;\n attributes = {\n ...withoutTarget(attributes, resource),\n ...strongestTarget([pickTarget(resolved.recovered), start === undefined ? {} : targetAttributes(start)]),\n ...(start?.agentName === undefined ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName }),\n ...(start?.agentVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion }),\n ...(end === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.reason }),\n ...usageAttributes(end?.usage, false),\n };\n if (end?.reason === \"error\" || end?.reason === \"timeout\") {\n status = { code: SpanStatusCode.ERROR, message: end.reason };\n }\n break;\n }\n case \"generation\": {\n const start = group.start?.type === \"generation.start\" ? group.start : undefined;\n const end = group.end?.type === \"generation.end\" ? group.end : undefined;\n const model = end?.model ?? start?.model;\n name = model === undefined ? \"generation\" : `generation ${model.modelId}`;\n kind = SpanKind.CLIENT;\n attributes = {\n ...attributes,\n [ATTR_GEN_AI_OPERATION_NAME]: \"chat\",\n ...(model?.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: model.vendor }),\n ...(start?.model?.modelId === undefined ? {} : { [ATTR_GEN_AI_REQUEST_MODEL]: start.model.modelId }),\n ...(end?.model?.modelId === undefined ? {} : { [ATTR_GEN_AI_RESPONSE_MODEL]: end.model.modelId }),\n // The provider's own id for this unit of work (Cursor generation,\n // Codex turn): the key a consumer stores a usage observation under.\n [ATTR_OTELHOOK_GENERATION_ID]: group.ref.scopeKey,\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...usageAttributes(end?.usage, false),\n ...(end?.usage === undefined || end.usagePartial === undefined\n ? {}\n : { [ATTR_OTELHOOK_USAGE_PARTIAL]: end.usagePartial }),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n case \"tool\": {\n const start = group.start?.type === \"tool.start\" ? group.start : undefined;\n const end = group.end?.type === \"tool.end\" ? group.end : undefined;\n const toolName = start?.toolName ?? end?.toolName ?? \"unknown\";\n name = `tool ${toolName}`;\n kind = SpanKind.CLIENT;\n attributes = {\n // Target keys are re-chosen below as one unit, never mixed across edges.\n ...withoutTarget(attributes, resource),\n [ATTR_GEN_AI_TOOL_NAME]: toolName,\n [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,\n ...(start?.toolKind === undefined ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind }),\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...strongestTarget([\n pickTarget(resolved.recovered),\n start === undefined ? {} : targetAttributes(start),\n end === undefined ? {} : targetAttributes(end),\n ]),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n case \"subagent\": {\n const start = group.start?.type === \"subagent.start\" ? group.start : undefined;\n const end = group.end?.type === \"subagent.end\" ? group.end : undefined;\n name = \"subagent\";\n kind = SpanKind.INTERNAL;\n attributes = {\n ...attributes,\n ...(start?.delegationDepth === undefined\n ? {}\n : { [ATTR_OTELHOOK_DELEGATION_DEPTH]: start.delegationDepth }),\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...usageAttributes(end?.usage, false),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n }\n\n if (status.code === SpanStatusCode.ERROR) {\n attributes = { ...attributes, [ATTR_ERROR_TYPE]: status.message ?? \"error\" };\n }\n\n return toReadableSpan({\n name,\n kind,\n startMillis: resolved.startMillis,\n endMillis: resolved.endMillis,\n attributes,\n status,\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n resource,\n instrumentationScope: scope,\n });\n};\n\nconst buildStandaloneSpan = (\n event: CanonicalEvent,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan => {\n const providerId = event.provenance.providerId;\n const traceId = deriveTraceId(providerId, event.sessionId);\n const spanId = deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId);\n const parent = parentScopeRefOf(event);\n const parentSpanId =\n parent === undefined ? undefined : deriveSpanId(providerId, event.sessionId, parent);\n let attributes: Attributes = {\n ...identityAttributes(event, resource, {\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n }),\n [ATTR_OTELHOOK_SPAN_PAIRED]: true,\n };\n let status: SpanStatus = { code: SpanStatusCode.UNSET };\n let name: string = event.type;\n\n switch (event.type) {\n case \"prompt.submitted\":\n name = \"prompt\";\n attributes = { ...attributes, \"otelhook.prompt.source\": event.promptSource, ...targetAttributes(event) };\n break;\n case \"compaction.performed\":\n name = \"compaction\";\n attributes = {\n ...attributes,\n [ATTR_OTELHOOK_COMPACTION_TRIGGER]: event.trigger,\n ...usageAttributes(event.usage, false),\n };\n break;\n case \"error.raised\":\n name = \"error\";\n status = { code: SpanStatusCode.ERROR, message: event.errorCode };\n attributes = {\n ...attributes,\n [ATTR_ERROR_TYPE]: event.errorCode,\n \"otelhook.error.phase\": event.phase,\n \"otelhook.error.retryable\": event.retryable,\n };\n break;\n default:\n break;\n }\n\n return toReadableSpan({\n name,\n kind: SpanKind.INTERNAL,\n startMillis: event.occurredAt,\n endMillis: event.occurredAt,\n attributes,\n status,\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n resource,\n instrumentationScope: scope,\n });\n};\n\nexport type SemanticMappingOptions = {\n readonly resource: Resource;\n readonly instrumentationScope?: InstrumentationScope;\n /**\n * Cross-process pairing facts, at most one entry per lifecycle scope in\n * `events`. Omitted entirely, the mapping degrades to in-batch pairing only —\n * the behavior of a host that wired no state store.\n */\n readonly correlations?: readonly SpanCorrelation[];\n /**\n * Whether a correlator was consulted at all, and whether it answered.\n *\n * This is what separates \"the state store is holding this start, so the end edge\n * will publish it\" from \"nothing recorded this start\". Both look like an empty\n * `correlations` list, and only the first is safe to drop — dropping the second\n * would discard an observation that was neither persisted nor exported, while a\n * caller that saw zero rejections went on to mark the callback handled.\n *\n * - `true` — the correlator ran; an absent or non-`defer` entry means emit.\n * - `false` — the correlator failed; every unpaired start is emitted as an\n * explicitly labelled, uniquely identified fallback.\n * - omitted — no correlator is wired, so cross-process pairing was never on\n * offer and an unpaired start is deferred (the documented no-state-root\n * degradation).\n */\n readonly correlationAvailable?: boolean;\n};\n\n/**\n * Fill in a correlation for an unpaired start that nothing recorded.\n *\n * Reached when a correlator was consulted and either failed outright or reported\n * nothing for this scope. The synthesized entry says what is true — the state was\n * not consulted successfully, so this span is unpaired and no end can complete it\n * — and carries a discriminator so the record cannot claim the span id a later end\n * will publish for the same scope.\n */\nconst effectiveCorrelation = (\n group: SpanGroup,\n correlation: SpanCorrelation | undefined,\n): SpanCorrelation | undefined => {\n if (correlation !== undefined || group.end !== undefined || group.start === undefined) {\n return correlation;\n }\n return {\n providerId: group.start.provenance.providerId,\n sessionId: group.start.sessionId,\n ref: group.ref,\n pairing: \"unpaired\",\n orphan: \"state-unavailable\",\n disposition: \"emit\",\n spanIdDiscriminator: group.start.eventId,\n };\n};\n\n/** How one batch's events distribute over the lifecycle scopes they are edges of. */\ntype BatchLayout = {\n readonly groups: ReadonlyMap<string, SpanGroup>;\n readonly standalone: readonly CanonicalEvent[];\n /** Event id of each lifecycle edge, mapped to the group key it belongs to. */\n readonly groupOf: ReadonlyMap<string, string>;\n};\n\nconst layoutBatch = (events: readonly CanonicalEvent[]): BatchLayout => {\n const groups = new Map<string, SpanGroup>();\n const standalone: CanonicalEvent[] = [];\n const groupOf = new Map<string, string>();\n\n for (const event of events) {\n const ref = spanScopeRefOf(event);\n if (ref === undefined) {\n standalone.push(event);\n continue;\n }\n const groupKey = correlationKey(event.provenance.providerId, event.sessionId, ref);\n const group: SpanGroup = groups.get(groupKey) ?? { ref };\n if (event.type.endsWith(\".start\")) {\n group.start = event;\n } else {\n group.end = event;\n }\n groups.set(groupKey, group);\n groupOf.set(event.eventId, groupKey);\n }\n return { groups, standalone, groupOf };\n};\n\nconst indexCorrelations = (\n correlations: readonly SpanCorrelation[] | undefined,\n): ReadonlyMap<string, SpanCorrelation> => {\n const indexed = new Map<string, SpanCorrelation>();\n for (const correlation of correlations ?? []) {\n indexed.set(\n correlationKey(correlation.providerId, correlation.sessionId, correlation.ref),\n correlation,\n );\n }\n return indexed;\n};\n\n/**\n * What this batch does with one lifecycle scope, decided once.\n *\n * Both the span mapping and the log mapping need the *same* answer to \"which\n * span id identifies this scope, and is a record for it going out now?\" — a log\n * record whose `spanContext` names a span id the exporter never published would\n * dangle at the collector. Computing it in one place is what keeps the two\n * signals pointing at the same span rather than at two plausible derivations of\n * it.\n */\ntype GroupPlan = {\n readonly group: SpanGroup;\n /** The event the span's identity and provenance are read from. */\n readonly anchor: CanonicalEvent;\n /**\n * False when the start is deferred: the state store is holding it and the end\n * edge will publish the one complete span, so nothing is exported for it now.\n */\n readonly emits: boolean;\n readonly correlation: SpanCorrelation | undefined;\n readonly traceId: string;\n readonly spanId: string;\n};\n\nconst planGroup = (\n group: SpanGroup,\n correlation: SpanCorrelation | undefined,\n correlationAvailable: boolean | undefined,\n): GroupPlan | undefined => {\n const anchor = group.start ?? group.end;\n if (anchor === undefined) {\n // Unreachable: a group exists only because an event was filed into it.\n return undefined;\n }\n const providerId = anchor.provenance.providerId;\n const sessionId = anchor.sessionId;\n\n // A start with no end in this batch is dropped **only** when something states\n // that it is durably recorded, because its span id is a pure function of the\n // scope: emitting here and again at the end edge would put two records with one\n // id on the wire, and OTLP has no update operation.\n //\n // `defer` is that statement, and it is the correlator's to make — it just wrote\n // the record. Anything else means nothing is holding this start, so dropping it\n // would lose an observation that was neither persisted nor exported, while the\n // caller saw zero rejections and marked the callback handled. Those are exported\n // under a discriminated span id instead.\n const durablyRecorded =\n group.end === undefined &&\n (correlation?.disposition === \"defer\" ||\n // No correlator wired at all: cross-process pairing was never on offer, so\n // this is the documented no-state-root degradation rather than a failure to\n // persist something that should have been persisted.\n (correlation === undefined && correlationAvailable === undefined));\n\n // A deferred start keeps the scope's *plain* span id, because that is the id the\n // end edge will publish. Only a record actually going out now may claim a\n // discriminated one.\n const effective = durablyRecorded ? correlation : effectiveCorrelation(group, correlation);\n const discriminator = durablyRecorded ? undefined : effective?.spanIdDiscriminator;\n\n return {\n group,\n anchor,\n emits: !durablyRecorded,\n correlation: effective,\n traceId: deriveTraceId(providerId, sessionId),\n spanId:\n discriminator === undefined\n ? deriveSpanId(providerId, sessionId, group.ref)\n : digestHex(\n [\n \"otelhook/span\",\n providerId,\n sessionId,\n group.ref.family,\n group.ref.scopeKey,\n discriminator,\n ],\n 16,\n ),\n };\n};\n\n/** Trace and span a record derived from one canonical event belongs to. */\nexport type EventTraceIdentity = {\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n};\n\n/**\n * Resolve the trace and span identity of every event in one batch.\n *\n * Exposed for signals other than traces — a log record correlates by carrying\n * the *same* derived ids the span mapping would compute, including the deferred\n * and discriminated cases. Whole batch at once because a start's identity\n * depends on whether its end is in the same batch.\n *\n * Both ids come from the event's own `(providerId, sessionId)`, never from a\n * batch-level or module-level value, which is what makes cross-session\n * contamination structurally impossible: two sessions in one batch derive two\n * different trace ids.\n */\nexport const canonicalEventTraceIdentities = (\n events: readonly CanonicalEvent[],\n options: {\n readonly correlations?: readonly SpanCorrelation[];\n readonly correlationAvailable?: boolean;\n } = {},\n): ReadonlyMap<string, EventTraceIdentity> => {\n const layout = layoutBatch(events);\n const correlations = indexCorrelations(options.correlations);\n const plans = new Map<string, GroupPlan>();\n for (const [groupKey, group] of layout.groups) {\n const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);\n if (plan !== undefined) {\n plans.set(groupKey, plan);\n }\n }\n\n const identities = new Map<string, EventTraceIdentity>();\n for (const event of events) {\n const providerId = event.provenance.providerId;\n const groupKey = layout.groupOf.get(event.eventId);\n const plan = groupKey === undefined ? undefined : plans.get(groupKey);\n if (plan === undefined) {\n const parent = parentScopeRefOf(event);\n identities.set(event.eventId, {\n traceId: deriveTraceId(providerId, event.sessionId),\n spanId: deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId),\n ...(parent === undefined\n ? {}\n : { parentSpanId: deriveSpanId(providerId, event.sessionId, parent) }),\n });\n continue;\n }\n const parent = plan.correlation?.parent ?? parentScopeRefOf(event);\n identities.set(event.eventId, {\n traceId: plan.traceId,\n spanId: plan.spanId,\n ...(parent === undefined\n ? {}\n : { parentSpanId: deriveSpanId(providerId, event.sessionId, parent) }),\n });\n }\n return identities;\n};\n\n/** Maps one invocation's canonical event batch into OTLP-ready spans. */\nexport const canonicalEventsToReadableSpans = (\n events: readonly CanonicalEvent[],\n options: SemanticMappingOptions,\n): readonly ReadableSpan[] => {\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const layout = layoutBatch(events);\n const correlations = indexCorrelations(options.correlations);\n\n const spans: ReadableSpan[] = [];\n for (const [groupKey, group] of layout.groups) {\n const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);\n if (plan === undefined || !plan.emits) {\n continue;\n }\n spans.push(buildLifecycleSpan(plan, options.resource, scope));\n }\n for (const event of layout.standalone) {\n spans.push(buildStandaloneSpan(event, options.resource, scope));\n }\n return spans;\n};\n","/**\n * Package version, kept in its own module so the CLI can report it without\n * importing the whole library barrel (and every provider adapter with it).\n *\n * Updated by `scripts/release/sync-version.mjs` during semantic-release.\n */\nexport const VERSION = \"0.11.0\";\n","import type { Attributes } from \"@opentelemetry/api\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport { ATTR_SESSION_ID } from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport { isTargetedEvent, type CanonicalEvent } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\n\n/**\n * W3C hex identity attributes on every log and span.\n *\n * Mission Control (and any consumer that decodes OTLP protobuf with a JSON\n * `toObject` that stringifies bytes as UTF-8) cannot recover a usable id from\n * the protobuf `trace_id` / `span_id` fields. These attributes are already hex\n * in the OpenTelemetry JS API; they are copied onto the attribute map so a\n * consumer never has to stringify binary ids.\n */\nexport const ATTR_TRACE_ID = \"trace_id\";\nexport const ATTR_SPAN_ID = \"span_id\";\nexport const ATTR_PARENT_SPAN_ID = \"parent_span_id\";\n\n/** Provider session id, kept when `session.id` is an externally supplied key. */\nexport const ATTR_OTELHOOK_SESSION_ID = \"otelhook.session.id\";\n/** Same provider session id under the gen_ai conversation attribute. */\nexport const ATTR_GEN_AI_CONVERSATION_ID = \"gen_ai.conversation.id\";\n\nexport const TRACE_ID_HEX_PATTERN = /^[0-9a-f]{32}$/;\nexport const SPAN_ID_HEX_PATTERN = /^[0-9a-f]{16}$/;\n\nconst ATTR_OTELHOOK_INVOCATION_ID = \"otelhook.invocation.id\";\nconst ATTR_OTELHOOK_PROVIDER_ID = \"otelhook.provider.id\";\nconst ATTR_OTELHOOK_PROVIDER_VERSION = \"otelhook.provider.version\";\nconst ATTR_OTELHOOK_WORKSPACE_ID = \"otelhook.workspace.id\";\n\n/**\n * Resource attributes a launcher may set to supply the session key, in\n * preference order: the OpenTelemetry semantic-convention `session.id`, then the\n * legacy `har.session_key` that earlier launchers still send.\n */\nexport const EXTERNAL_SESSION_KEY_ATTRIBUTES: readonly string[] = Object.freeze([\n ATTR_SESSION_ID,\n \"har.session_key\",\n]);\n\n/**\n * The provider's own subagent id (Claude Code `agent_id`), on every record of an\n * event emitted inside a subagent. Same class as `session.id`: a provider-minted\n * opaque identifier, exported verbatim so a consumer can join it to the\n * provider's own per-subagent records.\n */\nexport const ATTR_OTELHOOK_SUBAGENT_ID = \"otelhook.subagent.id\";\n\n/**\n * Worktree an event targeted (ADR 0008): the one a tool call touched, or the one\n * a session runs in on its start and prompts. Branch under the OTel VCS\n * attribute; the worktree root, and its repository's main worktree root, only\n * as salted `git-root` handles.\n */\nexport const ATTR_VCS_REF_HEAD_NAME = \"vcs.ref.head.name\";\nexport const ATTR_OTELHOOK_TARGET_WORKSPACE_ID = \"otelhook.target.workspace.id\";\nexport const ATTR_OTELHOOK_TARGET_SOURCE = \"otelhook.target.source\";\nexport const ATTR_OTELHOOK_TARGET_REPOSITORY_ID = \"otelhook.target.repository.id\";\nexport const ATTR_OTELHOOK_TARGET_WORKTREE_KIND = \"otelhook.target.worktree.kind\";\n\n/** Whether `gen_ai.usage.*` on this record is a delta or a running total. */\nexport const ATTR_OTELHOOK_USAGE_TEMPORALITY = \"otelhook.usage.temporality\";\n\n/** Target attributes for a targeted event; empty when the core resolved none. */\nexport const targetAttributes = (event: CanonicalEvent): Attributes => {\n if (!isTargetedEvent(event) || event.target === undefined) {\n return {};\n }\n const { target } = event;\n return {\n [ATTR_OTELHOOK_TARGET_WORKSPACE_ID]: target.workspaceId,\n [ATTR_OTELHOOK_TARGET_SOURCE]: target.source,\n ...(target.vcsBranchName === undefined ? {} : { [ATTR_VCS_REF_HEAD_NAME]: target.vcsBranchName }),\n ...(target.repositoryId === undefined\n ? {}\n : { [ATTR_OTELHOOK_TARGET_REPOSITORY_ID]: target.repositoryId }),\n ...(target.worktreeKind === undefined\n ? {}\n : { [ATTR_OTELHOOK_TARGET_WORKTREE_KIND]: target.worktreeKind }),\n };\n};\n\n/** Temporality of reported usage, so a consumer never sums running totals. */\nexport const usageTemporalityAttributes = (usage: CanonicalUsage | undefined): Attributes =>\n usage === undefined ? {} : { [ATTR_OTELHOOK_USAGE_TEMPORALITY]: usage.temporality };\n\nconst isPrimitiveAttribute = (value: unknown): value is string | number | boolean =>\n typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\";\n\n/**\n * Resource attribute namespaces a launcher puts on the process that are also\n * copied onto every span and log record.\n *\n * Many backends index only record attributes (filters, search, dashboards), so a\n * value that exists only on the Resource is invisible there. Copied:\n *\n * - `har.*` — attributes earlier launchers send;\n * - `factory.*` — the Factory Commits telemetry profile (work unit, slot, …),\n * **except** `factory.local.*`, which the profile defines as local-only: it\n * stays on the Resource and never reaches a record;\n * - `vcs.*` — OpenTelemetry VCS attributes. An event's own resolved target\n * (ADR 0008) still wins for the keys it sets, such as `vcs.ref.head.name`.\n *\n * `session.id` is not copied: it is resolved separately (see\n * `resolveExportedSessionId`), so a resource value cannot overwrite the\n * trimmed, resolved one.\n */\nexport const PASSTHROUGH_RESOURCE_PREFIXES: readonly string[] = Object.freeze([\"har.\", \"factory.\", \"vcs.\"]);\n/** Local-only profile namespace: never copied from the Resource onto records. */\nexport const LOCAL_ONLY_RESOURCE_PREFIX = \"factory.local.\";\n\nconst isPassthroughKey = (key: string): boolean =>\n PASSTHROUGH_RESOURCE_PREFIXES.some((prefix) => key.startsWith(prefix)) &&\n !key.startsWith(LOCAL_ONLY_RESOURCE_PREFIX) &&\n key !== \"factory.local\";\n\n/**\n * Primitive resource attributes to copy onto every log and span record.\n *\n * Only the namespaces in `PASSTHROUGH_RESOURCE_PREFIXES` are forwarded, minus\n * `factory.local.*`; nothing is invented when they are absent.\n */\nexport const passthroughResourceAttributes = (resource: Resource): Attributes => {\n const attributes: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(resource.attributes)) {\n if (isPassthroughKey(key) && isPrimitiveAttribute(value)) {\n attributes[key] = value;\n }\n }\n return attributes;\n};\n\n/**\n * Session id to put on `session.id`, preferring an externally supplied key.\n *\n * A launcher supplies the key as a resource attribute (usually through\n * `OTEL_RESOURCE_ATTRIBUTES`): `session.id` first, then the legacy\n * `har.session_key`, then the provider's own session id. The provider's id is\n * never discarded: it is returned separately so callers can emit it as\n * `otelhook.session.id` / `gen_ai.conversation.id`.\n */\nexport const resolveExportedSessionId = (\n eventSessionId: string,\n resource: Resource,\n): { readonly sessionId: string; readonly providerSessionId: string } => {\n for (const key of EXTERNAL_SESSION_KEY_ATTRIBUTES) {\n const supplied = resource.attributes[key];\n if (typeof supplied === \"string\") {\n const trimmed = supplied.trim();\n if (trimmed.length > 0) {\n return { sessionId: trimmed, providerSessionId: eventSessionId };\n }\n }\n }\n return { sessionId: eventSessionId, providerSessionId: eventSessionId };\n};\n\nexport type ExportedTraceIds = {\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n};\n\n/**\n * Hex-only trace/span attributes. A value that is not W3C hex is omitted\n * rather than stringified — binary blobs must never appear in id fields.\n */\nexport const hexTraceAttributes = (ids: ExportedTraceIds): Attributes => ({\n ...(TRACE_ID_HEX_PATTERN.test(ids.traceId) ? { [ATTR_TRACE_ID]: ids.traceId } : {}),\n ...(SPAN_ID_HEX_PATTERN.test(ids.spanId) ? { [ATTR_SPAN_ID]: ids.spanId } : {}),\n ...(ids.parentSpanId !== undefined && SPAN_ID_HEX_PATTERN.test(ids.parentSpanId)\n ? { [ATTR_PARENT_SPAN_ID]: ids.parentSpanId }\n : {}),\n});\n\n/**\n * Identity attributes shared by the log and span mappings.\n *\n * `session.id` is the externally supplied session key when the resource carries\n * one (`session.id`, then `har.session_key`), otherwise the provider session id.\n * The provider id is always also emitted under `otelhook.session.id` and\n * `gen_ai.conversation.id`. Profile resource attributes are copied on too (see\n * `passthroughResourceAttributes`).\n */\nexport const exportIdentityAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n ids: ExportedTraceIds,\n): Attributes => {\n const { sessionId, providerSessionId } = resolveExportedSessionId(event.sessionId, resource);\n return {\n [ATTR_SESSION_ID]: sessionId,\n [ATTR_OTELHOOK_SESSION_ID]: providerSessionId,\n [ATTR_GEN_AI_CONVERSATION_ID]: providerSessionId,\n [ATTR_OTELHOOK_INVOCATION_ID]: event.invocationId,\n [ATTR_OTELHOOK_PROVIDER_ID]: event.provenance.providerId,\n ...(event.provenance.providerVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event.provenance.providerVersion }),\n [ATTR_OTELHOOK_WORKSPACE_ID]: event.workspace.workspaceId,\n ...(event.subagentId === undefined ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event.subagentId }),\n ...passthroughResourceAttributes(resource),\n ...hexTraceAttributes(ids),\n };\n};\n","import { z } from \"zod\";\n\nimport {\n errorPhaseSchema,\n errorSeveritySchema,\n otelHookErrorCodeSchema,\n} from \"../errors/taxonomy.js\";\nimport { contentFactSchema, contentFactsSchema } from \"./content.js\";\nimport { extensionsSchema, emptyExtensions } from \"./extensions.js\";\nimport { sourceProvenanceSchema, workspaceIdentitySchema } from \"./identity.js\";\nimport { subagentIdSchema, workspaceTargetSchema } from \"./target.js\";\nimport {\n durationMillisSchema,\n epochMillisSchema,\n eventIdSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n sequenceNumberSchema,\n sessionIdSchema,\n tokenCountSchema,\n} from \"./primitives.js\";\nimport { canonicalUsageSchema, type CanonicalUsage } from \"./usage.js\";\nimport { canonicalSchemaVersionSchema } from \"./version.js\";\n\n/** Model being invoked. Model identifiers are not treated as sensitive. */\nexport const modelDescriptorSchema = z.strictObject({\n modelId: nonEmptyStringSchema,\n /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */\n vendor: nonEmptyStringSchema.optional(),\n family: nonEmptyStringSchema.optional(),\n});\nexport type ModelDescriptor = z.infer<typeof modelDescriptorSchema>;\n\nexport const costFactsSchema = z.strictObject({\n /** ISO 4217 code. */\n currency: z.string().length(3),\n amount: z.number().min(0).finite(),\n source: z.enum([\"provider-reported\", \"computed\"]),\n});\nexport type CostFacts = z.infer<typeof costFactsSchema>;\n\nexport const canonicalEventTypeSchema = z.enum([\n \"session.start\",\n \"session.end\",\n \"prompt.submitted\",\n \"generation.start\",\n \"generation.end\",\n \"tool.start\",\n \"tool.end\",\n \"subagent.start\",\n \"subagent.end\",\n \"compaction.performed\",\n \"error.raised\",\n]);\nexport type CanonicalEventType = z.infer<typeof canonicalEventTypeSchema>;\n\nexport const CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;\n\nconst outcomeSchema = z.enum([\"ok\", \"error\", \"cancelled\", \"timeout\", \"denied\", \"unknown\"]);\nexport type EventOutcome = z.infer<typeof outcomeSchema>;\n\n/**\n * Fields present on every canonical event.\n *\n * Identity fields are duplicated onto each event rather than referenced through\n * shared state, so an event is self-describing once it leaves the process.\n */\nconst baseEventFields = {\n schemaVersion: canonicalSchemaVersionSchema,\n eventId: eventIdSchema,\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Per-invocation ordering key. Stable across replays of the same input. */\n sequence: sequenceNumberSchema,\n occurredAt: epochMillisSchema,\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n /**\n * The provider's own id for the subagent this event was emitted inside (e.g.\n * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event\n * factory, never by hand.\n */\n subagentId: subagentIdSchema.optional(),\n extensions: extensionsSchema.default(emptyExtensions),\n} 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\nimport { attributeValueSchema, type AttributeValue } from \"./primitives.js\";\n\n/**\n * Extension keys must be namespaced: at least one dot-separated segment before\n * the leaf, e.g. `acme.deployment-tier`. Namespacing keeps provider- and\n * consumer-specific fields from colliding with core fields or each other.\n */\nexport const EXTENSION_KEY_PATTERN =\n /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;\n\n/** Namespaces owned by the core model; extensions may not use them. */\nexport const RESERVED_EXTENSION_NAMESPACES: readonly string[] = Object.freeze([\n \"otelhook\",\n \"otel\",\n \"telemetry\",\n]);\n\nexport const MAX_EXTENSION_ENTRIES = 64;\n\nexport const extensionKeyNamespace = (key: string): string => key.slice(0, key.indexOf(\".\"));\n\nexport const isReservedExtensionNamespace = (key: string): boolean =>\n RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));\n\nexport const isValidExtensionKey = (key: string): boolean =>\n EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);\n\n/**\n * Namespaced extension bag.\n *\n * Values are restricted to attribute primitives, so extensions cannot carry\n * nested provider payloads.\n */\nexport const extensionsSchema = z\n .record(z.string(), attributeValueSchema)\n .check((ctx) => {\n const keys = Object.keys(ctx.value);\n if (keys.length > MAX_EXTENSION_ENTRIES) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`,\n });\n }\n for (const key of keys) {\n if (!EXTENSION_KEY_PATTERN.test(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. \"acme.tier\"`,\n });\n continue;\n }\n if (isReservedExtensionNamespace(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`,\n });\n }\n }\n });\n\nexport type Extensions = Record<string, AttributeValue>;\n\nexport const EMPTY_EXTENSIONS: Extensions = Object.freeze({});\n\nexport const emptyExtensions = (): Extensions => ({});\n","import { z } from \"zod\";\n\nimport {\n attributesSchema,\n detectionConfidenceSchema,\n DETECTION_CONFIDENCE_RANK,\n epochMillisSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n resolvedProviderIdSchema,\n sessionIdSchema,\n sourceTransportSchema,\n workspaceIdSchema,\n type DetectionConfidence,\n type InvocationId,\n type SessionId,\n type WorkspaceId,\n} from \"./primitives.js\";\n\n/**\n * Where a workspace identifier came from.\n *\n * Ordered from most to least stable. The source is recorded so consumers can\n * tell a repository-scoped identity from a directory-scoped one instead of\n * assuming they are comparable.\n */\nexport const workspaceKeySourceSchema = z.enum([\n \"git-remote\",\n \"git-root\",\n \"working-directory\",\n \"explicit\",\n \"unknown\",\n]);\nexport type WorkspaceKeySource = z.infer<typeof workspaceKeySourceSchema>;\n\n/**\n * Privacy-safe workspace identity.\n *\n * Only opaque handles and explicitly allowed labels are modelled. There is no\n * field for a filesystem path, so paths cannot be exported through this type.\n */\nexport const workspaceIdentitySchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n keySource: workspaceKeySourceSchema,\n /** Repository name only; never an owner path or URL with credentials. */\n repositoryName: nonEmptyStringSchema.optional(),\n vcsBranchName: nonEmptyStringSchema.optional(),\n /** Opaque handle for the checked-out revision. */\n vcsRevisionId: nonEmptyStringSchema.optional(),\n })\n .readonly();\nexport type WorkspaceIdentity = z.infer<typeof workspaceIdentitySchema>;\n\nexport const UNKNOWN_WORKSPACE_ID = \"unknown:0000000000000000\" as WorkspaceId;\n\nexport const unknownWorkspaceIdentity = (): WorkspaceIdentity =>\n workspaceIdentitySchema.parse({\n workspaceId: UNKNOWN_WORKSPACE_ID,\n keySource: \"unknown\",\n });\n\n/**\n * Provenance of an observation: which provider produced it and which adapter\n * interpreted it, with the confidence of that attribution.\n */\nexport const sourceProvenanceSchema = z\n .strictObject({\n providerId: resolvedProviderIdSchema,\n providerVersion: nonEmptyStringSchema.optional(),\n adapterId: nonEmptyStringSchema,\n adapterVersion: nonEmptyStringSchema,\n detectionConfidence: detectionConfidenceSchema,\n /** The provider's own name for the source event, e.g. a hook event name. */\n sourceEventName: nonEmptyStringSchema.optional(),\n transport: sourceTransportSchema,\n })\n .readonly();\nexport type SourceProvenance = z.infer<typeof sourceProvenanceSchema>;\n\n/**\n * Opaque, immutable metadata supplied by the embedding consumer.\n *\n * The library never interprets these values; it only carries and exports them.\n */\nexport const consumerAttributesSchema = attributesSchema.readonly();\nexport type ConsumerAttributes = z.infer<typeof consumerAttributesSchema>;\n\n/**\n * Immutable identity of a single hook invocation.\n *\n * Frozen on parse. There is deliberately no setter, no builder that mutates in\n * place, and no module-level instance: identity is passed explicitly so two\n * concurrent invocations can never observe each other's fields.\n */\nexport const invocationIdentitySchema = z\n .strictObject({\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Set when this invocation runs beneath another agent invocation. */\n parentInvocationId: invocationIdSchema.optional(),\n /** Root of the session tree when the provider exposes one. */\n rootSessionId: sessionIdSchema.optional(),\n /** Stable handle for the agent process/instance, when available. */\n agentInstanceId: nonEmptyStringSchema.optional(),\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n startedAt: epochMillisSchema,\n consumerAttributes: consumerAttributesSchema,\n })\n .readonly();\nexport type InvocationIdentity = z.infer<typeof invocationIdentitySchema>;\n\n/** Fields an identity claim may contribute. */\nexport const identityClaimFieldsSchema = z.strictObject({\n invocationId: invocationIdSchema.optional(),\n sessionId: sessionIdSchema.optional(),\n parentInvocationId: invocationIdSchema.optional(),\n rootSessionId: sessionIdSchema.optional(),\n agentInstanceId: nonEmptyStringSchema.optional(),\n workspace: workspaceIdentitySchema.optional(),\n startedAt: epochMillisSchema.optional(),\n});\nexport type IdentityClaimFields = z.infer<typeof identityClaimFieldsSchema>;\n\n/**\n * A claim about invocation identity from one source.\n *\n * Claims are evidence, not truth. Resolution keeps the highest-confidence claim\n * per field and refuses to merge disagreeing peers.\n */\nexport const identityClaimSchema = z.strictObject({\n /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */\n source: nonEmptyStringSchema,\n confidence: detectionConfidenceSchema,\n fields: identityClaimFieldsSchema,\n});\nexport type IdentityClaim = z.infer<typeof identityClaimSchema>;\n\nexport type IdentityConflict = {\n readonly field: keyof IdentityClaimFields;\n readonly confidence: DetectionConfidence;\n /** Rendered, non-sensitive representations of the disagreeing values. */\n readonly values: readonly string[];\n readonly sources: readonly string[];\n};\n\nexport type IdentityResolution =\n | { readonly status: \"resolved\"; readonly identity: InvocationIdentity }\n | {\n readonly status: \"conflict\";\n readonly conflicts: readonly IdentityConflict[];\n }\n | {\n readonly status: \"incomplete\";\n readonly missing: readonly (keyof IdentityClaimFields)[];\n }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nconst CLAIM_FIELDS = [\n \"invocationId\",\n \"sessionId\",\n \"parentInvocationId\",\n \"rootSessionId\",\n \"agentInstanceId\",\n \"workspace\",\n \"startedAt\",\n] as const satisfies readonly (keyof IdentityClaimFields)[];\n\nconst renderClaimValue = (value: unknown): string => {\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (value !== null && typeof value === \"object\" && \"workspaceId\" in value) {\n const { workspaceId } = value;\n return typeof workspaceId === \"string\" ? workspaceId : \"<workspace>\";\n }\n return \"<opaque>\";\n};\n\nexport type ResolveIdentityInput = {\n readonly claims: readonly IdentityClaim[];\n readonly provenance: SourceProvenance;\n /** Used only for fields no claim provides and that have a safe default. */\n readonly fallback?: {\n readonly startedAt?: number;\n readonly workspace?: WorkspaceIdentity;\n };\n readonly consumerAttributes?: Readonly<Record<string, unknown>>;\n};\n\n/**\n * Resolve identity from claims, failing closed.\n *\n * Rules:\n * 1. For each field, only claims at the highest confidence that provided it are\n * considered. Lower-confidence claims never fill in or override.\n * 2. Two distinct values at that highest confidence produce a `conflict`. The\n * invocation is then not attributed at all — a mislabelled session is worse\n * than a missing one.\n * 3. `invocationId` and `sessionId` are mandatory. Missing either yields\n * `incomplete`; neither is invented here.\n * 4. `startedAt` and `workspace` may come from an explicit fallback, because a\n * clock reading and an `unknown` workspace handle assert nothing false.\n */\nexport const resolveInvocationIdentity = (input: ResolveIdentityInput): IdentityResolution => {\n const parsedClaims: IdentityClaim[] = [];\n const issues: string[] = [];\n for (const [index, claim] of input.claims.entries()) {\n const parsed = identityClaimSchema.safeParse(claim);\n if (parsed.success) {\n parsedClaims.push(parsed.data);\n } else {\n issues.push(\n `claim[${index}]: ${parsed.error.issues.map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`).join(\", \")}`,\n );\n }\n }\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const conflicts: IdentityConflict[] = [];\n const selected: Record<string, unknown> = {};\n\n for (const field of CLAIM_FIELDS) {\n const contributors = parsedClaims.filter((claim) => claim.fields[field] !== undefined);\n if (contributors.length === 0) {\n continue;\n }\n const bestRank = Math.max(\n ...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence]),\n );\n const best = contributors.filter(\n (claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank,\n );\n const rendered = new Map<string, string[]>();\n for (const claim of best) {\n const key = JSON.stringify(claim.fields[field]);\n const sources = rendered.get(key) ?? [];\n sources.push(claim.source);\n rendered.set(key, sources);\n }\n if (rendered.size > 1) {\n const [firstBest] = best;\n conflicts.push({\n field,\n confidence: firstBest?.confidence ?? \"none\",\n values: best.map((claim) => renderClaimValue(claim.fields[field])),\n sources: best.map((claim) => claim.source),\n });\n continue;\n }\n const [winner] = best;\n if (winner !== undefined) {\n selected[field] = winner.fields[field];\n }\n }\n\n if (conflicts.length > 0) {\n return { status: \"conflict\", conflicts };\n }\n\n const missing: (keyof IdentityClaimFields)[] = [];\n if (selected.invocationId === undefined) {\n missing.push(\"invocationId\");\n }\n if (selected.sessionId === undefined) {\n missing.push(\"sessionId\");\n }\n if (missing.length > 0) {\n return { status: \"incomplete\", missing };\n }\n\n const startedAt = (selected.startedAt as number | undefined) ?? input.fallback?.startedAt;\n if (startedAt === undefined) {\n return { status: \"incomplete\", missing: [\"startedAt\"] };\n }\n const workspace =\n (selected.workspace as WorkspaceIdentity | undefined) ??\n input.fallback?.workspace ??\n unknownWorkspaceIdentity();\n\n const candidate = {\n invocationId: selected.invocationId as InvocationId,\n sessionId: selected.sessionId as SessionId,\n ...(selected.parentInvocationId === undefined\n ? {}\n : { parentInvocationId: selected.parentInvocationId as InvocationId }),\n ...(selected.rootSessionId === undefined\n ? {}\n : { rootSessionId: selected.rootSessionId as SessionId }),\n ...(selected.agentInstanceId === undefined\n ? {}\n : { agentInstanceId: selected.agentInstanceId as string }),\n provenance: input.provenance,\n workspace,\n startedAt,\n consumerAttributes: input.consumerAttributes ?? {},\n };\n\n const parsed = invocationIdentitySchema.safeParse(candidate);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n }\n return { status: \"resolved\", identity: parsed.data };\n};\n","import { z } from \"zod\";\n\nimport { nonEmptyStringSchema, workspaceIdSchema } from \"./primitives.js\";\n\n/**\n * Per-event workspace targeting (ADR 0008).\n *\n * A session's `workspace` is where the agent was *started*. An agent routinely\n * works somewhere else — in a linked git worktree beside the checkout it was\n * launched from — and the session-level identity cannot show that. A tool event\n * can: the file it edited, or the directory its shell command ran in, names the\n * worktree it actually touched.\n *\n * Two values model that, and the split between them is the privacy boundary:\n *\n * - {@link TargetHint} is what an adapter observed — local paths. It is an\n * in-process value only: it is never part of a {@link CanonicalEvent}, never\n * persisted, never exported. The core resolves it and drops it.\n * - {@link WorkspaceTarget} is what the core resolved — salted handles of the\n * worktree and its repository, the worktree's kind, the checked-out branch, and\n * what the evidence was. It travels on the event.\n */\n\n/**\n * What a target was derived from, strongest evidence first.\n *\n * - `tool-path` — a path the tool call itself named (an edited or read file, a\n * patch header).\n * - `shell-cwd` — the working directory the provider reports a shell command ran in.\n * - `session-cwd` — only the session's own directory was known; the event may\n * have reached elsewhere (e.g. a shell `cd`) without the provider saying so.\n */\nexport const targetSourceSchema = z.enum([\"tool-path\", \"shell-cwd\", \"session-cwd\"]);\nexport type TargetSource = z.infer<typeof targetSourceSchema>;\n\n/** Most paths one hint may name; a bound, not a sampling rule (all must agree). */\nexport const MAX_TARGET_HINT_PATHS = 8;\n\n/** Longest local path a hint may carry. Longer input is dropped, never truncated. */\nexport const MAX_TARGET_PATH_LENGTH = 4096;\n\nconst localPathSchema = z\n .string()\n .min(1)\n .max(MAX_TARGET_PATH_LENGTH)\n .refine((value) => !value.includes(\"\\u0000\"), \"path must not contain NUL\");\n\n/**\n * An adapter's observation of where a tool event pointed. **Carries local paths**\n * — in-process only, see the module note.\n *\n * Every path in one hint must resolve to the same worktree, or the event gets no\n * target at all: a patch touching two worktrees did not target either of them.\n */\nexport const targetHintSchema = z\n .strictObject({\n source: targetSourceSchema,\n paths: z.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),\n /** Absolute directory that relative `paths` resolve against. */\n baseDirectory: localPathSchema.optional(),\n })\n .readonly();\nexport type TargetHint = z.infer<typeof targetHintSchema>;\n\n/**\n * The weakest hint: the session's own directory. Every adapter gives it to a\n * session start and a prompt, and to a tool call that names no path.\n */\nexport const sessionCwdHint = (cwd: string | undefined): TargetHint | undefined =>\n cwd === undefined || cwd.length === 0 ? undefined : { source: \"session-cwd\", paths: [cwd] };\n\n/**\n * Whether a worktree is its repository's main checkout (`main`) or one added\n * beside it with `git worktree add` (`linked`).\n */\nexport const worktreeKindSchema = z.enum([\"main\", \"linked\"]);\nexport type WorktreeKind = z.infer<typeof worktreeKindSchema>;\n\n/**\n * The git worktree a tool event targeted. Exported; carries no path.\n *\n * `workspaceId` is derived exactly like a `git-root` workspace identity, so a\n * consumer holding the same salt can match it against one it derived itself.\n * `repositoryId` is the same derivation applied to the repository's main\n * worktree, so every worktree of one repository shares it — and for a main\n * worktree it equals `workspaceId`.\n */\nexport const workspaceTargetSchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n /** Branch checked out in that worktree; absent on a detached HEAD. */\n vcsBranchName: nonEmptyStringSchema.optional(),\n source: targetSourceSchema,\n /** `git-root` handle of the repository's main worktree; absent when there is none to name. */\n repositoryId: workspaceIdSchema.optional(),\n worktreeKind: worktreeKindSchema.optional(),\n })\n .readonly();\nexport type WorkspaceTarget = z.infer<typeof workspaceTargetSchema>;\n\n/**\n * Shape a provider's own subagent identifier must have to be exported.\n *\n * Identifier-shaped on purpose — no whitespace, no path separators — so a\n * malformed payload field cannot carry prose or a path onto the wire under an id\n * attribute. A value that does not fit is dropped, not repaired.\n */\nexport const SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;\nexport const subagentIdSchema = z.string().regex(SUBAGENT_ID_PATTERN);\nexport type SubagentId = z.infer<typeof subagentIdSchema>;\n","import { z } from \"zod\";\n\nimport { tokenCountSchema } from \"./primitives.js\";\n\n/**\n * Whether an observation reports the change since the previous observation\n * (`delta`) or the running total for the session/generation (`cumulative`).\n *\n * The canonical model keeps temporality explicit rather than assuming one:\n * summing cumulative observations double-counts, and diffing delta observations\n * silently loses tokens.\n */\nexport const usageTemporalitySchema = z.enum([\"delta\", \"cumulative\"]);\nexport type UsageTemporality = z.infer<typeof usageTemporalitySchema>;\n\n/**\n * Whether the provider counts cache-creation tokens inside its input total or\n * reports them as a disjoint bucket.\n *\n * - `included-in-input`: `cacheCreationInputTokens` is a subset of `inputTokens`.\n * - `disjoint-from-input`: cache-creation tokens are billed in addition to\n * `inputTokens` and must be added when computing a total.\n * - `not-reported`: the provider exposes no cache-creation counter; the field is\n * pinned to zero.\n */\nexport const cacheCreationAccountingSchema = z.enum([\n \"included-in-input\",\n \"disjoint-from-input\",\n \"not-reported\",\n]);\nexport type CacheCreationAccounting = z.infer<typeof cacheCreationAccountingSchema>;\n\n/** Whether a provider-reported total agrees with the canonical computation. */\nexport const providerTotalAgreementSchema = z.enum([\"unreported\", \"agrees\", \"disagrees\"]);\nexport type ProviderTotalAgreement = z.infer<typeof providerTotalAgreementSchema>;\n\n/**\n * What an adapter reports, before normalization.\n *\n * `inputTokens` is *inclusive*: it counts every input token the provider\n * attributes to the call, including cache reads (and cache creation when the\n * provider folds it in). `outputTokens` is likewise inclusive of reasoning\n * output. Subset fields describe portions of those totals, never additions.\n */\nexport const usageReportSchema = z.strictObject({\n temporality: usageTemporalitySchema,\n /** Inclusive input tokens. */\n inputTokens: tokenCountSchema.optional(),\n /** Subset of `inputTokens` served from a prompt cache. */\n cachedInputTokens: tokenCountSchema.optional(),\n /** Tokens written to a prompt cache. */\n cacheCreationInputTokens: tokenCountSchema.optional(),\n /** Required when `cacheCreationInputTokens` is present and non-zero. */\n cacheCreationAccounting: cacheCreationAccountingSchema.optional(),\n /** Inclusive output tokens. */\n outputTokens: tokenCountSchema.optional(),\n /** Subset of `outputTokens` spent on reasoning. */\n reasoningOutputTokens: tokenCountSchema.optional(),\n /** Total exactly as the provider reported it, if it reported one. */\n providerTotalTokens: tokenCountSchema.optional(),\n});\nexport type UsageReport = z.infer<typeof usageReportSchema>;\n\n/**\n * Fully normalized usage.\n *\n * Derived fields (`uncachedInputTokens`, `totalTokens`,\n * `providerTotalAgreement`) are part of the schema and are re-checked on parse,\n * so an inconsistent object cannot exist. Construct values with\n * {@link normalizeUsage} rather than by hand.\n */\nexport const canonicalUsageSchema = z\n .strictObject({\n temporality: usageTemporalitySchema,\n inputTokens: tokenCountSchema,\n cachedInputTokens: tokenCountSchema,\n cacheCreationInputTokens: tokenCountSchema,\n cacheCreationAccounting: cacheCreationAccountingSchema,\n outputTokens: tokenCountSchema,\n reasoningOutputTokens: tokenCountSchema,\n /** Derived: input tokens that were neither cache reads nor cache writes. */\n uncachedInputTokens: tokenCountSchema,\n /** Derived: canonical billable total. */\n totalTokens: tokenCountSchema,\n providerTotalTokens: tokenCountSchema.optional(),\n providerTotalAgreement: providerTotalAgreementSchema,\n })\n .check((ctx) => {\n const usage = ctx.value;\n const push = (message: string): void => {\n ctx.issues.push({ code: \"custom\", input: usage, message });\n };\n\n if (usage.cachedInputTokens > usage.inputTokens) {\n push(\"cachedInputTokens must not exceed inputTokens (it is a subset)\");\n }\n if (usage.reasoningOutputTokens > usage.outputTokens) {\n push(\"reasoningOutputTokens must not exceed outputTokens (it is a subset)\");\n }\n if (usage.cacheCreationAccounting === \"not-reported\" && usage.cacheCreationInputTokens !== 0) {\n push(\"cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported\");\n }\n const creationInsideInput =\n usage.cacheCreationAccounting === \"included-in-input\" ? usage.cacheCreationInputTokens : 0;\n if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {\n push(\n \"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input\",\n );\n }\n const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;\n if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {\n push(`uncachedInputTokens must equal ${expectedUncached}`);\n }\n const creationOutsideInput =\n usage.cacheCreationAccounting === \"disjoint-from-input\" ? usage.cacheCreationInputTokens : 0;\n const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;\n if (usage.totalTokens !== expectedTotal) {\n push(`totalTokens must equal ${expectedTotal}`);\n }\n const expectedAgreement: ProviderTotalAgreement =\n usage.providerTotalTokens === undefined\n ? \"unreported\"\n : usage.providerTotalTokens === expectedTotal\n ? \"agrees\"\n : \"disagrees\";\n if (usage.providerTotalAgreement !== expectedAgreement) {\n push(`providerTotalAgreement must be ${expectedAgreement}`);\n }\n });\nexport type CanonicalUsage = z.infer<typeof canonicalUsageSchema>;\n\nexport type UsageNormalizationIssue = {\n readonly code:\n | \"invalid-report\"\n | \"cached-exceeds-input\"\n | \"reasoning-exceeds-output\"\n | \"cache-creation-exceeds-input\"\n | \"cache-creation-accounting-missing\";\n readonly message: string;\n};\n\nexport type UsageNormalizationResult =\n | { readonly status: \"ok\"; readonly usage: CanonicalUsage; readonly notes: readonly string[] }\n | { readonly status: \"invalid\"; readonly issues: readonly UsageNormalizationIssue[] };\n\n/**\n * Normalize a provider usage report into canonical usage.\n *\n * Deterministic rules:\n * 1. Absent counters default to `0`; `providerTotalTokens` stays absent.\n * 2. Non-integer, negative, or non-finite counters are rejected.\n * 3. A subset exceeding its total is rejected — never clamped — because\n * clamping would silently invent a billing story.\n * 4. `cacheCreationAccounting` defaults to `not-reported` when no cache-creation\n * tokens are reported, and is *required* when they are: guessing whether the\n * bucket is disjoint would mis-total every downstream cost calculation.\n * 5. A provider total that disagrees with the canonical total is preserved as\n * reported and flagged `disagrees`. Both numbers survive; neither is edited.\n */\nexport const normalizeUsage = (report: unknown): UsageNormalizationResult => {\n const parsed = usageReportSchema.safeParse(report);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map((issue) => ({\n code: \"invalid-report\" as const,\n message: `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n })),\n };\n }\n\n const input = parsed.data;\n const issues: UsageNormalizationIssue[] = [];\n const notes: string[] = [];\n\n const inputTokens = input.inputTokens ?? 0;\n const cachedInputTokens = input.cachedInputTokens ?? 0;\n const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;\n const outputTokens = input.outputTokens ?? 0;\n const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;\n\n let accounting: CacheCreationAccounting;\n if (cacheCreationInputTokens === 0) {\n accounting = input.cacheCreationAccounting ?? \"not-reported\";\n if (accounting !== \"not-reported\") {\n notes.push(\n `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`,\n );\n }\n } else if (input.cacheCreationAccounting === undefined) {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message:\n \"cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred\",\n });\n accounting = \"not-reported\";\n } else if (input.cacheCreationAccounting === \"not-reported\") {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message: \"cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens\",\n });\n accounting = \"not-reported\";\n } else {\n accounting = input.cacheCreationAccounting;\n }\n\n if (cachedInputTokens > inputTokens) {\n issues.push({\n code: \"cached-exceeds-input\",\n message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n if (reasoningOutputTokens > outputTokens) {\n issues.push({\n code: \"reasoning-exceeds-output\",\n message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`,\n });\n }\n\n const creationInsideInput = accounting === \"included-in-input\" ? cacheCreationInputTokens : 0;\n if (cachedInputTokens + creationInsideInput > inputTokens) {\n issues.push({\n code: \"cache-creation-exceeds-input\",\n message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const creationOutsideInput = accounting === \"disjoint-from-input\" ? cacheCreationInputTokens : 0;\n const totalTokens = inputTokens + creationOutsideInput + outputTokens;\n const providerTotalAgreement: ProviderTotalAgreement =\n input.providerTotalTokens === undefined\n ? \"unreported\"\n : input.providerTotalTokens === totalTokens\n ? \"agrees\"\n : \"disagrees\";\n\n if (providerTotalAgreement === \"disagrees\") {\n notes.push(\n `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`,\n );\n }\n\n const usage: CanonicalUsage = {\n temporality: input.temporality,\n inputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens,\n reasoningOutputTokens,\n uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,\n totalTokens,\n ...(input.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: input.providerTotalTokens }),\n providerTotalAgreement,\n };\n\n return { status: \"ok\", usage, notes };\n};\n\nexport class UsageNormalizationError extends Error {\n public readonly issues: readonly UsageNormalizationIssue[];\n\n public constructor(issues: readonly UsageNormalizationIssue[]) {\n super(`invalid usage report: ${issues.map((issue) => issue.message).join(\"; \")}`);\n this.name = \"UsageNormalizationError\";\n this.issues = issues;\n }\n}\n\n/** Convenience wrapper for call sites that treat invalid usage as a bug. */\nexport const normalizeUsageOrThrow = (report: unknown): CanonicalUsage => {\n const result = normalizeUsage(report);\n if (result.status === \"invalid\") {\n throw new UsageNormalizationError(result.issues);\n }\n return result.usage;\n};\n\nexport const EMPTY_DELTA_USAGE: CanonicalUsage = Object.freeze(\n normalizeUsageOrThrow({ temporality: \"delta\" }),\n);\n\nexport type UsageDeltaResult = {\n readonly usage: CanonicalUsage;\n /**\n * True when the current snapshot is smaller than the previous one on any\n * counter. That means the cumulative series restarted (new session, replayed\n * transcript, provider reset), so the current snapshot is emitted as the delta\n * instead of a negative difference.\n */\n readonly resetDetected: boolean;\n};\n\nconst requireCumulative = (usage: CanonicalUsage, label: string): void => {\n if (usage.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: `${label} must have cumulative temporality` },\n ]);\n }\n};\n\n/**\n * Convert two cumulative snapshots into a delta observation.\n *\n * Replay safety: re-processing the same snapshot yields an all-zero delta, and a\n * decreasing series is reported as a reset rather than a negative delta.\n * Accounting mode must match; mixing modes would make the subtraction meaningless.\n */\nexport const cumulativeToDelta = (\n previous: CanonicalUsage,\n current: CanonicalUsage,\n): UsageDeltaResult => {\n requireCumulative(previous, \"previous usage\");\n requireCumulative(current, \"current usage\");\n\n if (\n previous.cacheCreationAccounting !== current.cacheCreationAccounting &&\n previous.cacheCreationInputTokens !== 0 &&\n current.cacheCreationInputTokens !== 0\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot diff cumulative usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const resetDetected =\n current.inputTokens < previous.inputTokens ||\n current.cachedInputTokens < previous.cachedInputTokens ||\n current.cacheCreationInputTokens < previous.cacheCreationInputTokens ||\n current.outputTokens < previous.outputTokens ||\n current.reasoningOutputTokens < previous.reasoningOutputTokens;\n\n if (resetDetected) {\n return {\n usage: normalizeUsageOrThrow({ ...toReport(current), temporality: \"delta\" }),\n resetDetected: true,\n };\n }\n\n const usage = normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: current.inputTokens - previous.inputTokens,\n cachedInputTokens: current.cachedInputTokens - previous.cachedInputTokens,\n cacheCreationInputTokens:\n current.cacheCreationInputTokens - previous.cacheCreationInputTokens,\n cacheCreationAccounting: current.cacheCreationAccounting,\n outputTokens: current.outputTokens - previous.outputTokens,\n reasoningOutputTokens: current.reasoningOutputTokens - previous.reasoningOutputTokens,\n });\n\n return { usage, resetDetected: false };\n};\n\n/** Project canonical usage back onto the reported shape. */\nexport const toReport = (usage: CanonicalUsage): UsageReport => ({\n temporality: usage.temporality,\n inputTokens: usage.inputTokens,\n cachedInputTokens: usage.cachedInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n cacheCreationAccounting: usage.cacheCreationAccounting,\n outputTokens: usage.outputTokens,\n reasoningOutputTokens: usage.reasoningOutputTokens,\n ...(usage.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: usage.providerTotalTokens }),\n});\n\n/**\n * Add two delta observations. Cumulative usage is never summed, because two\n * running totals do not compose.\n */\nexport const addUsage = (a: CanonicalUsage, b: CanonicalUsage): CanonicalUsage => {\n if (a.temporality !== \"delta\" || b.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"only delta usage may be summed\" },\n ]);\n }\n const accounting =\n a.cacheCreationInputTokens === 0 && a.cacheCreationAccounting === \"not-reported\"\n ? b.cacheCreationAccounting\n : b.cacheCreationInputTokens === 0 && b.cacheCreationAccounting === \"not-reported\"\n ? a.cacheCreationAccounting\n : a.cacheCreationAccounting;\n\n if (\n a.cacheCreationInputTokens !== 0 &&\n b.cacheCreationInputTokens !== 0 &&\n a.cacheCreationAccounting !== b.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot sum usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n a.providerTotalTokens === undefined && b.providerTotalTokens === undefined\n ? undefined\n : (a.providerTotalTokens ?? 0) + (b.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: a.inputTokens + b.inputTokens,\n cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,\n cacheCreationInputTokens: a.cacheCreationInputTokens + b.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: a.outputTokens + b.outputTokens,\n reasoningOutputTokens: a.reasoningOutputTokens + b.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n","import { z } from \"zod\";\n\n/**\n * Version of the canonical event model.\n *\n * Every emitted event carries this value. Consumers must treat an unknown\n * version as unreadable rather than guessing field semantics.\n *\n * Compatibility rules:\n * - Additive optional fields do not change the version.\n * - Renaming, removing, or re-interpreting a field increments the version.\n */\nexport const CANONICAL_SCHEMA_VERSION = 1 as const;\n\nexport type CanonicalSchemaVersion = typeof CANONICAL_SCHEMA_VERSION;\n\nexport const canonicalSchemaVersionSchema = z.literal(CANONICAL_SCHEMA_VERSION);\n","import type { Attributes as SpanAttributes } from \"@opentelemetry/api\";\n\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport {\n MAX_ATTRIBUTE_STRING_LENGTH,\n MAX_IDENTIFIER_LENGTH,\n type Attributes,\n} from \"../model/primitives.js\";\nimport type { Clock, StateStore, StateValue } from \"../runtime/ports.js\";\nimport { withOptionalSessionLock } from \"../state/store.js\";\nimport {\n MAX_RECOVERED_START_ATTRIBUTES,\n parentScopeRefOf,\n spanScopeRefOf,\n startOnlySpanAttributes,\n type SpanCorrelation,\n type SpanFamily,\n type SpanOrphanClassification,\n type SpanScopeRef,\n} from \"../telemetry/semconv.js\";\nimport { spanKey, spanScanPrefix } from \"./keys.js\";\n\n/** Correlation scopes that pair a `*.start` event with a later `*.end` event. */\nexport type LifecycleScope = SpanFamily;\n\n/**\n * Shape version of a persisted span record.\n *\n * A record written under a different version is discarded on read rather than\n * interpreted: guessing at an older layout is exactly the kind of silent\n * mis-attribution this library refuses to do. See `docs/state-retention.md`.\n */\nexport const SPAN_RECORD_VERSION = 2;\n\n/** Facts about a span recovered from, or written to, persisted state. */\nexport type SpanCorrelationFacts = {\n readonly startedAt?: number;\n readonly endedAt?: number;\n readonly parent?: SpanScopeRef;\n readonly attributes?: SpanAttributes;\n};\n\nexport type SpanStartInput = {\n readonly sessionId: string;\n /** Attribution boundary: a scope recorded by one provider never pairs with another's. */\n readonly providerId: string;\n readonly scope: LifecycleScope;\n readonly scopeKey: string;\n /** The canonical event id of the start event; used to detect redelivery. */\n readonly eventId: string;\n readonly occurredAt: number;\n /** Where this span hangs, so an end-only process reparents it identically. */\n readonly parent?: SpanScopeRef;\n /** Attributes only the start edge knows; carried forward to the end-side span. */\n readonly attributes?: SpanAttributes;\n};\n\nexport type SpanEndInput = {\n readonly sessionId: string;\n readonly providerId: string;\n readonly scope: LifecycleScope;\n readonly scopeKey: string;\n readonly eventId: string;\n readonly occurredAt: number;\n};\n\nexport type SpanStartResult =\n | { readonly status: \"recorded\"; readonly facts: SpanCorrelationFacts }\n /** The same start (by event id) was already recorded; state is unchanged. */\n | { readonly status: \"duplicate\"; readonly facts: SpanCorrelationFacts }\n /**\n * The record was completed, but an OTLP record for this scope has already been\n * published under its span id — so this edge must not export one.\n */\n | { readonly status: \"published\"; readonly facts: SpanCorrelationFacts }\n /** A different provider owns this scope key in this session; nothing was written. */\n | { readonly status: \"conflict\"; readonly reason: \"provider-mismatch\" };\n\n/** Why an end could not be paired with a recorded start. */\nexport type SpanEndOrphanReason =\n | \"no-start-recorded\"\n | \"start-expired\"\n | \"already-closed\"\n | \"provider-mismatch\"\n | \"state-incompatible\"\n | \"state-corrupt\";\n\nexport type SpanEndResult =\n | {\n readonly status: \"matched\";\n readonly startedAt: number;\n readonly durationMillis: number;\n readonly facts: SpanCorrelationFacts;\n }\n /** This exact end (by event id) was already applied; the same facts are replayed. */\n | { readonly status: \"duplicate\"; readonly facts: SpanCorrelationFacts }\n | {\n readonly status: \"orphaned\";\n readonly reason: SpanEndOrphanReason;\n readonly facts: SpanCorrelationFacts;\n };\n\nexport type SpanCleanupResult = {\n readonly removed: number;\n readonly scanned: number;\n /**\n * Records dropped that held a start and never received an end.\n *\n * These are the spans that will never be exported at all: the end edge is what\n * emits a lifecycle span, so a scope whose end never arrives — a session the\n * host killed, a tool call that outlived the retention window — produces no\n * OTLP record. That is the standard OpenTelemetry outcome for a span that never\n * ends, and it is deliberately not papered over with a synthetic end time,\n * because a fabricated duration is a wrong measurement rather than a missing\n * one. Counting them keeps the cost visible: a non-zero number here means real\n * activity went unreported, which is a signal about the host or the retention\n * window rather than noise. See `docs/state-retention.md`.\n */\n readonly expiredOpen: number;\n};\n\n/**\n * Cross-invocation start/end correlation for session, generation, tool, and\n * subagent scopes.\n *\n * A coding-agent hook fires once per lifecycle edge, usually as a separate\n * short-lived process for the start and for the end. This records an open span\n * in the shared state store so the end side can report a real start time,\n * duration, parent, and start-only attributes even though its process has no\n * memory of the start — and so a redelivered start or end (an at-least-once\n * host retry) re-exports an identical span instead of being double-counted.\n *\n * ## What it refuses to do\n *\n * - **Pair across sessions.** The state key is session-scoped, so two sessions\n * cannot see each other's open spans.\n * - **Pair across providers.** The key is provider-scoped *and* the record\n * carries the provider that wrote it, so a mismatch is reported rather than\n * guessed at — the same defense in depth the durable spool uses.\n * - **Trust a stale start.** A start older than `maxStartAgeMillis` when its end\n * arrives is dropped and classified `start-expired`, rather than reporting a\n * duration that really measures a machine suspend or a reused id.\n * - **Interpret a record it does not understand.** A corrupt or wrong-version\n * record is deleted and classified, never partially read.\n */\nexport interface SpanCorrelator {\n recordStart(input: SpanStartInput): Promise<SpanStartResult>;\n recordEnd(input: SpanEndInput): Promise<SpanEndResult>;\n /**\n * Records every lifecycle edge in a batch and reports what the exported spans\n * should say. Never rejects: a state failure degrades one scope to\n * `state-unavailable` rather than losing the batch (fail-open telemetry).\n */\n correlateBatch(events: readonly CanonicalEvent[]): Promise<readonly SpanCorrelation[]>;\n /** Bounded sweep: drops spans untouched for longer than `maxAgeMillis`. */\n cleanup(\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<SpanCleanupResult>;\n}\n\nexport type SpanCorrelatorDependencies = {\n readonly stateStore: StateStore;\n readonly clock: Clock;\n /**\n * A recorded start older than this when its end arrives is not trusted.\n * Default 24 hours, matching the janitor's retention window.\n */\n readonly maxStartAgeMillis?: number;\n};\n\nconst DEFAULT_MAX_START_AGE_MILLIS = 24 * 60 * 60 * 1000;\nconst ATTRIBUTE_PREFIX = \"a:\";\n\ntype SpanRecord = {\n readonly providerId: string;\n readonly startEventId?: string;\n readonly startedAt?: number;\n readonly endEventId?: string;\n readonly endedAt?: number;\n readonly parent?: SpanScopeRef;\n readonly attributes?: SpanAttributes;\n /**\n * True once an OTLP record has been produced for this scope under its derived\n * span id.\n *\n * Needed for the ordering nobody controls: the end edge can be mapped before\n * the start edge, and then the end has already exported an orphan carrying the\n * scope's canonical span id. Without this flag the late start would look like\n * the benign \"end raced ahead\" case and export a *second* record with that same\n * id — the duplicate the whole defer strategy exists to avoid. So the flag turns\n * \"was this scope already published?\" into a fact on disk rather than an\n * assumption about arrival order.\n */\n readonly exported?: boolean;\n};\n\ntype DecodedRecord =\n | { readonly kind: \"absent\" }\n | { readonly kind: \"incompatible\" }\n | { readonly kind: \"corrupt\" }\n | { readonly kind: \"present\"; readonly record: SpanRecord };\n\nconst SPAN_FAMILIES: readonly SpanFamily[] = [\"session\", \"generation\", \"tool\", \"subagent\"];\n\nconst isSpanFamily = (value: unknown): value is SpanFamily =>\n typeof value === \"string\" && (SPAN_FAMILIES as readonly string[]).includes(value);\n\nconst optionalNumber = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n\nconst optionalString = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 ? value : undefined;\n\n/**\n * Persisted attributes are flattened under a prefix rather than nested: the\n * state schema admits only flat primitives, which is what keeps a provider\n * payload from ever being smuggled through the state store.\n */\nconst encodeAttributes = (attributes: SpanAttributes | undefined): Attributes => {\n const encoded: Record<string, string | number | boolean> = {};\n let count = 0;\n for (const [key, value] of Object.entries(attributes ?? {})) {\n if (count >= MAX_RECOVERED_START_ATTRIBUTES) {\n break;\n }\n const encodedKey = `${ATTRIBUTE_PREFIX}${key}`;\n if (encodedKey.length > MAX_IDENTIFIER_LENGTH) {\n continue;\n }\n if (typeof value === \"string\") {\n encoded[encodedKey] = value.slice(0, MAX_ATTRIBUTE_STRING_LENGTH);\n } else if (typeof value === \"number\" && Number.isFinite(value)) {\n encoded[encodedKey] = value;\n } else if (typeof value === \"boolean\") {\n encoded[encodedKey] = value;\n } else {\n continue;\n }\n count += 1;\n }\n return encoded;\n};\n\nconst decodeAttributes = (attributes: Attributes): SpanAttributes | undefined => {\n const decoded: Record<string, string | number | boolean> = {};\n let count = 0;\n for (const [key, value] of Object.entries(attributes)) {\n if (!key.startsWith(ATTRIBUTE_PREFIX) || count >= MAX_RECOVERED_START_ATTRIBUTES) {\n continue;\n }\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n decoded[key.slice(ATTRIBUTE_PREFIX.length)] = value;\n count += 1;\n }\n }\n return count === 0 ? undefined : decoded;\n};\n\nconst encodeRecord = (record: SpanRecord): StateValue => ({\n kind: \"attributes\",\n attributes: {\n v: SPAN_RECORD_VERSION,\n providerId: record.providerId,\n ...(record.startEventId === undefined ? {} : { startEventId: record.startEventId }),\n ...(record.startedAt === undefined ? {} : { startedAt: record.startedAt }),\n ...(record.endEventId === undefined ? {} : { endEventId: record.endEventId }),\n ...(record.endedAt === undefined ? {} : { endedAt: record.endedAt }),\n ...(record.exported === true ? { exported: true } : {}),\n ...(record.parent === undefined\n ? {}\n : { parentFamily: record.parent.family, parentScopeKey: record.parent.scopeKey }),\n ...encodeAttributes(record.attributes),\n },\n});\n\nconst decodeRecord = (attributes: Attributes): DecodedRecord => {\n if (attributes[\"v\"] !== SPAN_RECORD_VERSION) {\n return { kind: \"incompatible\" };\n }\n const providerId = optionalString(attributes[\"providerId\"]);\n if (providerId === undefined) {\n return { kind: \"corrupt\" };\n }\n // A half-written edge (a timestamp with no event id, or the reverse) is not\n // an edge we can reason about; the record is refused rather than completed\n // with an invented half.\n const startedAt = optionalNumber(attributes[\"startedAt\"]);\n const startEventId = optionalString(attributes[\"startEventId\"]);\n if ((startedAt === undefined) !== (startEventId === undefined)) {\n return { kind: \"corrupt\" };\n }\n const endedAt = optionalNumber(attributes[\"endedAt\"]);\n const endEventId = optionalString(attributes[\"endEventId\"]);\n if ((endedAt === undefined) !== (endEventId === undefined)) {\n return { kind: \"corrupt\" };\n }\n const exported = attributes[\"exported\"] === true;\n const parentFamily = attributes[\"parentFamily\"];\n const parentScopeKey = optionalString(attributes[\"parentScopeKey\"]);\n const parent =\n isSpanFamily(parentFamily) && parentScopeKey !== undefined\n ? { family: parentFamily, scopeKey: parentScopeKey }\n : undefined;\n const decodedAttributes = decodeAttributes(attributes);\n return {\n kind: \"present\",\n record: {\n providerId,\n ...(startEventId === undefined ? {} : { startEventId }),\n ...(startedAt === undefined ? {} : { startedAt }),\n ...(endEventId === undefined ? {} : { endEventId }),\n ...(endedAt === undefined ? {} : { endedAt }),\n ...(parent === undefined ? {} : { parent }),\n ...(exported ? { exported: true } : {}),\n ...(decodedAttributes === undefined ? {} : { attributes: decodedAttributes }),\n },\n };\n};\n\nconst factsOf = (record: SpanRecord): SpanCorrelationFacts => ({\n ...(record.startedAt === undefined ? {} : { startedAt: record.startedAt }),\n ...(record.endedAt === undefined ? {} : { endedAt: record.endedAt }),\n ...(record.parent === undefined ? {} : { parent: record.parent }),\n ...(record.attributes === undefined ? {} : { attributes: record.attributes }),\n});\n\n/**\n * Persisted facts speak in event time (`startedAt`); a span speaks in the\n * milliseconds it is stamped with. Translated in one place so the two\n * vocabularies cannot silently drift apart.\n */\nconst correlationTimesOf = (\n facts: SpanCorrelationFacts,\n options: { readonly withStart: boolean } = { withStart: true },\n): Pick<SpanCorrelation, \"startMillis\" | \"endMillis\" | \"parent\" | \"attributes\"> => ({\n ...(facts.startedAt === undefined || !options.withStart ? {} : { startMillis: facts.startedAt }),\n ...(facts.endedAt === undefined ? {} : { endMillis: facts.endedAt }),\n ...(facts.parent === undefined ? {} : { parent: facts.parent }),\n ...(facts.attributes === undefined ? {} : { attributes: facts.attributes }),\n});\n\nconst orphanClassificationOf = (reason: SpanEndOrphanReason): SpanOrphanClassification => {\n switch (reason) {\n case \"no-start-recorded\":\n return \"missing-start\";\n case \"start-expired\":\n return \"expired-start\";\n case \"already-closed\":\n return \"already-closed\";\n case \"provider-mismatch\":\n return \"provider-mismatch\";\n case \"state-incompatible\":\n return \"state-incompatible\";\n case \"state-corrupt\":\n return \"state-corrupt\";\n }\n};\n\ntype BatchGroup = {\n readonly providerId: string;\n readonly sessionId: string;\n readonly ref: SpanScopeRef;\n start?: CanonicalEvent;\n end?: CanonicalEvent;\n};\n\nexport const createSpanCorrelator = (deps: SpanCorrelatorDependencies): SpanCorrelator => {\n const { stateStore, clock } = deps;\n const maxStartAgeMillis = deps.maxStartAgeMillis ?? DEFAULT_MAX_START_AGE_MILLIS;\n\n const keyFor = (input: {\n readonly sessionId: string;\n readonly providerId: string;\n readonly scope: LifecycleScope;\n readonly scopeKey: string;\n }): string => spanKey(input.sessionId, input.providerId, input.scope, input.scopeKey);\n\n /**\n * Reads and validates one record, deleting anything it refuses to interpret.\n * Self-healing on purpose: a single unreadable record must not make the same\n * scope unreadable forever.\n */\n const readRecord = async (key: string): Promise<DecodedRecord> => {\n const existing = await stateStore.read(key);\n if (existing === undefined) {\n return { kind: \"absent\" };\n }\n if (existing.value.kind !== \"attributes\") {\n await stateStore.delete(key);\n return { kind: \"corrupt\" };\n }\n const decoded = decodeRecord(existing.value.attributes);\n if (decoded.kind === \"corrupt\" || decoded.kind === \"incompatible\") {\n await stateStore.delete(key);\n }\n return decoded;\n };\n\n const recordStart = (input: SpanStartInput): Promise<SpanStartResult> =>\n withOptionalSessionLock(stateStore, input.sessionId, async (): Promise<SpanStartResult> => {\n const key = keyFor(input);\n const decoded = await readRecord(key);\n\n if (decoded.kind === \"present\") {\n const existing = decoded.record;\n if (existing.providerId !== input.providerId) {\n return { status: \"conflict\", reason: \"provider-mismatch\" };\n }\n if (existing.startEventId === input.eventId) {\n return { status: \"duplicate\", facts: factsOf(existing) };\n }\n if (existing.startEventId === undefined && existing.endEventId !== undefined) {\n // The end raced ahead of the start (two hook processes, no ordering\n // guarantee between them). Complete the record rather than treating\n // the late start as the beginning of a second span.\n //\n // If that end was already exported, the scope's canonical span id is\n // already on the wire and this start must stay silent: re-exporting a\n // now-complete span under the same id would be a duplicate, not a\n // correction, because OTLP has no update. The enrichment is lost and the\n // published record remains the orphan the end could honestly produce.\n const completed: SpanRecord = {\n ...existing,\n startEventId: input.eventId,\n startedAt: input.occurredAt,\n ...(input.parent === undefined ? {} : { parent: input.parent }),\n ...(input.attributes === undefined ? {} : { attributes: input.attributes }),\n };\n await stateStore.write(key, encodeRecord(completed));\n return existing.exported === true\n ? { status: \"published\", facts: factsOf(completed) }\n : { status: \"recorded\", facts: factsOf(completed) };\n }\n }\n\n // Either nothing was recorded, or a *different* start claims this scope\n // key: the previous span is superseded rather than merged into.\n const fresh: SpanRecord = {\n providerId: input.providerId,\n startEventId: input.eventId,\n startedAt: input.occurredAt,\n ...(input.parent === undefined ? {} : { parent: input.parent }),\n ...(input.attributes === undefined ? {} : { attributes: input.attributes }),\n };\n await stateStore.write(key, encodeRecord(fresh));\n return { status: \"recorded\", facts: factsOf(fresh) };\n });\n\n const recordEnd = (input: SpanEndInput): Promise<SpanEndResult> =>\n withOptionalSessionLock(stateStore, input.sessionId, async (): Promise<SpanEndResult> => {\n const key = keyFor(input);\n const decoded = await readRecord(key);\n\n if (decoded.kind === \"incompatible\" || decoded.kind === \"corrupt\") {\n const reason = decoded.kind === \"incompatible\" ? \"state-incompatible\" : \"state-corrupt\";\n return { status: \"orphaned\", reason, facts: { endedAt: input.occurredAt } };\n }\n if (decoded.kind === \"absent\") {\n // Remember the end anyway: a start that arrives late still deserves to\n // be paired rather than exported as a second orphan.\n const endOnly: SpanRecord = {\n providerId: input.providerId,\n endEventId: input.eventId,\n endedAt: input.occurredAt,\n // This end is about to be exported as an orphan under the scope's\n // canonical span id, so a start arriving later must not reuse it.\n exported: true,\n };\n await stateStore.write(key, encodeRecord(endOnly));\n return { status: \"orphaned\", reason: \"no-start-recorded\", facts: factsOf(endOnly) };\n }\n\n const existing = decoded.record;\n if (existing.providerId !== input.providerId) {\n return {\n status: \"orphaned\",\n reason: \"provider-mismatch\",\n facts: { endedAt: input.occurredAt },\n };\n }\n if (existing.endEventId === input.eventId) {\n // Idempotent replay: answer with the facts already on disk so the\n // re-exported span is byte-identical to the first one.\n return { status: \"duplicate\", facts: factsOf(existing) };\n }\n if (existing.endEventId !== undefined) {\n return {\n status: \"orphaned\",\n reason: \"already-closed\",\n facts: { endedAt: input.occurredAt },\n };\n }\n if (existing.startedAt === undefined) {\n const replaced: SpanRecord = {\n ...existing,\n endEventId: input.eventId,\n endedAt: input.occurredAt,\n exported: true,\n };\n await stateStore.write(key, encodeRecord(replaced));\n return { status: \"orphaned\", reason: \"no-start-recorded\", facts: factsOf(replaced) };\n }\n if (input.occurredAt - existing.startedAt > maxStartAgeMillis) {\n await stateStore.delete(key);\n return { status: \"orphaned\", reason: \"start-expired\", facts: { endedAt: input.occurredAt } };\n }\n\n const closed: SpanRecord = {\n ...existing,\n endEventId: input.eventId,\n endedAt: input.occurredAt,\n exported: true,\n };\n await stateStore.write(key, encodeRecord(closed));\n return {\n status: \"matched\",\n startedAt: existing.startedAt,\n durationMillis: Math.max(0, input.occurredAt - existing.startedAt),\n facts: factsOf(closed),\n };\n });\n\n const correlateGroup = async (group: BatchGroup): Promise<SpanCorrelation> => {\n const base = {\n providerId: group.providerId,\n sessionId: group.sessionId,\n ref: group.ref,\n } as const;\n const unpaired = (\n orphan: SpanOrphanClassification,\n facts: SpanCorrelationFacts,\n ): SpanCorrelation => ({\n ...base,\n pairing: \"unpaired\",\n orphan,\n // An unpaired span has no trustworthy start, so a start time is the one\n // fact it must not carry; everything else recovered is still true.\n ...correlationTimesOf(facts, { withStart: false }),\n });\n\n let startFacts: SpanCorrelationFacts | undefined;\n if (group.start !== undefined) {\n const parent = parentScopeRefOf(group.start);\n const result = await recordStart({\n sessionId: group.sessionId,\n providerId: group.providerId,\n scope: group.ref.family,\n scopeKey: group.ref.scopeKey,\n eventId: group.start.eventId,\n occurredAt: group.start.occurredAt,\n ...(parent === undefined ? {} : { parent }),\n attributes: startOnlySpanAttributes(group.start),\n });\n if (result.status === \"conflict\") {\n return unpaired(\"provider-mismatch\", {});\n }\n if (result.status === \"published\" && group.end === undefined) {\n // The end already exported this scope's span. Completing the record was\n // still worth doing (a redelivered end replays identical facts), but\n // emitting here would duplicate a span id already on the wire.\n return { ...unpaired(\"already-closed\", result.facts), disposition: \"defer\" };\n }\n startFacts = result.facts;\n }\n\n if (group.end === undefined) {\n const facts = startFacts ?? {};\n // A start whose end already landed (the racing-process case) closes a\n // complete span, even though only the start is in this batch.\n if (facts.endedAt !== undefined) {\n return {\n ...base,\n pairing: \"cross-process\",\n orphan: \"none\",\n disposition: \"emit\",\n ...correlationTimesOf(facts),\n };\n }\n // The end has not arrived. The start is durable now, so the end edge will\n // export one complete span under this scope's derived id; exporting a\n // zero-duration record here as well would put two records with that same id\n // on the wire, and OTLP cannot revise a span.\n return { ...unpaired(\"missing-end\", facts), disposition: \"defer\" };\n }\n\n const result = await recordEnd({\n sessionId: group.sessionId,\n providerId: group.providerId,\n scope: group.ref.family,\n scopeKey: group.ref.scopeKey,\n eventId: group.end.eventId,\n occurredAt: group.end.occurredAt,\n });\n\n if (result.status === \"orphaned\") {\n const orphan = orphanClassificationOf(result.reason);\n // `already-closed` means a *second, distinct* end for a scope whose first\n // end has already been exported under this scope's derived span id. Both\n // ends are real observations, so neither is dropped — but the second must\n // not reuse that id. Keying the discriminator on the end event id keeps a\n // redelivery of this same second end idempotent, since it recomputes the\n // same id rather than inventing a third.\n return orphan === \"already-closed\"\n ? {\n ...unpaired(orphan, result.facts),\n disposition: \"emit\",\n spanIdDiscriminator: group.end.eventId,\n }\n : { ...unpaired(orphan, result.facts), disposition: \"emit\" };\n }\n if (result.status === \"duplicate\" && result.facts.startedAt === undefined) {\n // A replayed end that never had a start is still an orphan.\n return { ...unpaired(\"missing-start\", result.facts), disposition: \"emit\" };\n }\n return {\n ...base,\n pairing: group.start === undefined ? \"cross-process\" : \"in-batch\",\n orphan: \"none\",\n disposition: \"emit\",\n ...correlationTimesOf(result.facts),\n };\n };\n\n const correlateBatch = async (\n events: readonly CanonicalEvent[],\n ): Promise<readonly SpanCorrelation[]> => {\n const groups = new Map<string, BatchGroup>();\n for (const event of events) {\n const ref = spanScopeRefOf(event);\n if (ref === undefined) {\n continue;\n }\n const providerId = event.provenance.providerId;\n const groupKey = [providerId, event.sessionId, ref.family, ref.scopeKey].join(\"\\u0000\");\n const group: BatchGroup = groups.get(groupKey) ?? {\n providerId,\n sessionId: event.sessionId,\n ref,\n };\n if (event.type.endsWith(\".start\")) {\n group.start = event;\n } else {\n group.end = event;\n }\n groups.set(groupKey, group);\n }\n\n const correlations: SpanCorrelation[] = [];\n for (const group of groups.values()) {\n try {\n correlations.push(await correlateGroup(group));\n } catch {\n // Fail open: an unreachable, locked, or unwritable state store costs a\n // span its pairing, never the whole export.\n //\n // A start whose record could not be written is the case that needs care.\n // It is *not* deferrable — deferring means \"the state store is holding\n // this, the end edge will publish it\", and here the state store is exactly\n // what failed. So it must be exported, and it must not use the scope's\n // canonical span id: nothing recorded this start, so a later end will\n // publish that id itself as an orphan, and reusing it would put two\n // records with one identity on the wire. Discriminating by the start's own\n // event id makes this record honest and collision-free.\n const unrecordedStart = group.start !== undefined && group.end === undefined;\n correlations.push({\n providerId: group.providerId,\n sessionId: group.sessionId,\n ref: group.ref,\n pairing: \"unpaired\",\n orphan: \"state-unavailable\",\n disposition: \"emit\",\n ...(unrecordedStart && group.start !== undefined\n ? { spanIdDiscriminator: group.start.eventId }\n : {}),\n });\n }\n }\n return correlations;\n };\n\n const cleanup = async (\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<SpanCleanupResult> => {\n const keys = await stateStore.keys(spanScanPrefix(options?.sessionId));\n const cap = options?.maxEntries ?? 1_000;\n const now = clock.now();\n let removed = 0;\n let scanned = 0;\n let expiredOpen = 0;\n for (const key of keys) {\n if (scanned >= cap) {\n break;\n }\n scanned += 1;\n const record = await stateStore.read(key);\n if (record !== undefined && now - record.updatedAt > maxAgeMillis) {\n // Classified before deletion: a record with a start and no end is a span\n // that will never be exported, which is worth counting rather than\n // discarding silently.\n if (record.value.kind === \"attributes\") {\n const decoded = decodeRecord(record.value.attributes);\n if (\n decoded.kind === \"present\" &&\n decoded.record.startedAt !== undefined &&\n decoded.record.endedAt === undefined\n ) {\n expiredOpen += 1;\n }\n }\n await stateStore.delete(key);\n removed += 1;\n }\n }\n return { removed, scanned, expiredOpen };\n };\n\n return { recordStart, recordEnd, correlateBatch, cleanup };\n};\n","import {\n UsageNormalizationError,\n normalizeUsageOrThrow,\n type CanonicalUsage,\n} from \"../model/usage.js\";\nimport type { Attributes } from \"../model/primitives.js\";\nimport type { Clock, StateStore } from \"../runtime/ports.js\";\nimport { withOptionalSessionLock } from \"../state/store.js\";\nimport { rollupEpochKey, rollupEpochScanPrefix, rollupScanPrefix, rollupUsageKey } from \"./keys.js\";\n\nexport type UsageAccumulatorKey = {\n readonly sessionId: string;\n readonly scope: string;\n readonly scopeKey: string;\n};\n\nexport type UsageAccumulatorSnapshot = {\n readonly total: CanonicalUsage;\n /** Increments every time {@link UsageAccumulator.recordReset} is called for this key. */\n readonly epoch: number;\n};\n\nexport type RollupCleanupResult = { readonly removed: number; readonly scanned: number };\n\n/**\n * Which delivery an accumulation belongs to, and which of its observations this is.\n *\n * Supplying it makes the accumulation idempotent for *that delivery*: a second\n * application of the same `(callbackId, ordinal)` is a no-op that returns the\n * current total. Omitting it keeps the old unconditional behaviour, which is right\n * for a caller that has no delivery identity to key on — there is nothing to\n * recognize a repeat by, and refusing to accumulate would lose a real observation.\n *\n * `callbackId` must be an opaque digest, not a raw host or provider id: it is\n * written into a state record.\n */\nexport type DeliveryStamp = {\n readonly callbackId: string;\n /** Zero-based index of this observation within the delivery, per rollup key. */\n readonly ordinal: number;\n};\n\nexport type AccumulateOptions = { readonly delivery?: DeliveryStamp };\n\n/**\n * Rolls a stream of `delta` usage observations up into a running `cumulative`\n * total per scope, independent of the orchestrator's own per-scope\n * cumulative-to-delta baseline (`docs/usage-semantics.md`) — that baseline\n * answers \"what changed since last time\"; this answers \"what is the running\n * total\", which a diagnostics view or a parent scope (tool -> generation ->\n * session) needs and the core does not compute.\n *\n * A provider counter can restart mid-session (a process restart, a replayed\n * transcript). Rather than let a smaller cumulative total silently deflate the\n * running rollup, {@link UsageAccumulator.recordReset} starts a new epoch: the\n * total resets to zero and the epoch number increments, so a downstream\n * consumer can tell \"the counter restarted\" from \"usage actually decreased\"\n * and never sums across the boundary as if it were one continuous series.\n */\nexport interface UsageAccumulator {\n /**\n * Fold `delta` into the running total for `key`.\n *\n * With `options.delivery`, folding is idempotent for that delivery: a redelivered\n * callback whose claim was reclaimed or superseded re-derives the same delta and\n * would otherwise count it twice. The marker lives in the same record as the total\n * it describes, so the check and the write are one atomic operation — which is the\n * only reason this is expressible without a multi-key transaction. What it does\n * *not* cover is a delivery whose marker a later, different delivery has since\n * overwritten: only the most recent delivery per rollup key is recognizable, which\n * is exactly the retry window and nothing beyond it.\n */\n accumulateDelta(\n key: UsageAccumulatorKey,\n delta: CanonicalUsage,\n options?: AccumulateOptions,\n ): Promise<UsageAccumulatorSnapshot>;\n /** Start a new epoch. Idempotent per delivery when `options.delivery` is given. */\n recordReset(key: UsageAccumulatorKey, options?: AccumulateOptions): Promise<{ readonly epoch: number }>;\n read(key: UsageAccumulatorKey): Promise<UsageAccumulatorSnapshot | undefined>;\n cleanup(\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<RollupCleanupResult>;\n}\n\nexport type UsageAccumulatorDependencies = {\n readonly stateStore: StateStore;\n readonly clock: Clock;\n};\n\nconst EMPTY_CUMULATIVE_USAGE: CanonicalUsage = normalizeUsageOrThrow({ temporality: \"cumulative\" });\n\nconst combineCumulativeWithDelta = (total: CanonicalUsage, delta: CanonicalUsage): CanonicalUsage => {\n if (total.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"usage rollup total must have cumulative temporality\" },\n ]);\n }\n if (delta.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"usage accumulator only accepts delta observations\" },\n ]);\n }\n\n const accounting =\n total.cacheCreationInputTokens === 0 && total.cacheCreationAccounting === \"not-reported\"\n ? delta.cacheCreationAccounting\n : delta.cacheCreationInputTokens === 0 && delta.cacheCreationAccounting === \"not-reported\"\n ? total.cacheCreationAccounting\n : total.cacheCreationAccounting;\n\n if (\n total.cacheCreationInputTokens !== 0 &&\n delta.cacheCreationInputTokens !== 0 &&\n total.cacheCreationAccounting !== delta.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot roll up usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n total.providerTotalTokens === undefined && delta.providerTotalTokens === undefined\n ? undefined\n : (total.providerTotalTokens ?? 0) + (delta.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"cumulative\",\n inputTokens: total.inputTokens + delta.inputTokens,\n cachedInputTokens: total.cachedInputTokens + delta.cachedInputTokens,\n cacheCreationInputTokens: total.cacheCreationInputTokens + delta.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: total.outputTokens + delta.outputTokens,\n reasoningOutputTokens: total.reasoningOutputTokens + delta.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n\nexport const createUsageAccumulator = (deps: UsageAccumulatorDependencies): UsageAccumulator => {\n const { stateStore, clock } = deps;\n\n /**\n * The epoch record's own delivery marker.\n *\n * Kept in the epoch record for the same reason the total's marker is kept in the\n * total: one write, so the counter and the statement about who moved it cannot\n * disagree. The epoch record is an `attributes` value, so the two fields are\n * flat rather than nested.\n */\n const readEpochMarker = (\n attributes: Attributes,\n ): { readonly callbackId: string; readonly applications: number } | undefined => {\n const callbackId = attributes.resetDelivery;\n const applications = attributes.resetApplications;\n if (\n typeof callbackId !== \"string\" ||\n callbackId.length === 0 ||\n typeof applications !== \"number\" ||\n !Number.isInteger(applications) ||\n applications < 1\n ) {\n return undefined;\n }\n return { callbackId, applications };\n };\n\n const readEpoch = async (key: UsageAccumulatorKey): Promise<number> => {\n const record = await stateStore.read(rollupEpochKey(key.sessionId, key.scope, key.scopeKey));\n if (record?.value.kind === \"attributes\" && typeof record.value.attributes.epoch === \"number\") {\n return record.value.attributes.epoch;\n }\n return 0;\n };\n\n /**\n * Whether this delivery's observation number `ordinal` is already folded in.\n *\n * The comparison is `<` rather than `===` because observations are applied in\n * order: `applications` is the count folded in so far, so any ordinal below it has\n * been seen. A marker naming a *different* delivery means this rollup has moved on\n * and nothing can be recognized.\n */\n const alreadyApplied = (\n marker: { readonly callbackId: string; readonly applications: number } | undefined,\n delivery: DeliveryStamp | undefined,\n ): boolean =>\n delivery !== undefined &&\n marker !== undefined &&\n marker.callbackId === delivery.callbackId &&\n delivery.ordinal < marker.applications;\n\n const markerFor = (\n delivery: DeliveryStamp | undefined,\n ): { readonly appliedDelivery?: { readonly callbackId: string; readonly applications: number } } =>\n delivery === undefined\n ? {}\n : {\n appliedDelivery: { callbackId: delivery.callbackId, applications: delivery.ordinal + 1 },\n };\n\n const accumulateDelta = (\n key: UsageAccumulatorKey,\n delta: CanonicalUsage,\n options?: AccumulateOptions,\n ): Promise<UsageAccumulatorSnapshot> =>\n withOptionalSessionLock(stateStore, key.sessionId, async (): Promise<UsageAccumulatorSnapshot> => {\n const usageKey = rollupUsageKey(key.sessionId, key.scope, key.scopeKey);\n const existing = await stateStore.read(usageKey);\n const previousTotal =\n existing?.value.kind === \"usage-cumulative\" ? existing.value.usage : EMPTY_CUMULATIVE_USAGE;\n\n if (\n existing?.value.kind === \"usage-cumulative\" &&\n alreadyApplied(existing.value.appliedDelivery, options?.delivery)\n ) {\n // This exact observation of this exact delivery is already in the total.\n // Reporting the total unchanged is the honest answer: the caller asked for\n // the running figure after its delta, and that is what this is.\n return { total: previousTotal, epoch: await readEpoch(key) };\n }\n\n const total = combineCumulativeWithDelta(previousTotal, delta);\n await stateStore.write(usageKey, {\n kind: \"usage-cumulative\",\n usage: total,\n ...markerFor(options?.delivery),\n });\n return { total, epoch: await readEpoch(key) };\n });\n\n const recordReset = (\n key: UsageAccumulatorKey,\n options?: AccumulateOptions,\n ): Promise<{ readonly epoch: number }> =>\n withOptionalSessionLock(stateStore, key.sessionId, async (): Promise<{ readonly epoch: number }> => {\n const epochKey = rollupEpochKey(key.sessionId, key.scope, key.scopeKey);\n const existingEpoch = await stateStore.read(epochKey);\n const marker =\n existingEpoch?.value.kind === \"attributes\"\n ? readEpochMarker(existingEpoch.value.attributes)\n : undefined;\n\n if (alreadyApplied(marker, options?.delivery)) {\n // A replayed reset must not open a second epoch: the epoch number is what a\n // consumer uses to refuse summing across a counter restart, and inflating it\n // twice for one restart makes a real series look like two.\n return { epoch: await readEpoch(key) };\n }\n\n const epoch = (await readEpoch(key)) + 1;\n const applied = markerFor(options?.delivery).appliedDelivery;\n await stateStore.write(epochKey, {\n kind: \"attributes\",\n attributes: {\n epoch,\n ...(applied === undefined\n ? {}\n : { resetDelivery: applied.callbackId, resetApplications: applied.applications }),\n },\n });\n await stateStore.delete(rollupUsageKey(key.sessionId, key.scope, key.scopeKey));\n return { epoch };\n });\n\n const read = async (key: UsageAccumulatorKey): Promise<UsageAccumulatorSnapshot | undefined> => {\n const record = await stateStore.read(rollupUsageKey(key.sessionId, key.scope, key.scopeKey));\n if (record?.value.kind !== \"usage-cumulative\") {\n return undefined;\n }\n return { total: record.value.usage, epoch: await readEpoch(key) };\n };\n\n const cleanup = async (\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<RollupCleanupResult> => {\n const cap = options?.maxEntries ?? 1_000;\n const now = clock.now();\n let removed = 0;\n let scanned = 0;\n\n const sweep = async (keys: readonly string[]): Promise<void> => {\n for (const key of keys) {\n if (scanned >= cap) {\n return;\n }\n scanned += 1;\n const record = await stateStore.read(key);\n if (record !== undefined && now - record.updatedAt > maxAgeMillis) {\n await stateStore.delete(key);\n removed += 1;\n }\n }\n };\n\n await sweep(await stateStore.keys(rollupScanPrefix(options?.sessionId)));\n await sweep(await stateStore.keys(rollupEpochScanPrefix(options?.sessionId)));\n return { removed, scanned };\n };\n\n return { accumulateDelta, recordReset, read, cleanup };\n};\n","import { createHash } from \"node:crypto\";\n\nimport type { Clock, StateStore } from \"../runtime/ports.js\";\nimport { withOptionalSessionLock } from \"../state/store.js\";\nimport {\n emptyHistogram,\n METRIC_INSTRUMENTS,\n recordIntoHistogram,\n seriesIdentity,\n type HistogramState,\n type MetricObservation,\n type MetricPoint,\n} from \"../telemetry/metric-model.js\";\nimport { metricSeriesKey, metricSeriesScanPrefix } from \"./keys.js\";\n\n/**\n * Cumulative metric series kept across hook processes (issue #69).\n *\n * A hook process lives for one callback, so an in-process `MeterProvider` would\n * only ever see one observation and restart every series at zero. Cumulative\n * temporality — what receivers that merge counters by keeping the largest value\n * need — therefore requires the running total to outlive the process. Each series\n * is one state record: read, fold the batch's observations in, write back, and\n * export the new total as a point whose interval starts at the series' first\n * observation.\n *\n * Folding is idempotent per delivery: the record names the last delivery folded\n * into it, so a callback replayed after a crash between \"recorded\" and \"committed\"\n * restates the total instead of adding to it.\n *\n * Concurrency: the read-fold-write runs under the session lock of the series'\n * scope (the provider session, or one shared lock for series that span sessions),\n * the same lock usage accounting uses, so two concurrent processes cannot both add\n * to the same stale total.\n */\n\nexport type MetricSeriesStoreDependencies = {\n readonly stateStore: StateStore;\n readonly clock: Clock;\n};\n\nexport type RecordCumulativeOptions = {\n /** Opaque digest of the delivery these observations came from. */\n readonly deliveryToken?: string;\n /** Whether series are per session (`session.id` on the points). Default true. */\n readonly perSession?: boolean;\n};\n\nexport type MetricSeriesCleanupResult = { readonly removed: number; readonly scanned: number };\n\nexport interface MetricSeriesStore {\n /** Fold observations into their series; returns one cumulative point per touched series. */\n recordCumulative(\n observations: readonly MetricObservation[],\n options?: RecordCumulativeOptions,\n ): Promise<readonly MetricPoint[]>;\n /** Remember when the session's current turn began (its last prompt). */\n recordTurnStart(sessionId: string, startMillis: number): Promise<void>;\n /** When the session's current turn began, if a prompt was recorded. */\n readTurnStart(sessionId: string): Promise<number | undefined>;\n cleanup(\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<MetricSeriesCleanupResult>;\n}\n\n/** Not a base64url digest (43 chars), so it can never collide with a series key. */\nconst TURN_START_SEGMENT = \"turn-start\";\n\n/** Lock and key scope for series that are not per session. */\nconst SHARED_SCOPE = \"all\";\nconst SHARED_LOCK = \"otelhook.metrics.shared\";\n\nconst sessionScope = (sessionId: string): string => `s=${sessionId}`;\n\nconst digest = (identity: string): string =>\n createHash(\"sha256\").update(identity).digest(\"base64url\").slice(0, 43);\n\ntype SeriesRecord = {\n readonly startTimeMillis: number;\n readonly value?: number | undefined;\n readonly histogram?: HistogramState | undefined;\n readonly appliedDelivery?: string | undefined;\n};\n\nconst toStoredHistogram = (\n histogram: HistogramState,\n): { count: number; sum: number; min: number; max: number; bucketCounts: number[] } => ({\n count: histogram.count,\n sum: histogram.sum,\n // An empty histogram has infinite min/max, which JSON cannot hold. A stored\n // histogram always has at least one value, so these are finite in practice.\n min: Number.isFinite(histogram.min) ? histogram.min : 0,\n max: Number.isFinite(histogram.max) ? histogram.max : 0,\n bucketCounts: [...histogram.bucketCounts],\n});\n\nexport const createMetricSeriesStore = (deps: MetricSeriesStoreDependencies): MetricSeriesStore => {\n const { stateStore, clock } = deps;\n\n const readSeries = async (key: string): Promise<SeriesRecord | undefined> => {\n const record = await stateStore.read(key);\n if (record?.value.kind !== \"metric-series\") {\n return undefined;\n }\n return record.value;\n };\n\n const recordGroup = async (\n scope: string,\n observations: readonly MetricObservation[],\n deliveryToken: string | undefined,\n ): Promise<MetricPoint[]> => {\n const bySeries = new Map<string, MetricObservation[]>();\n for (const observation of observations) {\n const identity = seriesIdentity(observation.instrument, observation.attributes);\n const group = bySeries.get(identity) ?? [];\n group.push(observation);\n bySeries.set(identity, group);\n }\n\n const now = clock.now();\n const points: MetricPoint[] = [];\n for (const [identity, group] of bySeries) {\n const first = group[0];\n if (first === undefined) {\n continue;\n }\n const instrument = METRIC_INSTRUMENTS[first.instrument];\n const key = metricSeriesKey(scope, digest(identity));\n const existing = await readSeries(key);\n const boundaries = instrument.boundaries;\n // A stored histogram whose bucket layout no longer matches the instrument\n // cannot be continued; it restarts, with a new start time, which a receiver\n // reads as a reset rather than as a decrease.\n const compatible =\n existing !== undefined &&\n (boundaries === undefined\n ? existing.value !== undefined\n : existing.histogram?.bucketCounts.length === boundaries.length + 1);\n const base = compatible ? existing : undefined;\n const replay = deliveryToken !== undefined && base?.appliedDelivery === deliveryToken;\n\n const earliest = Math.min(...group.map((observation) => observation.timeMillis));\n const startTimeMillis = base?.startTimeMillis ?? Math.min(earliest, now);\n let value = base?.value ?? 0;\n let histogram: HistogramState | undefined =\n boundaries === undefined\n ? undefined\n : base?.histogram === undefined\n ? emptyHistogram(boundaries)\n : base.histogram;\n\n if (!replay) {\n for (const observation of group) {\n if (histogram !== undefined && boundaries !== undefined) {\n histogram = recordIntoHistogram(histogram, boundaries, observation.value);\n } else {\n value += observation.value;\n }\n }\n await stateStore.write(key, {\n kind: \"metric-series\",\n startTimeMillis,\n ...(histogram === undefined ? { value } : { histogram: toStoredHistogram(histogram) }),\n ...(deliveryToken === undefined ? {} : { appliedDelivery: deliveryToken }),\n });\n }\n\n points.push({\n instrument: first.instrument,\n temporality: \"cumulative\",\n attributes: first.attributes,\n startTimeMillis,\n timeMillis: Math.max(now, startTimeMillis),\n ...(histogram === undefined ? { value } : { histogram }),\n });\n }\n return points;\n };\n\n const recordCumulative = async (\n observations: readonly MetricObservation[],\n options?: RecordCumulativeOptions,\n ): Promise<readonly MetricPoint[]> => {\n if (observations.length === 0) {\n return [];\n }\n if (options?.perSession === false) {\n return withOptionalSessionLock(stateStore, SHARED_LOCK, () =>\n recordGroup(SHARED_SCOPE, observations, options.deliveryToken),\n );\n }\n const bySession = new Map<string, MetricObservation[]>();\n for (const observation of observations) {\n const group = bySession.get(observation.sessionId) ?? [];\n group.push(observation);\n bySession.set(observation.sessionId, group);\n }\n const points: MetricPoint[] = [];\n for (const [sessionId, group] of bySession) {\n points.push(\n ...(await withOptionalSessionLock(stateStore, sessionId, () =>\n recordGroup(sessionScope(sessionId), group, options?.deliveryToken),\n )),\n );\n }\n return points;\n };\n\n const cleanup = async (\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<MetricSeriesCleanupResult> => {\n const cap = options?.maxEntries ?? 1_000;\n const now = clock.now();\n let removed = 0;\n let scanned = 0;\n const prefix = metricSeriesScanPrefix(\n options?.sessionId === undefined ? undefined : sessionScope(options.sessionId),\n );\n for (const key of await stateStore.keys(prefix)) {\n if (scanned >= cap) {\n break;\n }\n scanned += 1;\n const record = await stateStore.read(key);\n if (record !== undefined && now - record.updatedAt > maxAgeMillis) {\n await stateStore.delete(key);\n removed += 1;\n }\n }\n return { removed, scanned };\n };\n\n const turnKey = (sessionId: string): string => metricSeriesKey(sessionScope(sessionId), TURN_START_SEGMENT);\n\n const recordTurnStart = (sessionId: string, startMillis: number): Promise<void> =>\n withOptionalSessionLock(stateStore, sessionId, async () => {\n const existing = await stateStore.read(turnKey(sessionId));\n const previous =\n existing?.value.kind === \"attributes\" && typeof existing.value.attributes.startMillis === \"number\"\n ? existing.value.attributes.startMillis\n : undefined;\n // Never move backwards: a late, redelivered prompt must not reopen an older turn.\n if (previous !== undefined && previous >= startMillis) {\n return;\n }\n await stateStore.write(turnKey(sessionId), { kind: \"attributes\", attributes: { startMillis } });\n });\n\n const readTurnStart = async (sessionId: string): Promise<number | undefined> => {\n const record = await stateStore.read(turnKey(sessionId));\n const value = record?.value.kind === \"attributes\" ? record.value.attributes.startMillis : undefined;\n return typeof value === \"number\" ? value : undefined;\n };\n\n return { recordCumulative, recordTurnStart, readTurnStart, cleanup };\n};\n","import type { Attributes } from \"@opentelemetry/api\";\nimport type { Resource } from \"@opentelemetry/resources\";\n\nimport type { CanonicalEvent, GenerationEndEvent } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\nimport { resolveExportedSessionId } from \"./export-identity.js\";\n\n/**\n * Metrics derived from hook events (issue #69).\n *\n * otel-hook already normalizes every provider's hook callbacks into canonical\n * events; this module turns one batch of those events into *observations* — a\n * value recorded against an instrument, with attributes. It is pure: it reads no\n * state and sends nothing. Aggregating observations into OTLP data points\n * (cumulative across processes, or delta per batch) and exporting them are the\n * jobs of `lifecycle/metric-series.ts` and `otlp-metric-sink.ts`.\n *\n * ## Why observations come from the runtime's accounting, not from the events alone\n *\n * Token usage is taken from the orchestrator's `UsageObservation` deltas rather than\n * from `generation.end.usage` directly. A provider that reports a session-wide\n * running total (Codex) stamps the *cumulative* figure on every turn; summing those\n * into a histogram would bill a three-turn session several times over. The\n * orchestrator already diffs them against a persisted baseline, exactly once per\n * delivery, so the metric reuses that answer.\n *\n * ## What is never on a metric\n *\n * No account identity (`user.*`, `enduser.*`, `organization.id`), no content, no\n * paths, and no per-event ids (`otelhook.event.id`, tool-call ids, generation ids):\n * an id per data point is a new series per data point. `session.id` is the one\n * high-cardinality attribute, and it can be switched off.\n */\n\n/** Recommended bucket boundaries from the GenAI semantic conventions. */\nexport const TOKEN_USAGE_BUCKETS: readonly number[] = Object.freeze([\n 1, 4, 16, 64, 256, 1_024, 4_096, 16_384, 65_536, 262_144, 1_048_576, 4_194_304, 16_777_216,\n 67_108_864,\n]);\nexport const OPERATION_DURATION_BUCKETS: readonly number[] = Object.freeze([\n 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24, 20.48, 40.96, 81.92,\n]);\n\nexport const METRIC_TOKEN_USAGE = \"gen_ai.client.token.usage\";\nexport const METRIC_OPERATION_DURATION = \"gen_ai.client.operation.duration\";\nexport const METRIC_SESSIONS = \"otelhook.sessions\";\nexport const METRIC_TOOL_CALLS = \"otelhook.tool.calls\";\nexport const METRIC_COST_USAGE = \"otelhook.cost.usage\";\n\nexport type MetricInstrumentName =\n | typeof METRIC_TOKEN_USAGE\n | typeof METRIC_OPERATION_DURATION\n | typeof METRIC_SESSIONS\n | typeof METRIC_TOOL_CALLS\n | typeof METRIC_COST_USAGE;\n\nexport type MetricInstrument = {\n readonly name: MetricInstrumentName;\n readonly kind: \"histogram\" | \"counter\";\n readonly unit: string;\n readonly description: string;\n /** Integer values (`asInt`) or doubles. Histograms always carry a double sum. */\n readonly valueType: \"int\" | \"double\";\n /** Histograms only. */\n readonly boundaries?: readonly number[];\n};\n\nexport const METRIC_INSTRUMENTS: Readonly<Record<MetricInstrumentName, MetricInstrument>> = Object.freeze({\n [METRIC_TOKEN_USAGE]: {\n name: METRIC_TOKEN_USAGE,\n kind: \"histogram\",\n unit: \"{token}\",\n description: \"Tokens used per generation, by token type (hook-derived)\",\n valueType: \"int\",\n boundaries: TOKEN_USAGE_BUCKETS,\n },\n [METRIC_OPERATION_DURATION]: {\n name: METRIC_OPERATION_DURATION,\n kind: \"histogram\",\n unit: \"s\",\n description: \"Generation duration, from its start hook to its end hook (hook-derived)\",\n valueType: \"double\",\n boundaries: OPERATION_DURATION_BUCKETS,\n },\n [METRIC_SESSIONS]: {\n name: METRIC_SESSIONS,\n kind: \"counter\",\n unit: \"{session}\",\n description: \"Agent sessions started\",\n valueType: \"int\",\n },\n [METRIC_TOOL_CALLS]: {\n name: METRIC_TOOL_CALLS,\n kind: \"counter\",\n unit: \"{call}\",\n description: \"Completed tool calls, by tool name and outcome\",\n valueType: \"int\",\n },\n [METRIC_COST_USAGE]: {\n name: METRIC_COST_USAGE,\n kind: \"counter\",\n unit: \"USD\",\n description: \"Cost reported by the provider; never estimated\",\n valueType: \"double\",\n },\n});\n\nexport const isMetricInstrumentName = (value: unknown): value is MetricInstrumentName =>\n typeof value === \"string\" && Object.hasOwn(METRIC_INSTRUMENTS, value);\n\nexport const ATTR_GEN_AI_TOKEN_TYPE = \"gen_ai.token.type\";\nexport const ATTR_GEN_AI_PROVIDER_NAME = \"gen_ai.provider.name\";\nconst ATTR_GEN_AI_OPERATION_NAME = \"gen_ai.operation.name\";\nconst ATTR_GEN_AI_REQUEST_MODEL = \"gen_ai.request.model\";\nconst ATTR_GEN_AI_RESPONSE_MODEL = \"gen_ai.response.model\";\nconst ATTR_GEN_AI_TOOL_NAME = \"gen_ai.tool.name\";\nconst ATTR_ERROR_TYPE = \"error.type\";\nconst ATTR_SESSION_ID = \"session.id\";\nconst ATTR_OTELHOOK_PROVIDER_ID = \"otelhook.provider.id\";\nconst ATTR_OTELHOOK_OUTCOME = \"otelhook.outcome\";\nconst ATTR_OTELHOOK_SESSION_KIND = \"otelhook.session.kind\";\n\n/**\n * Token types on `gen_ai.client.token.usage`.\n *\n * `input` is inclusive of cache reads, as the GenAI conventions define\n * `gen_ai.usage.input_tokens`. `cache_read` and `cache_creation` are extra series\n * describing parts of the input; summing every token type double-counts.\n */\nexport type TokenType = \"input\" | \"output\" | \"cache_read\" | \"cache_creation\";\n\nexport type MetricsTemporality = \"cumulative\" | \"delta\";\n\n/** One recorded value. */\nexport type MetricObservation = {\n readonly instrument: MetricInstrumentName;\n readonly value: number;\n /** Data-point attributes. Primitives only. */\n readonly attributes: Readonly<Record<string, string | number | boolean>>;\n /** When the observed thing happened, in epoch milliseconds. */\n readonly timeMillis: number;\n /** Provider session the observation belongs to; scopes cumulative state. */\n readonly sessionId: string;\n};\n\n/** A start time recovered for a generation, by generation id. */\nexport type GenerationStart = {\n readonly startMillis: number;\n readonly requestModel?: string;\n};\n\n/** The usage delta the orchestrator derived for one usage-bearing event. */\nexport type MetricUsageInput = {\n readonly eventId: string;\n readonly scope: string;\n readonly delta: CanonicalUsage;\n};\n\nexport type DeriveMetricObservationsInput = {\n readonly events: readonly CanonicalEvent[];\n readonly usage: readonly MetricUsageInput[];\n /** The exported resource; supplies the launcher's `session.id` when it sets one. */\n readonly resource: Resource;\n /** Put `session.id` on every data point. Default true. */\n readonly includeSessionId?: boolean;\n /**\n * Start times for generations whose start edge is not in this batch (it was\n * recorded by an earlier hook process). Looked up by generation id.\n */\n readonly generationStarts?: (generationId: string) => GenerationStart | undefined;\n /**\n * When the session's current turn began: the last `prompt.submitted` recorded,\n * by an earlier callback or this one. The fallback duration source for\n * providers whose generation is a turn (Claude Code, Codex).\n */\n readonly turnStart?: (sessionId: string) => number | undefined;\n};\n\nconst commonAttributes = (\n event: CanonicalEvent,\n resource: Resource,\n includeSessionId: boolean,\n): Record<string, string | number | boolean> => ({\n [ATTR_OTELHOOK_PROVIDER_ID]: event.provenance.providerId,\n ...(includeSessionId\n ? { [ATTR_SESSION_ID]: resolveExportedSessionId(event.sessionId, resource).sessionId }\n : {}),\n});\n\nconst generationAttributes = (\n end: GenerationEndEvent,\n requestModel: string | undefined,\n): Record<string, string> => ({\n [ATTR_GEN_AI_OPERATION_NAME]: \"chat\",\n ...(end.model.vendor === undefined ? {} : { [ATTR_GEN_AI_PROVIDER_NAME]: end.model.vendor }),\n [ATTR_GEN_AI_REQUEST_MODEL]: requestModel ?? end.model.modelId,\n [ATTR_GEN_AI_RESPONSE_MODEL]: end.model.modelId,\n});\n\nconst TOKEN_FIELDS: readonly (readonly [TokenType, (usage: CanonicalUsage) => number])[] = [\n [\"input\", (usage) => usage.inputTokens],\n [\"output\", (usage) => usage.outputTokens],\n [\"cache_read\", (usage) => usage.cachedInputTokens],\n [\"cache_creation\", (usage) => usage.cacheCreationInputTokens],\n];\n\nconst isFailedOutcome = (outcome: string): boolean =>\n outcome !== \"ok\" && outcome !== \"unknown\" && outcome !== \"cancelled\";\n\n/**\n * Observations for one batch.\n *\n * - `otelhook.sessions`: one per `session.start`.\n * - `otelhook.tool.calls`: one per `tool.end`.\n * - `gen_ai.client.operation.duration`: one per `generation.end` whose duration is\n * known, from the first source that has it:\n * 1. the duration the provider stated (`durationMillis`);\n * 2. a `generation.start` recorded by an *earlier* callback;\n * 3. the turn's start: the last `prompt.submitted` of the session, no later than\n * the end. For Claude Code and Codex a generation is a turn, so this is the\n * turn's wall-clock time, tool calls included.\n * A `generation.start` in the *same* batch as its end is not a start: an\n * adapter that emits both from one callback (Claude Code's `Stop`) synthesized\n * it, and measuring from it would record a zero.\n * - `gen_ai.client.token.usage`: per generation-scoped usage delta, one per token\n * type. A zero `cache_read` / `cache_creation` is not recorded: a provider that\n * never reports cache tokens would otherwise fill the low bucket with zeros.\n * `input` and `output` are always recorded, zero included, so the count of a\n * token histogram is the number of generations with usage.\n * - `otelhook.cost.usage`: per `generation.end` with a provider-reported USD cost.\n */\nexport const deriveMetricObservations = (\n input: DeriveMetricObservationsInput,\n): readonly MetricObservation[] => {\n const includeSessionId = input.includeSessionId ?? true;\n const observations: MetricObservation[] = [];\n const byId = new Map<string, CanonicalEvent>();\n const startsInBatch = new Map<string, GenerationStart>();\n for (const event of input.events) {\n byId.set(event.eventId, event);\n if (event.type === \"generation.start\") {\n startsInBatch.set(event.generationId, {\n startMillis: event.occurredAt,\n requestModel: event.model.modelId,\n });\n }\n }\n // Request model only: a start in this batch says what was asked for, but not when.\n const requestModelOf = (generationId: string): string | undefined =>\n startsInBatch.get(generationId)?.requestModel ?? input.generationStarts?.(generationId)?.requestModel;\n let lastPromptInBatch: Map<string, number> | undefined;\n for (const event of input.events) {\n if (event.type === \"prompt.submitted\") {\n lastPromptInBatch ??= new Map();\n lastPromptInBatch.set(event.sessionId, Math.max(lastPromptInBatch.get(event.sessionId) ?? 0, event.occurredAt));\n }\n }\n const measuredDurationOf = (end: GenerationEndEvent): number | undefined => {\n if (end.durationMillis !== undefined) {\n return end.durationMillis;\n }\n const recovered = startsInBatch.has(end.generationId) ? undefined : input.generationStarts?.(end.generationId);\n if (recovered !== undefined) {\n return end.occurredAt - recovered.startMillis;\n }\n const turn = lastPromptInBatch?.get(end.sessionId) ?? input.turnStart?.(end.sessionId);\n return turn === undefined || turn > end.occurredAt ? undefined : end.occurredAt - turn;\n };\n\n const push = (\n event: CanonicalEvent,\n instrument: MetricInstrumentName,\n value: number,\n attributes: Record<string, string | number | boolean>,\n ): void => {\n if (!Number.isFinite(value) || value < 0) {\n return;\n }\n observations.push({\n instrument,\n value,\n attributes: { ...commonAttributes(event, input.resource, includeSessionId), ...attributes },\n timeMillis: event.occurredAt,\n sessionId: event.sessionId,\n });\n };\n\n for (const event of input.events) {\n switch (event.type) {\n case \"session.start\":\n push(event, METRIC_SESSIONS, 1, { [ATTR_OTELHOOK_SESSION_KIND]: event.sessionKind });\n break;\n case \"tool.end\":\n push(event, METRIC_TOOL_CALLS, 1, {\n [ATTR_GEN_AI_TOOL_NAME]: event.toolName,\n [ATTR_OTELHOOK_OUTCOME]: event.outcome,\n });\n break;\n case \"generation.end\": {\n const attributes = generationAttributes(event, requestModelOf(event.generationId));\n const durationMillis = measuredDurationOf(event);\n if (durationMillis !== undefined && durationMillis >= 0) {\n push(event, METRIC_OPERATION_DURATION, durationMillis / 1000, {\n ...attributes,\n ...(isFailedOutcome(event.outcome) ? { [ATTR_ERROR_TYPE]: event.outcome } : {}),\n });\n }\n if (\n event.cost !== undefined &&\n event.cost.source === \"provider-reported\" &&\n event.cost.currency === \"USD\"\n ) {\n push(event, METRIC_COST_USAGE, event.cost.amount, attributes);\n }\n break;\n }\n default:\n break;\n }\n }\n\n for (const observation of input.usage) {\n if (observation.scope !== \"generation\") {\n // Session totals and subagent rollups restate generation spend; counting them\n // too would double it.\n continue;\n }\n const event = byId.get(observation.eventId);\n if (event?.type !== \"generation.end\") {\n continue;\n }\n const attributes = generationAttributes(event, requestModelOf(event.generationId));\n for (const [tokenType, read] of TOKEN_FIELDS) {\n const value = read(observation.delta);\n if (value === 0 && (tokenType === \"cache_read\" || tokenType === \"cache_creation\")) {\n continue;\n }\n push(event, METRIC_TOKEN_USAGE, value, { ...attributes, [ATTR_GEN_AI_TOKEN_TYPE]: tokenType });\n }\n }\n return observations;\n};\n\n/** Accumulated histogram state for one series. */\nexport type HistogramState = {\n readonly count: number;\n readonly sum: number;\n readonly min: number;\n readonly max: number;\n /** One more entry than the instrument's boundaries. */\n readonly bucketCounts: readonly number[];\n};\n\n/**\n * One OTLP data point, as plain JSON so it can be spooled.\n *\n * A point is self-describing: the instrument, its temporality, and its interval.\n * A cumulative point is a snapshot of a running total, so resending one (from a\n * spool) restates a value rather than adding to it.\n */\nexport type MetricPoint = {\n readonly instrument: MetricInstrumentName;\n readonly temporality: MetricsTemporality;\n readonly attributes: Readonly<Record<string, string | number | boolean>>;\n readonly startTimeMillis: number;\n readonly timeMillis: number;\n /** Counters. */\n readonly value?: number;\n /** Histograms. */\n readonly histogram?: HistogramState;\n};\n\nexport const emptyHistogram = (boundaries: readonly number[]): HistogramState => ({\n count: 0,\n sum: 0,\n min: Number.POSITIVE_INFINITY,\n max: Number.NEGATIVE_INFINITY,\n bucketCounts: new Array<number>(boundaries.length + 1).fill(0),\n});\n\n/** OTLP explicit buckets: bucket `i` holds values in `(boundaries[i-1], boundaries[i]]`. */\nexport const bucketIndex = (boundaries: readonly number[], value: number): number => {\n for (let index = 0; index < boundaries.length; index += 1) {\n const bound = boundaries[index];\n if (bound !== undefined && value <= bound) {\n return index;\n }\n }\n return boundaries.length;\n};\n\nexport const recordIntoHistogram = (\n state: HistogramState,\n boundaries: readonly number[],\n value: number,\n): HistogramState => {\n const bucketCounts = [...state.bucketCounts];\n const index = bucketIndex(boundaries, value);\n bucketCounts[index] = (bucketCounts[index] ?? 0) + 1;\n return {\n count: state.count + 1,\n sum: state.sum + value,\n min: Math.min(state.min, value),\n max: Math.max(state.max, value),\n bucketCounts,\n };\n};\n\n/**\n * Stable identity of a series: instrument plus sorted attributes.\n *\n * Used as a map key and, digested, as a state key. JSON of sorted entries is\n * unambiguous where a joined string would not be.\n */\nexport const seriesIdentity = (\n instrument: MetricInstrumentName,\n attributes: Readonly<Record<string, string | number | boolean>>,\n): string =>\n JSON.stringify([\n instrument,\n Object.entries(attributes).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),\n ]);\n\n/**\n * Delta points for one batch: observations of the same series folded together,\n * over the interval from the earliest observation to `nowMillis`.\n */\nexport const aggregateDeltaPoints = (\n observations: readonly MetricObservation[],\n nowMillis: number,\n): readonly MetricPoint[] => {\n const series = new Map<\n string,\n { observation: MetricObservation; start: number; value: number; histogram?: HistogramState }\n >();\n for (const observation of observations) {\n const instrument = METRIC_INSTRUMENTS[observation.instrument];\n const key = seriesIdentity(observation.instrument, observation.attributes);\n const existing =\n series.get(key) ??\n ({\n observation,\n start: observation.timeMillis,\n value: 0,\n ...(instrument.boundaries === undefined ? {} : { histogram: emptyHistogram(instrument.boundaries) }),\n });\n existing.start = Math.min(existing.start, observation.timeMillis);\n if (existing.histogram !== undefined && instrument.boundaries !== undefined) {\n existing.histogram = recordIntoHistogram(existing.histogram, instrument.boundaries, observation.value);\n } else {\n existing.value += observation.value;\n }\n series.set(key, existing);\n }\n return [...series.values()].map((entry) => ({\n instrument: entry.observation.instrument,\n temporality: \"delta\",\n attributes: entry.observation.attributes,\n startTimeMillis: Math.min(entry.start, nowMillis),\n timeMillis: Math.max(nowMillis, entry.start),\n ...(entry.histogram === undefined ? { value: entry.value } : { histogram: entry.histogram }),\n }));\n};\n\n/** Data-point attribute keys that must never appear on a metric. */\nexport const FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES: readonly string[] = Object.freeze([\n \"user.\",\n \"enduser.\",\n \"organization.\",\n]);\n\n/** Strip anything account-shaped from attributes, as a last line of defence. */\nexport const withoutAccountIdentity = (attributes: Attributes): Attributes =>\n Object.fromEntries(\n Object.entries(attributes).filter(\n ([key]) => !FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES.some((prefix) => key.startsWith(prefix)),\n ),\n );\n","import type { CallbackDeduplicator } from \"./dedup.js\";\nimport type { SpanCorrelator } from \"./span-correlator.js\";\nimport type { MetricSeriesStore } from \"./metric-series.js\";\nimport type { UsageAccumulator } from \"./usage-accumulator.js\";\n\nconst DEFAULT_MAX_AGE_MILLIS = 24 * 60 * 60 * 1000;\nconst DEFAULT_MAX_ENTRIES_PER_COMPONENT = 1_000;\n\nexport type LifecycleJanitorOptions = {\n readonly spanCorrelator?: SpanCorrelator;\n readonly deduplicator?: CallbackDeduplicator;\n readonly usageAccumulator?: UsageAccumulator;\n /** Cumulative metric series state; swept by age, like usage rollups. */\n readonly metricSeries?: MetricSeriesStore;\n readonly spanMaxAgeMillis?: number;\n readonly dedupMaxAgeMillis?: number;\n /**\n * Floor on how long an uncommitted delivery claim survives the sweep, whatever\n * `dedupMaxAgeMillis` says.\n *\n * Passed through rather than left to the deduplicator's default so it can be the\n * *effective* window the runtime computed, which is raised from the requested one\n * to cover a process's whole export budget. A sweep using a smaller number than\n * the claim path uses would delete claims the claim path still considers live.\n */\n readonly dedupStaleClaimMillis?: number;\n readonly usageMaxAgeMillis?: number;\n /** Caps how many keys any single component scans per sweep. */\n readonly maxEntriesPerComponent?: number;\n};\n\nexport type LifecycleSweepStats = {\n readonly removed: number;\n readonly scanned: number;\n /**\n * Span records dropped with a start and no end — spans that were never\n * exported. Reported only by the span sweep; see `SpanCleanupResult`.\n */\n readonly expiredOpen?: number;\n /**\n * Aged-out records kept back because they are delivery claims a live process may\n * still hold. Reported only by the dedup sweep; see `DedupCleanupResult`.\n */\n readonly retainedInFlight?: number;\n};\n\nexport type LifecycleCleanupReport = {\n readonly span?: LifecycleSweepStats;\n readonly dedup?: LifecycleSweepStats;\n readonly usage?: LifecycleSweepStats;\n readonly metrics?: LifecycleSweepStats;\n};\n\n/**\n * Fans a single bounded cleanup pass out across whichever lifecycle\n * components are configured.\n *\n * Each component already bounds its own sweep (`maxEntries`); this exists so\n * a caller — a CLI subcommand, a periodic timer, an opportunistic call at the\n * end of `flush()` — can run \"the\" cleanup without wiring each component by\n * hand, and so the bound is enforced uniformly rather than per call site.\n */\nexport interface LifecycleJanitor {\n runOnce(sessionId?: string): Promise<LifecycleCleanupReport>;\n}\n\nexport const createLifecycleJanitor = (options: LifecycleJanitorOptions): LifecycleJanitor => {\n const maxEntries = options.maxEntriesPerComponent ?? DEFAULT_MAX_ENTRIES_PER_COMPONENT;\n const spanMaxAge = options.spanMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;\n const dedupMaxAge = options.dedupMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;\n const usageMaxAge = options.usageMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;\n\n const runOnce = async (sessionId?: string): Promise<LifecycleCleanupReport> => {\n const scope = { maxEntries, ...(sessionId === undefined ? {} : { sessionId }) };\n const [span, dedup, usage, metrics] = await Promise.all([\n options.spanCorrelator?.cleanup(spanMaxAge, scope),\n // Deduplication is deliberately swept across every scope rather than the\n // ending session's: a delivery scope is a host-chosen namespace or a\n // digest of provider/installation/session, never a session id, so scoping\n // this sweep by `sessionId` would match nothing and let records accumulate\n // forever. The sweep is TTL-driven and still bounded by `maxEntries`.\n options.deduplicator?.cleanup(dedupMaxAge, {\n maxEntries,\n ...(options.dedupStaleClaimMillis === undefined\n ? {}\n : { staleClaimMillis: options.dedupStaleClaimMillis }),\n }),\n options.usageAccumulator?.cleanup(usageMaxAge, scope),\n options.metricSeries?.cleanup(usageMaxAge, scope),\n ]);\n return {\n ...(span === undefined ? {} : { span }),\n ...(dedup === undefined ? {} : { dedup }),\n ...(usage === undefined ? {} : { usage }),\n ...(metrics === undefined ? {} : { metrics }),\n };\n };\n\n return { runOnce };\n};\n"],"mappings":";AAAA,SAAS,mBAAmB;;;ACqDrB,IAAM,sBAAsB,CAAC,UAClC,OAAQ,MAAqC,oBAAoB;AAG5D,IAAM,0BAA0B,OACrC,OACA,WACA,IACA,YACe;AACf,MAAI,oBAAoB,KAAK,GAAG;AAC9B,WAAO,MAAM,gBAAgB,WAAW,IAAI,OAAO;AAAA,EACrD;AACA,SAAO,GAAG;AACZ;;;ACxDO,IAAM,mBAAmB;AAUzB,IAAM,mBAAmB;AASzB,IAAM,oBAAoB;AAgBjC,IAAM,gBAAgB,CAAC,YACrB,QAAQ,WAAW,KAAK,KAAK,EAAE,WAAW,KAAK,KAAK;AAQ/C,IAAM,UAAU,CACrB,WACA,YACA,OACA,aAEA,GAAG,eAAe,SAAS,CAAC,GAAG,cAAc,UAAU,CAAC,IAAI,cAAc,KAAK,CAAC,IAAI,cAAc,QAAQ,CAAC;AAQtG,IAAM,iBAAiB,CAAC,cAC7B,cAAc,SACV,GAAG,gBAAgB,WACnB,GAAG,gBAAgB,UAAU,OAAO,gBAAgB,CAAC,IAAI,cAAc,SAAS,CAAC;AAShF,IAAM,WAAW,CAAC,OAAe,eACtC,GAAG,gBAAgB,KAAK,CAAC,GAAG,cAAc,UAAU,CAAC;AAEhD,IAAM,kBAAkB,CAAC,UAC9B,UAAU,SACN,GAAG,gBAAgB,YACnB,GAAG,gBAAgB,WAAW,OAAO,iBAAiB,CAAC,IAAI,cAAc,KAAK,CAAC;AAErF,IAAM,gBAAgB,CAAC,YACrB,QAAQ,WAAW,OAAO,GAAG,EAAE,WAAW,OAAO,GAAG;AAc/C,IAAM,eAAe,CAAC,QAAoC;AAC/D,QAAM,SAAS,GAAG,gBAAgB,WA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