@osfactory/otel-hook 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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/lifecycle/span-correlator.ts","../src/model/usage.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 ATTR_SESSION_ID,\n} from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport type { CanonicalEvent, CanonicalEventType } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\nimport { VERSION } from \"../version.js\";\n\nconst SCOPE_NAME = \"@osfactory/otel-hook\";\n\nexport const DEFAULT_INSTRUMENTATION_SCOPE: InstrumentationScope = Object.freeze({\n name: SCOPE_NAME,\n version: VERSION,\n});\n\nconst ATTR_OTELHOOK_INVOCATION_ID = \"otelhook.invocation.id\";\nconst ATTR_OTELHOOK_PROVIDER_ID = \"otelhook.provider.id\";\nconst ATTR_OTELHOOK_PROVIDER_VERSION = \"otelhook.provider.version\";\nconst ATTR_OTELHOOK_WORKSPACE_ID = \"otelhook.workspace.id\";\nconst ATTR_OTELHOOK_SPAN_PAIRED = \"otelhook.span.paired\";\nconst ATTR_OTELHOOK_SPAN_PAIRING = \"otelhook.span.pairing\";\nconst ATTR_OTELHOOK_SPAN_ORPHAN = \"otelhook.span.orphan\";\nconst ATTR_OTELHOOK_OUTCOME = \"otelhook.outcome\";\nconst ATTR_OTELHOOK_RESET_DETECTED = \"otelhook.usage.reset_detected\";\nconst ATTR_OTELHOOK_TOOL_KIND = \"otelhook.tool.kind\";\nconst ATTR_OTELHOOK_DELEGATION_DEPTH = \"otelhook.delegation_depth\";\nconst ATTR_OTELHOOK_COMPACTION_TRIGGER = \"otelhook.compaction.trigger\";\nconst ATTR_OTELHOOK_AGENT_NAME = \"otelhook.agent.name\";\nconst ATTR_OTELHOOK_AGENT_VERSION = \"otelhook.agent.version\";\n\n/**\n * Pure, stateless canonical-event-to-span mapping.\n *\n * Isolated in one module so every other piece of the telemetry pipeline\n * — batching, retry, spooling — can change without touching what an attribute\n * means. Two edges of the same lifecycle scope are merged into one span when\n * they appear in the same batch; when they arrive in *different* short-lived\n * hook processes they are merged through a {@link SpanCorrelation} the caller\n * resolved from persisted state. Either way the mapping itself stays a pure\n * function: state is read by the correlator, never by this module.\n *\n * ## Identity of a span\n *\n * Trace and span ids are derived, never random, so two processes that never\n * meet still agree on them:\n *\n * - `traceId = H(providerId, sessionId)` — one trace per session per provider.\n * Deriving it from the session rather than the invocation is what lets a\n * `tool.end` emitted minutes later land in the same trace as its `tool.start`;\n * including the provider is what stops two providers that happen to reuse a\n * session id from being stitched into one trace.\n * - `spanId = H(providerId, sessionId, family, scopeKey)` — stable across\n * processes and idempotent under redelivery, so a collector that sees a\n * start-only span and later the completed span treats them as one span\n * rather than two.\n */\n// NUL, so joined parts cannot collide across a different split: no identifier\n// this library accepts can contain one, which a printable separator cannot\n// promise. Never emitted — only hashed, or used as an in-memory map key.\nconst FIELD_SEPARATOR = \"\\u0000\";\n\nconst digestHex = (parts: readonly string[], length: number): string =>\n createHash(\"sha256\").update(parts.join(FIELD_SEPARATOR)).digest(\"hex\").slice(0, length);\n\n/** Lifecycle scopes that pair a `*.start` edge with a later `*.end` edge. */\nexport type SpanFamily = \"session\" | \"generation\" | \"tool\" | \"subagent\";\n\n/** Identifies one lifecycle span within a session. */\nexport type SpanScopeRef = {\n readonly family: SpanFamily;\n readonly scopeKey: string;\n};\n\n/**\n * Why a lifecycle span is, or is not, a complete pair.\n *\n * Deliberately explicit rather than a bare boolean: \"we never saw the start\",\n * \"we saw it but it aged out of state\", and \"state could not be read at all\"\n * are different operational facts, and a dashboard that cannot tell them apart\n * cannot tell a broken host from a broken exporter.\n */\nexport type SpanOrphanClassification =\n /** Both edges are known — from this batch, or from persisted state. */\n | \"none\"\n /** The start is known; its end has not arrived yet. */\n | \"missing-end\"\n /** An end arrived and no start was ever recorded for this scope. */\n | \"missing-start\"\n /** A start was recorded but aged past the retention window before the end arrived. */\n | \"expired-start\"\n /** A start exists but was recorded by a different provider; pairing it would be a guess. */\n | \"provider-mismatch\"\n /** A second, distinct end arrived for a scope that was already closed. */\n | \"already-closed\"\n /** The persisted record was written by an incompatible version and was discarded. */\n | \"state-incompatible\"\n /** The persisted record could not be understood. */\n | \"state-corrupt\"\n /** State could not be consulted at all; the mapping degraded rather than failing. */\n | \"state-unavailable\";\n\nexport type SpanPairing =\n /** Both edges were present in this batch. */\n | \"in-batch\"\n /** The other edge came from state written by an earlier process. */\n | \"cross-process\"\n | \"unpaired\";\n\n/**\n * Whether this scope should produce an OTLP record now.\n *\n * OTLP has no notion of updating a span: a span is exported once, when it ends,\n * and a second record carrying the same trace and span id is not a revision of\n * the first — it is a duplicate that backends variously drop, keep the older of,\n * or display twice. Since every lifecycle span id here is *derived* from\n * `(provider, session, family, scopeKey)`, a `*.start` edge and its later `*.end`\n * edge compute the identical id, so exporting on both is precisely that\n * duplicate.\n *\n * `defer` is therefore the answer for a start whose end has not arrived: the\n * start is durable in the state store, and the end edge exports the one complete\n * span using the times recovered from it. Nothing is lost by waiting, and what is\n * gained is that the record a collector receives has a real duration.\n */\nexport type SpanDisposition =\n /** Export a record for this scope now. */\n | \"emit\"\n /** Hold: the start is recorded, and the end edge will export the complete span. */\n | \"defer\";\n\n/**\n * One scope's correlation facts, resolved from persisted state by the caller.\n *\n * Plain data on purpose: the telemetry layer must not reach into the state\n * store itself (ADR 0006), so it declares what it needs and the lifecycle layer\n * supplies it.\n */\nexport type SpanCorrelation = {\n readonly providerId: string;\n readonly sessionId: string;\n readonly ref: SpanScopeRef;\n readonly pairing: SpanPairing;\n readonly orphan: SpanOrphanClassification;\n /**\n * Whether to export a record for this scope now. Defaults to `emit` when a\n * correlation is supplied without one.\n */\n readonly disposition?: SpanDisposition;\n /**\n * Extra component mixed into the derived span id.\n *\n * Set only when this record is a genuinely *additional* observation of a scope\n * that has already been exported once — a second, distinct end for a scope that\n * was already closed. Both records are real, so neither is dropped, and the\n * discriminator keeps them from claiming the same span id.\n */\n readonly spanIdDiscriminator?: string;\n /** Start recovered from state; authoritative over the batch's own start edge. */\n readonly startMillis?: number;\n /** End recovered from state; authoritative so a redelivered end re-exports an identical span. */\n readonly endMillis?: number;\n /** Parent recorded at start time, so an end-only process hangs the span in the same place. */\n readonly parent?: SpanScopeRef;\n /** Attributes only the start edge could supply, recovered for an end-only span. */\n readonly attributes?: Attributes;\n};\n\n/**\n * Resolves persisted correlation for one batch.\n *\n * Must never reject: a state failure is a degraded span, never a lost export.\n */\nexport type SpanCorrelationResolver = (\n events: readonly CanonicalEvent[],\n) => Promise<readonly SpanCorrelation[]>;\n\n/**\n * Upper bound on how many start-edge attributes the correlator may carry\n * forward, so persisted state cannot grow with provider-controlled input.\n */\nexport const MAX_RECOVERED_START_ATTRIBUTES = 16;\n\nconst familyOf = (type: CanonicalEventType): SpanFamily | undefined => {\n switch (type) {\n case \"session.start\":\n case \"session.end\":\n return \"session\";\n case \"generation.start\":\n case \"generation.end\":\n return \"generation\";\n case \"tool.start\":\n case \"tool.end\":\n return \"tool\";\n case \"subagent.start\":\n case \"subagent.end\":\n return \"subagent\";\n default:\n return undefined;\n }\n};\n\n/** The lifecycle span an event is an edge of, or undefined for a point-in-time event. */\nexport const spanScopeRefOf = (event: CanonicalEvent): SpanScopeRef | undefined => {\n const family = familyOf(event.type);\n if (family === undefined) {\n return undefined;\n }\n switch (event.type) {\n case \"session.start\":\n case \"session.end\":\n return { family, scopeKey: event.sessionId };\n case \"generation.start\":\n case \"generation.end\":\n return { family, scopeKey: event.generationId };\n case \"tool.start\":\n case \"tool.end\":\n return { family, scopeKey: event.toolCallId };\n case \"subagent.start\":\n case \"subagent.end\":\n return { family, scopeKey: event.subagentInvocationId };\n default:\n return undefined;\n }\n};\n\n/**\n * Where a span hangs in the trace, judged from this event alone.\n *\n * Everything in a session descends from the session span. A tool call names its\n * generation only on `tool.start`, which is exactly why the correlator persists\n * the parent: the `tool.end` process would otherwise reparent the same span to\n * the session and produce a tree whose shape depends on which edge happened to\n * be exported last.\n */\nexport const parentScopeRefOf = (event: CanonicalEvent): SpanScopeRef | undefined => {\n if (event.type === \"session.start\" || event.type === \"session.end\") {\n return undefined;\n }\n if (event.type === \"tool.start\" && event.generationId !== undefined) {\n return { family: \"generation\", scopeKey: event.generationId };\n }\n return { family: \"session\", scopeKey: event.sessionId };\n};\n\n/**\n * Span attributes that only a `*.start` edge can supply.\n *\n * The correlator persists these verbatim so an end-only span in a later process\n * still carries the tool kind, requested model, delegation depth, or agent name\n * the start process saw. An allowlist, and bounded, so persisted state can\n * never become a second route for provider payload content to escape.\n */\nexport const startOnlySpanAttributes = (event: CanonicalEvent): Attributes => {\n switch (event.type) {\n case \"session.start\":\n return {\n ...(event.agentName === undefined ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: event.agentName }),\n ...(event.agentVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_AGENT_VERSION]: event.agentVersion }),\n };\n case \"generation.start\":\n return {\n [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId,\n ...(event.model.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: event.model.vendor }),\n };\n // `toolName` and `toolCallId` are on both tool edges, so they are not\n // start-only and persisting them would just pad every record.\n case \"tool.start\":\n return { [ATTR_OTELHOOK_TOOL_KIND]: event.toolKind };\n case \"subagent.start\":\n return { [ATTR_OTELHOOK_DELEGATION_DEPTH]: event.delegationDepth };\n default:\n return {};\n }\n};\n\nconst deriveTraceId = (providerId: string, sessionId: string): string =>\n digestHex([\"otelhook/trace\", providerId, sessionId], 32);\n\nconst deriveSpanId = (providerId: string, sessionId: string, ref: SpanScopeRef): string =>\n digestHex([\"otelhook/span\", providerId, sessionId, ref.family, ref.scopeKey], 16);\n\nconst deriveStandaloneSpanId = (\n providerId: string,\n sessionId: string,\n eventType: string,\n eventId: string,\n): string => digestHex([\"otelhook/span\", providerId, sessionId, \"event\", eventType, eventId], 16);\n\nconst correlationKey = (providerId: string, sessionId: string, ref: SpanScopeRef): string =>\n [providerId, sessionId, ref.family, ref.scopeKey].join(FIELD_SEPARATOR);\n\nconst outcomeStatus = (outcome: string | undefined): SpanStatus => {\n if (outcome === undefined || outcome === \"ok\" || outcome === \"unknown\") {\n return { code: SpanStatusCode.UNSET };\n }\n if (outcome === \"cancelled\") {\n return { code: SpanStatusCode.UNSET };\n }\n return { code: SpanStatusCode.ERROR, message: outcome };\n};\n\nconst identityAttributes = (event: CanonicalEvent): Attributes => ({\n [ATTR_SESSION_ID]: event.sessionId,\n [ATTR_OTELHOOK_INVOCATION_ID]: event.invocationId,\n [ATTR_OTELHOOK_PROVIDER_ID]: event.provenance.providerId,\n ...(event.provenance.providerVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event.provenance.providerVersion }),\n [ATTR_OTELHOOK_WORKSPACE_ID]: event.workspace.workspaceId,\n});\n\nconst usageAttributes = (usage: CanonicalUsage | undefined, resetDetected: boolean): Attributes => {\n if (usage === undefined) {\n return {};\n }\n return {\n [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: usage.inputTokens,\n [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: usage.outputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: usage.cachedInputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: usage.cacheCreationInputTokens,\n [ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]: usage.reasoningOutputTokens,\n ...(resetDetected ? { [ATTR_OTELHOOK_RESET_DETECTED]: true } : {}),\n };\n};\n\ntype SpanGroup = {\n readonly ref: SpanScopeRef;\n start?: CanonicalEvent;\n end?: CanonicalEvent;\n};\n\nconst buildSpanContext = (traceId: string, spanId: string): SpanContext => ({\n traceId,\n spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n});\n\nexport type ReadableSpanInput = {\n readonly name: string;\n readonly kind: SpanKind;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly attributes: Attributes;\n readonly status: SpanStatus;\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n};\n\n/** Reconstructs a {@link ReadableSpan} from plain, serializable fields. Used by the durable spool to replay a span it persisted earlier. */\nexport const assembleReadableSpan = (input: ReadableSpanInput): ReadableSpan => toReadableSpan(input);\n\nconst toReadableSpan = (input: ReadableSpanInput): ReadableSpan => {\n const startTime = millisToHrTime(input.startMillis);\n const endTime = millisToHrTime(Math.max(input.startMillis, input.endMillis));\n const duration = millisToHrTime(Math.max(0, input.endMillis - input.startMillis));\n return {\n name: input.name,\n kind: input.kind,\n spanContext: (): SpanContext => buildSpanContext(input.traceId, input.spanId),\n ...(input.parentSpanId === undefined\n ? {}\n : { parentSpanContext: buildSpanContext(input.traceId, input.parentSpanId) }),\n startTime,\n endTime,\n status: input.status,\n attributes: input.attributes,\n links: [],\n events: [],\n duration,\n ended: true,\n resource: input.resource,\n instrumentationScope: input.instrumentationScope,\n droppedAttributesCount: 0,\n droppedEventsCount: 0,\n droppedLinksCount: 0,\n };\n};\n\ntype ResolvedPairing = {\n readonly pairing: SpanPairing;\n readonly orphan: SpanOrphanClassification;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly parent: SpanScopeRef | undefined;\n readonly recovered: Attributes;\n};\n\nconst resolvePairing = (\n group: SpanGroup,\n anchor: CanonicalEvent,\n correlation: SpanCorrelation | undefined,\n): ResolvedPairing => {\n const inBatch = group.start !== undefined && group.end !== undefined;\n const batchStart = group.start?.occurredAt ?? anchor.occurredAt;\n const batchEnd = group.end?.occurredAt ?? anchor.occurredAt;\n\n if (correlation === undefined) {\n return {\n pairing: inBatch ? \"in-batch\" : \"unpaired\",\n orphan: inBatch ? \"none\" : group.start === undefined ? \"missing-start\" : \"missing-end\",\n startMillis: batchStart,\n endMillis: inBatch ? batchEnd : batchStart,\n parent: parentScopeRefOf(anchor),\n recovered: {},\n };\n }\n\n // A correlation that reports no start (an orphaned end) must not fabricate\n // one: the span collapses onto the end instant rather than claiming a\n // duration measured from an event nobody ever saw.\n const startMillis = correlation.startMillis ?? (inBatch ? batchStart : batchEnd);\n const endMillis = correlation.endMillis ?? (group.end === undefined ? startMillis : batchEnd);\n return {\n pairing: correlation.pairing,\n orphan: correlation.orphan,\n startMillis,\n endMillis,\n parent: correlation.parent ?? parentScopeRefOf(anchor),\n recovered: correlation.attributes ?? {},\n };\n};\n\nconst buildLifecycleSpan = (\n plan: GroupPlan,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan => {\n const group = plan.group;\n const anchor = plan.anchor;\n const correlation = plan.correlation;\n const providerId = anchor.provenance.providerId;\n const sessionId = anchor.sessionId;\n const resolved = resolvePairing(group, anchor, correlation);\n const traceId = plan.traceId;\n const spanId = plan.spanId;\n const parentSpanId =\n resolved.parent === undefined ? undefined : deriveSpanId(providerId, sessionId, resolved.parent);\n\n let name: string = group.ref.family;\n let kind: SpanKind = SpanKind.INTERNAL;\n let status: SpanStatus = { code: SpanStatusCode.UNSET };\n // Attributes recovered from the start process sit *beneath* whatever this\n // batch observed: a live edge always wins over a remembered one.\n let attributes: Attributes = {\n ...identityAttributes(anchor),\n ...resolved.recovered,\n [ATTR_OTELHOOK_SPAN_PAIRED]: resolved.pairing !== \"unpaired\",\n [ATTR_OTELHOOK_SPAN_PAIRING]: resolved.pairing,\n [ATTR_OTELHOOK_SPAN_ORPHAN]: resolved.orphan,\n };\n\n switch (group.ref.family) {\n case \"session\": {\n const end = group.end?.type === \"session.end\" ? group.end : undefined;\n const start = group.start?.type === \"session.start\" ? group.start : undefined;\n name = \"session\";\n kind = SpanKind.INTERNAL;\n attributes = {\n ...attributes,\n ...(start?.agentName === undefined ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName }),\n ...(start?.agentVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion }),\n ...(end === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.reason }),\n ...usageAttributes(end?.usage, false),\n };\n if (end?.reason === \"error\" || end?.reason === \"timeout\") {\n status = { code: SpanStatusCode.ERROR, message: end.reason };\n }\n break;\n }\n case \"generation\": {\n const start = group.start?.type === \"generation.start\" ? group.start : undefined;\n const end = group.end?.type === \"generation.end\" ? group.end : undefined;\n const model = end?.model ?? start?.model;\n name = model === undefined ? \"generation\" : `generation ${model.modelId}`;\n kind = SpanKind.CLIENT;\n attributes = {\n ...attributes,\n [ATTR_GEN_AI_OPERATION_NAME]: \"chat\",\n ...(model?.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: model.vendor }),\n ...(start?.model?.modelId === undefined ? {} : { [ATTR_GEN_AI_REQUEST_MODEL]: start.model.modelId }),\n ...(end?.model?.modelId === undefined ? {} : { [ATTR_GEN_AI_RESPONSE_MODEL]: end.model.modelId }),\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...usageAttributes(end?.usage, false),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n case \"tool\": {\n const start = group.start?.type === \"tool.start\" ? group.start : undefined;\n const end = group.end?.type === \"tool.end\" ? group.end : undefined;\n const toolName = start?.toolName ?? end?.toolName ?? \"unknown\";\n name = `tool ${toolName}`;\n kind = SpanKind.CLIENT;\n attributes = {\n ...attributes,\n [ATTR_GEN_AI_TOOL_NAME]: toolName,\n [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,\n ...(start?.toolKind === undefined ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind }),\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n case \"subagent\": {\n const start = group.start?.type === \"subagent.start\" ? group.start : undefined;\n const end = group.end?.type === \"subagent.end\" ? group.end : undefined;\n name = \"subagent\";\n kind = SpanKind.INTERNAL;\n attributes = {\n ...attributes,\n ...(start?.delegationDepth === undefined\n ? {}\n : { [ATTR_OTELHOOK_DELEGATION_DEPTH]: start.delegationDepth }),\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...usageAttributes(end?.usage, false),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n }\n\n if (status.code === SpanStatusCode.ERROR) {\n attributes = { ...attributes, [ATTR_ERROR_TYPE]: status.message ?? \"error\" };\n }\n\n return toReadableSpan({\n name,\n kind,\n startMillis: resolved.startMillis,\n endMillis: resolved.endMillis,\n attributes,\n status,\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n resource,\n instrumentationScope: scope,\n });\n};\n\nconst buildStandaloneSpan = (\n event: CanonicalEvent,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan => {\n const providerId = event.provenance.providerId;\n const traceId = deriveTraceId(providerId, event.sessionId);\n const spanId = deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId);\n const parent = parentScopeRefOf(event);\n let attributes: Attributes = { ...identityAttributes(event), [ATTR_OTELHOOK_SPAN_PAIRED]: true };\n let status: SpanStatus = { code: SpanStatusCode.UNSET };\n let name: string = event.type;\n\n switch (event.type) {\n case \"prompt.submitted\":\n name = \"prompt\";\n attributes = { ...attributes, \"otelhook.prompt.source\": event.promptSource };\n break;\n case \"compaction.performed\":\n name = \"compaction\";\n attributes = {\n ...attributes,\n [ATTR_OTELHOOK_COMPACTION_TRIGGER]: event.trigger,\n ...usageAttributes(event.usage, false),\n };\n break;\n case \"error.raised\":\n name = \"error\";\n status = { code: SpanStatusCode.ERROR, message: event.errorCode };\n attributes = {\n ...attributes,\n [ATTR_ERROR_TYPE]: event.errorCode,\n \"otelhook.error.phase\": event.phase,\n \"otelhook.error.retryable\": event.retryable,\n };\n break;\n default:\n break;\n }\n\n return toReadableSpan({\n name,\n kind: SpanKind.INTERNAL,\n startMillis: event.occurredAt,\n endMillis: event.occurredAt,\n attributes,\n status,\n traceId,\n spanId,\n ...(parent === undefined\n ? {}\n : { parentSpanId: deriveSpanId(providerId, event.sessionId, parent) }),\n resource,\n instrumentationScope: scope,\n });\n};\n\nexport type SemanticMappingOptions = {\n readonly resource: Resource;\n readonly instrumentationScope?: InstrumentationScope;\n /**\n * Cross-process pairing facts, at most one entry per lifecycle scope in\n * `events`. Omitted entirely, the mapping degrades to in-batch pairing only —\n * the behavior of a host that wired no state store.\n */\n readonly correlations?: readonly SpanCorrelation[];\n /**\n * Whether a correlator was consulted at all, and whether it answered.\n *\n * This is what separates \"the state store is holding this start, so the end edge\n * will publish it\" from \"nothing recorded this start\". Both look like an empty\n * `correlations` list, and only the first is safe to drop — dropping the second\n * would discard an observation that was neither persisted nor exported, while a\n * caller that saw zero rejections went on to mark the callback handled.\n *\n * - `true` — the correlator ran; an absent or non-`defer` entry means emit.\n * - `false` — the correlator failed; every unpaired start is emitted as an\n * explicitly labelled, uniquely identified fallback.\n * - omitted — no correlator is wired, so cross-process pairing was never on\n * offer and an unpaired start is deferred (the documented no-state-root\n * degradation).\n */\n readonly correlationAvailable?: boolean;\n};\n\n/**\n * Fill in a correlation for an unpaired start that nothing recorded.\n *\n * Reached when a correlator was consulted and either failed outright or reported\n * nothing for this scope. The synthesized entry says what is true — the state was\n * not consulted successfully, so this span is unpaired and no end can complete it\n * — and carries a discriminator so the record cannot claim the span id a later end\n * will publish for the same scope.\n */\nconst effectiveCorrelation = (\n group: SpanGroup,\n correlation: SpanCorrelation | undefined,\n): SpanCorrelation | undefined => {\n if (correlation !== undefined || group.end !== undefined || group.start === undefined) {\n return correlation;\n }\n return {\n providerId: group.start.provenance.providerId,\n sessionId: group.start.sessionId,\n ref: group.ref,\n pairing: \"unpaired\",\n orphan: \"state-unavailable\",\n disposition: \"emit\",\n spanIdDiscriminator: group.start.eventId,\n };\n};\n\n/** How one batch's events distribute over the lifecycle scopes they are edges of. */\ntype BatchLayout = {\n readonly groups: ReadonlyMap<string, SpanGroup>;\n readonly standalone: readonly CanonicalEvent[];\n /** Event id of each lifecycle edge, mapped to the group key it belongs to. */\n readonly groupOf: ReadonlyMap<string, string>;\n};\n\nconst layoutBatch = (events: readonly CanonicalEvent[]): BatchLayout => {\n const groups = new Map<string, SpanGroup>();\n const standalone: CanonicalEvent[] = [];\n const groupOf = new Map<string, string>();\n\n for (const event of events) {\n const ref = spanScopeRefOf(event);\n if (ref === undefined) {\n standalone.push(event);\n continue;\n }\n const groupKey = correlationKey(event.provenance.providerId, event.sessionId, ref);\n const group: SpanGroup = groups.get(groupKey) ?? { ref };\n if (event.type.endsWith(\".start\")) {\n group.start = event;\n } else {\n group.end = event;\n }\n groups.set(groupKey, group);\n groupOf.set(event.eventId, groupKey);\n }\n return { groups, standalone, groupOf };\n};\n\nconst indexCorrelations = (\n correlations: readonly SpanCorrelation[] | undefined,\n): ReadonlyMap<string, SpanCorrelation> => {\n const indexed = new Map<string, SpanCorrelation>();\n for (const correlation of correlations ?? []) {\n indexed.set(\n correlationKey(correlation.providerId, correlation.sessionId, correlation.ref),\n correlation,\n );\n }\n return indexed;\n};\n\n/**\n * What this batch does with one lifecycle scope, decided once.\n *\n * Both the span mapping and the log mapping need the *same* answer to \"which\n * span id identifies this scope, and is a record for it going out now?\" — a log\n * record whose `spanContext` names a span id the exporter never published would\n * dangle at the collector. Computing it in one place is what keeps the two\n * signals pointing at the same span rather than at two plausible derivations of\n * it.\n */\ntype GroupPlan = {\n readonly group: SpanGroup;\n /** The event the span's identity and provenance are read from. */\n readonly anchor: CanonicalEvent;\n /**\n * False when the start is deferred: the state store is holding it and the end\n * edge will publish the one complete span, so nothing is exported for it now.\n */\n readonly emits: boolean;\n readonly correlation: SpanCorrelation | undefined;\n readonly traceId: string;\n readonly spanId: string;\n};\n\nconst planGroup = (\n group: SpanGroup,\n correlation: SpanCorrelation | undefined,\n correlationAvailable: boolean | undefined,\n): GroupPlan | undefined => {\n const anchor = group.start ?? group.end;\n if (anchor === undefined) {\n // Unreachable: a group exists only because an event was filed into it.\n return undefined;\n }\n const providerId = anchor.provenance.providerId;\n const sessionId = anchor.sessionId;\n\n // A start with no end in this batch is dropped **only** when something states\n // that it is durably recorded, because its span id is a pure function of the\n // scope: emitting here and again at the end edge would put two records with one\n // id on the wire, and OTLP has no update operation.\n //\n // `defer` is that statement, and it is the correlator's to make — it just wrote\n // the record. Anything else means nothing is holding this start, so dropping it\n // would lose an observation that was neither persisted nor exported, while the\n // caller saw zero rejections and marked the callback handled. Those are exported\n // under a discriminated span id instead.\n const durablyRecorded =\n group.end === undefined &&\n (correlation?.disposition === \"defer\" ||\n // No correlator wired at all: cross-process pairing was never on offer, so\n // this is the documented no-state-root degradation rather than a failure to\n // persist something that should have been persisted.\n (correlation === undefined && correlationAvailable === undefined));\n\n // A deferred start keeps the scope's *plain* span id, because that is the id the\n // end edge will publish. Only a record actually going out now may claim a\n // discriminated one.\n const effective = durablyRecorded ? correlation : effectiveCorrelation(group, correlation);\n const discriminator = durablyRecorded ? undefined : effective?.spanIdDiscriminator;\n\n return {\n group,\n anchor,\n emits: !durablyRecorded,\n correlation: effective,\n traceId: deriveTraceId(providerId, sessionId),\n spanId:\n discriminator === undefined\n ? deriveSpanId(providerId, sessionId, group.ref)\n : digestHex(\n [\n \"otelhook/span\",\n providerId,\n sessionId,\n group.ref.family,\n group.ref.scopeKey,\n discriminator,\n ],\n 16,\n ),\n };\n};\n\n/** Trace and span a record derived from one canonical event belongs to. */\nexport type EventTraceIdentity = {\n readonly traceId: string;\n readonly spanId: string;\n};\n\n/**\n * Resolve the trace and span identity of every event in one batch.\n *\n * Exposed for signals other than traces — a log record correlates by carrying\n * the *same* derived ids the span mapping would compute, including the deferred\n * and discriminated cases. Whole batch at once because a start's identity\n * depends on whether its end is in the same batch.\n *\n * Both ids come from the event's own `(providerId, sessionId)`, never from a\n * batch-level or module-level value, which is what makes cross-session\n * contamination structurally impossible: two sessions in one batch derive two\n * different trace ids.\n */\nexport const canonicalEventTraceIdentities = (\n events: readonly CanonicalEvent[],\n options: {\n readonly correlations?: readonly SpanCorrelation[];\n readonly correlationAvailable?: boolean;\n } = {},\n): ReadonlyMap<string, EventTraceIdentity> => {\n const layout = layoutBatch(events);\n const correlations = indexCorrelations(options.correlations);\n const plans = new Map<string, GroupPlan>();\n for (const [groupKey, group] of layout.groups) {\n const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);\n if (plan !== undefined) {\n plans.set(groupKey, plan);\n }\n }\n\n const identities = new Map<string, EventTraceIdentity>();\n for (const event of events) {\n const providerId = event.provenance.providerId;\n const groupKey = layout.groupOf.get(event.eventId);\n const plan = groupKey === undefined ? undefined : plans.get(groupKey);\n if (plan === undefined) {\n identities.set(event.eventId, {\n traceId: deriveTraceId(providerId, event.sessionId),\n spanId: deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId),\n });\n continue;\n }\n identities.set(event.eventId, { traceId: plan.traceId, spanId: plan.spanId });\n }\n return identities;\n};\n\n/** Maps one invocation's canonical event batch into OTLP-ready spans. */\nexport const canonicalEventsToReadableSpans = (\n events: readonly CanonicalEvent[],\n options: SemanticMappingOptions,\n): readonly ReadableSpan[] => {\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const layout = layoutBatch(events);\n const correlations = indexCorrelations(options.correlations);\n\n const spans: ReadableSpan[] = [];\n for (const [groupKey, group] of layout.groups) {\n const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);\n if (plan === undefined || !plan.emits) {\n continue;\n }\n spans.push(buildLifecycleSpan(plan, options.resource, scope));\n }\n for (const event of layout.standalone) {\n spans.push(buildStandaloneSpan(event, options.resource, scope));\n }\n return spans;\n};\n","/**\n * Package version, kept in its own module so the CLI can report it without\n * importing the whole library barrel (and every provider adapter with it).\n *\n * Updated by `scripts/release/sync-version.mjs` during semantic-release.\n */\nexport const VERSION = \"0.1.2\";\n","import type { Attributes as SpanAttributes } from \"@opentelemetry/api\";\n\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport {\n MAX_ATTRIBUTE_STRING_LENGTH,\n MAX_IDENTIFIER_LENGTH,\n type Attributes,\n} from \"../model/primitives.js\";\nimport type { Clock, StateStore, StateValue } from \"../runtime/ports.js\";\nimport { withOptionalSessionLock } from \"../state/store.js\";\nimport {\n MAX_RECOVERED_START_ATTRIBUTES,\n parentScopeRefOf,\n spanScopeRefOf,\n startOnlySpanAttributes,\n type SpanCorrelation,\n type SpanFamily,\n type SpanOrphanClassification,\n type SpanScopeRef,\n} from \"../telemetry/semconv.js\";\nimport { spanKey, spanScanPrefix } from \"./keys.js\";\n\n/** Correlation scopes that pair a `*.start` event with a later `*.end` event. */\nexport type LifecycleScope = SpanFamily;\n\n/**\n * Shape version of a persisted span record.\n *\n * A record written under a different version is discarded on read rather than\n * interpreted: guessing at an older layout is exactly the kind of silent\n * mis-attribution this library refuses to do. See `docs/state-retention.md`.\n */\nexport const SPAN_RECORD_VERSION = 2;\n\n/** Facts about a span recovered from, or written to, persisted state. */\nexport type SpanCorrelationFacts = {\n readonly startedAt?: number;\n readonly endedAt?: number;\n readonly parent?: SpanScopeRef;\n readonly attributes?: SpanAttributes;\n};\n\nexport type SpanStartInput = {\n readonly sessionId: string;\n /** Attribution boundary: a scope recorded by one provider never pairs with another's. */\n readonly providerId: string;\n readonly scope: LifecycleScope;\n readonly scopeKey: string;\n /** The canonical event id of the start event; used to detect redelivery. */\n readonly eventId: string;\n readonly occurredAt: number;\n /** Where this span hangs, so an end-only process reparents it identically. */\n readonly parent?: SpanScopeRef;\n /** Attributes only the start edge knows; carried forward to the end-side span. */\n readonly attributes?: SpanAttributes;\n};\n\nexport type SpanEndInput = {\n readonly sessionId: string;\n readonly providerId: string;\n readonly scope: LifecycleScope;\n readonly scopeKey: string;\n readonly eventId: string;\n readonly occurredAt: number;\n};\n\nexport type SpanStartResult =\n | { readonly status: \"recorded\"; readonly facts: SpanCorrelationFacts }\n /** The same start (by event id) was already recorded; state is unchanged. */\n | { readonly status: \"duplicate\"; readonly facts: SpanCorrelationFacts }\n /**\n * The record was completed, but an OTLP record for this scope has already been\n * published under its span id — so this edge must not export one.\n */\n | { readonly status: \"published\"; readonly facts: SpanCorrelationFacts }\n /** A different provider owns this scope key in this session; nothing was written. */\n | { readonly status: \"conflict\"; readonly reason: \"provider-mismatch\" };\n\n/** Why an end could not be paired with a recorded start. */\nexport type SpanEndOrphanReason =\n | \"no-start-recorded\"\n | \"start-expired\"\n | \"already-closed\"\n | \"provider-mismatch\"\n | \"state-incompatible\"\n | \"state-corrupt\";\n\nexport type SpanEndResult =\n | {\n readonly status: \"matched\";\n readonly startedAt: number;\n readonly durationMillis: number;\n readonly facts: SpanCorrelationFacts;\n }\n /** This exact end (by event id) was already applied; the same facts are replayed. */\n | { readonly status: \"duplicate\"; readonly facts: SpanCorrelationFacts }\n | {\n readonly status: \"orphaned\";\n readonly reason: SpanEndOrphanReason;\n readonly facts: SpanCorrelationFacts;\n };\n\nexport type SpanCleanupResult = {\n readonly removed: number;\n readonly scanned: number;\n /**\n * Records dropped that held a start and never received an end.\n *\n * These are the spans that will never be exported at all: the end edge is what\n * emits a lifecycle span, so a scope whose end never arrives — a session the\n * host killed, a tool call that outlived the retention window — produces no\n * OTLP record. That is the standard OpenTelemetry outcome for a span that never\n * ends, and it is deliberately not papered over with a synthetic end time,\n * because a fabricated duration is a wrong measurement rather than a missing\n * one. Counting them keeps the cost visible: a non-zero number here means real\n * activity went unreported, which is a signal about the host or the retention\n * window rather than noise. See `docs/state-retention.md`.\n */\n readonly expiredOpen: number;\n};\n\n/**\n * Cross-invocation start/end correlation for session, generation, tool, and\n * subagent scopes.\n *\n * A coding-agent hook fires once per lifecycle edge, usually as a separate\n * short-lived process for the start and for the end. This records an open span\n * in the shared state store so the end side can report a real start time,\n * duration, parent, and start-only attributes even though its process has no\n * memory of the start — and so a redelivered start or end (an at-least-once\n * host retry) re-exports an identical span instead of being double-counted.\n *\n * ## What it refuses to do\n *\n * - **Pair across sessions.** The state key is session-scoped, so two sessions\n * cannot see each other's open spans.\n * - **Pair across providers.** The key is provider-scoped *and* the record\n * carries the provider that wrote it, so a mismatch is reported rather than\n * guessed at — the same defense in depth the durable spool uses.\n * - **Trust a stale start.** A start older than `maxStartAgeMillis` when its end\n * arrives is dropped and classified `start-expired`, rather than reporting a\n * duration that really measures a machine suspend or a reused id.\n * - **Interpret a record it does not understand.** A corrupt or wrong-version\n * record is deleted and classified, never partially read.\n */\nexport interface SpanCorrelator {\n recordStart(input: SpanStartInput): Promise<SpanStartResult>;\n recordEnd(input: SpanEndInput): Promise<SpanEndResult>;\n /**\n * Records every lifecycle edge in a batch and reports what the exported spans\n * should say. Never rejects: a state failure degrades one scope to\n * `state-unavailable` rather than losing the batch (fail-open telemetry).\n */\n correlateBatch(events: readonly CanonicalEvent[]): Promise<readonly SpanCorrelation[]>;\n /** Bounded sweep: drops spans untouched for longer than `maxAgeMillis`. */\n cleanup(\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<SpanCleanupResult>;\n}\n\nexport type SpanCorrelatorDependencies = {\n readonly stateStore: StateStore;\n readonly clock: Clock;\n /**\n * A recorded start older than this when its end arrives is not trusted.\n * Default 24 hours, matching the janitor's retention window.\n */\n readonly maxStartAgeMillis?: number;\n};\n\nconst DEFAULT_MAX_START_AGE_MILLIS = 24 * 60 * 60 * 1000;\nconst ATTRIBUTE_PREFIX = \"a:\";\n\ntype SpanRecord = {\n readonly providerId: string;\n readonly startEventId?: string;\n readonly startedAt?: number;\n readonly endEventId?: string;\n readonly endedAt?: number;\n readonly parent?: SpanScopeRef;\n readonly attributes?: SpanAttributes;\n /**\n * True once an OTLP record has been produced for this scope under its derived\n * span id.\n *\n * Needed for the ordering nobody controls: the end edge can be mapped before\n * the start edge, and then the end has already exported an orphan carrying the\n * scope's canonical span id. Without this flag the late start would look like\n * the benign \"end raced ahead\" case and export a *second* record with that same\n * id — the duplicate the whole defer strategy exists to avoid. So the flag turns\n * \"was this scope already published?\" into a fact on disk rather than an\n * assumption about arrival order.\n */\n readonly exported?: boolean;\n};\n\ntype DecodedRecord =\n | { readonly kind: \"absent\" }\n | { readonly kind: \"incompatible\" }\n | { readonly kind: \"corrupt\" }\n | { readonly kind: \"present\"; readonly record: SpanRecord };\n\nconst SPAN_FAMILIES: readonly SpanFamily[] = [\"session\", \"generation\", \"tool\", \"subagent\"];\n\nconst isSpanFamily = (value: unknown): value is SpanFamily =>\n typeof value === \"string\" && (SPAN_FAMILIES as readonly string[]).includes(value);\n\nconst optionalNumber = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n\nconst optionalString = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 ? value : undefined;\n\n/**\n * Persisted attributes are flattened under a prefix rather than nested: the\n * state schema admits only flat primitives, which is what keeps a provider\n * payload from ever being smuggled through the state store.\n */\nconst encodeAttributes = (attributes: SpanAttributes | undefined): Attributes => {\n const encoded: Record<string, string | number | boolean> = {};\n let count = 0;\n for (const [key, value] of Object.entries(attributes ?? {})) {\n if (count >= MAX_RECOVERED_START_ATTRIBUTES) {\n break;\n }\n const encodedKey = `${ATTRIBUTE_PREFIX}${key}`;\n if (encodedKey.length > MAX_IDENTIFIER_LENGTH) {\n continue;\n }\n if (typeof value === \"string\") {\n encoded[encodedKey] = value.slice(0, MAX_ATTRIBUTE_STRING_LENGTH);\n } else if (typeof value === \"number\" && Number.isFinite(value)) {\n encoded[encodedKey] = value;\n } else if (typeof value === \"boolean\") {\n encoded[encodedKey] = value;\n } else {\n continue;\n }\n count += 1;\n }\n return encoded;\n};\n\nconst decodeAttributes = (attributes: Attributes): SpanAttributes | undefined => {\n const decoded: Record<string, string | number | boolean> = {};\n let count = 0;\n for (const [key, value] of Object.entries(attributes)) {\n if (!key.startsWith(ATTRIBUTE_PREFIX) || count >= MAX_RECOVERED_START_ATTRIBUTES) {\n continue;\n }\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n decoded[key.slice(ATTRIBUTE_PREFIX.length)] = value;\n count += 1;\n }\n }\n return count === 0 ? undefined : decoded;\n};\n\nconst encodeRecord = (record: SpanRecord): StateValue => ({\n kind: \"attributes\",\n attributes: {\n v: SPAN_RECORD_VERSION,\n providerId: record.providerId,\n ...(record.startEventId === undefined ? {} : { startEventId: record.startEventId }),\n ...(record.startedAt === undefined ? {} : { startedAt: record.startedAt }),\n ...(record.endEventId === undefined ? {} : { endEventId: record.endEventId }),\n ...(record.endedAt === undefined ? {} : { endedAt: record.endedAt }),\n ...(record.exported === true ? { exported: true } : {}),\n ...(record.parent === undefined\n ? {}\n : { parentFamily: record.parent.family, parentScopeKey: record.parent.scopeKey }),\n ...encodeAttributes(record.attributes),\n },\n});\n\nconst decodeRecord = (attributes: Attributes): DecodedRecord => {\n if (attributes[\"v\"] !== SPAN_RECORD_VERSION) {\n return { kind: \"incompatible\" };\n }\n const providerId = optionalString(attributes[\"providerId\"]);\n if (providerId === undefined) {\n return { kind: \"corrupt\" };\n }\n // A half-written edge (a timestamp with no event id, or the reverse) is not\n // an edge we can reason about; the record is refused rather than completed\n // with an invented half.\n const startedAt = optionalNumber(attributes[\"startedAt\"]);\n const startEventId = optionalString(attributes[\"startEventId\"]);\n if ((startedAt === undefined) !== (startEventId === undefined)) {\n return { kind: \"corrupt\" };\n }\n const endedAt = optionalNumber(attributes[\"endedAt\"]);\n const endEventId = optionalString(attributes[\"endEventId\"]);\n if ((endedAt === undefined) !== (endEventId === undefined)) {\n return { kind: \"corrupt\" };\n }\n const exported = attributes[\"exported\"] === true;\n const parentFamily = attributes[\"parentFamily\"];\n const parentScopeKey = optionalString(attributes[\"parentScopeKey\"]);\n const parent =\n isSpanFamily(parentFamily) && parentScopeKey !== undefined\n ? { family: parentFamily, scopeKey: parentScopeKey }\n : undefined;\n const decodedAttributes = decodeAttributes(attributes);\n return {\n kind: \"present\",\n record: {\n providerId,\n ...(startEventId === undefined ? {} : { startEventId }),\n ...(startedAt === undefined ? {} : { startedAt }),\n ...(endEventId === undefined ? {} : { endEventId }),\n ...(endedAt === undefined ? {} : { endedAt }),\n ...(parent === undefined ? {} : { parent }),\n ...(exported ? { exported: true } : {}),\n ...(decodedAttributes === undefined ? {} : { attributes: decodedAttributes }),\n },\n };\n};\n\nconst factsOf = (record: SpanRecord): SpanCorrelationFacts => ({\n ...(record.startedAt === undefined ? {} : { startedAt: record.startedAt }),\n ...(record.endedAt === undefined ? {} : { endedAt: record.endedAt }),\n ...(record.parent === undefined ? {} : { parent: record.parent }),\n ...(record.attributes === undefined ? {} : { attributes: record.attributes }),\n});\n\n/**\n * Persisted facts speak in event time (`startedAt`); a span speaks in the\n * milliseconds it is stamped with. Translated in one place so the two\n * vocabularies cannot silently drift apart.\n */\nconst correlationTimesOf = (\n facts: SpanCorrelationFacts,\n options: { readonly withStart: boolean } = { withStart: true },\n): Pick<SpanCorrelation, \"startMillis\" | \"endMillis\" | \"parent\" | \"attributes\"> => ({\n ...(facts.startedAt === undefined || !options.withStart ? {} : { startMillis: facts.startedAt }),\n ...(facts.endedAt === undefined ? {} : { endMillis: facts.endedAt }),\n ...(facts.parent === undefined ? {} : { parent: facts.parent }),\n ...(facts.attributes === undefined ? {} : { attributes: facts.attributes }),\n});\n\nconst orphanClassificationOf = (reason: SpanEndOrphanReason): SpanOrphanClassification => {\n switch (reason) {\n case \"no-start-recorded\":\n return \"missing-start\";\n case \"start-expired\":\n return \"expired-start\";\n case \"already-closed\":\n return \"already-closed\";\n case \"provider-mismatch\":\n return \"provider-mismatch\";\n case \"state-incompatible\":\n return \"state-incompatible\";\n case \"state-corrupt\":\n return \"state-corrupt\";\n }\n};\n\ntype BatchGroup = {\n readonly providerId: string;\n readonly sessionId: string;\n readonly ref: SpanScopeRef;\n start?: CanonicalEvent;\n end?: CanonicalEvent;\n};\n\nexport const createSpanCorrelator = (deps: SpanCorrelatorDependencies): SpanCorrelator => {\n const { stateStore, clock } = deps;\n const maxStartAgeMillis = deps.maxStartAgeMillis ?? DEFAULT_MAX_START_AGE_MILLIS;\n\n const keyFor = (input: {\n readonly sessionId: string;\n readonly providerId: string;\n readonly scope: LifecycleScope;\n readonly scopeKey: string;\n }): string => spanKey(input.sessionId, input.providerId, input.scope, input.scopeKey);\n\n /**\n * Reads and validates one record, deleting anything it refuses to interpret.\n * Self-healing on purpose: a single unreadable record must not make the same\n * scope unreadable forever.\n */\n const readRecord = async (key: string): Promise<DecodedRecord> => {\n const existing = await stateStore.read(key);\n if (existing === undefined) {\n return { kind: \"absent\" };\n }\n if (existing.value.kind !== \"attributes\") {\n await stateStore.delete(key);\n return { kind: \"corrupt\" };\n }\n const decoded = decodeRecord(existing.value.attributes);\n if (decoded.kind === \"corrupt\" || decoded.kind === \"incompatible\") {\n await stateStore.delete(key);\n }\n return decoded;\n };\n\n const recordStart = (input: SpanStartInput): Promise<SpanStartResult> =>\n withOptionalSessionLock(stateStore, input.sessionId, async (): Promise<SpanStartResult> => {\n const key = keyFor(input);\n const decoded = await readRecord(key);\n\n if (decoded.kind === \"present\") {\n const existing = decoded.record;\n if (existing.providerId !== input.providerId) {\n return { status: \"conflict\", reason: \"provider-mismatch\" };\n }\n if (existing.startEventId === input.eventId) {\n return { status: \"duplicate\", facts: factsOf(existing) };\n }\n if (existing.startEventId === undefined && existing.endEventId !== undefined) {\n // The end raced ahead of the start (two hook processes, no ordering\n // guarantee between them). Complete the record rather than treating\n // the late start as the beginning of a second span.\n //\n // If that end was already exported, the scope's canonical span id is\n // already on the wire and this start must stay silent: re-exporting a\n // now-complete span under the same id would be a duplicate, not a\n // correction, because OTLP has no update. The enrichment is lost and the\n // published record remains the orphan the end could honestly produce.\n const completed: SpanRecord = {\n ...existing,\n startEventId: input.eventId,\n startedAt: input.occurredAt,\n ...(input.parent === undefined ? {} : { parent: input.parent }),\n ...(input.attributes === undefined ? {} : { attributes: input.attributes }),\n };\n await stateStore.write(key, encodeRecord(completed));\n return existing.exported === true\n ? { status: \"published\", facts: factsOf(completed) }\n : { status: \"recorded\", facts: factsOf(completed) };\n }\n }\n\n // Either nothing was recorded, or a *different* start claims this scope\n // key: the previous span is superseded rather than merged into.\n const fresh: SpanRecord = {\n providerId: input.providerId,\n startEventId: input.eventId,\n startedAt: input.occurredAt,\n ...(input.parent === undefined ? {} : { parent: input.parent }),\n ...(input.attributes === undefined ? {} : { attributes: input.attributes }),\n };\n await stateStore.write(key, encodeRecord(fresh));\n return { status: \"recorded\", facts: factsOf(fresh) };\n });\n\n const recordEnd = (input: SpanEndInput): Promise<SpanEndResult> =>\n withOptionalSessionLock(stateStore, input.sessionId, async (): Promise<SpanEndResult> => {\n const key = keyFor(input);\n const decoded = await readRecord(key);\n\n if (decoded.kind === \"incompatible\" || decoded.kind === \"corrupt\") {\n const reason = decoded.kind === \"incompatible\" ? \"state-incompatible\" : \"state-corrupt\";\n return { status: \"orphaned\", reason, facts: { endedAt: input.occurredAt } };\n }\n if (decoded.kind === \"absent\") {\n // Remember the end anyway: a start that arrives late still deserves to\n // be paired rather than exported as a second orphan.\n const endOnly: SpanRecord = {\n providerId: input.providerId,\n endEventId: input.eventId,\n endedAt: input.occurredAt,\n // This end is about to be exported as an orphan under the scope's\n // canonical span id, so a start arriving later must not reuse it.\n exported: true,\n };\n await stateStore.write(key, encodeRecord(endOnly));\n return { status: \"orphaned\", reason: \"no-start-recorded\", facts: factsOf(endOnly) };\n }\n\n const existing = decoded.record;\n if (existing.providerId !== input.providerId) {\n return {\n status: \"orphaned\",\n reason: \"provider-mismatch\",\n facts: { endedAt: input.occurredAt },\n };\n }\n if (existing.endEventId === input.eventId) {\n // Idempotent replay: answer with the facts already on disk so the\n // re-exported span is byte-identical to the first one.\n return { status: \"duplicate\", facts: factsOf(existing) };\n }\n if (existing.endEventId !== undefined) {\n return {\n status: \"orphaned\",\n reason: \"already-closed\",\n facts: { endedAt: input.occurredAt },\n };\n }\n if (existing.startedAt === undefined) {\n const replaced: SpanRecord = {\n ...existing,\n endEventId: input.eventId,\n endedAt: input.occurredAt,\n exported: true,\n };\n await stateStore.write(key, encodeRecord(replaced));\n return { status: \"orphaned\", reason: \"no-start-recorded\", facts: factsOf(replaced) };\n }\n if (input.occurredAt - existing.startedAt > maxStartAgeMillis) {\n await stateStore.delete(key);\n return { status: \"orphaned\", reason: \"start-expired\", facts: { endedAt: input.occurredAt } };\n }\n\n const closed: SpanRecord = {\n ...existing,\n endEventId: input.eventId,\n endedAt: input.occurredAt,\n exported: true,\n };\n await stateStore.write(key, encodeRecord(closed));\n return {\n status: \"matched\",\n startedAt: existing.startedAt,\n durationMillis: Math.max(0, input.occurredAt - existing.startedAt),\n facts: factsOf(closed),\n };\n });\n\n const correlateGroup = async (group: BatchGroup): Promise<SpanCorrelation> => {\n const base = {\n providerId: group.providerId,\n sessionId: group.sessionId,\n ref: group.ref,\n } as const;\n const unpaired = (\n orphan: SpanOrphanClassification,\n facts: SpanCorrelationFacts,\n ): SpanCorrelation => ({\n ...base,\n pairing: \"unpaired\",\n orphan,\n // An unpaired span has no trustworthy start, so a start time is the one\n // fact it must not carry; everything else recovered is still true.\n ...correlationTimesOf(facts, { withStart: false }),\n });\n\n let startFacts: SpanCorrelationFacts | undefined;\n if (group.start !== undefined) {\n const parent = parentScopeRefOf(group.start);\n const result = await recordStart({\n sessionId: group.sessionId,\n providerId: group.providerId,\n scope: group.ref.family,\n scopeKey: group.ref.scopeKey,\n eventId: group.start.eventId,\n occurredAt: group.start.occurredAt,\n ...(parent === undefined ? {} : { parent }),\n attributes: startOnlySpanAttributes(group.start),\n });\n if (result.status === \"conflict\") {\n return unpaired(\"provider-mismatch\", {});\n }\n if (result.status === \"published\" && group.end === undefined) {\n // The end already exported this scope's span. Completing the record was\n // still worth doing (a redelivered end replays identical facts), but\n // emitting here would duplicate a span id already on the wire.\n return { ...unpaired(\"already-closed\", result.facts), disposition: \"defer\" };\n }\n startFacts = result.facts;\n }\n\n if (group.end === undefined) {\n const facts = startFacts ?? {};\n // A start whose end already landed (the racing-process case) closes a\n // complete span, even though only the start is in this batch.\n if (facts.endedAt !== undefined) {\n return {\n ...base,\n pairing: \"cross-process\",\n orphan: \"none\",\n disposition: \"emit\",\n ...correlationTimesOf(facts),\n };\n }\n // The end has not arrived. The start is durable now, so the end edge will\n // export one complete span under this scope's derived id; exporting a\n // zero-duration record here as well would put two records with that same id\n // on the wire, and OTLP cannot revise a span.\n return { ...unpaired(\"missing-end\", facts), disposition: \"defer\" };\n }\n\n const result = await recordEnd({\n sessionId: group.sessionId,\n providerId: group.providerId,\n scope: group.ref.family,\n scopeKey: group.ref.scopeKey,\n eventId: group.end.eventId,\n occurredAt: group.end.occurredAt,\n });\n\n if (result.status === \"orphaned\") {\n const orphan = orphanClassificationOf(result.reason);\n // `already-closed` means a *second, distinct* end for a scope whose first\n // end has already been exported under this scope's derived span id. Both\n // ends are real observations, so neither is dropped — but the second must\n // not reuse that id. Keying the discriminator on the end event id keeps a\n // redelivery of this same second end idempotent, since it recomputes the\n // same id rather than inventing a third.\n return orphan === \"already-closed\"\n ? {\n ...unpaired(orphan, result.facts),\n disposition: \"emit\",\n spanIdDiscriminator: group.end.eventId,\n }\n : { ...unpaired(orphan, result.facts), disposition: \"emit\" };\n }\n if (result.status === \"duplicate\" && result.facts.startedAt === undefined) {\n // A replayed end that never had a start is still an orphan.\n return { ...unpaired(\"missing-start\", result.facts), disposition: \"emit\" };\n }\n return {\n ...base,\n pairing: group.start === undefined ? \"cross-process\" : \"in-batch\",\n orphan: \"none\",\n disposition: \"emit\",\n ...correlationTimesOf(result.facts),\n };\n };\n\n const correlateBatch = async (\n events: readonly CanonicalEvent[],\n ): Promise<readonly SpanCorrelation[]> => {\n const groups = new Map<string, BatchGroup>();\n for (const event of events) {\n const ref = spanScopeRefOf(event);\n if (ref === undefined) {\n continue;\n }\n const providerId = event.provenance.providerId;\n const groupKey = [providerId, event.sessionId, ref.family, ref.scopeKey].join(\"\\u0000\");\n const group: BatchGroup = groups.get(groupKey) ?? {\n providerId,\n sessionId: event.sessionId,\n ref,\n };\n if (event.type.endsWith(\".start\")) {\n group.start = event;\n } else {\n group.end = event;\n }\n groups.set(groupKey, group);\n }\n\n const correlations: SpanCorrelation[] = [];\n for (const group of groups.values()) {\n try {\n correlations.push(await correlateGroup(group));\n } catch {\n // Fail open: an unreachable, locked, or unwritable state store costs a\n // span its pairing, never the whole export.\n //\n // A start whose record could not be written is the case that needs care.\n // It is *not* deferrable — deferring means \"the state store is holding\n // this, the end edge will publish it\", and here the state store is exactly\n // what failed. So it must be exported, and it must not use the scope's\n // canonical span id: nothing recorded this start, so a later end will\n // publish that id itself as an orphan, and reusing it would put two\n // records with one identity on the wire. Discriminating by the start's own\n // event id makes this record honest and collision-free.\n const unrecordedStart = group.start !== undefined && group.end === undefined;\n correlations.push({\n providerId: group.providerId,\n sessionId: group.sessionId,\n ref: group.ref,\n pairing: \"unpaired\",\n orphan: \"state-unavailable\",\n disposition: \"emit\",\n ...(unrecordedStart && group.start !== undefined\n ? { spanIdDiscriminator: group.start.eventId }\n : {}),\n });\n }\n }\n return correlations;\n };\n\n const cleanup = async (\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<SpanCleanupResult> => {\n const keys = await stateStore.keys(spanScanPrefix(options?.sessionId));\n const cap = options?.maxEntries ?? 1_000;\n const now = clock.now();\n let removed = 0;\n let scanned = 0;\n let expiredOpen = 0;\n for (const key of keys) {\n if (scanned >= cap) {\n break;\n }\n scanned += 1;\n const record = await stateStore.read(key);\n if (record !== undefined && now - record.updatedAt > maxAgeMillis) {\n // Classified before deletion: a record with a start and no end is a span\n // that will never be exported, which is worth counting rather than\n // discarding silently.\n if (record.value.kind === \"attributes\") {\n const decoded = decodeRecord(record.value.attributes);\n if (\n decoded.kind === \"present\" &&\n decoded.record.startedAt !== undefined &&\n decoded.record.endedAt === undefined\n ) {\n expiredOpen += 1;\n }\n }\n await stateStore.delete(key);\n removed += 1;\n }\n }\n return { removed, scanned, expiredOpen };\n };\n\n return { recordStart, recordEnd, correlateBatch, cleanup };\n};\n","import { z } from \"zod\";\n\nimport { tokenCountSchema } from \"./primitives.js\";\n\n/**\n * Whether an observation reports the change since the previous observation\n * (`delta`) or the running total for the session/generation (`cumulative`).\n *\n * The canonical model keeps temporality explicit rather than assuming one:\n * summing cumulative observations double-counts, and diffing delta observations\n * silently loses tokens.\n */\nexport const usageTemporalitySchema = z.enum([\"delta\", \"cumulative\"]);\nexport type UsageTemporality = z.infer<typeof usageTemporalitySchema>;\n\n/**\n * Whether the provider counts cache-creation tokens inside its input total or\n * reports them as a disjoint bucket.\n *\n * - `included-in-input`: `cacheCreationInputTokens` is a subset of `inputTokens`.\n * - `disjoint-from-input`: cache-creation tokens are billed in addition to\n * `inputTokens` and must be added when computing a total.\n * - `not-reported`: the provider exposes no cache-creation counter; the field is\n * pinned to zero.\n */\nexport const cacheCreationAccountingSchema = z.enum([\n \"included-in-input\",\n \"disjoint-from-input\",\n \"not-reported\",\n]);\nexport type CacheCreationAccounting = z.infer<typeof cacheCreationAccountingSchema>;\n\n/** Whether a provider-reported total agrees with the canonical computation. */\nexport const providerTotalAgreementSchema = z.enum([\"unreported\", \"agrees\", \"disagrees\"]);\nexport type ProviderTotalAgreement = z.infer<typeof providerTotalAgreementSchema>;\n\n/**\n * What an adapter reports, before normalization.\n *\n * `inputTokens` is *inclusive*: it counts every input token the provider\n * attributes to the call, including cache reads (and cache creation when the\n * provider folds it in). `outputTokens` is likewise inclusive of reasoning\n * output. Subset fields describe portions of those totals, never additions.\n */\nexport const usageReportSchema = z.strictObject({\n temporality: usageTemporalitySchema,\n /** Inclusive input tokens. */\n inputTokens: tokenCountSchema.optional(),\n /** Subset of `inputTokens` served from a prompt cache. */\n cachedInputTokens: tokenCountSchema.optional(),\n /** Tokens written to a prompt cache. */\n cacheCreationInputTokens: tokenCountSchema.optional(),\n /** Required when `cacheCreationInputTokens` is present and non-zero. */\n cacheCreationAccounting: cacheCreationAccountingSchema.optional(),\n /** Inclusive output tokens. */\n outputTokens: tokenCountSchema.optional(),\n /** Subset of `outputTokens` spent on reasoning. */\n reasoningOutputTokens: tokenCountSchema.optional(),\n /** Total exactly as the provider reported it, if it reported one. */\n providerTotalTokens: tokenCountSchema.optional(),\n});\nexport type UsageReport = z.infer<typeof usageReportSchema>;\n\n/**\n * Fully normalized usage.\n *\n * Derived fields (`uncachedInputTokens`, `totalTokens`,\n * `providerTotalAgreement`) are part of the schema and are re-checked on parse,\n * so an inconsistent object cannot exist. Construct values with\n * {@link normalizeUsage} rather than by hand.\n */\nexport const canonicalUsageSchema = z\n .strictObject({\n temporality: usageTemporalitySchema,\n inputTokens: tokenCountSchema,\n cachedInputTokens: tokenCountSchema,\n cacheCreationInputTokens: tokenCountSchema,\n cacheCreationAccounting: cacheCreationAccountingSchema,\n outputTokens: tokenCountSchema,\n reasoningOutputTokens: tokenCountSchema,\n /** Derived: input tokens that were neither cache reads nor cache writes. */\n uncachedInputTokens: tokenCountSchema,\n /** Derived: canonical billable total. */\n totalTokens: tokenCountSchema,\n providerTotalTokens: tokenCountSchema.optional(),\n providerTotalAgreement: providerTotalAgreementSchema,\n })\n .check((ctx) => {\n const usage = ctx.value;\n const push = (message: string): void => {\n ctx.issues.push({ code: \"custom\", input: usage, message });\n };\n\n if (usage.cachedInputTokens > usage.inputTokens) {\n push(\"cachedInputTokens must not exceed inputTokens (it is a subset)\");\n }\n if (usage.reasoningOutputTokens > usage.outputTokens) {\n push(\"reasoningOutputTokens must not exceed outputTokens (it is a subset)\");\n }\n if (usage.cacheCreationAccounting === \"not-reported\" && usage.cacheCreationInputTokens !== 0) {\n push(\"cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported\");\n }\n const creationInsideInput =\n usage.cacheCreationAccounting === \"included-in-input\" ? usage.cacheCreationInputTokens : 0;\n if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {\n push(\n \"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input\",\n );\n }\n const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;\n if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {\n push(`uncachedInputTokens must equal ${expectedUncached}`);\n }\n const creationOutsideInput =\n usage.cacheCreationAccounting === \"disjoint-from-input\" ? usage.cacheCreationInputTokens : 0;\n const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;\n if (usage.totalTokens !== expectedTotal) {\n push(`totalTokens must equal ${expectedTotal}`);\n }\n const expectedAgreement: ProviderTotalAgreement =\n usage.providerTotalTokens === undefined\n ? \"unreported\"\n : usage.providerTotalTokens === expectedTotal\n ? \"agrees\"\n : \"disagrees\";\n if (usage.providerTotalAgreement !== expectedAgreement) {\n push(`providerTotalAgreement must be ${expectedAgreement}`);\n }\n });\nexport type CanonicalUsage = z.infer<typeof canonicalUsageSchema>;\n\nexport type UsageNormalizationIssue = {\n readonly code:\n | \"invalid-report\"\n | \"cached-exceeds-input\"\n | \"reasoning-exceeds-output\"\n | \"cache-creation-exceeds-input\"\n | \"cache-creation-accounting-missing\";\n readonly message: string;\n};\n\nexport type UsageNormalizationResult =\n | { readonly status: \"ok\"; readonly usage: CanonicalUsage; readonly notes: readonly string[] }\n | { readonly status: \"invalid\"; readonly issues: readonly UsageNormalizationIssue[] };\n\n/**\n * Normalize a provider usage report into canonical usage.\n *\n * Deterministic rules:\n * 1. Absent counters default to `0`; `providerTotalTokens` stays absent.\n * 2. Non-integer, negative, or non-finite counters are rejected.\n * 3. A subset exceeding its total is rejected — never clamped — because\n * clamping would silently invent a billing story.\n * 4. `cacheCreationAccounting` defaults to `not-reported` when no cache-creation\n * tokens are reported, and is *required* when they are: guessing whether the\n * bucket is disjoint would mis-total every downstream cost calculation.\n * 5. A provider total that disagrees with the canonical total is preserved as\n * reported and flagged `disagrees`. Both numbers survive; neither is edited.\n */\nexport const normalizeUsage = (report: unknown): UsageNormalizationResult => {\n const parsed = usageReportSchema.safeParse(report);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map((issue) => ({\n code: \"invalid-report\" as const,\n message: `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n })),\n };\n }\n\n const input = parsed.data;\n const issues: UsageNormalizationIssue[] = [];\n const notes: string[] = [];\n\n const inputTokens = input.inputTokens ?? 0;\n const cachedInputTokens = input.cachedInputTokens ?? 0;\n const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;\n const outputTokens = input.outputTokens ?? 0;\n const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;\n\n let accounting: CacheCreationAccounting;\n if (cacheCreationInputTokens === 0) {\n accounting = input.cacheCreationAccounting ?? \"not-reported\";\n if (accounting !== \"not-reported\") {\n notes.push(\n `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`,\n );\n }\n } else if (input.cacheCreationAccounting === undefined) {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message:\n \"cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred\",\n });\n accounting = \"not-reported\";\n } else if (input.cacheCreationAccounting === \"not-reported\") {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message: \"cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens\",\n });\n accounting = \"not-reported\";\n } else {\n accounting = input.cacheCreationAccounting;\n }\n\n if (cachedInputTokens > inputTokens) {\n issues.push({\n code: \"cached-exceeds-input\",\n message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n if (reasoningOutputTokens > outputTokens) {\n issues.push({\n code: \"reasoning-exceeds-output\",\n message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`,\n });\n }\n\n const creationInsideInput = accounting === \"included-in-input\" ? cacheCreationInputTokens : 0;\n if (cachedInputTokens + creationInsideInput > inputTokens) {\n issues.push({\n code: \"cache-creation-exceeds-input\",\n message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const creationOutsideInput = accounting === \"disjoint-from-input\" ? cacheCreationInputTokens : 0;\n const totalTokens = inputTokens + creationOutsideInput + outputTokens;\n const providerTotalAgreement: ProviderTotalAgreement =\n input.providerTotalTokens === undefined\n ? \"unreported\"\n : input.providerTotalTokens === totalTokens\n ? \"agrees\"\n : \"disagrees\";\n\n if (providerTotalAgreement === \"disagrees\") {\n notes.push(\n `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`,\n );\n }\n\n const usage: CanonicalUsage = {\n temporality: input.temporality,\n inputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens,\n reasoningOutputTokens,\n uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,\n totalTokens,\n ...(input.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: input.providerTotalTokens }),\n providerTotalAgreement,\n };\n\n return { status: \"ok\", usage, notes };\n};\n\nexport class UsageNormalizationError extends Error {\n public readonly issues: readonly UsageNormalizationIssue[];\n\n public constructor(issues: readonly UsageNormalizationIssue[]) {\n super(`invalid usage report: ${issues.map((issue) => issue.message).join(\"; \")}`);\n this.name = \"UsageNormalizationError\";\n this.issues = issues;\n }\n}\n\n/** Convenience wrapper for call sites that treat invalid usage as a bug. */\nexport const normalizeUsageOrThrow = (report: unknown): CanonicalUsage => {\n const result = normalizeUsage(report);\n if (result.status === \"invalid\") {\n throw new UsageNormalizationError(result.issues);\n }\n return result.usage;\n};\n\nexport const EMPTY_DELTA_USAGE: CanonicalUsage = Object.freeze(\n normalizeUsageOrThrow({ temporality: \"delta\" }),\n);\n\nexport type UsageDeltaResult = {\n readonly usage: CanonicalUsage;\n /**\n * True when the current snapshot is smaller than the previous one on any\n * counter. That means the cumulative series restarted (new session, replayed\n * transcript, provider reset), so the current snapshot is emitted as the delta\n * instead of a negative difference.\n */\n readonly resetDetected: boolean;\n};\n\nconst requireCumulative = (usage: CanonicalUsage, label: string): void => {\n if (usage.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: `${label} must have cumulative temporality` },\n ]);\n }\n};\n\n/**\n * Convert two cumulative snapshots into a delta observation.\n *\n * Replay safety: re-processing the same snapshot yields an all-zero delta, and a\n * decreasing series is reported as a reset rather than a negative delta.\n * Accounting mode must match; mixing modes would make the subtraction meaningless.\n */\nexport const cumulativeToDelta = (\n previous: CanonicalUsage,\n current: CanonicalUsage,\n): UsageDeltaResult => {\n requireCumulative(previous, \"previous usage\");\n requireCumulative(current, \"current usage\");\n\n if (\n previous.cacheCreationAccounting !== current.cacheCreationAccounting &&\n previous.cacheCreationInputTokens !== 0 &&\n current.cacheCreationInputTokens !== 0\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot diff cumulative usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const resetDetected =\n current.inputTokens < previous.inputTokens ||\n current.cachedInputTokens < previous.cachedInputTokens ||\n current.cacheCreationInputTokens < previous.cacheCreationInputTokens ||\n current.outputTokens < previous.outputTokens ||\n current.reasoningOutputTokens < previous.reasoningOutputTokens;\n\n if (resetDetected) {\n return {\n usage: normalizeUsageOrThrow({ ...toReport(current), temporality: \"delta\" }),\n resetDetected: true,\n };\n }\n\n const usage = normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: current.inputTokens - previous.inputTokens,\n cachedInputTokens: current.cachedInputTokens - previous.cachedInputTokens,\n cacheCreationInputTokens:\n current.cacheCreationInputTokens - previous.cacheCreationInputTokens,\n cacheCreationAccounting: current.cacheCreationAccounting,\n outputTokens: current.outputTokens - previous.outputTokens,\n reasoningOutputTokens: current.reasoningOutputTokens - previous.reasoningOutputTokens,\n });\n\n return { usage, resetDetected: false };\n};\n\n/** Project canonical usage back onto the reported shape. */\nexport const toReport = (usage: CanonicalUsage): UsageReport => ({\n temporality: usage.temporality,\n inputTokens: usage.inputTokens,\n cachedInputTokens: usage.cachedInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n cacheCreationAccounting: usage.cacheCreationAccounting,\n outputTokens: usage.outputTokens,\n reasoningOutputTokens: usage.reasoningOutputTokens,\n ...(usage.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: usage.providerTotalTokens }),\n});\n\n/**\n * Add two delta observations. Cumulative usage is never summed, because two\n * running totals do not compose.\n */\nexport const addUsage = (a: CanonicalUsage, b: CanonicalUsage): CanonicalUsage => {\n if (a.temporality !== \"delta\" || b.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"only delta usage may be summed\" },\n ]);\n }\n const accounting =\n a.cacheCreationInputTokens === 0 && a.cacheCreationAccounting === \"not-reported\"\n ? b.cacheCreationAccounting\n : b.cacheCreationInputTokens === 0 && b.cacheCreationAccounting === \"not-reported\"\n ? a.cacheCreationAccounting\n : a.cacheCreationAccounting;\n\n if (\n a.cacheCreationInputTokens !== 0 &&\n b.cacheCreationInputTokens !== 0 &&\n a.cacheCreationAccounting !== b.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot sum usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n a.providerTotalTokens === undefined && b.providerTotalTokens === undefined\n ? undefined\n : (a.providerTotalTokens ?? 0) + (b.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: a.inputTokens + b.inputTokens,\n cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,\n cacheCreationInputTokens: a.cacheCreationInputTokens + b.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: a.outputTokens + b.outputTokens,\n reasoningOutputTokens: a.reasoningOutputTokens + b.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n","import {\n UsageNormalizationError,\n normalizeUsageOrThrow,\n type CanonicalUsage,\n} from \"../model/usage.js\";\nimport type { Attributes } from \"../model/primitives.js\";\nimport type { Clock, StateStore } from \"../runtime/ports.js\";\nimport { withOptionalSessionLock } from \"../state/store.js\";\nimport { rollupEpochKey, rollupEpochScanPrefix, rollupScanPrefix, rollupUsageKey } from \"./keys.js\";\n\nexport type UsageAccumulatorKey = {\n readonly sessionId: string;\n readonly scope: string;\n readonly scopeKey: string;\n};\n\nexport type UsageAccumulatorSnapshot = {\n readonly total: CanonicalUsage;\n /** Increments every time {@link UsageAccumulator.recordReset} is called for this key. */\n readonly epoch: number;\n};\n\nexport type RollupCleanupResult = { readonly removed: number; readonly scanned: number };\n\n/**\n * Which delivery an accumulation belongs to, and which of its observations this is.\n *\n * Supplying it makes the accumulation idempotent for *that delivery*: a second\n * application of the same `(callbackId, ordinal)` is a no-op that returns the\n * current total. Omitting it keeps the old unconditional behaviour, which is right\n * for a caller that has no delivery identity to key on — there is nothing to\n * recognize a repeat by, and refusing to accumulate would lose a real observation.\n *\n * `callbackId` must be an opaque digest, not a raw host or provider id: it is\n * written into a state record.\n */\nexport type DeliveryStamp = {\n readonly callbackId: string;\n /** Zero-based index of this observation within the delivery, per rollup key. */\n readonly ordinal: number;\n};\n\nexport type AccumulateOptions = { readonly delivery?: DeliveryStamp };\n\n/**\n * Rolls a stream of `delta` usage observations up into a running `cumulative`\n * total per scope, independent of the orchestrator's own per-scope\n * cumulative-to-delta baseline (`docs/usage-semantics.md`) — that baseline\n * answers \"what changed since last time\"; this answers \"what is the running\n * total\", which a diagnostics view or a parent scope (tool -> generation ->\n * session) needs and the core does not compute.\n *\n * A provider counter can restart mid-session (a process restart, a replayed\n * transcript). Rather than let a smaller cumulative total silently deflate the\n * running rollup, {@link UsageAccumulator.recordReset} starts a new epoch: the\n * total resets to zero and the epoch number increments, so a downstream\n * consumer can tell \"the counter restarted\" from \"usage actually decreased\"\n * and never sums across the boundary as if it were one continuous series.\n */\nexport interface UsageAccumulator {\n /**\n * Fold `delta` into the running total for `key`.\n *\n * With `options.delivery`, folding is idempotent for that delivery: a redelivered\n * callback whose claim was reclaimed or superseded re-derives the same delta and\n * would otherwise count it twice. The marker lives in the same record as the total\n * it describes, so the check and the write are one atomic operation — which is the\n * only reason this is expressible without a multi-key transaction. What it does\n * *not* cover is a delivery whose marker a later, different delivery has since\n * overwritten: only the most recent delivery per rollup key is recognizable, which\n * is exactly the retry window and nothing beyond it.\n */\n accumulateDelta(\n key: UsageAccumulatorKey,\n delta: CanonicalUsage,\n options?: AccumulateOptions,\n ): Promise<UsageAccumulatorSnapshot>;\n /** Start a new epoch. Idempotent per delivery when `options.delivery` is given. */\n recordReset(key: UsageAccumulatorKey, options?: AccumulateOptions): Promise<{ readonly epoch: number }>;\n read(key: UsageAccumulatorKey): Promise<UsageAccumulatorSnapshot | undefined>;\n cleanup(\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<RollupCleanupResult>;\n}\n\nexport type UsageAccumulatorDependencies = {\n readonly stateStore: StateStore;\n readonly clock: Clock;\n};\n\nconst EMPTY_CUMULATIVE_USAGE: CanonicalUsage = normalizeUsageOrThrow({ temporality: \"cumulative\" });\n\nconst combineCumulativeWithDelta = (total: CanonicalUsage, delta: CanonicalUsage): CanonicalUsage => {\n if (total.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"usage rollup total must have cumulative temporality\" },\n ]);\n }\n if (delta.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"usage accumulator only accepts delta observations\" },\n ]);\n }\n\n const accounting =\n total.cacheCreationInputTokens === 0 && total.cacheCreationAccounting === \"not-reported\"\n ? delta.cacheCreationAccounting\n : delta.cacheCreationInputTokens === 0 && delta.cacheCreationAccounting === \"not-reported\"\n ? total.cacheCreationAccounting\n : total.cacheCreationAccounting;\n\n if (\n total.cacheCreationInputTokens !== 0 &&\n delta.cacheCreationInputTokens !== 0 &&\n total.cacheCreationAccounting !== delta.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot roll up usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n total.providerTotalTokens === undefined && delta.providerTotalTokens === undefined\n ? undefined\n : (total.providerTotalTokens ?? 0) + (delta.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"cumulative\",\n inputTokens: total.inputTokens + delta.inputTokens,\n cachedInputTokens: total.cachedInputTokens + delta.cachedInputTokens,\n cacheCreationInputTokens: total.cacheCreationInputTokens + delta.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: total.outputTokens + delta.outputTokens,\n reasoningOutputTokens: total.reasoningOutputTokens + delta.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n\nexport const createUsageAccumulator = (deps: UsageAccumulatorDependencies): UsageAccumulator => {\n const { stateStore, clock } = deps;\n\n /**\n * The epoch record's own delivery marker.\n *\n * Kept in the epoch record for the same reason the total's marker is kept in the\n * total: one write, so the counter and the statement about who moved it cannot\n * disagree. The epoch record is an `attributes` value, so the two fields are\n * flat rather than nested.\n */\n const readEpochMarker = (\n attributes: Attributes,\n ): { readonly callbackId: string; readonly applications: number } | undefined => {\n const callbackId = attributes.resetDelivery;\n const applications = attributes.resetApplications;\n if (\n typeof callbackId !== \"string\" ||\n callbackId.length === 0 ||\n typeof applications !== \"number\" ||\n !Number.isInteger(applications) ||\n applications < 1\n ) {\n return undefined;\n }\n return { callbackId, applications };\n };\n\n const readEpoch = async (key: UsageAccumulatorKey): Promise<number> => {\n const record = await stateStore.read(rollupEpochKey(key.sessionId, key.scope, key.scopeKey));\n if (record?.value.kind === \"attributes\" && typeof record.value.attributes.epoch === \"number\") {\n return record.value.attributes.epoch;\n }\n return 0;\n };\n\n /**\n * Whether this delivery's observation number `ordinal` is already folded in.\n *\n * The comparison is `<` rather than `===` because observations are applied in\n * order: `applications` is the count folded in so far, so any ordinal below it has\n * been seen. A marker naming a *different* delivery means this rollup has moved on\n * and nothing can be recognized.\n */\n const alreadyApplied = (\n marker: { readonly callbackId: string; readonly applications: number } | undefined,\n delivery: DeliveryStamp | undefined,\n ): boolean =>\n delivery !== undefined &&\n marker !== undefined &&\n marker.callbackId === delivery.callbackId &&\n delivery.ordinal < marker.applications;\n\n const markerFor = (\n delivery: DeliveryStamp | undefined,\n ): { readonly appliedDelivery?: { readonly callbackId: string; readonly applications: number } } =>\n delivery === undefined\n ? {}\n : {\n appliedDelivery: { callbackId: delivery.callbackId, applications: delivery.ordinal + 1 },\n };\n\n const accumulateDelta = (\n key: UsageAccumulatorKey,\n delta: CanonicalUsage,\n options?: AccumulateOptions,\n ): Promise<UsageAccumulatorSnapshot> =>\n withOptionalSessionLock(stateStore, key.sessionId, async (): Promise<UsageAccumulatorSnapshot> => {\n const usageKey = rollupUsageKey(key.sessionId, key.scope, key.scopeKey);\n const existing = await stateStore.read(usageKey);\n const previousTotal =\n existing?.value.kind === \"usage-cumulative\" ? existing.value.usage : EMPTY_CUMULATIVE_USAGE;\n\n if (\n existing?.value.kind === \"usage-cumulative\" &&\n alreadyApplied(existing.value.appliedDelivery, options?.delivery)\n ) {\n // This exact observation of this exact delivery is already in the total.\n // Reporting the total unchanged is the honest answer: the caller asked for\n // the running figure after its delta, and that is what this is.\n return { total: previousTotal, epoch: await readEpoch(key) };\n }\n\n const total = combineCumulativeWithDelta(previousTotal, delta);\n await stateStore.write(usageKey, {\n kind: \"usage-cumulative\",\n usage: total,\n ...markerFor(options?.delivery),\n });\n return { total, epoch: await readEpoch(key) };\n });\n\n const recordReset = (\n key: UsageAccumulatorKey,\n options?: AccumulateOptions,\n ): Promise<{ readonly epoch: number }> =>\n withOptionalSessionLock(stateStore, key.sessionId, async (): Promise<{ readonly epoch: number }> => {\n const epochKey = rollupEpochKey(key.sessionId, key.scope, key.scopeKey);\n const existingEpoch = await stateStore.read(epochKey);\n const marker =\n existingEpoch?.value.kind === \"attributes\"\n ? readEpochMarker(existingEpoch.value.attributes)\n : undefined;\n\n if (alreadyApplied(marker, options?.delivery)) {\n // A replayed reset must not open a second epoch: the epoch number is what a\n // consumer uses to refuse summing across a counter restart, and inflating it\n // twice for one restart makes a real series look like two.\n return { epoch: await readEpoch(key) };\n }\n\n const epoch = (await readEpoch(key)) + 1;\n const applied = markerFor(options?.delivery).appliedDelivery;\n await stateStore.write(epochKey, {\n kind: \"attributes\",\n attributes: {\n epoch,\n ...(applied === undefined\n ? {}\n : { resetDelivery: applied.callbackId, resetApplications: applied.applications }),\n },\n });\n await stateStore.delete(rollupUsageKey(key.sessionId, key.scope, key.scopeKey));\n return { epoch };\n });\n\n const read = async (key: UsageAccumulatorKey): Promise<UsageAccumulatorSnapshot | undefined> => {\n const record = await stateStore.read(rollupUsageKey(key.sessionId, key.scope, key.scopeKey));\n if (record?.value.kind !== \"usage-cumulative\") {\n return undefined;\n }\n return { total: record.value.usage, epoch: await readEpoch(key) };\n };\n\n const cleanup = async (\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<RollupCleanupResult> => {\n const cap = options?.maxEntries ?? 1_000;\n const now = clock.now();\n let removed = 0;\n let scanned = 0;\n\n const sweep = async (keys: readonly string[]): Promise<void> => {\n for (const key of keys) {\n if (scanned >= cap) {\n return;\n }\n scanned += 1;\n const record = await stateStore.read(key);\n if (record !== undefined && now - record.updatedAt > maxAgeMillis) {\n await stateStore.delete(key);\n removed += 1;\n }\n }\n };\n\n await sweep(await stateStore.keys(rollupScanPrefix(options?.sessionId)));\n await sweep(await stateStore.keys(rollupEpochScanPrefix(options?.sessionId)));\n return { removed, scanned };\n };\n\n return { accumulateDelta, recordReset, read, cleanup };\n};\n","import 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,SA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QAAQ,EAAE,YAAY,GAAI,cAAc,SAAY,CAAC,IAAI,EAAE,UAAU,EAAG;AAC9E,UAAM,CAAC,MAAM,OAAO,KAAK,IAAI,MAAM,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","result","z","z"]}
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/lifecycle/span-correlator.ts","../src/model/usage.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 ATTR_SESSION_ID,\n} from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport type { CanonicalEvent, CanonicalEventType } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\nimport { VERSION } from \"../version.js\";\n\nconst SCOPE_NAME = \"@osfactory/otel-hook\";\n\nexport const DEFAULT_INSTRUMENTATION_SCOPE: InstrumentationScope = Object.freeze({\n name: SCOPE_NAME,\n version: VERSION,\n});\n\nconst ATTR_OTELHOOK_INVOCATION_ID = \"otelhook.invocation.id\";\nconst ATTR_OTELHOOK_PROVIDER_ID = \"otelhook.provider.id\";\nconst ATTR_OTELHOOK_PROVIDER_VERSION = \"otelhook.provider.version\";\nconst ATTR_OTELHOOK_WORKSPACE_ID = \"otelhook.workspace.id\";\nconst ATTR_OTELHOOK_SPAN_PAIRED = \"otelhook.span.paired\";\nconst ATTR_OTELHOOK_SPAN_PAIRING = \"otelhook.span.pairing\";\nconst ATTR_OTELHOOK_SPAN_ORPHAN = \"otelhook.span.orphan\";\nconst ATTR_OTELHOOK_OUTCOME = \"otelhook.outcome\";\nconst ATTR_OTELHOOK_RESET_DETECTED = \"otelhook.usage.reset_detected\";\nconst ATTR_OTELHOOK_TOOL_KIND = \"otelhook.tool.kind\";\nconst ATTR_OTELHOOK_DELEGATION_DEPTH = \"otelhook.delegation_depth\";\nconst ATTR_OTELHOOK_COMPACTION_TRIGGER = \"otelhook.compaction.trigger\";\nconst ATTR_OTELHOOK_AGENT_NAME = \"otelhook.agent.name\";\nconst ATTR_OTELHOOK_AGENT_VERSION = \"otelhook.agent.version\";\n\n/**\n * Pure, stateless canonical-event-to-span mapping.\n *\n * Isolated in one module so every other piece of the telemetry pipeline\n * — batching, retry, spooling — can change without touching what an attribute\n * means. Two edges of the same lifecycle scope are merged into one span when\n * they appear in the same batch; when they arrive in *different* short-lived\n * hook processes they are merged through a {@link SpanCorrelation} the caller\n * resolved from persisted state. Either way the mapping itself stays a pure\n * function: state is read by the correlator, never by this module.\n *\n * ## Identity of a span\n *\n * Trace and span ids are derived, never random, so two processes that never\n * meet still agree on them:\n *\n * - `traceId = H(providerId, sessionId)` — one trace per session per provider.\n * Deriving it from the session rather than the invocation is what lets a\n * `tool.end` emitted minutes later land in the same trace as its `tool.start`;\n * including the provider is what stops two providers that happen to reuse a\n * session id from being stitched into one trace.\n * - `spanId = H(providerId, sessionId, family, scopeKey)` — stable across\n * processes and idempotent under redelivery, so a collector that sees a\n * start-only span and later the completed span treats them as one span\n * rather than two.\n */\n// NUL, so joined parts cannot collide across a different split: no identifier\n// this library accepts can contain one, which a printable separator cannot\n// promise. Never emitted — only hashed, or used as an in-memory map key.\nconst FIELD_SEPARATOR = \"\\u0000\";\n\nconst digestHex = (parts: readonly string[], length: number): string =>\n createHash(\"sha256\").update(parts.join(FIELD_SEPARATOR)).digest(\"hex\").slice(0, length);\n\n/** Lifecycle scopes that pair a `*.start` edge with a later `*.end` edge. */\nexport type SpanFamily = \"session\" | \"generation\" | \"tool\" | \"subagent\";\n\n/** Identifies one lifecycle span within a session. */\nexport type SpanScopeRef = {\n readonly family: SpanFamily;\n readonly scopeKey: string;\n};\n\n/**\n * Why a lifecycle span is, or is not, a complete pair.\n *\n * Deliberately explicit rather than a bare boolean: \"we never saw the start\",\n * \"we saw it but it aged out of state\", and \"state could not be read at all\"\n * are different operational facts, and a dashboard that cannot tell them apart\n * cannot tell a broken host from a broken exporter.\n */\nexport type SpanOrphanClassification =\n /** Both edges are known — from this batch, or from persisted state. */\n | \"none\"\n /** The start is known; its end has not arrived yet. */\n | \"missing-end\"\n /** An end arrived and no start was ever recorded for this scope. */\n | \"missing-start\"\n /** A start was recorded but aged past the retention window before the end arrived. */\n | \"expired-start\"\n /** A start exists but was recorded by a different provider; pairing it would be a guess. */\n | \"provider-mismatch\"\n /** A second, distinct end arrived for a scope that was already closed. */\n | \"already-closed\"\n /** The persisted record was written by an incompatible version and was discarded. */\n | \"state-incompatible\"\n /** The persisted record could not be understood. */\n | \"state-corrupt\"\n /** State could not be consulted at all; the mapping degraded rather than failing. */\n | \"state-unavailable\";\n\nexport type SpanPairing =\n /** Both edges were present in this batch. */\n | \"in-batch\"\n /** The other edge came from state written by an earlier process. */\n | \"cross-process\"\n | \"unpaired\";\n\n/**\n * Whether this scope should produce an OTLP record now.\n *\n * OTLP has no notion of updating a span: a span is exported once, when it ends,\n * and a second record carrying the same trace and span id is not a revision of\n * the first — it is a duplicate that backends variously drop, keep the older of,\n * or display twice. Since every lifecycle span id here is *derived* from\n * `(provider, session, family, scopeKey)`, a `*.start` edge and its later `*.end`\n * edge compute the identical id, so exporting on both is precisely that\n * duplicate.\n *\n * `defer` is therefore the answer for a start whose end has not arrived: the\n * start is durable in the state store, and the end edge exports the one complete\n * span using the times recovered from it. Nothing is lost by waiting, and what is\n * gained is that the record a collector receives has a real duration.\n */\nexport type SpanDisposition =\n /** Export a record for this scope now. */\n | \"emit\"\n /** Hold: the start is recorded, and the end edge will export the complete span. */\n | \"defer\";\n\n/**\n * One scope's correlation facts, resolved from persisted state by the caller.\n *\n * Plain data on purpose: the telemetry layer must not reach into the state\n * store itself (ADR 0006), so it declares what it needs and the lifecycle layer\n * supplies it.\n */\nexport type SpanCorrelation = {\n readonly providerId: string;\n readonly sessionId: string;\n readonly ref: SpanScopeRef;\n readonly pairing: SpanPairing;\n readonly orphan: SpanOrphanClassification;\n /**\n * Whether to export a record for this scope now. Defaults to `emit` when a\n * correlation is supplied without one.\n */\n readonly disposition?: SpanDisposition;\n /**\n * Extra component mixed into the derived span id.\n *\n * Set only when this record is a genuinely *additional* observation of a scope\n * that has already been exported once — a second, distinct end for a scope that\n * was already closed. Both records are real, so neither is dropped, and the\n * discriminator keeps them from claiming the same span id.\n */\n readonly spanIdDiscriminator?: string;\n /** Start recovered from state; authoritative over the batch's own start edge. */\n readonly startMillis?: number;\n /** End recovered from state; authoritative so a redelivered end re-exports an identical span. */\n readonly endMillis?: number;\n /** Parent recorded at start time, so an end-only process hangs the span in the same place. */\n readonly parent?: SpanScopeRef;\n /** Attributes only the start edge could supply, recovered for an end-only span. */\n readonly attributes?: Attributes;\n};\n\n/**\n * Resolves persisted correlation for one batch.\n *\n * Must never reject: a state failure is a degraded span, never a lost export.\n */\nexport type SpanCorrelationResolver = (\n events: readonly CanonicalEvent[],\n) => Promise<readonly SpanCorrelation[]>;\n\n/**\n * Upper bound on how many start-edge attributes the correlator may carry\n * forward, so persisted state cannot grow with provider-controlled input.\n */\nexport const MAX_RECOVERED_START_ATTRIBUTES = 16;\n\nconst familyOf = (type: CanonicalEventType): SpanFamily | undefined => {\n switch (type) {\n case \"session.start\":\n case \"session.end\":\n return \"session\";\n case \"generation.start\":\n case \"generation.end\":\n return \"generation\";\n case \"tool.start\":\n case \"tool.end\":\n return \"tool\";\n case \"subagent.start\":\n case \"subagent.end\":\n return \"subagent\";\n default:\n return undefined;\n }\n};\n\n/** The lifecycle span an event is an edge of, or undefined for a point-in-time event. */\nexport const spanScopeRefOf = (event: CanonicalEvent): SpanScopeRef | undefined => {\n const family = familyOf(event.type);\n if (family === undefined) {\n return undefined;\n }\n switch (event.type) {\n case \"session.start\":\n case \"session.end\":\n return { family, scopeKey: event.sessionId };\n case \"generation.start\":\n case \"generation.end\":\n return { family, scopeKey: event.generationId };\n case \"tool.start\":\n case \"tool.end\":\n return { family, scopeKey: event.toolCallId };\n case \"subagent.start\":\n case \"subagent.end\":\n return { family, scopeKey: event.subagentInvocationId };\n default:\n return undefined;\n }\n};\n\n/**\n * Where a span hangs in the trace, judged from this event alone.\n *\n * Everything in a session descends from the session span. A tool call names its\n * generation only on `tool.start`, which is exactly why the correlator persists\n * the parent: the `tool.end` process would otherwise reparent the same span to\n * the session and produce a tree whose shape depends on which edge happened to\n * be exported last.\n */\nexport const parentScopeRefOf = (event: CanonicalEvent): SpanScopeRef | undefined => {\n if (event.type === \"session.start\" || event.type === \"session.end\") {\n return undefined;\n }\n if (event.type === \"tool.start\" && event.generationId !== undefined) {\n return { family: \"generation\", scopeKey: event.generationId };\n }\n return { family: \"session\", scopeKey: event.sessionId };\n};\n\n/**\n * Span attributes that only a `*.start` edge can supply.\n *\n * The correlator persists these verbatim so an end-only span in a later process\n * still carries the tool kind, requested model, delegation depth, or agent name\n * the start process saw. An allowlist, and bounded, so persisted state can\n * never become a second route for provider payload content to escape.\n */\nexport const startOnlySpanAttributes = (event: CanonicalEvent): Attributes => {\n switch (event.type) {\n case \"session.start\":\n return {\n ...(event.agentName === undefined ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: event.agentName }),\n ...(event.agentVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_AGENT_VERSION]: event.agentVersion }),\n };\n case \"generation.start\":\n return {\n [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId,\n ...(event.model.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: event.model.vendor }),\n };\n // `toolName` and `toolCallId` are on both tool edges, so they are not\n // start-only and persisting them would just pad every record.\n case \"tool.start\":\n return { [ATTR_OTELHOOK_TOOL_KIND]: event.toolKind };\n case \"subagent.start\":\n return { [ATTR_OTELHOOK_DELEGATION_DEPTH]: event.delegationDepth };\n default:\n return {};\n }\n};\n\nconst deriveTraceId = (providerId: string, sessionId: string): string =>\n digestHex([\"otelhook/trace\", providerId, sessionId], 32);\n\nconst deriveSpanId = (providerId: string, sessionId: string, ref: SpanScopeRef): string =>\n digestHex([\"otelhook/span\", providerId, sessionId, ref.family, ref.scopeKey], 16);\n\nconst deriveStandaloneSpanId = (\n providerId: string,\n sessionId: string,\n eventType: string,\n eventId: string,\n): string => digestHex([\"otelhook/span\", providerId, sessionId, \"event\", eventType, eventId], 16);\n\nconst correlationKey = (providerId: string, sessionId: string, ref: SpanScopeRef): string =>\n [providerId, sessionId, ref.family, ref.scopeKey].join(FIELD_SEPARATOR);\n\nconst outcomeStatus = (outcome: string | undefined): SpanStatus => {\n if (outcome === undefined || outcome === \"ok\" || outcome === \"unknown\") {\n return { code: SpanStatusCode.UNSET };\n }\n if (outcome === \"cancelled\") {\n return { code: SpanStatusCode.UNSET };\n }\n return { code: SpanStatusCode.ERROR, message: outcome };\n};\n\nconst identityAttributes = (event: CanonicalEvent): Attributes => ({\n [ATTR_SESSION_ID]: event.sessionId,\n [ATTR_OTELHOOK_INVOCATION_ID]: event.invocationId,\n [ATTR_OTELHOOK_PROVIDER_ID]: event.provenance.providerId,\n ...(event.provenance.providerVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event.provenance.providerVersion }),\n [ATTR_OTELHOOK_WORKSPACE_ID]: event.workspace.workspaceId,\n});\n\nconst usageAttributes = (usage: CanonicalUsage | undefined, resetDetected: boolean): Attributes => {\n if (usage === undefined) {\n return {};\n }\n return {\n [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: usage.inputTokens,\n [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: usage.outputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: usage.cachedInputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: usage.cacheCreationInputTokens,\n [ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]: usage.reasoningOutputTokens,\n ...(resetDetected ? { [ATTR_OTELHOOK_RESET_DETECTED]: true } : {}),\n };\n};\n\ntype SpanGroup = {\n readonly ref: SpanScopeRef;\n start?: CanonicalEvent;\n end?: CanonicalEvent;\n};\n\nconst buildSpanContext = (traceId: string, spanId: string): SpanContext => ({\n traceId,\n spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n});\n\nexport type ReadableSpanInput = {\n readonly name: string;\n readonly kind: SpanKind;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly attributes: Attributes;\n readonly status: SpanStatus;\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n};\n\n/** Reconstructs a {@link ReadableSpan} from plain, serializable fields. Used by the durable spool to replay a span it persisted earlier. */\nexport const assembleReadableSpan = (input: ReadableSpanInput): ReadableSpan => toReadableSpan(input);\n\nconst toReadableSpan = (input: ReadableSpanInput): ReadableSpan => {\n const startTime = millisToHrTime(input.startMillis);\n const endTime = millisToHrTime(Math.max(input.startMillis, input.endMillis));\n const duration = millisToHrTime(Math.max(0, input.endMillis - input.startMillis));\n return {\n name: input.name,\n kind: input.kind,\n spanContext: (): SpanContext => buildSpanContext(input.traceId, input.spanId),\n ...(input.parentSpanId === undefined\n ? {}\n : { parentSpanContext: buildSpanContext(input.traceId, input.parentSpanId) }),\n startTime,\n endTime,\n status: input.status,\n attributes: input.attributes,\n links: [],\n events: [],\n duration,\n ended: true,\n resource: input.resource,\n instrumentationScope: input.instrumentationScope,\n droppedAttributesCount: 0,\n droppedEventsCount: 0,\n droppedLinksCount: 0,\n };\n};\n\ntype ResolvedPairing = {\n readonly pairing: SpanPairing;\n readonly orphan: SpanOrphanClassification;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly parent: SpanScopeRef | undefined;\n readonly recovered: Attributes;\n};\n\nconst resolvePairing = (\n group: SpanGroup,\n anchor: CanonicalEvent,\n correlation: SpanCorrelation | undefined,\n): ResolvedPairing => {\n const inBatch = group.start !== undefined && group.end !== undefined;\n const batchStart = group.start?.occurredAt ?? anchor.occurredAt;\n const batchEnd = group.end?.occurredAt ?? anchor.occurredAt;\n\n if (correlation === undefined) {\n return {\n pairing: inBatch ? \"in-batch\" : \"unpaired\",\n orphan: inBatch ? \"none\" : group.start === undefined ? \"missing-start\" : \"missing-end\",\n startMillis: batchStart,\n endMillis: inBatch ? batchEnd : batchStart,\n parent: parentScopeRefOf(anchor),\n recovered: {},\n };\n }\n\n // A correlation that reports no start (an orphaned end) must not fabricate\n // one: the span collapses onto the end instant rather than claiming a\n // duration measured from an event nobody ever saw.\n const startMillis = correlation.startMillis ?? (inBatch ? batchStart : batchEnd);\n const endMillis = correlation.endMillis ?? (group.end === undefined ? startMillis : batchEnd);\n return {\n pairing: correlation.pairing,\n orphan: correlation.orphan,\n startMillis,\n endMillis,\n parent: correlation.parent ?? parentScopeRefOf(anchor),\n recovered: correlation.attributes ?? {},\n };\n};\n\nconst buildLifecycleSpan = (\n plan: GroupPlan,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan => {\n const group = plan.group;\n const anchor = plan.anchor;\n const correlation = plan.correlation;\n const providerId = anchor.provenance.providerId;\n const sessionId = anchor.sessionId;\n const resolved = resolvePairing(group, anchor, correlation);\n const traceId = plan.traceId;\n const spanId = plan.spanId;\n const parentSpanId =\n resolved.parent === undefined ? undefined : deriveSpanId(providerId, sessionId, resolved.parent);\n\n let name: string = group.ref.family;\n let kind: SpanKind = SpanKind.INTERNAL;\n let status: SpanStatus = { code: SpanStatusCode.UNSET };\n // Attributes recovered from the start process sit *beneath* whatever this\n // batch observed: a live edge always wins over a remembered one.\n let attributes: Attributes = {\n ...identityAttributes(anchor),\n ...resolved.recovered,\n [ATTR_OTELHOOK_SPAN_PAIRED]: resolved.pairing !== \"unpaired\",\n [ATTR_OTELHOOK_SPAN_PAIRING]: resolved.pairing,\n [ATTR_OTELHOOK_SPAN_ORPHAN]: resolved.orphan,\n };\n\n switch (group.ref.family) {\n case \"session\": {\n const end = group.end?.type === \"session.end\" ? group.end : undefined;\n const start = group.start?.type === \"session.start\" ? group.start : undefined;\n name = \"session\";\n kind = SpanKind.INTERNAL;\n attributes = {\n ...attributes,\n ...(start?.agentName === undefined ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName }),\n ...(start?.agentVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion }),\n ...(end === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.reason }),\n ...usageAttributes(end?.usage, false),\n };\n if (end?.reason === \"error\" || end?.reason === \"timeout\") {\n status = { code: SpanStatusCode.ERROR, message: end.reason };\n }\n break;\n }\n case \"generation\": {\n const start = group.start?.type === \"generation.start\" ? group.start : undefined;\n const end = group.end?.type === \"generation.end\" ? group.end : undefined;\n const model = end?.model ?? start?.model;\n name = model === undefined ? \"generation\" : `generation ${model.modelId}`;\n kind = SpanKind.CLIENT;\n attributes = {\n ...attributes,\n [ATTR_GEN_AI_OPERATION_NAME]: \"chat\",\n ...(model?.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: model.vendor }),\n ...(start?.model?.modelId === undefined ? {} : { [ATTR_GEN_AI_REQUEST_MODEL]: start.model.modelId }),\n ...(end?.model?.modelId === undefined ? {} : { [ATTR_GEN_AI_RESPONSE_MODEL]: end.model.modelId }),\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...usageAttributes(end?.usage, false),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n case \"tool\": {\n const start = group.start?.type === \"tool.start\" ? group.start : undefined;\n const end = group.end?.type === \"tool.end\" ? group.end : undefined;\n const toolName = start?.toolName ?? end?.toolName ?? \"unknown\";\n name = `tool ${toolName}`;\n kind = SpanKind.CLIENT;\n attributes = {\n ...attributes,\n [ATTR_GEN_AI_TOOL_NAME]: toolName,\n [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,\n ...(start?.toolKind === undefined ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind }),\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n case \"subagent\": {\n const start = group.start?.type === \"subagent.start\" ? group.start : undefined;\n const end = group.end?.type === \"subagent.end\" ? group.end : undefined;\n name = \"subagent\";\n kind = SpanKind.INTERNAL;\n attributes = {\n ...attributes,\n ...(start?.delegationDepth === undefined\n ? {}\n : { [ATTR_OTELHOOK_DELEGATION_DEPTH]: start.delegationDepth }),\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...usageAttributes(end?.usage, false),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n }\n\n if (status.code === SpanStatusCode.ERROR) {\n attributes = { ...attributes, [ATTR_ERROR_TYPE]: status.message ?? \"error\" };\n }\n\n return toReadableSpan({\n name,\n kind,\n startMillis: resolved.startMillis,\n endMillis: resolved.endMillis,\n attributes,\n status,\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n resource,\n instrumentationScope: scope,\n });\n};\n\nconst buildStandaloneSpan = (\n event: CanonicalEvent,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan => {\n const providerId = event.provenance.providerId;\n const traceId = deriveTraceId(providerId, event.sessionId);\n const spanId = deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId);\n const parent = parentScopeRefOf(event);\n let attributes: Attributes = { ...identityAttributes(event), [ATTR_OTELHOOK_SPAN_PAIRED]: true };\n let status: SpanStatus = { code: SpanStatusCode.UNSET };\n let name: string = event.type;\n\n switch (event.type) {\n case \"prompt.submitted\":\n name = \"prompt\";\n attributes = { ...attributes, \"otelhook.prompt.source\": event.promptSource };\n break;\n case \"compaction.performed\":\n name = \"compaction\";\n attributes = {\n ...attributes,\n [ATTR_OTELHOOK_COMPACTION_TRIGGER]: event.trigger,\n ...usageAttributes(event.usage, false),\n };\n break;\n case \"error.raised\":\n name = \"error\";\n status = { code: SpanStatusCode.ERROR, message: event.errorCode };\n attributes = {\n ...attributes,\n [ATTR_ERROR_TYPE]: event.errorCode,\n \"otelhook.error.phase\": event.phase,\n \"otelhook.error.retryable\": event.retryable,\n };\n break;\n default:\n break;\n }\n\n return toReadableSpan({\n name,\n kind: SpanKind.INTERNAL,\n startMillis: event.occurredAt,\n endMillis: event.occurredAt,\n attributes,\n status,\n traceId,\n spanId,\n ...(parent === undefined\n ? {}\n : { parentSpanId: deriveSpanId(providerId, event.sessionId, parent) }),\n resource,\n instrumentationScope: scope,\n });\n};\n\nexport type SemanticMappingOptions = {\n readonly resource: Resource;\n readonly instrumentationScope?: InstrumentationScope;\n /**\n * Cross-process pairing facts, at most one entry per lifecycle scope in\n * `events`. Omitted entirely, the mapping degrades to in-batch pairing only —\n * the behavior of a host that wired no state store.\n */\n readonly correlations?: readonly SpanCorrelation[];\n /**\n * Whether a correlator was consulted at all, and whether it answered.\n *\n * This is what separates \"the state store is holding this start, so the end edge\n * will publish it\" from \"nothing recorded this start\". Both look like an empty\n * `correlations` list, and only the first is safe to drop — dropping the second\n * would discard an observation that was neither persisted nor exported, while a\n * caller that saw zero rejections went on to mark the callback handled.\n *\n * - `true` — the correlator ran; an absent or non-`defer` entry means emit.\n * - `false` — the correlator failed; every unpaired start is emitted as an\n * explicitly labelled, uniquely identified fallback.\n * - omitted — no correlator is wired, so cross-process pairing was never on\n * offer and an unpaired start is deferred (the documented no-state-root\n * degradation).\n */\n readonly correlationAvailable?: boolean;\n};\n\n/**\n * Fill in a correlation for an unpaired start that nothing recorded.\n *\n * Reached when a correlator was consulted and either failed outright or reported\n * nothing for this scope. The synthesized entry says what is true — the state was\n * not consulted successfully, so this span is unpaired and no end can complete it\n * — and carries a discriminator so the record cannot claim the span id a later end\n * will publish for the same scope.\n */\nconst effectiveCorrelation = (\n group: SpanGroup,\n correlation: SpanCorrelation | undefined,\n): SpanCorrelation | undefined => {\n if (correlation !== undefined || group.end !== undefined || group.start === undefined) {\n return correlation;\n }\n return {\n providerId: group.start.provenance.providerId,\n sessionId: group.start.sessionId,\n ref: group.ref,\n pairing: \"unpaired\",\n orphan: \"state-unavailable\",\n disposition: \"emit\",\n spanIdDiscriminator: group.start.eventId,\n };\n};\n\n/** How one batch's events distribute over the lifecycle scopes they are edges of. */\ntype BatchLayout = {\n readonly groups: ReadonlyMap<string, SpanGroup>;\n readonly standalone: readonly CanonicalEvent[];\n /** Event id of each lifecycle edge, mapped to the group key it belongs to. */\n readonly groupOf: ReadonlyMap<string, string>;\n};\n\nconst layoutBatch = (events: readonly CanonicalEvent[]): BatchLayout => {\n const groups = new Map<string, SpanGroup>();\n const standalone: CanonicalEvent[] = [];\n const groupOf = new Map<string, string>();\n\n for (const event of events) {\n const ref = spanScopeRefOf(event);\n if (ref === undefined) {\n standalone.push(event);\n continue;\n }\n const groupKey = correlationKey(event.provenance.providerId, event.sessionId, ref);\n const group: SpanGroup = groups.get(groupKey) ?? { ref };\n if (event.type.endsWith(\".start\")) {\n group.start = event;\n } else {\n group.end = event;\n }\n groups.set(groupKey, group);\n groupOf.set(event.eventId, groupKey);\n }\n return { groups, standalone, groupOf };\n};\n\nconst indexCorrelations = (\n correlations: readonly SpanCorrelation[] | undefined,\n): ReadonlyMap<string, SpanCorrelation> => {\n const indexed = new Map<string, SpanCorrelation>();\n for (const correlation of correlations ?? []) {\n indexed.set(\n correlationKey(correlation.providerId, correlation.sessionId, correlation.ref),\n correlation,\n );\n }\n return indexed;\n};\n\n/**\n * What this batch does with one lifecycle scope, decided once.\n *\n * Both the span mapping and the log mapping need the *same* answer to \"which\n * span id identifies this scope, and is a record for it going out now?\" — a log\n * record whose `spanContext` names a span id the exporter never published would\n * dangle at the collector. Computing it in one place is what keeps the two\n * signals pointing at the same span rather than at two plausible derivations of\n * it.\n */\ntype GroupPlan = {\n readonly group: SpanGroup;\n /** The event the span's identity and provenance are read from. */\n readonly anchor: CanonicalEvent;\n /**\n * False when the start is deferred: the state store is holding it and the end\n * edge will publish the one complete span, so nothing is exported for it now.\n */\n readonly emits: boolean;\n readonly correlation: SpanCorrelation | undefined;\n readonly traceId: string;\n readonly spanId: string;\n};\n\nconst planGroup = (\n group: SpanGroup,\n correlation: SpanCorrelation | undefined,\n correlationAvailable: boolean | undefined,\n): GroupPlan | undefined => {\n const anchor = group.start ?? group.end;\n if (anchor === undefined) {\n // Unreachable: a group exists only because an event was filed into it.\n return undefined;\n }\n const providerId = anchor.provenance.providerId;\n const sessionId = anchor.sessionId;\n\n // A start with no end in this batch is dropped **only** when something states\n // that it is durably recorded, because its span id is a pure function of the\n // scope: emitting here and again at the end edge would put two records with one\n // id on the wire, and OTLP has no update operation.\n //\n // `defer` is that statement, and it is the correlator's to make — it just wrote\n // the record. Anything else means nothing is holding this start, so dropping it\n // would lose an observation that was neither persisted nor exported, while the\n // caller saw zero rejections and marked the callback handled. Those are exported\n // under a discriminated span id instead.\n const durablyRecorded =\n group.end === undefined &&\n (correlation?.disposition === \"defer\" ||\n // No correlator wired at all: cross-process pairing was never on offer, so\n // this is the documented no-state-root degradation rather than a failure to\n // persist something that should have been persisted.\n (correlation === undefined && correlationAvailable === undefined));\n\n // A deferred start keeps the scope's *plain* span id, because that is the id the\n // end edge will publish. Only a record actually going out now may claim a\n // discriminated one.\n const effective = durablyRecorded ? correlation : effectiveCorrelation(group, correlation);\n const discriminator = durablyRecorded ? undefined : effective?.spanIdDiscriminator;\n\n return {\n group,\n anchor,\n emits: !durablyRecorded,\n correlation: effective,\n traceId: deriveTraceId(providerId, sessionId),\n spanId:\n discriminator === undefined\n ? deriveSpanId(providerId, sessionId, group.ref)\n : digestHex(\n [\n \"otelhook/span\",\n providerId,\n sessionId,\n group.ref.family,\n group.ref.scopeKey,\n discriminator,\n ],\n 16,\n ),\n };\n};\n\n/** Trace and span a record derived from one canonical event belongs to. */\nexport type EventTraceIdentity = {\n readonly traceId: string;\n readonly spanId: string;\n};\n\n/**\n * Resolve the trace and span identity of every event in one batch.\n *\n * Exposed for signals other than traces — a log record correlates by carrying\n * the *same* derived ids the span mapping would compute, including the deferred\n * and discriminated cases. Whole batch at once because a start's identity\n * depends on whether its end is in the same batch.\n *\n * Both ids come from the event's own `(providerId, sessionId)`, never from a\n * batch-level or module-level value, which is what makes cross-session\n * contamination structurally impossible: two sessions in one batch derive two\n * different trace ids.\n */\nexport const canonicalEventTraceIdentities = (\n events: readonly CanonicalEvent[],\n options: {\n readonly correlations?: readonly SpanCorrelation[];\n readonly correlationAvailable?: boolean;\n } = {},\n): ReadonlyMap<string, EventTraceIdentity> => {\n const layout = layoutBatch(events);\n const correlations = indexCorrelations(options.correlations);\n const plans = new Map<string, GroupPlan>();\n for (const [groupKey, group] of layout.groups) {\n const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);\n if (plan !== undefined) {\n plans.set(groupKey, plan);\n }\n }\n\n const identities = new Map<string, EventTraceIdentity>();\n for (const event of events) {\n const providerId = event.provenance.providerId;\n const groupKey = layout.groupOf.get(event.eventId);\n const plan = groupKey === undefined ? undefined : plans.get(groupKey);\n if (plan === undefined) {\n identities.set(event.eventId, {\n traceId: deriveTraceId(providerId, event.sessionId),\n spanId: deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId),\n });\n continue;\n }\n identities.set(event.eventId, { traceId: plan.traceId, spanId: plan.spanId });\n }\n return identities;\n};\n\n/** Maps one invocation's canonical event batch into OTLP-ready spans. */\nexport const canonicalEventsToReadableSpans = (\n events: readonly CanonicalEvent[],\n options: SemanticMappingOptions,\n): readonly ReadableSpan[] => {\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const layout = layoutBatch(events);\n const correlations = indexCorrelations(options.correlations);\n\n const spans: ReadableSpan[] = [];\n for (const [groupKey, group] of layout.groups) {\n const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);\n if (plan === undefined || !plan.emits) {\n continue;\n }\n spans.push(buildLifecycleSpan(plan, options.resource, scope));\n }\n for (const event of layout.standalone) {\n spans.push(buildStandaloneSpan(event, options.resource, scope));\n }\n return spans;\n};\n","/**\n * Package version, kept in its own module so the CLI can report it without\n * importing the whole library barrel (and every provider adapter with it).\n *\n * Updated by `scripts/release/sync-version.mjs` during semantic-release.\n */\nexport const VERSION = \"0.2.0\";\n","import type { Attributes as SpanAttributes } from \"@opentelemetry/api\";\n\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport {\n MAX_ATTRIBUTE_STRING_LENGTH,\n MAX_IDENTIFIER_LENGTH,\n type Attributes,\n} from \"../model/primitives.js\";\nimport type { Clock, StateStore, StateValue } from \"../runtime/ports.js\";\nimport { withOptionalSessionLock } from \"../state/store.js\";\nimport {\n MAX_RECOVERED_START_ATTRIBUTES,\n parentScopeRefOf,\n spanScopeRefOf,\n startOnlySpanAttributes,\n type SpanCorrelation,\n type SpanFamily,\n type SpanOrphanClassification,\n type SpanScopeRef,\n} from \"../telemetry/semconv.js\";\nimport { spanKey, spanScanPrefix } from \"./keys.js\";\n\n/** Correlation scopes that pair a `*.start` event with a later `*.end` event. */\nexport type LifecycleScope = SpanFamily;\n\n/**\n * Shape version of a persisted span record.\n *\n * A record written under a different version is discarded on read rather than\n * interpreted: guessing at an older layout is exactly the kind of silent\n * mis-attribution this library refuses to do. See `docs/state-retention.md`.\n */\nexport const SPAN_RECORD_VERSION = 2;\n\n/** Facts about a span recovered from, or written to, persisted state. */\nexport type SpanCorrelationFacts = {\n readonly startedAt?: number;\n readonly endedAt?: number;\n readonly parent?: SpanScopeRef;\n readonly attributes?: SpanAttributes;\n};\n\nexport type SpanStartInput = {\n readonly sessionId: string;\n /** Attribution boundary: a scope recorded by one provider never pairs with another's. */\n readonly providerId: string;\n readonly scope: LifecycleScope;\n readonly scopeKey: string;\n /** The canonical event id of the start event; used to detect redelivery. */\n readonly eventId: string;\n readonly occurredAt: number;\n /** Where this span hangs, so an end-only process reparents it identically. */\n readonly parent?: SpanScopeRef;\n /** Attributes only the start edge knows; carried forward to the end-side span. */\n readonly attributes?: SpanAttributes;\n};\n\nexport type SpanEndInput = {\n readonly sessionId: string;\n readonly providerId: string;\n readonly scope: LifecycleScope;\n readonly scopeKey: string;\n readonly eventId: string;\n readonly occurredAt: number;\n};\n\nexport type SpanStartResult =\n | { readonly status: \"recorded\"; readonly facts: SpanCorrelationFacts }\n /** The same start (by event id) was already recorded; state is unchanged. */\n | { readonly status: \"duplicate\"; readonly facts: SpanCorrelationFacts }\n /**\n * The record was completed, but an OTLP record for this scope has already been\n * published under its span id — so this edge must not export one.\n */\n | { readonly status: \"published\"; readonly facts: SpanCorrelationFacts }\n /** A different provider owns this scope key in this session; nothing was written. */\n | { readonly status: \"conflict\"; readonly reason: \"provider-mismatch\" };\n\n/** Why an end could not be paired with a recorded start. */\nexport type SpanEndOrphanReason =\n | \"no-start-recorded\"\n | \"start-expired\"\n | \"already-closed\"\n | \"provider-mismatch\"\n | \"state-incompatible\"\n | \"state-corrupt\";\n\nexport type SpanEndResult =\n | {\n readonly status: \"matched\";\n readonly startedAt: number;\n readonly durationMillis: number;\n readonly facts: SpanCorrelationFacts;\n }\n /** This exact end (by event id) was already applied; the same facts are replayed. */\n | { readonly status: \"duplicate\"; readonly facts: SpanCorrelationFacts }\n | {\n readonly status: \"orphaned\";\n readonly reason: SpanEndOrphanReason;\n readonly facts: SpanCorrelationFacts;\n };\n\nexport type SpanCleanupResult = {\n readonly removed: number;\n readonly scanned: number;\n /**\n * Records dropped that held a start and never received an end.\n *\n * These are the spans that will never be exported at all: the end edge is what\n * emits a lifecycle span, so a scope whose end never arrives — a session the\n * host killed, a tool call that outlived the retention window — produces no\n * OTLP record. That is the standard OpenTelemetry outcome for a span that never\n * ends, and it is deliberately not papered over with a synthetic end time,\n * because a fabricated duration is a wrong measurement rather than a missing\n * one. Counting them keeps the cost visible: a non-zero number here means real\n * activity went unreported, which is a signal about the host or the retention\n * window rather than noise. See `docs/state-retention.md`.\n */\n readonly expiredOpen: number;\n};\n\n/**\n * Cross-invocation start/end correlation for session, generation, tool, and\n * subagent scopes.\n *\n * A coding-agent hook fires once per lifecycle edge, usually as a separate\n * short-lived process for the start and for the end. This records an open span\n * in the shared state store so the end side can report a real start time,\n * duration, parent, and start-only attributes even though its process has no\n * memory of the start — and so a redelivered start or end (an at-least-once\n * host retry) re-exports an identical span instead of being double-counted.\n *\n * ## What it refuses to do\n *\n * - **Pair across sessions.** The state key is session-scoped, so two sessions\n * cannot see each other's open spans.\n * - **Pair across providers.** The key is provider-scoped *and* the record\n * carries the provider that wrote it, so a mismatch is reported rather than\n * guessed at — the same defense in depth the durable spool uses.\n * - **Trust a stale start.** A start older than `maxStartAgeMillis` when its end\n * arrives is dropped and classified `start-expired`, rather than reporting a\n * duration that really measures a machine suspend or a reused id.\n * - **Interpret a record it does not understand.** A corrupt or wrong-version\n * record is deleted and classified, never partially read.\n */\nexport interface SpanCorrelator {\n recordStart(input: SpanStartInput): Promise<SpanStartResult>;\n recordEnd(input: SpanEndInput): Promise<SpanEndResult>;\n /**\n * Records every lifecycle edge in a batch and reports what the exported spans\n * should say. Never rejects: a state failure degrades one scope to\n * `state-unavailable` rather than losing the batch (fail-open telemetry).\n */\n correlateBatch(events: readonly CanonicalEvent[]): Promise<readonly SpanCorrelation[]>;\n /** Bounded sweep: drops spans untouched for longer than `maxAgeMillis`. */\n cleanup(\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<SpanCleanupResult>;\n}\n\nexport type SpanCorrelatorDependencies = {\n readonly stateStore: StateStore;\n readonly clock: Clock;\n /**\n * A recorded start older than this when its end arrives is not trusted.\n * Default 24 hours, matching the janitor's retention window.\n */\n readonly maxStartAgeMillis?: number;\n};\n\nconst DEFAULT_MAX_START_AGE_MILLIS = 24 * 60 * 60 * 1000;\nconst ATTRIBUTE_PREFIX = \"a:\";\n\ntype SpanRecord = {\n readonly providerId: string;\n readonly startEventId?: string;\n readonly startedAt?: number;\n readonly endEventId?: string;\n readonly endedAt?: number;\n readonly parent?: SpanScopeRef;\n readonly attributes?: SpanAttributes;\n /**\n * True once an OTLP record has been produced for this scope under its derived\n * span id.\n *\n * Needed for the ordering nobody controls: the end edge can be mapped before\n * the start edge, and then the end has already exported an orphan carrying the\n * scope's canonical span id. Without this flag the late start would look like\n * the benign \"end raced ahead\" case and export a *second* record with that same\n * id — the duplicate the whole defer strategy exists to avoid. So the flag turns\n * \"was this scope already published?\" into a fact on disk rather than an\n * assumption about arrival order.\n */\n readonly exported?: boolean;\n};\n\ntype DecodedRecord =\n | { readonly kind: \"absent\" }\n | { readonly kind: \"incompatible\" }\n | { readonly kind: \"corrupt\" }\n | { readonly kind: \"present\"; readonly record: SpanRecord };\n\nconst SPAN_FAMILIES: readonly SpanFamily[] = [\"session\", \"generation\", \"tool\", \"subagent\"];\n\nconst isSpanFamily = (value: unknown): value is SpanFamily =>\n typeof value === \"string\" && (SPAN_FAMILIES as readonly string[]).includes(value);\n\nconst optionalNumber = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n\nconst optionalString = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 ? value : undefined;\n\n/**\n * Persisted attributes are flattened under a prefix rather than nested: the\n * state schema admits only flat primitives, which is what keeps a provider\n * payload from ever being smuggled through the state store.\n */\nconst encodeAttributes = (attributes: SpanAttributes | undefined): Attributes => {\n const encoded: Record<string, string | number | boolean> = {};\n let count = 0;\n for (const [key, value] of Object.entries(attributes ?? {})) {\n if (count >= MAX_RECOVERED_START_ATTRIBUTES) {\n break;\n }\n const encodedKey = `${ATTRIBUTE_PREFIX}${key}`;\n if (encodedKey.length > MAX_IDENTIFIER_LENGTH) {\n continue;\n }\n if (typeof value === \"string\") {\n encoded[encodedKey] = value.slice(0, MAX_ATTRIBUTE_STRING_LENGTH);\n } else if (typeof value === \"number\" && Number.isFinite(value)) {\n encoded[encodedKey] = value;\n } else if (typeof value === \"boolean\") {\n encoded[encodedKey] = value;\n } else {\n continue;\n }\n count += 1;\n }\n return encoded;\n};\n\nconst decodeAttributes = (attributes: Attributes): SpanAttributes | undefined => {\n const decoded: Record<string, string | number | boolean> = {};\n let count = 0;\n for (const [key, value] of Object.entries(attributes)) {\n if (!key.startsWith(ATTRIBUTE_PREFIX) || count >= MAX_RECOVERED_START_ATTRIBUTES) {\n continue;\n }\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n decoded[key.slice(ATTRIBUTE_PREFIX.length)] = value;\n count += 1;\n }\n }\n return count === 0 ? undefined : decoded;\n};\n\nconst encodeRecord = (record: SpanRecord): StateValue => ({\n kind: \"attributes\",\n attributes: {\n v: SPAN_RECORD_VERSION,\n providerId: record.providerId,\n ...(record.startEventId === undefined ? {} : { startEventId: record.startEventId }),\n ...(record.startedAt === undefined ? {} : { startedAt: record.startedAt }),\n ...(record.endEventId === undefined ? {} : { endEventId: record.endEventId }),\n ...(record.endedAt === undefined ? {} : { endedAt: record.endedAt }),\n ...(record.exported === true ? { exported: true } : {}),\n ...(record.parent === undefined\n ? {}\n : { parentFamily: record.parent.family, parentScopeKey: record.parent.scopeKey }),\n ...encodeAttributes(record.attributes),\n },\n});\n\nconst decodeRecord = (attributes: Attributes): DecodedRecord => {\n if (attributes[\"v\"] !== SPAN_RECORD_VERSION) {\n return { kind: \"incompatible\" };\n }\n const providerId = optionalString(attributes[\"providerId\"]);\n if (providerId === undefined) {\n return { kind: \"corrupt\" };\n }\n // A half-written edge (a timestamp with no event id, or the reverse) is not\n // an edge we can reason about; the record is refused rather than completed\n // with an invented half.\n const startedAt = optionalNumber(attributes[\"startedAt\"]);\n const startEventId = optionalString(attributes[\"startEventId\"]);\n if ((startedAt === undefined) !== (startEventId === undefined)) {\n return { kind: \"corrupt\" };\n }\n const endedAt = optionalNumber(attributes[\"endedAt\"]);\n const endEventId = optionalString(attributes[\"endEventId\"]);\n if ((endedAt === undefined) !== (endEventId === undefined)) {\n return { kind: \"corrupt\" };\n }\n const exported = attributes[\"exported\"] === true;\n const parentFamily = attributes[\"parentFamily\"];\n const parentScopeKey = optionalString(attributes[\"parentScopeKey\"]);\n const parent =\n isSpanFamily(parentFamily) && parentScopeKey !== undefined\n ? { family: parentFamily, scopeKey: parentScopeKey }\n : undefined;\n const decodedAttributes = decodeAttributes(attributes);\n return {\n kind: \"present\",\n record: {\n providerId,\n ...(startEventId === undefined ? {} : { startEventId }),\n ...(startedAt === undefined ? {} : { startedAt }),\n ...(endEventId === undefined ? {} : { endEventId }),\n ...(endedAt === undefined ? {} : { endedAt }),\n ...(parent === undefined ? {} : { parent }),\n ...(exported ? { exported: true } : {}),\n ...(decodedAttributes === undefined ? {} : { attributes: decodedAttributes }),\n },\n };\n};\n\nconst factsOf = (record: SpanRecord): SpanCorrelationFacts => ({\n ...(record.startedAt === undefined ? {} : { startedAt: record.startedAt }),\n ...(record.endedAt === undefined ? {} : { endedAt: record.endedAt }),\n ...(record.parent === undefined ? {} : { parent: record.parent }),\n ...(record.attributes === undefined ? {} : { attributes: record.attributes }),\n});\n\n/**\n * Persisted facts speak in event time (`startedAt`); a span speaks in the\n * milliseconds it is stamped with. Translated in one place so the two\n * vocabularies cannot silently drift apart.\n */\nconst correlationTimesOf = (\n facts: SpanCorrelationFacts,\n options: { readonly withStart: boolean } = { withStart: true },\n): Pick<SpanCorrelation, \"startMillis\" | \"endMillis\" | \"parent\" | \"attributes\"> => ({\n ...(facts.startedAt === undefined || !options.withStart ? {} : { startMillis: facts.startedAt }),\n ...(facts.endedAt === undefined ? {} : { endMillis: facts.endedAt }),\n ...(facts.parent === undefined ? {} : { parent: facts.parent }),\n ...(facts.attributes === undefined ? {} : { attributes: facts.attributes }),\n});\n\nconst orphanClassificationOf = (reason: SpanEndOrphanReason): SpanOrphanClassification => {\n switch (reason) {\n case \"no-start-recorded\":\n return \"missing-start\";\n case \"start-expired\":\n return \"expired-start\";\n case \"already-closed\":\n return \"already-closed\";\n case \"provider-mismatch\":\n return \"provider-mismatch\";\n case \"state-incompatible\":\n return \"state-incompatible\";\n case \"state-corrupt\":\n return \"state-corrupt\";\n }\n};\n\ntype BatchGroup = {\n readonly providerId: string;\n readonly sessionId: string;\n readonly ref: SpanScopeRef;\n start?: CanonicalEvent;\n end?: CanonicalEvent;\n};\n\nexport const createSpanCorrelator = (deps: SpanCorrelatorDependencies): SpanCorrelator => {\n const { stateStore, clock } = deps;\n const maxStartAgeMillis = deps.maxStartAgeMillis ?? DEFAULT_MAX_START_AGE_MILLIS;\n\n const keyFor = (input: {\n readonly sessionId: string;\n readonly providerId: string;\n readonly scope: LifecycleScope;\n readonly scopeKey: string;\n }): string => spanKey(input.sessionId, input.providerId, input.scope, input.scopeKey);\n\n /**\n * Reads and validates one record, deleting anything it refuses to interpret.\n * Self-healing on purpose: a single unreadable record must not make the same\n * scope unreadable forever.\n */\n const readRecord = async (key: string): Promise<DecodedRecord> => {\n const existing = await stateStore.read(key);\n if (existing === undefined) {\n return { kind: \"absent\" };\n }\n if (existing.value.kind !== \"attributes\") {\n await stateStore.delete(key);\n return { kind: \"corrupt\" };\n }\n const decoded = decodeRecord(existing.value.attributes);\n if (decoded.kind === \"corrupt\" || decoded.kind === \"incompatible\") {\n await stateStore.delete(key);\n }\n return decoded;\n };\n\n const recordStart = (input: SpanStartInput): Promise<SpanStartResult> =>\n withOptionalSessionLock(stateStore, input.sessionId, async (): Promise<SpanStartResult> => {\n const key = keyFor(input);\n const decoded = await readRecord(key);\n\n if (decoded.kind === \"present\") {\n const existing = decoded.record;\n if (existing.providerId !== input.providerId) {\n return { status: \"conflict\", reason: \"provider-mismatch\" };\n }\n if (existing.startEventId === input.eventId) {\n return { status: \"duplicate\", facts: factsOf(existing) };\n }\n if (existing.startEventId === undefined && existing.endEventId !== undefined) {\n // The end raced ahead of the start (two hook processes, no ordering\n // guarantee between them). Complete the record rather than treating\n // the late start as the beginning of a second span.\n //\n // If that end was already exported, the scope's canonical span id is\n // already on the wire and this start must stay silent: re-exporting a\n // now-complete span under the same id would be a duplicate, not a\n // correction, because OTLP has no update. The enrichment is lost and the\n // published record remains the orphan the end could honestly produce.\n const completed: SpanRecord = {\n ...existing,\n startEventId: input.eventId,\n startedAt: input.occurredAt,\n ...(input.parent === undefined ? {} : { parent: input.parent }),\n ...(input.attributes === undefined ? {} : { attributes: input.attributes }),\n };\n await stateStore.write(key, encodeRecord(completed));\n return existing.exported === true\n ? { status: \"published\", facts: factsOf(completed) }\n : { status: \"recorded\", facts: factsOf(completed) };\n }\n }\n\n // Either nothing was recorded, or a *different* start claims this scope\n // key: the previous span is superseded rather than merged into.\n const fresh: SpanRecord = {\n providerId: input.providerId,\n startEventId: input.eventId,\n startedAt: input.occurredAt,\n ...(input.parent === undefined ? {} : { parent: input.parent }),\n ...(input.attributes === undefined ? {} : { attributes: input.attributes }),\n };\n await stateStore.write(key, encodeRecord(fresh));\n return { status: \"recorded\", facts: factsOf(fresh) };\n });\n\n const recordEnd = (input: SpanEndInput): Promise<SpanEndResult> =>\n withOptionalSessionLock(stateStore, input.sessionId, async (): Promise<SpanEndResult> => {\n const key = keyFor(input);\n const decoded = await readRecord(key);\n\n if (decoded.kind === \"incompatible\" || decoded.kind === \"corrupt\") {\n const reason = decoded.kind === \"incompatible\" ? \"state-incompatible\" : \"state-corrupt\";\n return { status: \"orphaned\", reason, facts: { endedAt: input.occurredAt } };\n }\n if (decoded.kind === \"absent\") {\n // Remember the end anyway: a start that arrives late still deserves to\n // be paired rather than exported as a second orphan.\n const endOnly: SpanRecord = {\n providerId: input.providerId,\n endEventId: input.eventId,\n endedAt: input.occurredAt,\n // This end is about to be exported as an orphan under the scope's\n // canonical span id, so a start arriving later must not reuse it.\n exported: true,\n };\n await stateStore.write(key, encodeRecord(endOnly));\n return { status: \"orphaned\", reason: \"no-start-recorded\", facts: factsOf(endOnly) };\n }\n\n const existing = decoded.record;\n if (existing.providerId !== input.providerId) {\n return {\n status: \"orphaned\",\n reason: \"provider-mismatch\",\n facts: { endedAt: input.occurredAt },\n };\n }\n if (existing.endEventId === input.eventId) {\n // Idempotent replay: answer with the facts already on disk so the\n // re-exported span is byte-identical to the first one.\n return { status: \"duplicate\", facts: factsOf(existing) };\n }\n if (existing.endEventId !== undefined) {\n return {\n status: \"orphaned\",\n reason: \"already-closed\",\n facts: { endedAt: input.occurredAt },\n };\n }\n if (existing.startedAt === undefined) {\n const replaced: SpanRecord = {\n ...existing,\n endEventId: input.eventId,\n endedAt: input.occurredAt,\n exported: true,\n };\n await stateStore.write(key, encodeRecord(replaced));\n return { status: \"orphaned\", reason: \"no-start-recorded\", facts: factsOf(replaced) };\n }\n if (input.occurredAt - existing.startedAt > maxStartAgeMillis) {\n await stateStore.delete(key);\n return { status: \"orphaned\", reason: \"start-expired\", facts: { endedAt: input.occurredAt } };\n }\n\n const closed: SpanRecord = {\n ...existing,\n endEventId: input.eventId,\n endedAt: input.occurredAt,\n exported: true,\n };\n await stateStore.write(key, encodeRecord(closed));\n return {\n status: \"matched\",\n startedAt: existing.startedAt,\n durationMillis: Math.max(0, input.occurredAt - existing.startedAt),\n facts: factsOf(closed),\n };\n });\n\n const correlateGroup = async (group: BatchGroup): Promise<SpanCorrelation> => {\n const base = {\n providerId: group.providerId,\n sessionId: group.sessionId,\n ref: group.ref,\n } as const;\n const unpaired = (\n orphan: SpanOrphanClassification,\n facts: SpanCorrelationFacts,\n ): SpanCorrelation => ({\n ...base,\n pairing: \"unpaired\",\n orphan,\n // An unpaired span has no trustworthy start, so a start time is the one\n // fact it must not carry; everything else recovered is still true.\n ...correlationTimesOf(facts, { withStart: false }),\n });\n\n let startFacts: SpanCorrelationFacts | undefined;\n if (group.start !== undefined) {\n const parent = parentScopeRefOf(group.start);\n const result = await recordStart({\n sessionId: group.sessionId,\n providerId: group.providerId,\n scope: group.ref.family,\n scopeKey: group.ref.scopeKey,\n eventId: group.start.eventId,\n occurredAt: group.start.occurredAt,\n ...(parent === undefined ? {} : { parent }),\n attributes: startOnlySpanAttributes(group.start),\n });\n if (result.status === \"conflict\") {\n return unpaired(\"provider-mismatch\", {});\n }\n if (result.status === \"published\" && group.end === undefined) {\n // The end already exported this scope's span. Completing the record was\n // still worth doing (a redelivered end replays identical facts), but\n // emitting here would duplicate a span id already on the wire.\n return { ...unpaired(\"already-closed\", result.facts), disposition: \"defer\" };\n }\n startFacts = result.facts;\n }\n\n if (group.end === undefined) {\n const facts = startFacts ?? {};\n // A start whose end already landed (the racing-process case) closes a\n // complete span, even though only the start is in this batch.\n if (facts.endedAt !== undefined) {\n return {\n ...base,\n pairing: \"cross-process\",\n orphan: \"none\",\n disposition: \"emit\",\n ...correlationTimesOf(facts),\n };\n }\n // The end has not arrived. The start is durable now, so the end edge will\n // export one complete span under this scope's derived id; exporting a\n // zero-duration record here as well would put two records with that same id\n // on the wire, and OTLP cannot revise a span.\n return { ...unpaired(\"missing-end\", facts), disposition: \"defer\" };\n }\n\n const result = await recordEnd({\n sessionId: group.sessionId,\n providerId: group.providerId,\n scope: group.ref.family,\n scopeKey: group.ref.scopeKey,\n eventId: group.end.eventId,\n occurredAt: group.end.occurredAt,\n });\n\n if (result.status === \"orphaned\") {\n const orphan = orphanClassificationOf(result.reason);\n // `already-closed` means a *second, distinct* end for a scope whose first\n // end has already been exported under this scope's derived span id. Both\n // ends are real observations, so neither is dropped — but the second must\n // not reuse that id. Keying the discriminator on the end event id keeps a\n // redelivery of this same second end idempotent, since it recomputes the\n // same id rather than inventing a third.\n return orphan === \"already-closed\"\n ? {\n ...unpaired(orphan, result.facts),\n disposition: \"emit\",\n spanIdDiscriminator: group.end.eventId,\n }\n : { ...unpaired(orphan, result.facts), disposition: \"emit\" };\n }\n if (result.status === \"duplicate\" && result.facts.startedAt === undefined) {\n // A replayed end that never had a start is still an orphan.\n return { ...unpaired(\"missing-start\", result.facts), disposition: \"emit\" };\n }\n return {\n ...base,\n pairing: group.start === undefined ? \"cross-process\" : \"in-batch\",\n orphan: \"none\",\n disposition: \"emit\",\n ...correlationTimesOf(result.facts),\n };\n };\n\n const correlateBatch = async (\n events: readonly CanonicalEvent[],\n ): Promise<readonly SpanCorrelation[]> => {\n const groups = new Map<string, BatchGroup>();\n for (const event of events) {\n const ref = spanScopeRefOf(event);\n if (ref === undefined) {\n continue;\n }\n const providerId = event.provenance.providerId;\n const groupKey = [providerId, event.sessionId, ref.family, ref.scopeKey].join(\"\\u0000\");\n const group: BatchGroup = groups.get(groupKey) ?? {\n providerId,\n sessionId: event.sessionId,\n ref,\n };\n if (event.type.endsWith(\".start\")) {\n group.start = event;\n } else {\n group.end = event;\n }\n groups.set(groupKey, group);\n }\n\n const correlations: SpanCorrelation[] = [];\n for (const group of groups.values()) {\n try {\n correlations.push(await correlateGroup(group));\n } catch {\n // Fail open: an unreachable, locked, or unwritable state store costs a\n // span its pairing, never the whole export.\n //\n // A start whose record could not be written is the case that needs care.\n // It is *not* deferrable — deferring means \"the state store is holding\n // this, the end edge will publish it\", and here the state store is exactly\n // what failed. So it must be exported, and it must not use the scope's\n // canonical span id: nothing recorded this start, so a later end will\n // publish that id itself as an orphan, and reusing it would put two\n // records with one identity on the wire. Discriminating by the start's own\n // event id makes this record honest and collision-free.\n const unrecordedStart = group.start !== undefined && group.end === undefined;\n correlations.push({\n providerId: group.providerId,\n sessionId: group.sessionId,\n ref: group.ref,\n pairing: \"unpaired\",\n orphan: \"state-unavailable\",\n disposition: \"emit\",\n ...(unrecordedStart && group.start !== undefined\n ? { spanIdDiscriminator: group.start.eventId }\n : {}),\n });\n }\n }\n return correlations;\n };\n\n const cleanup = async (\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<SpanCleanupResult> => {\n const keys = await stateStore.keys(spanScanPrefix(options?.sessionId));\n const cap = options?.maxEntries ?? 1_000;\n const now = clock.now();\n let removed = 0;\n let scanned = 0;\n let expiredOpen = 0;\n for (const key of keys) {\n if (scanned >= cap) {\n break;\n }\n scanned += 1;\n const record = await stateStore.read(key);\n if (record !== undefined && now - record.updatedAt > maxAgeMillis) {\n // Classified before deletion: a record with a start and no end is a span\n // that will never be exported, which is worth counting rather than\n // discarding silently.\n if (record.value.kind === \"attributes\") {\n const decoded = decodeRecord(record.value.attributes);\n if (\n decoded.kind === \"present\" &&\n decoded.record.startedAt !== undefined &&\n decoded.record.endedAt === undefined\n ) {\n expiredOpen += 1;\n }\n }\n await stateStore.delete(key);\n removed += 1;\n }\n }\n return { removed, scanned, expiredOpen };\n };\n\n return { recordStart, recordEnd, correlateBatch, cleanup };\n};\n","import { z } from \"zod\";\n\nimport { tokenCountSchema } from \"./primitives.js\";\n\n/**\n * Whether an observation reports the change since the previous observation\n * (`delta`) or the running total for the session/generation (`cumulative`).\n *\n * The canonical model keeps temporality explicit rather than assuming one:\n * summing cumulative observations double-counts, and diffing delta observations\n * silently loses tokens.\n */\nexport const usageTemporalitySchema = z.enum([\"delta\", \"cumulative\"]);\nexport type UsageTemporality = z.infer<typeof usageTemporalitySchema>;\n\n/**\n * Whether the provider counts cache-creation tokens inside its input total or\n * reports them as a disjoint bucket.\n *\n * - `included-in-input`: `cacheCreationInputTokens` is a subset of `inputTokens`.\n * - `disjoint-from-input`: cache-creation tokens are billed in addition to\n * `inputTokens` and must be added when computing a total.\n * - `not-reported`: the provider exposes no cache-creation counter; the field is\n * pinned to zero.\n */\nexport const cacheCreationAccountingSchema = z.enum([\n \"included-in-input\",\n \"disjoint-from-input\",\n \"not-reported\",\n]);\nexport type CacheCreationAccounting = z.infer<typeof cacheCreationAccountingSchema>;\n\n/** Whether a provider-reported total agrees with the canonical computation. */\nexport const providerTotalAgreementSchema = z.enum([\"unreported\", \"agrees\", \"disagrees\"]);\nexport type ProviderTotalAgreement = z.infer<typeof providerTotalAgreementSchema>;\n\n/**\n * What an adapter reports, before normalization.\n *\n * `inputTokens` is *inclusive*: it counts every input token the provider\n * attributes to the call, including cache reads (and cache creation when the\n * provider folds it in). `outputTokens` is likewise inclusive of reasoning\n * output. Subset fields describe portions of those totals, never additions.\n */\nexport const usageReportSchema = z.strictObject({\n temporality: usageTemporalitySchema,\n /** Inclusive input tokens. */\n inputTokens: tokenCountSchema.optional(),\n /** Subset of `inputTokens` served from a prompt cache. */\n cachedInputTokens: tokenCountSchema.optional(),\n /** Tokens written to a prompt cache. */\n cacheCreationInputTokens: tokenCountSchema.optional(),\n /** Required when `cacheCreationInputTokens` is present and non-zero. */\n cacheCreationAccounting: cacheCreationAccountingSchema.optional(),\n /** Inclusive output tokens. */\n outputTokens: tokenCountSchema.optional(),\n /** Subset of `outputTokens` spent on reasoning. */\n reasoningOutputTokens: tokenCountSchema.optional(),\n /** Total exactly as the provider reported it, if it reported one. */\n providerTotalTokens: tokenCountSchema.optional(),\n});\nexport type UsageReport = z.infer<typeof usageReportSchema>;\n\n/**\n * Fully normalized usage.\n *\n * Derived fields (`uncachedInputTokens`, `totalTokens`,\n * `providerTotalAgreement`) are part of the schema and are re-checked on parse,\n * so an inconsistent object cannot exist. Construct values with\n * {@link normalizeUsage} rather than by hand.\n */\nexport const canonicalUsageSchema = z\n .strictObject({\n temporality: usageTemporalitySchema,\n inputTokens: tokenCountSchema,\n cachedInputTokens: tokenCountSchema,\n cacheCreationInputTokens: tokenCountSchema,\n cacheCreationAccounting: cacheCreationAccountingSchema,\n outputTokens: tokenCountSchema,\n reasoningOutputTokens: tokenCountSchema,\n /** Derived: input tokens that were neither cache reads nor cache writes. */\n uncachedInputTokens: tokenCountSchema,\n /** Derived: canonical billable total. */\n totalTokens: tokenCountSchema,\n providerTotalTokens: tokenCountSchema.optional(),\n providerTotalAgreement: providerTotalAgreementSchema,\n })\n .check((ctx) => {\n const usage = ctx.value;\n const push = (message: string): void => {\n ctx.issues.push({ code: \"custom\", input: usage, message });\n };\n\n if (usage.cachedInputTokens > usage.inputTokens) {\n push(\"cachedInputTokens must not exceed inputTokens (it is a subset)\");\n }\n if (usage.reasoningOutputTokens > usage.outputTokens) {\n push(\"reasoningOutputTokens must not exceed outputTokens (it is a subset)\");\n }\n if (usage.cacheCreationAccounting === \"not-reported\" && usage.cacheCreationInputTokens !== 0) {\n push(\"cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported\");\n }\n const creationInsideInput =\n usage.cacheCreationAccounting === \"included-in-input\" ? usage.cacheCreationInputTokens : 0;\n if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {\n push(\n \"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input\",\n );\n }\n const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;\n if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {\n push(`uncachedInputTokens must equal ${expectedUncached}`);\n }\n const creationOutsideInput =\n usage.cacheCreationAccounting === \"disjoint-from-input\" ? usage.cacheCreationInputTokens : 0;\n const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;\n if (usage.totalTokens !== expectedTotal) {\n push(`totalTokens must equal ${expectedTotal}`);\n }\n const expectedAgreement: ProviderTotalAgreement =\n usage.providerTotalTokens === undefined\n ? \"unreported\"\n : usage.providerTotalTokens === expectedTotal\n ? \"agrees\"\n : \"disagrees\";\n if (usage.providerTotalAgreement !== expectedAgreement) {\n push(`providerTotalAgreement must be ${expectedAgreement}`);\n }\n });\nexport type CanonicalUsage = z.infer<typeof canonicalUsageSchema>;\n\nexport type UsageNormalizationIssue = {\n readonly code:\n | \"invalid-report\"\n | \"cached-exceeds-input\"\n | \"reasoning-exceeds-output\"\n | \"cache-creation-exceeds-input\"\n | \"cache-creation-accounting-missing\";\n readonly message: string;\n};\n\nexport type UsageNormalizationResult =\n | { readonly status: \"ok\"; readonly usage: CanonicalUsage; readonly notes: readonly string[] }\n | { readonly status: \"invalid\"; readonly issues: readonly UsageNormalizationIssue[] };\n\n/**\n * Normalize a provider usage report into canonical usage.\n *\n * Deterministic rules:\n * 1. Absent counters default to `0`; `providerTotalTokens` stays absent.\n * 2. Non-integer, negative, or non-finite counters are rejected.\n * 3. A subset exceeding its total is rejected — never clamped — because\n * clamping would silently invent a billing story.\n * 4. `cacheCreationAccounting` defaults to `not-reported` when no cache-creation\n * tokens are reported, and is *required* when they are: guessing whether the\n * bucket is disjoint would mis-total every downstream cost calculation.\n * 5. A provider total that disagrees with the canonical total is preserved as\n * reported and flagged `disagrees`. Both numbers survive; neither is edited.\n */\nexport const normalizeUsage = (report: unknown): UsageNormalizationResult => {\n const parsed = usageReportSchema.safeParse(report);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map((issue) => ({\n code: \"invalid-report\" as const,\n message: `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n })),\n };\n }\n\n const input = parsed.data;\n const issues: UsageNormalizationIssue[] = [];\n const notes: string[] = [];\n\n const inputTokens = input.inputTokens ?? 0;\n const cachedInputTokens = input.cachedInputTokens ?? 0;\n const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;\n const outputTokens = input.outputTokens ?? 0;\n const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;\n\n let accounting: CacheCreationAccounting;\n if (cacheCreationInputTokens === 0) {\n accounting = input.cacheCreationAccounting ?? \"not-reported\";\n if (accounting !== \"not-reported\") {\n notes.push(\n `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`,\n );\n }\n } else if (input.cacheCreationAccounting === undefined) {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message:\n \"cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred\",\n });\n accounting = \"not-reported\";\n } else if (input.cacheCreationAccounting === \"not-reported\") {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message: \"cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens\",\n });\n accounting = \"not-reported\";\n } else {\n accounting = input.cacheCreationAccounting;\n }\n\n if (cachedInputTokens > inputTokens) {\n issues.push({\n code: \"cached-exceeds-input\",\n message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n if (reasoningOutputTokens > outputTokens) {\n issues.push({\n code: \"reasoning-exceeds-output\",\n message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`,\n });\n }\n\n const creationInsideInput = accounting === \"included-in-input\" ? cacheCreationInputTokens : 0;\n if (cachedInputTokens + creationInsideInput > inputTokens) {\n issues.push({\n code: \"cache-creation-exceeds-input\",\n message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const creationOutsideInput = accounting === \"disjoint-from-input\" ? cacheCreationInputTokens : 0;\n const totalTokens = inputTokens + creationOutsideInput + outputTokens;\n const providerTotalAgreement: ProviderTotalAgreement =\n input.providerTotalTokens === undefined\n ? \"unreported\"\n : input.providerTotalTokens === totalTokens\n ? \"agrees\"\n : \"disagrees\";\n\n if (providerTotalAgreement === \"disagrees\") {\n notes.push(\n `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`,\n );\n }\n\n const usage: CanonicalUsage = {\n temporality: input.temporality,\n inputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens,\n reasoningOutputTokens,\n uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,\n totalTokens,\n ...(input.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: input.providerTotalTokens }),\n providerTotalAgreement,\n };\n\n return { status: \"ok\", usage, notes };\n};\n\nexport class UsageNormalizationError extends Error {\n public readonly issues: readonly UsageNormalizationIssue[];\n\n public constructor(issues: readonly UsageNormalizationIssue[]) {\n super(`invalid usage report: ${issues.map((issue) => issue.message).join(\"; \")}`);\n this.name = \"UsageNormalizationError\";\n this.issues = issues;\n }\n}\n\n/** Convenience wrapper for call sites that treat invalid usage as a bug. */\nexport const normalizeUsageOrThrow = (report: unknown): CanonicalUsage => {\n const result = normalizeUsage(report);\n if (result.status === \"invalid\") {\n throw new UsageNormalizationError(result.issues);\n }\n return result.usage;\n};\n\nexport const EMPTY_DELTA_USAGE: CanonicalUsage = Object.freeze(\n normalizeUsageOrThrow({ temporality: \"delta\" }),\n);\n\nexport type UsageDeltaResult = {\n readonly usage: CanonicalUsage;\n /**\n * True when the current snapshot is smaller than the previous one on any\n * counter. That means the cumulative series restarted (new session, replayed\n * transcript, provider reset), so the current snapshot is emitted as the delta\n * instead of a negative difference.\n */\n readonly resetDetected: boolean;\n};\n\nconst requireCumulative = (usage: CanonicalUsage, label: string): void => {\n if (usage.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: `${label} must have cumulative temporality` },\n ]);\n }\n};\n\n/**\n * Convert two cumulative snapshots into a delta observation.\n *\n * Replay safety: re-processing the same snapshot yields an all-zero delta, and a\n * decreasing series is reported as a reset rather than a negative delta.\n * Accounting mode must match; mixing modes would make the subtraction meaningless.\n */\nexport const cumulativeToDelta = (\n previous: CanonicalUsage,\n current: CanonicalUsage,\n): UsageDeltaResult => {\n requireCumulative(previous, \"previous usage\");\n requireCumulative(current, \"current usage\");\n\n if (\n previous.cacheCreationAccounting !== current.cacheCreationAccounting &&\n previous.cacheCreationInputTokens !== 0 &&\n current.cacheCreationInputTokens !== 0\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot diff cumulative usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const resetDetected =\n current.inputTokens < previous.inputTokens ||\n current.cachedInputTokens < previous.cachedInputTokens ||\n current.cacheCreationInputTokens < previous.cacheCreationInputTokens ||\n current.outputTokens < previous.outputTokens ||\n current.reasoningOutputTokens < previous.reasoningOutputTokens;\n\n if (resetDetected) {\n return {\n usage: normalizeUsageOrThrow({ ...toReport(current), temporality: \"delta\" }),\n resetDetected: true,\n };\n }\n\n const usage = normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: current.inputTokens - previous.inputTokens,\n cachedInputTokens: current.cachedInputTokens - previous.cachedInputTokens,\n cacheCreationInputTokens:\n current.cacheCreationInputTokens - previous.cacheCreationInputTokens,\n cacheCreationAccounting: current.cacheCreationAccounting,\n outputTokens: current.outputTokens - previous.outputTokens,\n reasoningOutputTokens: current.reasoningOutputTokens - previous.reasoningOutputTokens,\n });\n\n return { usage, resetDetected: false };\n};\n\n/** Project canonical usage back onto the reported shape. */\nexport const toReport = (usage: CanonicalUsage): UsageReport => ({\n temporality: usage.temporality,\n inputTokens: usage.inputTokens,\n cachedInputTokens: usage.cachedInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n cacheCreationAccounting: usage.cacheCreationAccounting,\n outputTokens: usage.outputTokens,\n reasoningOutputTokens: usage.reasoningOutputTokens,\n ...(usage.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: usage.providerTotalTokens }),\n});\n\n/**\n * Add two delta observations. Cumulative usage is never summed, because two\n * running totals do not compose.\n */\nexport const addUsage = (a: CanonicalUsage, b: CanonicalUsage): CanonicalUsage => {\n if (a.temporality !== \"delta\" || b.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"only delta usage may be summed\" },\n ]);\n }\n const accounting =\n a.cacheCreationInputTokens === 0 && a.cacheCreationAccounting === \"not-reported\"\n ? b.cacheCreationAccounting\n : b.cacheCreationInputTokens === 0 && b.cacheCreationAccounting === \"not-reported\"\n ? a.cacheCreationAccounting\n : a.cacheCreationAccounting;\n\n if (\n a.cacheCreationInputTokens !== 0 &&\n b.cacheCreationInputTokens !== 0 &&\n a.cacheCreationAccounting !== b.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot sum usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n a.providerTotalTokens === undefined && b.providerTotalTokens === undefined\n ? undefined\n : (a.providerTotalTokens ?? 0) + (b.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: a.inputTokens + b.inputTokens,\n cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,\n cacheCreationInputTokens: a.cacheCreationInputTokens + b.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: a.outputTokens + b.outputTokens,\n reasoningOutputTokens: a.reasoningOutputTokens + b.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n","import {\n UsageNormalizationError,\n normalizeUsageOrThrow,\n type CanonicalUsage,\n} from \"../model/usage.js\";\nimport type { Attributes } from \"../model/primitives.js\";\nimport type { Clock, StateStore } from \"../runtime/ports.js\";\nimport { withOptionalSessionLock } from \"../state/store.js\";\nimport { rollupEpochKey, rollupEpochScanPrefix, rollupScanPrefix, rollupUsageKey } from \"./keys.js\";\n\nexport type UsageAccumulatorKey = {\n readonly sessionId: string;\n readonly scope: string;\n readonly scopeKey: string;\n};\n\nexport type UsageAccumulatorSnapshot = {\n readonly total: CanonicalUsage;\n /** Increments every time {@link UsageAccumulator.recordReset} is called for this key. */\n readonly epoch: number;\n};\n\nexport type RollupCleanupResult = { readonly removed: number; readonly scanned: number };\n\n/**\n * Which delivery an accumulation belongs to, and which of its observations this is.\n *\n * Supplying it makes the accumulation idempotent for *that delivery*: a second\n * application of the same `(callbackId, ordinal)` is a no-op that returns the\n * current total. Omitting it keeps the old unconditional behaviour, which is right\n * for a caller that has no delivery identity to key on — there is nothing to\n * recognize a repeat by, and refusing to accumulate would lose a real observation.\n *\n * `callbackId` must be an opaque digest, not a raw host or provider id: it is\n * written into a state record.\n */\nexport type DeliveryStamp = {\n readonly callbackId: string;\n /** Zero-based index of this observation within the delivery, per rollup key. */\n readonly ordinal: number;\n};\n\nexport type AccumulateOptions = { readonly delivery?: DeliveryStamp };\n\n/**\n * Rolls a stream of `delta` usage observations up into a running `cumulative`\n * total per scope, independent of the orchestrator's own per-scope\n * cumulative-to-delta baseline (`docs/usage-semantics.md`) — that baseline\n * answers \"what changed since last time\"; this answers \"what is the running\n * total\", which a diagnostics view or a parent scope (tool -> generation ->\n * session) needs and the core does not compute.\n *\n * A provider counter can restart mid-session (a process restart, a replayed\n * transcript). Rather than let a smaller cumulative total silently deflate the\n * running rollup, {@link UsageAccumulator.recordReset} starts a new epoch: the\n * total resets to zero and the epoch number increments, so a downstream\n * consumer can tell \"the counter restarted\" from \"usage actually decreased\"\n * and never sums across the boundary as if it were one continuous series.\n */\nexport interface UsageAccumulator {\n /**\n * Fold `delta` into the running total for `key`.\n *\n * With `options.delivery`, folding is idempotent for that delivery: a redelivered\n * callback whose claim was reclaimed or superseded re-derives the same delta and\n * would otherwise count it twice. The marker lives in the same record as the total\n * it describes, so the check and the write are one atomic operation — which is the\n * only reason this is expressible without a multi-key transaction. What it does\n * *not* cover is a delivery whose marker a later, different delivery has since\n * overwritten: only the most recent delivery per rollup key is recognizable, which\n * is exactly the retry window and nothing beyond it.\n */\n accumulateDelta(\n key: UsageAccumulatorKey,\n delta: CanonicalUsage,\n options?: AccumulateOptions,\n ): Promise<UsageAccumulatorSnapshot>;\n /** Start a new epoch. Idempotent per delivery when `options.delivery` is given. */\n recordReset(key: UsageAccumulatorKey, options?: AccumulateOptions): Promise<{ readonly epoch: number }>;\n read(key: UsageAccumulatorKey): Promise<UsageAccumulatorSnapshot | undefined>;\n cleanup(\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<RollupCleanupResult>;\n}\n\nexport type UsageAccumulatorDependencies = {\n readonly stateStore: StateStore;\n readonly clock: Clock;\n};\n\nconst EMPTY_CUMULATIVE_USAGE: CanonicalUsage = normalizeUsageOrThrow({ temporality: \"cumulative\" });\n\nconst combineCumulativeWithDelta = (total: CanonicalUsage, delta: CanonicalUsage): CanonicalUsage => {\n if (total.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"usage rollup total must have cumulative temporality\" },\n ]);\n }\n if (delta.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"usage accumulator only accepts delta observations\" },\n ]);\n }\n\n const accounting =\n total.cacheCreationInputTokens === 0 && total.cacheCreationAccounting === \"not-reported\"\n ? delta.cacheCreationAccounting\n : delta.cacheCreationInputTokens === 0 && delta.cacheCreationAccounting === \"not-reported\"\n ? total.cacheCreationAccounting\n : total.cacheCreationAccounting;\n\n if (\n total.cacheCreationInputTokens !== 0 &&\n delta.cacheCreationInputTokens !== 0 &&\n total.cacheCreationAccounting !== delta.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot roll up usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n total.providerTotalTokens === undefined && delta.providerTotalTokens === undefined\n ? undefined\n : (total.providerTotalTokens ?? 0) + (delta.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"cumulative\",\n inputTokens: total.inputTokens + delta.inputTokens,\n cachedInputTokens: total.cachedInputTokens + delta.cachedInputTokens,\n cacheCreationInputTokens: total.cacheCreationInputTokens + delta.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: total.outputTokens + delta.outputTokens,\n reasoningOutputTokens: total.reasoningOutputTokens + delta.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n\nexport const createUsageAccumulator = (deps: UsageAccumulatorDependencies): UsageAccumulator => {\n const { stateStore, clock } = deps;\n\n /**\n * The epoch record's own delivery marker.\n *\n * Kept in the epoch record for the same reason the total's marker is kept in the\n * total: one write, so the counter and the statement about who moved it cannot\n * disagree. The epoch record is an `attributes` value, so the two fields are\n * flat rather than nested.\n */\n const readEpochMarker = (\n attributes: Attributes,\n ): { readonly callbackId: string; readonly applications: number } | undefined => {\n const callbackId = attributes.resetDelivery;\n const applications = attributes.resetApplications;\n if (\n typeof callbackId !== \"string\" ||\n callbackId.length === 0 ||\n typeof applications !== \"number\" ||\n !Number.isInteger(applications) ||\n applications < 1\n ) {\n return undefined;\n }\n return { callbackId, applications };\n };\n\n const readEpoch = async (key: UsageAccumulatorKey): Promise<number> => {\n const record = await stateStore.read(rollupEpochKey(key.sessionId, key.scope, key.scopeKey));\n if (record?.value.kind === \"attributes\" && typeof record.value.attributes.epoch === \"number\") {\n return record.value.attributes.epoch;\n }\n return 0;\n };\n\n /**\n * Whether this delivery's observation number `ordinal` is already folded in.\n *\n * The comparison is `<` rather than `===` because observations are applied in\n * order: `applications` is the count folded in so far, so any ordinal below it has\n * been seen. A marker naming a *different* delivery means this rollup has moved on\n * and nothing can be recognized.\n */\n const alreadyApplied = (\n marker: { readonly callbackId: string; readonly applications: number } | undefined,\n delivery: DeliveryStamp | undefined,\n ): boolean =>\n delivery !== undefined &&\n marker !== undefined &&\n marker.callbackId === delivery.callbackId &&\n delivery.ordinal < marker.applications;\n\n const markerFor = (\n delivery: DeliveryStamp | undefined,\n ): { readonly appliedDelivery?: { readonly callbackId: string; readonly applications: number } } =>\n delivery === undefined\n ? {}\n : {\n appliedDelivery: { callbackId: delivery.callbackId, applications: delivery.ordinal + 1 },\n };\n\n const accumulateDelta = (\n key: UsageAccumulatorKey,\n delta: CanonicalUsage,\n options?: AccumulateOptions,\n ): Promise<UsageAccumulatorSnapshot> =>\n withOptionalSessionLock(stateStore, key.sessionId, async (): Promise<UsageAccumulatorSnapshot> => {\n const usageKey = rollupUsageKey(key.sessionId, key.scope, key.scopeKey);\n const existing = await stateStore.read(usageKey);\n const previousTotal =\n existing?.value.kind === \"usage-cumulative\" ? existing.value.usage : EMPTY_CUMULATIVE_USAGE;\n\n if (\n existing?.value.kind === \"usage-cumulative\" &&\n alreadyApplied(existing.value.appliedDelivery, options?.delivery)\n ) {\n // This exact observation of this exact delivery is already in the total.\n // Reporting the total unchanged is the honest answer: the caller asked for\n // the running figure after its delta, and that is what this is.\n return { total: previousTotal, epoch: await readEpoch(key) };\n }\n\n const total = combineCumulativeWithDelta(previousTotal, delta);\n await stateStore.write(usageKey, {\n kind: \"usage-cumulative\",\n usage: total,\n ...markerFor(options?.delivery),\n });\n return { total, epoch: await readEpoch(key) };\n });\n\n const recordReset = (\n key: UsageAccumulatorKey,\n options?: AccumulateOptions,\n ): Promise<{ readonly epoch: number }> =>\n withOptionalSessionLock(stateStore, key.sessionId, async (): Promise<{ readonly epoch: number }> => {\n const epochKey = rollupEpochKey(key.sessionId, key.scope, key.scopeKey);\n const existingEpoch = await stateStore.read(epochKey);\n const marker =\n existingEpoch?.value.kind === \"attributes\"\n ? readEpochMarker(existingEpoch.value.attributes)\n : undefined;\n\n if (alreadyApplied(marker, options?.delivery)) {\n // A replayed reset must not open a second epoch: the epoch number is what a\n // consumer uses to refuse summing across a counter restart, and inflating it\n // twice for one restart makes a real series look like two.\n return { epoch: await readEpoch(key) };\n }\n\n const epoch = (await readEpoch(key)) + 1;\n const applied = markerFor(options?.delivery).appliedDelivery;\n await stateStore.write(epochKey, {\n kind: \"attributes\",\n attributes: {\n epoch,\n ...(applied === undefined\n ? {}\n : { resetDelivery: applied.callbackId, resetApplications: applied.applications }),\n },\n });\n await stateStore.delete(rollupUsageKey(key.sessionId, key.scope, key.scopeKey));\n return { epoch };\n });\n\n const read = async (key: UsageAccumulatorKey): Promise<UsageAccumulatorSnapshot | undefined> => {\n const record = await stateStore.read(rollupUsageKey(key.sessionId, key.scope, key.scopeKey));\n if (record?.value.kind !== \"usage-cumulative\") {\n return undefined;\n }\n return { total: record.value.usage, epoch: await readEpoch(key) };\n };\n\n const cleanup = async (\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<RollupCleanupResult> => {\n const cap = options?.maxEntries ?? 1_000;\n const now = clock.now();\n let removed = 0;\n let scanned = 0;\n\n const sweep = async (keys: readonly string[]): Promise<void> => {\n for (const key of keys) {\n if (scanned >= cap) {\n return;\n }\n scanned += 1;\n const record = await stateStore.read(key);\n if (record !== undefined && now - record.updatedAt > maxAgeMillis) {\n await stateStore.delete(key);\n removed += 1;\n }\n }\n };\n\n await sweep(await stateStore.keys(rollupScanPrefix(options?.sessionId)));\n await sweep(await stateStore.keys(rollupEpochScanPrefix(options?.sessionId)));\n return { removed, scanned };\n };\n\n return { accumulateDelta, recordReset, read, cleanup };\n};\n","import 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,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,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