@osfactory/otel-hook 0.14.0 → 0.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -3
- package/dist/{adapter-D5R8lhfl.d.ts → adapter-But5fFCk.d.ts} +8 -1
- package/dist/cli.js +210 -45
- package/dist/cli.js.map +1 -1
- package/dist/{export-destinations-DvoH4QOe.d.ts → export-destinations-8tNkIC8a.d.ts} +12 -4
- package/dist/{filesystem-store-B3CpiIRl.d.ts → filesystem-store-Z8XgDtFj.d.ts} +1 -1
- package/dist/{hook-DVK8Don-.d.ts → hook-D7XABd4f.d.ts} +17 -3
- package/dist/index.d.ts +10 -10
- package/dist/index.js +211 -45
- package/dist/index.js.map +1 -1
- package/dist/install.d.ts +3 -3
- package/dist/install.js.map +1 -1
- package/dist/integration.d.ts +6 -6
- package/dist/integration.js +188 -40
- package/dist/integration.js.map +1 -1
- package/dist/lifecycle.d.ts +1 -1
- package/dist/lifecycle.js +1 -1
- package/dist/lifecycle.js.map +1 -1
- package/dist/{memory-B3r6sZtC.d.ts → memory-gipZUiXP.d.ts} +1 -1
- package/dist/{payload-D4r71EL-.d.ts → payload-DWdx9yk3.d.ts} +1 -1
- package/dist/{ports-DhpSDIkp.d.ts → ports-qZTwK-z2.d.ts} +22 -2
- package/dist/providers.d.ts +7 -7
- package/dist/providers.js +22 -5
- package/dist/providers.js.map +1 -1
- package/dist/{registry-DOJh9mzB.d.ts → registry-D9rmMYxw.d.ts} +1 -1
- package/dist/runtime.d.ts +22 -7
- package/dist/runtime.js +154 -28
- package/dist/runtime.js.map +1 -1
- package/dist/state.d.ts +3 -3
- package/dist/state.js.map +1 -1
- package/dist/telemetry.d.ts +2 -2
- package/dist/telemetry.js +26 -9
- package/dist/telemetry.js.map +1 -1
- package/dist/testing.d.ts +6 -6
- package/dist/testing.js +57 -8
- package/dist/testing.js.map +1 -1
- package/package.json +1 -1
package/dist/state.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/state/async-lock.ts","../src/state/store.ts","../src/runtime/ports.ts","../src/model/events.ts","../src/errors/taxonomy.ts","../src/model/content.ts","../src/model/primitives.ts","../src/model/extensions.ts","../src/model/identity.ts","../src/model/target.ts","../src/model/usage.ts","../src/model/version.ts","../src/state/memory-store.ts","../src/state/filesystem-store.ts","../src/state/keys.ts"],"sourcesContent":["/**\n * Per-key async mutex.\n *\n * Ordinary promises already serialize a single caller's `await`s, but two\n * concurrent callers racing a read-modify-write against the same key (two\n * hook invocations updating the same session, in the same process) are not\n * serialized by anything. This chains each key's operations through a promise\n * tail so they run one at a time, in arrival order, without blocking unrelated\n * keys.\n */\nexport interface AsyncLock {\n /**\n * `timeoutMillis` bounds how long the caller waits to *acquire* the key.\n *\n * Two guarantees, and the boundary between them is the whole contract:\n *\n * - **A timed-out caller's `fn` never runs.** Giving up on the wait cancels the\n * queued operation. It has to: a caller that has been told \"I could not take\n * the lock\" will report contention and move on, and if `fn` then ran anyway it\n * would mutate state after the caller had already declared that nothing\n * happened. That is worse than either outcome on its own — the state changes\n * and nobody is watching.\n * - **Work is never cancelled after acquisition.** Once `fn` has started the\n * timeout is irrelevant; interrupting a read-modify-write partway through is\n * exactly the corruption a mutex exists to prevent. So the timeout bounds\n * *waiting*, never *exclusivity* and never *completion*.\n *\n * Cancellation does not let a waiter skip the queue: the cancelled slot still\n * settles in order, so everyone behind it keeps its place. A cancelled call\n * rejects with {@link LockWaitTimeoutError}, the same error a timed-out wait\n * produces, because from the caller's side they are one condition.\n */\n run<T>(key: string, fn: () => Promise<T>, timeoutMillis?: number): Promise<T>;\n}\n\nexport class LockWaitTimeoutError extends Error {\n public readonly lockKey: string;\n\n public constructor(key: string, timeoutMillis: number) {\n super(`lock wait exceeded ${timeoutMillis}ms`);\n this.name = \"LockWaitTimeoutError\";\n this.lockKey = key;\n }\n}\n\nexport const createAsyncLock = (): AsyncLock => {\n const tail = new Map<string, Promise<void>>();\n\n const run = async <T>(key: string, fn: () => Promise<T>, timeoutMillis?: number): Promise<T> => {\n const previous = tail.get(key) ?? Promise.resolve();\n const queued = previous.then(\n () => undefined,\n () => undefined,\n );\n\n /**\n * `entered` flips synchronously, immediately before `fn` is invoked, and\n * `cancelled` is only ever set from the timer while `entered` is false.\n *\n * That ordering is what makes the two guarantees exclusive rather than racy.\n * Microtasks drain before timers, so if this slot's turn has arrived at all,\n * the callback below has already run and set `entered` before any timer\n * callback can observe it — there is no window in which the timer sees a\n * not-yet-entered slot that is in fact about to run.\n */\n let cancelled = false;\n let entered = false;\n\n const current = queued.then((): T | Promise<T> => {\n if (cancelled) {\n // The waiter gave up before its turn came, so `fn` is skipped entirely.\n // The slot still settles here, in order, so nothing behind it is reordered.\n throw new LockWaitTimeoutError(key, timeoutMillis ?? 0);\n }\n entered = true;\n return fn();\n });\n\n const swallowed = current.then(\n () => undefined,\n () => undefined,\n );\n tail.set(key, swallowed);\n void swallowed.then(() => {\n if (tail.get(key) === swallowed) {\n tail.delete(key);\n }\n });\n\n if (timeoutMillis === undefined) {\n return current;\n }\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n if (!entered) {\n cancelled = true;\n }\n reject(new LockWaitTimeoutError(key, timeoutMillis));\n }, timeoutMillis);\n timer.unref?.();\n });\n try {\n // Raced against the queue gate, not against `current`: once the slot is\n // entered the caller waits for `fn` however long it takes.\n await Promise.race([queued, timeout]);\n } finally {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n }\n return current;\n };\n\n return { run };\n};\n","import type { Clock, StateStore } from \"../runtime/ports.js\";\nimport { LockWaitTimeoutError } from \"./async-lock.js\";\n\n/**\n * A lock could not be acquired within its wait bound because somebody else holds\n * it.\n *\n * Distinct from \"the store is broken\" on purpose, and the distinction is\n * load-bearing for callers that guard a read-modify-write with it. Contention\n * means a peer is plausibly *inside* the critical section right now, so\n * proceeding unlocked would produce exactly the lost update the lock exists to\n * prevent. A store that cannot lock at all — an unwritable directory, a full\n * disk — protects nothing, because the state the lock guards is equally\n * unreachable; there proceeding is the fail-open answer and costs nothing.\n */\nexport class StateLockTimeoutError extends Error {\n public readonly lockKey: string;\n\n public constructor(key: string, timeoutMillis: number) {\n super(`state store lock wait for \"${key}\" exceeded ${String(timeoutMillis)}ms`);\n this.name = \"StateLockTimeoutError\";\n this.lockKey = key;\n }\n}\n\n/**\n * Whether a thrown value means \"somebody else holds the lock\".\n *\n * Also true for {@link LockWaitTimeoutError}, the in-process variant, which\n * carries a second warning for callers: a timed-out wait does not cancel the\n * queued critical section, so it may still run afterwards. A caller that treats\n * contention as \"retry unlocked\" would therefore risk running the section twice.\n */\nexport const isStateLockContention = (thrown: unknown): boolean =>\n thrown instanceof StateLockTimeoutError || thrown instanceof LockWaitTimeoutError;\n\n/**\n * Optional capability beyond the frozen {@link StateStore} contract: a\n * session-scoped lock a caller can use to make a multi-step read-modify-write\n * atomic across an entire session, not just a single key.\n *\n * Deliberately keyed by an explicit `sessionId` the caller already knows,\n * rather than derived by parsing the store's own keys, so a store never has\n * to understand any particular key scheme.\n */\nexport interface LockingStateStore extends StateStore {\n withSessionLock<T>(\n sessionId: string,\n fn: () => Promise<T>,\n options?: { readonly timeoutMillis?: number },\n ): Promise<T>;\n}\n\nexport const isLockingStateStore = (store: StateStore): store is LockingStateStore =>\n typeof (store as Partial<LockingStateStore>).withSessionLock === \"function\";\n\n/** Runs `fn` under the store's session lock when it has one; otherwise runs it directly. */\nexport const withOptionalSessionLock = async <T>(\n store: StateStore,\n sessionId: string,\n fn: () => Promise<T>,\n options?: { readonly timeoutMillis?: number },\n): Promise<T> => {\n if (isLockingStateStore(store)) {\n return store.withSessionLock(sessionId, fn, options);\n }\n return fn();\n};\n\nexport type StateStoreDependencies = {\n readonly clock: Clock;\n};\n","import { z } from \"zod\";\n\nimport type { OtelHookErrorInfo } from \"../errors/index.js\";\nimport { modelDescriptorSchema, type CanonicalEvent } from \"../model/events.js\";\nimport {\n attributesSchema,\n epochMillisSchema,\n sequenceNumberSchema,\n type Attributes,\n type EpochMillis,\n type EventId,\n type InvocationId,\n} from \"../model/primitives.js\";\nimport type { WorktreeKind } from \"../model/target.js\";\nimport { canonicalUsageSchema } from \"../model/usage.js\";\n\n/**\n * Time source.\n *\n * Injected rather than read from `Date.now()` so tests are deterministic and so\n * a host with its own time authority can supply it.\n */\nexport interface Clock {\n /** Wall-clock time in whole milliseconds since the Unix epoch. */\n now(): EpochMillis;\n /** Monotonic reading for durations; unrelated to wall clock. */\n monotonicMillis(): number;\n}\n\n/** Stable inputs from which an invocation id is derived. */\nexport type InvocationIdSeed = {\n readonly providerId: string;\n readonly sessionId: string;\n readonly sourceEventName?: string;\n readonly occurredAt: number;\n /** Provider-supplied uniqueness, e.g. a request id. */\n readonly discriminator?: string;\n};\n\n/** Stable inputs from which an event id is derived. */\nexport type EventIdSeed = {\n readonly invocationId: string;\n readonly sequence: number;\n readonly eventType: string;\n readonly discriminator?: string;\n};\n\n/**\n * Identifier factory.\n *\n * Seeds are structured rather than free-form so the default implementation can\n * be a pure function of its inputs: replaying the same source data produces the\n * same ids, which lets a collector dedupe instead of double-counting.\n */\nexport interface IdGenerator {\n newInvocationId(seed: InvocationIdSeed): InvocationId;\n newEventId(seed: EventIdSeed): EventId;\n /** Short opaque id for spans and generations, derived from its parts. */\n newOpaqueId(parts: readonly string[]): string;\n}\n\n/**\n * Which delivery's observations are already folded into a stored total.\n *\n * The reason this rides *inside* the total's own record rather than beside it: the\n * store has no multi-key transaction, so a marker in a second key could be written\n * without the total or the other way round, and a marker that can disagree with\n * what it describes is worse than none. In one record the two move together under a\n * single write, which is what makes re-applying a redelivered callback's usage a\n * no-op instead of a double count.\n *\n * `callbackId` is an opaque digest supplied by the caller, never a host's raw\n * delivery id: a state record is somewhere a raw provider or host identifier must\n * not appear as a side effect of deduplicating on it.\n */\nexport const appliedDeliverySchema = z.strictObject({\n callbackId: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/),\n /** How many of that delivery's observations are folded in, counted from one. */\n applications: z.number().int().min(1).max(4_096),\n});\nexport type AppliedDelivery = z.infer<typeof appliedDeliverySchema>;\n\n/** Values the state store may hold. Restricted so state stays inspectable. */\nexport const stateValueSchema = z.discriminatedUnion(\"kind\", [\n z.strictObject({\n kind: z.literal(\"usage-cumulative\"),\n usage: canonicalUsageSchema,\n /**\n * Optional: absent on every record written before this field existed, which\n * reads as \"unknown provenance\" and simply forgoes the idempotency check\n * rather than resetting a baseline to gain it.\n */\n appliedDelivery: appliedDeliverySchema.optional(),\n }),\n z.strictObject({\n kind: z.literal(\"sequence\"),\n next: sequenceNumberSchema,\n }),\n z.strictObject({\n kind: z.literal(\"attributes\"),\n attributes: attributesSchema,\n }),\n /**\n * The model a session last reported, so a later invocation whose payload names\n * none (Claude Code's `Stop`) can still say which model it was. A model id is\n * not sensitive (`modelDescriptorSchema`), and the descriptor is the strict,\n * bounded canonical shape, never a payload fragment.\n */\n z.strictObject({\n kind: z.literal(\"session-model\"),\n model: modelDescriptorSchema,\n }),\n /**\n * How far a {@link PayloadEnricher} has read a session's append-only source\n * (Claude Code's transcript), so the next read starts where the last ended.\n * `source` is an opaque digest of what was read, never a path.\n */\n /**\n * Running state of one metric series (issue #69), so a cumulative data point\n * exported by a later hook process continues the same total. Holds numbers and\n * a series digest only; the series' attributes are re-supplied by the caller\n * and never read back from disk.\n */\n z.strictObject({\n kind: z.literal(\"metric-series\"),\n /** Start of the cumulative interval. */\n startTimeMillis: epochMillisSchema,\n /** Counters: the running total. */\n value: z.number().finite().min(0).optional(),\n /** Histograms: the running aggregation. */\n histogram: z\n .strictObject({\n count: z.number().int().min(0),\n sum: z.number().finite().min(0),\n min: z.number().finite(),\n max: z.number().finite(),\n bucketCounts: z.array(z.number().int().min(0)).max(64),\n })\n .optional(),\n /** Opaque digest of the last delivery folded in; makes a replay a no-op. */\n appliedDelivery: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional(),\n }),\n z.strictObject({\n kind: z.literal(\"read-cursor\"),\n source: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/),\n offset: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),\n }),\n]);\nexport type StateValue = z.infer<typeof stateValueSchema>;\n\nexport const stateRecordSchema = z.strictObject({\n /** Incremented on each write; lets callers detect lost updates. */\n revision: z.number().int().min(0),\n updatedAt: epochMillisSchema,\n value: stateValueSchema,\n});\nexport type StateRecord = z.infer<typeof stateRecordSchema>;\n\n/**\n * Durable-ish key/value state.\n *\n * Needed because a hook process is short-lived but usage accounting spans an\n * entire session. The interface is intentionally minimal: no transactions, no\n * queries, nothing a file or a KV row cannot provide.\n */\nexport interface StateStore {\n read(key: string): Promise<StateRecord | undefined>;\n /** Writes unconditionally, returning the stored record. */\n write(key: string, value: StateValue): Promise<StateRecord>;\n delete(key: string): Promise<void>;\n keys(prefix: string): Promise<readonly string[]>;\n}\n\nexport type TelemetryEmitResult = {\n readonly accepted: number;\n readonly rejected: number;\n readonly errors: readonly OtelHookErrorInfo[];\n};\n\n/**\n * Destination for canonical events.\n *\n * The sink receives canonical events only — never provider payloads — so an\n * exporter cannot become a second, unaudited disclosure path.\n */\nexport interface TelemetrySink {\n emit(events: readonly CanonicalEvent[]): Promise<TelemetryEmitResult>;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nexport const logLevelSchema = z.enum([\"silent\", \"error\", \"warn\", \"info\", \"debug\"]);\nexport type LogLevel = z.infer<typeof logLevelSchema>;\n\nexport const LOG_LEVEL_RANK: Readonly<Record<LogLevel, number>> = Object.freeze({\n silent: 0,\n error: 1,\n warn: 2,\n info: 3,\n debug: 4,\n});\n\n/**\n * Diagnostic logger.\n *\n * Fields are attribute values, not arbitrary objects, so a log line cannot\n * become a way to print a provider payload. Implementations must never write to\n * stdout (ADR 0004).\n */\nexport interface Logger {\n error(message: string, fields?: Attributes): void;\n warn(message: string, fields?: Attributes): void;\n info(message: string, fields?: Attributes): void;\n debug(message: string, fields?: Attributes): void;\n}\n\n/** A git worktree found on the local filesystem. Holds a path: never exported. */\nexport type LocatedWorktree = {\n /** Absolute path of the worktree's top-level directory (the one holding `.git`). */\n readonly root: string;\n /** Branch checked out there, from `HEAD`; absent when HEAD is detached. */\n readonly branch?: string;\n /** Main checkout or linked worktree; absent when the locator does not tell. */\n readonly kind?: WorktreeKind;\n /**\n * Absolute path of the repository's main worktree — `root` itself for a main\n * worktree. Absent when there is none to name: a bare repository, a main\n * checkout that is gone, or a layout the locator cannot read.\n */\n readonly mainRoot?: string;\n};\n\n/**\n * Finds the git worktree containing a local path (ADR 0008).\n *\n * The only port that reads the filesystem on behalf of event content, which is\n * why it is a port: the core decides *when* to ask and what of the answer may be\n * exported, the implementation only answers. Implementations must never throw or\n * reject — any failure is `undefined` — and must not spawn processes.\n */\nexport interface WorktreeLocator {\n locate(absolutePath: string): Promise<LocatedWorktree | undefined>;\n}\n\n/** Where an enricher stopped reading a session's source; see the `read-cursor` state value. */\nexport type ReadCursor = {\n /** Opaque digest naming the source, so a cursor never applies to another file. */\n readonly source: string;\n /** Byte offset the next read starts at. */\n readonly offset: number;\n};\n\nexport type PayloadEnrichmentInput = {\n readonly payload: unknown;\n readonly sessionId: string;\n /** The cursor this enricher stored for this session (and cursor scope) last time, if any. */\n readonly cursor?: ReadCursor;\n};\n\nexport type PayloadEnrichment = {\n /** The payload the adapter parses: the input, or a copy with fields attached. */\n readonly payload: unknown;\n /** A cursor to store for this session; absent leaves the stored one as it is. */\n readonly cursor?: ReadCursor;\n /** Short, non-sensitive notes for the debug log (why a read fell back, ...). */\n readonly notes?: readonly string[];\n};\n\n/**\n * Host-side step that attaches facts to a provider payload before its adapter\n * parses it — for facts the provider writes somewhere other than the hook\n * payload, such as Claude Code's transcript.\n *\n * Not an adapter capability, on purpose: adapters get no filesystem handle (ADR\n * 0003). An enricher is configured by the host, runs inside the session lock so\n * its cursor is read and written atomically, and must be bounded and never throw\n * (a throw is contained and the original payload is parsed). It never runs for a\n * redelivered callback, which is not a new observation.\n */\nexport interface PayloadEnricher {\n /** Stable id; namespaces the enricher's cursor in the state store. */\n readonly id: string;\n /** The provider whose payloads it enriches. Others are never passed to it. */\n readonly providerId: string;\n /**\n * Which of the session's cursors this payload reads, when a session has more\n * than one source (Claude Code writes each subagent to its own transcript).\n * `undefined`, or no function, selects the session's own cursor. A scope is\n * part of a state key, never exported; it must not hold a path.\n */\n cursorScope?(payload: unknown): string | undefined;\n enrich(input: PayloadEnrichmentInput): Promise<PayloadEnrichment>;\n}\n\n/**\n * One window of a session's context: the attributes in force from `from`\n * (inclusive) until `to` (exclusive), or open-ended when `to` is `null`.\n * Attributes are already screened (see `sanitizeSessionContextAttributes`).\n */\nexport type SessionContextSegment = {\n readonly from: EpochMillis;\n readonly to: EpochMillis | null;\n readonly attributes: Readonly<Record<string, string | number | boolean>>;\n};\n\nexport type SessionContextRequest = {\n /** The detected provider, e.g. `claude-code`. The reader maps it to its directory name. */\n readonly providerId: string;\n /**\n * The session whose context applies: always the invocation's session, which\n * for a subagent event is its parent's — never the subagent's own id.\n */\n readonly sessionId: string;\n};\n\n/**\n * Reads the session context a harness wrote for one agent session.\n *\n * A port for the same reason {@link WorktreeLocator} is one: the core decides\n * when to ask and what of the answer reaches a record; the implementation only\n * reads. Adapters never see it (ADR 0003). Implementations must never throw or\n * reject: no file, an unreadable file, an invalid one, or one of an unknown\n * version are all `undefined`, and the core then stamps nothing.\n */\nexport interface SessionContextReader {\n read(request: SessionContextRequest): Promise<readonly SessionContextSegment[] | undefined>;\n}\n","import { z } from \"zod\";\n\nimport {\n errorPhaseSchema,\n errorSeveritySchema,\n otelHookErrorCodeSchema,\n} from \"../errors/taxonomy.js\";\nimport { contentFactSchema, contentFactsSchema } from \"./content.js\";\nimport { extensionsSchema, emptyExtensions } from \"./extensions.js\";\nimport { sourceProvenanceSchema, workspaceIdentitySchema } from \"./identity.js\";\nimport { subagentIdSchema, workspaceTargetSchema } from \"./target.js\";\nimport {\n durationMillisSchema,\n epochMillisSchema,\n eventIdSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n sequenceNumberSchema,\n sessionIdSchema,\n tokenCountSchema,\n} from \"./primitives.js\";\nimport { canonicalUsageSchema, type CanonicalUsage } from \"./usage.js\";\nimport { canonicalSchemaVersionSchema } from \"./version.js\";\n\n/** Model being invoked. Model identifiers are not treated as sensitive. */\nexport const modelDescriptorSchema = z.strictObject({\n modelId: nonEmptyStringSchema,\n /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */\n vendor: nonEmptyStringSchema.optional(),\n family: nonEmptyStringSchema.optional(),\n});\nexport type ModelDescriptor = z.infer<typeof modelDescriptorSchema>;\n\nexport const costFactsSchema = z.strictObject({\n /** ISO 4217 code. */\n currency: z.string().length(3),\n amount: z.number().min(0).finite(),\n source: z.enum([\"provider-reported\", \"computed\"]),\n});\nexport type CostFacts = z.infer<typeof costFactsSchema>;\n\nexport const canonicalEventTypeSchema = z.enum([\n \"session.start\",\n \"session.end\",\n \"prompt.submitted\",\n \"generation.start\",\n \"generation.end\",\n \"tool.start\",\n \"tool.end\",\n \"subagent.start\",\n \"subagent.end\",\n \"compaction.performed\",\n \"error.raised\",\n]);\nexport type CanonicalEventType = z.infer<typeof canonicalEventTypeSchema>;\n\nexport const CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;\n\nconst outcomeSchema = z.enum([\"ok\", \"error\", \"cancelled\", \"timeout\", \"denied\", \"unknown\"]);\nexport type EventOutcome = z.infer<typeof outcomeSchema>;\n\n/**\n * Fields present on every canonical event.\n *\n * Identity fields are duplicated onto each event rather than referenced through\n * shared state, so an event is self-describing once it leaves the process.\n */\nconst baseEventFields = {\n schemaVersion: canonicalSchemaVersionSchema,\n eventId: eventIdSchema,\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Per-invocation ordering key. Stable across replays of the same input. */\n sequence: sequenceNumberSchema,\n occurredAt: epochMillisSchema,\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n /**\n * The provider's own id for the subagent this event was emitted inside (e.g.\n * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event\n * factory, never by hand.\n */\n subagentId: subagentIdSchema.optional(),\n extensions: extensionsSchema.default(emptyExtensions),\n /**\n * Attributes of the session context segment in force when the event\n * occurred (`docs/session-context.md`), stamped by the core from a file a\n * harness wrote. Exported on every record of the event, over the same keys\n * from the Resource. Absent when no context applies. Set by the core only,\n * never by an adapter.\n */\n contextAttributes: z.record(z.string().min(1).max(255), z.union([z.string(), z.number(), z.boolean()])).optional(),\n} as const;\n\nconst event = <TShape extends z.ZodRawShape>(shape: TShape) =>\n z.strictObject({ ...baseEventFields, ...shape });\n\nexport const sessionStartEventSchema = event({\n type: z.literal(\"session.start\"),\n sessionKind: z.enum([\"interactive\", \"non-interactive\", \"unknown\"]),\n agentName: nonEmptyStringSchema.optional(),\n agentVersion: nonEmptyStringSchema.optional(),\n model: modelDescriptorSchema.optional(),\n /** The git worktree the session runs in, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const sessionEndEventSchema = event({\n type: z.literal(\"session.end\"),\n reason: z.enum([\"completed\", \"aborted\", \"error\", \"timeout\", \"unknown\"]),\n durationMillis: durationMillisSchema.optional(),\n /** Session totals, typically cumulative. */\n usage: canonicalUsageSchema.optional(),\n cost: costFactsSchema.optional(),\n});\n\nexport const promptSubmittedEventSchema = event({\n type: z.literal(\"prompt.submitted\"),\n promptSource: z.enum([\"user\", \"automation\", \"resumed\", \"unknown\"]),\n content: contentFactSchema.optional(),\n turnIndex: z.number().int().min(0).optional(),\n /** The git worktree the session runs in, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const generationStartEventSchema = event({\n type: z.literal(\"generation.start\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n requestedMaxOutputTokens: tokenCountSchema.optional(),\n inputContent: contentFactsSchema.optional(),\n});\n\nexport const generationEndEventSchema = event({\n type: z.literal(\"generation.end\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n outcome: outcomeSchema,\n stopReason: nonEmptyStringSchema.optional(),\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n /**\n * True when `usage` is known to cover only part of the generation (for\n * example the last model request of a multi-request turn); false when the\n * provider or harness said it is the whole. Absent: not stated. Meaningless\n * without `usage`.\n */\n usagePartial: z.boolean().optional(),\n cost: costFactsSchema.optional(),\n outputContent: contentFactsSchema.optional(),\n});\n\nexport const toolKindSchema = z.enum([\n \"read\",\n \"write\",\n \"execute\",\n \"search\",\n \"network\",\n \"delegate\",\n \"other\",\n \"unknown\",\n]);\nexport type ToolKind = z.infer<typeof toolKindSchema>;\n\nexport const toolStartEventSchema = event({\n type: z.literal(\"tool.start\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n toolKind: toolKindSchema,\n generationId: nonEmptyStringSchema.optional(),\n input: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const toolEndEventSchema = event({\n type: z.literal(\"tool.end\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n /** Present when the host asked for or recorded a permission decision. */\n permissionDecision: z.enum([\"allowed\", \"denied\", \"deferred\", \"not-required\"]).optional(),\n output: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const subagentStartEventSchema = event({\n type: z.literal(\"subagent.start\"),\n subagentInvocationId: invocationIdSchema,\n subagentType: nonEmptyStringSchema.optional(),\n /** 0 for the top-level agent; 1 for its direct children. */\n delegationDepth: z.number().int().min(0).max(64),\n model: modelDescriptorSchema.optional(),\n});\n\nexport const subagentEndEventSchema = event({\n type: z.literal(\"subagent.end\"),\n subagentInvocationId: invocationIdSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const compactionPerformedEventSchema = event({\n type: z.literal(\"compaction.performed\"),\n trigger: z.enum([\"automatic\", \"manual\", \"unknown\"]),\n /** Provider-reported context size before and after compaction, if known. */\n contextTokensBefore: tokenCountSchema.optional(),\n contextTokensAfter: tokenCountSchema.optional(),\n droppedMessageCount: z.number().int().min(0).optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const errorRaisedEventSchema = event({\n type: z.literal(\"error.raised\"),\n errorCode: otelHookErrorCodeSchema,\n severity: errorSeveritySchema,\n phase: errorPhaseSchema,\n retryable: z.boolean(),\n /** Error text is content: it is described, never embedded verbatim by default. */\n message: contentFactSchema.optional(),\n /** Non-sensitive, provider-agnostic short label. */\n detail: nonEmptyStringSchema.optional(),\n});\n\nexport const canonicalEventSchema = z.discriminatedUnion(\"type\", [\n sessionStartEventSchema,\n sessionEndEventSchema,\n promptSubmittedEventSchema,\n generationStartEventSchema,\n generationEndEventSchema,\n toolStartEventSchema,\n toolEndEventSchema,\n subagentStartEventSchema,\n subagentEndEventSchema,\n compactionPerformedEventSchema,\n errorRaisedEventSchema,\n]);\n\nexport type CanonicalEvent = z.infer<typeof canonicalEventSchema>;\nexport type CanonicalEventInput = z.input<typeof canonicalEventSchema>;\n\nexport type SessionStartEvent = z.infer<typeof sessionStartEventSchema>;\nexport type SessionEndEvent = z.infer<typeof sessionEndEventSchema>;\nexport type PromptSubmittedEvent = z.infer<typeof promptSubmittedEventSchema>;\nexport type GenerationStartEvent = z.infer<typeof generationStartEventSchema>;\nexport type GenerationEndEvent = z.infer<typeof generationEndEventSchema>;\nexport type ToolStartEvent = z.infer<typeof toolStartEventSchema>;\nexport type ToolEndEvent = z.infer<typeof toolEndEventSchema>;\nexport type SubagentStartEvent = z.infer<typeof subagentStartEventSchema>;\nexport type SubagentEndEvent = z.infer<typeof subagentEndEventSchema>;\nexport type CompactionPerformedEvent = z.infer<typeof compactionPerformedEventSchema>;\nexport type ErrorRaisedEvent = z.infer<typeof errorRaisedEventSchema>;\n\nexport type CanonicalEventOfType<TType extends CanonicalEventType> = Extract<\n CanonicalEvent,\n { type: TType }\n>;\n\n/**\n * The event types that may carry a resolved `target` (ADR 0008): a tool call\n * names the worktree it touched; a session start and a prompt name the one the\n * session runs in, so a consumer knows the session's place before its first\n * tool call.\n */\nexport const TARGETED_EVENT_TYPES = [\"session.start\", \"prompt.submitted\", \"tool.start\", \"tool.end\"] as const;\nexport type TargetedEventType = (typeof TARGETED_EVENT_TYPES)[number];\nexport type TargetedEvent = CanonicalEventOfType<TargetedEventType>;\n\nconst TARGETED: ReadonlySet<string> = new Set(TARGETED_EVENT_TYPES);\nexport const isTargetedEvent = (event: CanonicalEvent): event is TargetedEvent => TARGETED.has(event.type);\n\nexport type EventValidationResult =\n | { readonly status: \"ok\"; readonly event: CanonicalEvent }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nexport const validateCanonicalEvent = (value: unknown): EventValidationResult => {\n const parsed = canonicalEventSchema.safeParse(value);\n if (parsed.success) {\n return { status: \"ok\", event: parsed.data };\n }\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n};\n\n/** Parse or throw. Intended for fixtures and tests, not the hook path. */\nexport const parseCanonicalEvent = (value: unknown): CanonicalEvent =>\n canonicalEventSchema.parse(value);\n\n/** Usage carried by an event, if the event type can carry any. */\nexport const eventUsage = (event: CanonicalEvent): CanonicalUsage | undefined =>\n \"usage\" in event ? event.usage : undefined;\n\n/** Stable ordering: by sequence, then by timestamp, then by event id. */\nexport const compareEvents = (a: CanonicalEvent, b: CanonicalEvent): number =>\n a.sequence - b.sequence || a.occurredAt - b.occurredAt || a.eventId.localeCompare(b.eventId);\n","import { z } from \"zod\";\n\n/**\n * Closed set of error codes. Adding a code is a minor change; changing what a\n * code means is a breaking change.\n */\nexport const otelHookErrorCodeSchema = z.enum([\n /** Input was not usable at all (empty stdin, unparsable JSON). */\n \"invalid-input\",\n /** Input parsed but failed canonical schema validation. */\n \"schema-validation-failed\",\n /** No adapter claimed the input with sufficient confidence. */\n \"provider-unknown\",\n /** Several adapters claimed the input at the same confidence. */\n \"provider-detection-ambiguous\",\n /** An adapter threw or returned a malformed result. */\n \"provider-adapter-failure\",\n /** Two identity claims disagreed at equal confidence. */\n \"identity-conflict\",\n /** Required identity fields were absent. */\n \"identity-incomplete\",\n /** A usage report violated the canonical usage invariants. */\n \"usage-invalid\",\n /** The state store could not be read or written. */\n \"state-store-failure\",\n /** The telemetry sink rejected or could not deliver a batch. */\n \"telemetry-export-failure\",\n /** Content reached the sink boundary in a state the policy forbids. */\n \"privacy-policy-violation\",\n /** Configuration could not be resolved. */\n \"configuration-invalid\",\n /** A configured bound (events, batch size) dropped data. */\n \"limit-exceeded\",\n /**\n * No replay-stable delivery identifier was available for a callback while\n * deduplication was required.\n */\n \"delivery-identifier-unavailable\",\n \"delivery-claim-superseded\",\n /** Anything unanticipated. Always reported, never fatal to the host. */\n \"internal-error\",\n]);\nexport type OtelHookErrorCode = z.infer<typeof otelHookErrorCodeSchema>;\n\nexport const errorSeveritySchema = z.enum([\"warning\", \"error\"]);\nexport type ErrorSeverity = z.infer<typeof errorSeveritySchema>;\n\n/** Pipeline stage where a failure occurred. */\nexport const errorPhaseSchema = z.enum([\n \"configuration\",\n \"detection\",\n \"identity\",\n \"parsing\",\n \"normalization\",\n \"privacy\",\n \"state\",\n \"export\",\n \"shutdown\",\n]);\nexport type ErrorPhase = z.infer<typeof errorPhaseSchema>;\n\n/**\n * Which of the two safety postures a code participates in.\n *\n * - `fail-open`: the hook still reports success to the host agent. Telemetry may\n * be incomplete; the coding agent is never blocked.\n * - `fail-closed-attribution`: the observation is not attributed to a session or\n * provider. Data is dropped rather than labelled with a guess.\n */\nexport const failurePostureSchema = z.enum([\"fail-open\", \"fail-closed-attribution\"]);\nexport type FailurePosture = z.infer<typeof failurePostureSchema>;\n\nexport type ErrorCodeDescriptor = {\n readonly code: OtelHookErrorCode;\n readonly severity: ErrorSeverity;\n readonly posture: FailurePosture;\n /** Whether retrying the same input could succeed. */\n readonly retryable: boolean;\n readonly summary: string;\n};\n\nexport const ERROR_TAXONOMY: Readonly<Record<OtelHookErrorCode, ErrorCodeDescriptor>> =\n Object.freeze({\n \"invalid-input\": {\n code: \"invalid-input\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Input could not be read or decoded.\",\n },\n \"schema-validation-failed\": {\n code: \"schema-validation-failed\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"A canonical event failed schema validation and was dropped.\",\n },\n \"provider-unknown\": {\n code: \"provider-unknown\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"No adapter recognized the source provider; the input stays unattributed.\",\n },\n \"provider-detection-ambiguous\": {\n code: \"provider-detection-ambiguous\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Multiple adapters claimed the input at equal confidence.\",\n },\n \"provider-adapter-failure\": {\n code: \"provider-adapter-failure\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A provider adapter failed while parsing.\",\n },\n \"identity-conflict\": {\n code: \"identity-conflict\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Identity claims disagreed; attribution was declined.\",\n },\n \"identity-incomplete\": {\n code: \"identity-incomplete\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Required identity fields were missing; attribution was declined.\",\n },\n \"usage-invalid\": {\n code: \"usage-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A usage report violated the canonical usage invariants.\",\n },\n \"state-store-failure\": {\n code: \"state-store-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"State could not be read or written; derived values may be incomplete.\",\n },\n \"telemetry-export-failure\": {\n code: \"telemetry-export-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"The telemetry sink could not accept a batch.\",\n },\n \"privacy-policy-violation\": {\n code: \"privacy-policy-violation\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Content violated the resolved privacy policy and was dropped.\",\n },\n \"configuration-invalid\": {\n code: \"configuration-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Configuration could not be resolved; defaults apply.\",\n },\n \"limit-exceeded\": {\n code: \"limit-exceeded\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A configured bound was reached and data was dropped.\",\n },\n \"delivery-identifier-unavailable\": {\n code: \"delivery-identifier-unavailable\",\n severity: \"warning\",\n // Fail-open: the observation is still attributed and exported. Only the\n // at-most-once guarantee is missing, and refusing the telemetry to protect\n // a duplicate count would trade a certain loss for a possible one.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"No replay-stable delivery identifier was available; this callback was exported without deduplication.\",\n },\n \"delivery-claim-superseded\": {\n code: \"delivery-claim-superseded\",\n severity: \"warning\",\n // Fail-open, and specifically *not* silent. A peer reclaimed this callback's\n // claim while this process was still working on it, which means the\n // configured stale window is shorter than this installation's real worst\n // case. Both processes may now have exported the callback, so the\n // at-most-once guarantee did not hold for it — the only honest response is\n // to say so and let the operator raise the window.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"A delivery claim was reclaimed by another process before this one committed; the callback may have been exported twice.\",\n },\n \"internal-error\": {\n code: \"internal-error\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"An unexpected failure was contained.\",\n },\n });\n\nexport const describeErrorCode = (code: OtelHookErrorCode): ErrorCodeDescriptor =>\n ERROR_TAXONOMY[code];\n\n/** Outcome of attributing an observation to a provider and session. */\nexport const attributionOutcomeSchema = z.enum([\n /** Identity resolved; events carry provider and session identity. */\n \"attributed\",\n /** Identity could not be established safely; nothing was attributed. */\n \"declined\",\n /** Attribution was attempted and failed unexpectedly. */\n \"failed\",\n /** Input was recognized but intentionally carried no telemetry. */\n \"not-applicable\",\n]);\nexport type AttributionOutcome = z.infer<typeof attributionOutcomeSchema>;\n\nexport const attributionReasonSchema = z.enum([\n \"provider-unknown\",\n \"provider-detection-ambiguous\",\n \"identity-conflict\",\n \"identity-incomplete\",\n \"adapter-ignored-input\",\n \"adapter-failure\",\n \"invalid-input\",\n \"internal-error\",\n]);\nexport type AttributionReason = z.infer<typeof attributionReasonSchema>;\n","import { z } from \"zod\";\n\nimport { nonEmptyStringSchema } from \"./primitives.js\";\n\n/** What kind of conversational or tool content a fact describes. */\nexport const contentKindSchema = z.enum([\n \"prompt\",\n \"response\",\n \"reasoning\",\n \"tool-input\",\n \"tool-output\",\n \"error-message\",\n \"system-instruction\",\n \"attachment\",\n]);\nexport type ContentKind = z.infer<typeof contentKindSchema>;\n\nexport const contentRoleSchema = z.enum([\"user\", \"assistant\", \"system\", \"tool\", \"unknown\"]);\nexport type ContentRole = z.infer<typeof contentRoleSchema>;\n\n/**\n * How much of the original content this fact discloses.\n *\n * - `omitted`: no text at all (the default posture).\n * - `masked`: a shape-preserving mask; non-whitespace characters replaced.\n * - `redacted`: text with secret-looking spans replaced by a placeholder.\n * - `raw`: verbatim text. Only reachable through explicit opt-in.\n */\nexport const contentDisclosureSchema = z.enum([\"omitted\", \"masked\", \"redacted\", \"raw\"]);\nexport type ContentDisclosure = z.infer<typeof contentDisclosureSchema>;\n\nexport const CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;\n\n/**\n * A privacy-safe description of content.\n *\n * Lengths and a stable hash are always present so consumers can measure and\n * correlate volume without receiving the content itself. `text` is present only\n * when the resolved privacy policy allows disclosure, and is produced solely by\n * the central privacy service.\n */\nexport const contentFactSchema = z.strictObject({\n kind: contentKindSchema,\n role: contentRoleSchema.optional(),\n /** Unicode code point count of the original content. */\n characterLength: z.number().int().min(0),\n /** UTF-8 byte length of the original content. */\n byteLength: z.number().int().min(0),\n /** Stable salted digest of the original content. */\n contentHash: z.string().regex(CONTENT_HASH_PATTERN),\n disclosure: contentDisclosureSchema,\n /** Disclosed text, bounded by the privacy policy. Absent when omitted. */\n text: z.string().optional(),\n /** True when `text` was cut short by the configured string bound. */\n truncated: z.boolean(),\n /** Number of secret-looking spans replaced while producing `text`. */\n secretsRedacted: z.number().int().min(0),\n /** Optional non-sensitive label, e.g. a MIME type or tool name. */\n label: nonEmptyStringSchema.optional(),\n});\nexport type ContentFact = z.infer<typeof contentFactSchema>;\n\nexport const contentFactsSchema = z.array(contentFactSchema).max(64);\n\n/**\n * Guard used in tests and at the sink boundary: an omitted fact must not carry\n * text, and a disclosing fact must carry it.\n */\nexport const isContentFactConsistent = (fact: ContentFact): boolean =>\n fact.disclosure === \"omitted\" ? fact.text === undefined : fact.text !== undefined;\n\n/**\n * A fact for a content kind the event can carry when the provider sent no text.\n *\n * Always `omitted` with zero length, regardless of the installation's content\n * mode: there is nothing to mask, redact, or export.\n */\nexport const isUnavailableContentFact = (fact: ContentFact): boolean =>\n fact.disclosure === \"omitted\" &&\n fact.text === undefined &&\n fact.characterLength === 0 &&\n fact.byteLength === 0;\n","import { z } from \"zod\";\n\n/** Maximum length accepted for short identifier-like strings. */\nexport const MAX_IDENTIFIER_LENGTH = 256;\n\n/** Maximum length accepted for a single string attribute value. */\nexport const MAX_ATTRIBUTE_STRING_LENGTH = 4096;\n\n/** Maximum number of entries accepted in an attribute array value. */\nexport const MAX_ATTRIBUTE_ARRAY_LENGTH = 128;\n\nexport const nonEmptyStringSchema = z.string().min(1).max(MAX_IDENTIFIER_LENGTH);\n\n/** Wall-clock time as whole milliseconds since the Unix epoch. */\nexport const epochMillisSchema = z.number().int().min(0).max(8_640_000_000_000_000);\nexport type EpochMillis = z.infer<typeof epochMillisSchema>;\n\n/** Non-negative duration in milliseconds; may be fractional. */\nexport const durationMillisSchema = z.number().min(0).finite();\n\n/** Token counts are always non-negative integers. */\nexport const tokenCountSchema = z.number().int().min(0);\n\n/** Monotonically increasing per-invocation ordering key. */\nexport const sequenceNumberSchema = z.number().int().min(0);\n\nconst brandedIdSchema = (): z.ZodString => z.string().min(1).max(MAX_IDENTIFIER_LENGTH);\n\nexport const invocationIdSchema = brandedIdSchema().brand<\"InvocationId\">();\nexport type InvocationId = z.infer<typeof invocationIdSchema>;\n\nexport const sessionIdSchema = brandedIdSchema().brand<\"SessionId\">();\nexport type SessionId = z.infer<typeof sessionIdSchema>;\n\nexport const eventIdSchema = brandedIdSchema().brand<\"EventId\">();\nexport type EventId = z.infer<typeof eventIdSchema>;\n\n/**\n * Workspace identifiers are opaque, privacy-safe handles of the form\n * `<scheme>:<token>`. Filesystem paths cannot satisfy this pattern, which keeps\n * home directories and repository paths out of telemetry by construction.\n */\nexport const WORKSPACE_ID_PATTERN = /^[a-z][a-z0-9]{0,15}:[A-Za-z0-9_-]{8,128}$/;\nexport const workspaceIdSchema = z\n .string()\n .regex(WORKSPACE_ID_PATTERN, \"workspace id must be an opaque `<scheme>:<token>` handle\")\n .brand<\"WorkspaceId\">();\nexport type WorkspaceId = z.infer<typeof workspaceIdSchema>;\n\n/** Provider ids are lowercase, hyphenated, and stable across releases. */\nexport const PROVIDER_ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\nexport const providerIdSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(PROVIDER_ID_PATTERN, \"provider id must be lowercase and hyphenated\")\n .brand<\"ProviderId\">();\nexport type ProviderId = z.infer<typeof providerIdSchema>;\n\n/** Sentinel used whenever the source provider could not be established. */\nexport const UNKNOWN_PROVIDER_ID = \"unknown\" as const;\nexport type UnknownProviderId = typeof UNKNOWN_PROVIDER_ID;\n\nexport const resolvedProviderIdSchema = z.union([\n providerIdSchema,\n z.literal(UNKNOWN_PROVIDER_ID),\n]);\nexport type ResolvedProviderId = z.infer<typeof resolvedProviderIdSchema>;\n\nexport const isUnknownProvider = (value: ResolvedProviderId): value is UnknownProviderId =>\n value === UNKNOWN_PROVIDER_ID;\n\n/**\n * Attribute values are restricted to OpenTelemetry-compatible primitives.\n *\n * This restriction is a containment boundary, not a convenience: because no\n * nested object can be represented, a raw provider payload cannot be smuggled\n * out of an adapter through attributes or extensions.\n */\nexport const attributePrimitiveSchema = z.union([\n z.string().max(MAX_ATTRIBUTE_STRING_LENGTH),\n z.number().finite(),\n z.boolean(),\n]);\nexport type AttributePrimitive = z.infer<typeof attributePrimitiveSchema>;\n\nexport const attributeValueSchema = z.union([\n attributePrimitiveSchema,\n z.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH),\n]);\nexport type AttributeValue = z.infer<typeof attributeValueSchema>;\n\nexport const attributesSchema = z.record(z.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);\nexport type Attributes = z.infer<typeof attributesSchema>;\n\n/** Ordered confidence ladder for provider detection. */\nexport const detectionConfidenceSchema = z.enum([\"none\", \"weak\", \"strong\", \"exact\"]);\nexport type DetectionConfidence = z.infer<typeof detectionConfidenceSchema>;\n\nexport const DETECTION_CONFIDENCE_RANK: Readonly<Record<DetectionConfidence, number>> =\n Object.freeze({\n none: 0,\n weak: 1,\n strong: 2,\n exact: 3,\n });\n\nexport const compareDetectionConfidence = (a: DetectionConfidence, b: DetectionConfidence): number =>\n DETECTION_CONFIDENCE_RANK[a] - DETECTION_CONFIDENCE_RANK[b];\n\n/** How the observed data reached this process. */\nexport const sourceTransportSchema = z.enum([\n \"hook-stdin\",\n \"cli-argument\",\n \"library-call\",\n \"test-fixture\",\n]);\nexport type SourceTransport = z.infer<typeof sourceTransportSchema>;\n","import { z } from \"zod\";\n\nimport { attributeValueSchema, type AttributeValue } from \"./primitives.js\";\n\n/**\n * Extension keys must be namespaced: at least one dot-separated segment before\n * the leaf, e.g. `acme.deployment-tier`. Namespacing keeps provider- and\n * consumer-specific fields from colliding with core fields or each other.\n */\nexport const EXTENSION_KEY_PATTERN =\n /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;\n\n/** Namespaces owned by the core model; extensions may not use them. */\nexport const RESERVED_EXTENSION_NAMESPACES: readonly string[] = Object.freeze([\n \"otelhook\",\n \"otel\",\n \"telemetry\",\n]);\n\nexport const MAX_EXTENSION_ENTRIES = 64;\n\nexport const extensionKeyNamespace = (key: string): string => key.slice(0, key.indexOf(\".\"));\n\nexport const isReservedExtensionNamespace = (key: string): boolean =>\n RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));\n\nexport const isValidExtensionKey = (key: string): boolean =>\n EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);\n\n/**\n * Namespaced extension bag.\n *\n * Values are restricted to attribute primitives, so extensions cannot carry\n * nested provider payloads.\n */\nexport const extensionsSchema = z\n .record(z.string(), attributeValueSchema)\n .check((ctx) => {\n const keys = Object.keys(ctx.value);\n if (keys.length > MAX_EXTENSION_ENTRIES) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`,\n });\n }\n for (const key of keys) {\n if (!EXTENSION_KEY_PATTERN.test(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. \"acme.tier\"`,\n });\n continue;\n }\n if (isReservedExtensionNamespace(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`,\n });\n }\n }\n });\n\nexport type Extensions = Record<string, AttributeValue>;\n\nexport const EMPTY_EXTENSIONS: Extensions = Object.freeze({});\n\nexport const emptyExtensions = (): Extensions => ({});\n","import { z } from \"zod\";\n\nimport {\n attributesSchema,\n detectionConfidenceSchema,\n DETECTION_CONFIDENCE_RANK,\n epochMillisSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n resolvedProviderIdSchema,\n sessionIdSchema,\n sourceTransportSchema,\n workspaceIdSchema,\n type DetectionConfidence,\n type InvocationId,\n type SessionId,\n type WorkspaceId,\n} from \"./primitives.js\";\n\n/**\n * Where a workspace identifier came from.\n *\n * Ordered from most to least stable. The source is recorded so consumers can\n * tell a repository-scoped identity from a directory-scoped one instead of\n * assuming they are comparable.\n */\nexport const workspaceKeySourceSchema = z.enum([\n \"git-remote\",\n \"git-root\",\n \"working-directory\",\n \"explicit\",\n \"unknown\",\n]);\nexport type WorkspaceKeySource = z.infer<typeof workspaceKeySourceSchema>;\n\n/**\n * Privacy-safe workspace identity.\n *\n * Only opaque handles and explicitly allowed labels are modelled. There is no\n * field for a filesystem path, so paths cannot be exported through this type.\n */\nexport const workspaceIdentitySchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n keySource: workspaceKeySourceSchema,\n /** Repository name only; never an owner path or URL with credentials. */\n repositoryName: nonEmptyStringSchema.optional(),\n vcsBranchName: nonEmptyStringSchema.optional(),\n /** Opaque handle for the checked-out revision. */\n vcsRevisionId: nonEmptyStringSchema.optional(),\n })\n .readonly();\nexport type WorkspaceIdentity = z.infer<typeof workspaceIdentitySchema>;\n\nexport const UNKNOWN_WORKSPACE_ID = \"unknown:0000000000000000\" as WorkspaceId;\n\nexport const unknownWorkspaceIdentity = (): WorkspaceIdentity =>\n workspaceIdentitySchema.parse({\n workspaceId: UNKNOWN_WORKSPACE_ID,\n keySource: \"unknown\",\n });\n\n/**\n * Provenance of an observation: which provider produced it and which adapter\n * interpreted it, with the confidence of that attribution.\n */\nexport const sourceProvenanceSchema = z\n .strictObject({\n providerId: resolvedProviderIdSchema,\n providerVersion: nonEmptyStringSchema.optional(),\n adapterId: nonEmptyStringSchema,\n adapterVersion: nonEmptyStringSchema,\n detectionConfidence: detectionConfidenceSchema,\n /** The provider's own name for the source event, e.g. a hook event name. */\n sourceEventName: nonEmptyStringSchema.optional(),\n transport: sourceTransportSchema,\n })\n .readonly();\nexport type SourceProvenance = z.infer<typeof sourceProvenanceSchema>;\n\n/**\n * Opaque, immutable metadata supplied by the embedding consumer.\n *\n * The library never interprets these values; it only carries and exports them.\n */\nexport const consumerAttributesSchema = attributesSchema.readonly();\nexport type ConsumerAttributes = z.infer<typeof consumerAttributesSchema>;\n\n/**\n * Immutable identity of a single hook invocation.\n *\n * Frozen on parse. There is deliberately no setter, no builder that mutates in\n * place, and no module-level instance: identity is passed explicitly so two\n * concurrent invocations can never observe each other's fields.\n */\nexport const invocationIdentitySchema = z\n .strictObject({\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Set when this invocation runs beneath another agent invocation. */\n parentInvocationId: invocationIdSchema.optional(),\n /** Root of the session tree when the provider exposes one. */\n rootSessionId: sessionIdSchema.optional(),\n /** Stable handle for the agent process/instance, when available. */\n agentInstanceId: nonEmptyStringSchema.optional(),\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n startedAt: epochMillisSchema,\n consumerAttributes: consumerAttributesSchema,\n })\n .readonly();\nexport type InvocationIdentity = z.infer<typeof invocationIdentitySchema>;\n\n/** Fields an identity claim may contribute. */\nexport const identityClaimFieldsSchema = z.strictObject({\n invocationId: invocationIdSchema.optional(),\n sessionId: sessionIdSchema.optional(),\n parentInvocationId: invocationIdSchema.optional(),\n rootSessionId: sessionIdSchema.optional(),\n agentInstanceId: nonEmptyStringSchema.optional(),\n workspace: workspaceIdentitySchema.optional(),\n startedAt: epochMillisSchema.optional(),\n});\nexport type IdentityClaimFields = z.infer<typeof identityClaimFieldsSchema>;\n\n/**\n * A claim about invocation identity from one source.\n *\n * Claims are evidence, not truth. Resolution keeps the highest-confidence claim\n * per field and refuses to merge disagreeing peers.\n */\nexport const identityClaimSchema = z.strictObject({\n /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */\n source: nonEmptyStringSchema,\n confidence: detectionConfidenceSchema,\n fields: identityClaimFieldsSchema,\n});\nexport type IdentityClaim = z.infer<typeof identityClaimSchema>;\n\nexport type IdentityConflict = {\n readonly field: keyof IdentityClaimFields;\n readonly confidence: DetectionConfidence;\n /** Rendered, non-sensitive representations of the disagreeing values. */\n readonly values: readonly string[];\n readonly sources: readonly string[];\n};\n\nexport type IdentityResolution =\n | { readonly status: \"resolved\"; readonly identity: InvocationIdentity }\n | {\n readonly status: \"conflict\";\n readonly conflicts: readonly IdentityConflict[];\n }\n | {\n readonly status: \"incomplete\";\n readonly missing: readonly (keyof IdentityClaimFields)[];\n }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nconst CLAIM_FIELDS = [\n \"invocationId\",\n \"sessionId\",\n \"parentInvocationId\",\n \"rootSessionId\",\n \"agentInstanceId\",\n \"workspace\",\n \"startedAt\",\n] as const satisfies readonly (keyof IdentityClaimFields)[];\n\nconst renderClaimValue = (value: unknown): string => {\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (value !== null && typeof value === \"object\" && \"workspaceId\" in value) {\n const { workspaceId } = value;\n return typeof workspaceId === \"string\" ? workspaceId : \"<workspace>\";\n }\n return \"<opaque>\";\n};\n\nexport type ResolveIdentityInput = {\n readonly claims: readonly IdentityClaim[];\n readonly provenance: SourceProvenance;\n /** Used only for fields no claim provides and that have a safe default. */\n readonly fallback?: {\n readonly startedAt?: number;\n readonly workspace?: WorkspaceIdentity;\n };\n readonly consumerAttributes?: Readonly<Record<string, unknown>>;\n};\n\n/**\n * Resolve identity from claims, failing closed.\n *\n * Rules:\n * 1. For each field, only claims at the highest confidence that provided it are\n * considered. Lower-confidence claims never fill in or override.\n * 2. Two distinct values at that highest confidence produce a `conflict`. The\n * invocation is then not attributed at all — a mislabelled session is worse\n * than a missing one.\n * 3. `invocationId` and `sessionId` are mandatory. Missing either yields\n * `incomplete`; neither is invented here.\n * 4. `startedAt` and `workspace` may come from an explicit fallback, because a\n * clock reading and an `unknown` workspace handle assert nothing false.\n */\nexport const resolveInvocationIdentity = (input: ResolveIdentityInput): IdentityResolution => {\n const parsedClaims: IdentityClaim[] = [];\n const issues: string[] = [];\n for (const [index, claim] of input.claims.entries()) {\n const parsed = identityClaimSchema.safeParse(claim);\n if (parsed.success) {\n parsedClaims.push(parsed.data);\n } else {\n issues.push(\n `claim[${index}]: ${parsed.error.issues.map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`).join(\", \")}`,\n );\n }\n }\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const conflicts: IdentityConflict[] = [];\n const selected: Record<string, unknown> = {};\n\n for (const field of CLAIM_FIELDS) {\n const contributors = parsedClaims.filter((claim) => claim.fields[field] !== undefined);\n if (contributors.length === 0) {\n continue;\n }\n const bestRank = Math.max(\n ...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence]),\n );\n const best = contributors.filter(\n (claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank,\n );\n const rendered = new Map<string, string[]>();\n for (const claim of best) {\n const key = JSON.stringify(claim.fields[field]);\n const sources = rendered.get(key) ?? [];\n sources.push(claim.source);\n rendered.set(key, sources);\n }\n if (rendered.size > 1) {\n const [firstBest] = best;\n conflicts.push({\n field,\n confidence: firstBest?.confidence ?? \"none\",\n values: best.map((claim) => renderClaimValue(claim.fields[field])),\n sources: best.map((claim) => claim.source),\n });\n continue;\n }\n const [winner] = best;\n if (winner !== undefined) {\n selected[field] = winner.fields[field];\n }\n }\n\n if (conflicts.length > 0) {\n return { status: \"conflict\", conflicts };\n }\n\n const missing: (keyof IdentityClaimFields)[] = [];\n if (selected.invocationId === undefined) {\n missing.push(\"invocationId\");\n }\n if (selected.sessionId === undefined) {\n missing.push(\"sessionId\");\n }\n if (missing.length > 0) {\n return { status: \"incomplete\", missing };\n }\n\n const startedAt = (selected.startedAt as number | undefined) ?? input.fallback?.startedAt;\n if (startedAt === undefined) {\n return { status: \"incomplete\", missing: [\"startedAt\"] };\n }\n const workspace =\n (selected.workspace as WorkspaceIdentity | undefined) ??\n input.fallback?.workspace ??\n unknownWorkspaceIdentity();\n\n const candidate = {\n invocationId: selected.invocationId as InvocationId,\n sessionId: selected.sessionId as SessionId,\n ...(selected.parentInvocationId === undefined\n ? {}\n : { parentInvocationId: selected.parentInvocationId as InvocationId }),\n ...(selected.rootSessionId === undefined\n ? {}\n : { rootSessionId: selected.rootSessionId as SessionId }),\n ...(selected.agentInstanceId === undefined\n ? {}\n : { agentInstanceId: selected.agentInstanceId as string }),\n provenance: input.provenance,\n workspace,\n startedAt,\n consumerAttributes: input.consumerAttributes ?? {},\n };\n\n const parsed = invocationIdentitySchema.safeParse(candidate);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n }\n return { status: \"resolved\", identity: parsed.data };\n};\n","import { z } from \"zod\";\n\nimport { nonEmptyStringSchema, workspaceIdSchema } from \"./primitives.js\";\n\n/**\n * Per-event workspace targeting (ADR 0008).\n *\n * A session's `workspace` is where the agent was *started*. An agent routinely\n * works somewhere else — in a linked git worktree beside the checkout it was\n * launched from — and the session-level identity cannot show that. A tool event\n * can: the file it edited, or the directory its shell command ran in, names the\n * worktree it actually touched.\n *\n * Two values model that, and the split between them is the privacy boundary:\n *\n * - {@link TargetHint} is what an adapter observed — local paths. It is an\n * in-process value only: it is never part of a {@link CanonicalEvent}, never\n * persisted, never exported. The core resolves it and drops it.\n * - {@link WorkspaceTarget} is what the core resolved — salted handles of the\n * worktree and its repository, the worktree's kind, the checked-out branch, and\n * what the evidence was. It travels on the event.\n */\n\n/**\n * What a target was derived from, strongest evidence first.\n *\n * - `tool-path` — a path the tool call itself named (an edited or read file, a\n * patch header).\n * - `shell-cwd` — the working directory the provider reports a shell command ran in.\n * - `session-cwd` — only the session's own directory was known; the event may\n * have reached elsewhere (e.g. a shell `cd`) without the provider saying so.\n */\nexport const targetSourceSchema = z.enum([\"tool-path\", \"shell-cwd\", \"session-cwd\"]);\nexport type TargetSource = z.infer<typeof targetSourceSchema>;\n\n/** Most paths one hint may name; a bound, not a sampling rule (all must agree). */\nexport const MAX_TARGET_HINT_PATHS = 8;\n\n/** Longest local path a hint may carry. Longer input is dropped, never truncated. */\nexport const MAX_TARGET_PATH_LENGTH = 4096;\n\nconst localPathSchema = z\n .string()\n .min(1)\n .max(MAX_TARGET_PATH_LENGTH)\n .refine((value) => !value.includes(\"\\u0000\"), \"path must not contain NUL\");\n\n/**\n * An adapter's observation of where a tool event pointed. **Carries local paths**\n * — in-process only, see the module note.\n *\n * Every path in one hint must resolve to the same worktree, or the event gets no\n * target at all: a patch touching two worktrees did not target either of them.\n */\nexport const targetHintSchema = z\n .strictObject({\n source: targetSourceSchema,\n paths: z.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),\n /** Absolute directory that relative `paths` resolve against. */\n baseDirectory: localPathSchema.optional(),\n })\n .readonly();\nexport type TargetHint = z.infer<typeof targetHintSchema>;\n\n/**\n * The weakest hint: the session's own directory. Every adapter gives it to a\n * session start and a prompt, and to a tool call that names no path.\n */\nexport const sessionCwdHint = (cwd: string | undefined): TargetHint | undefined =>\n cwd === undefined || cwd.length === 0 ? undefined : { source: \"session-cwd\", paths: [cwd] };\n\n/**\n * Whether a worktree is its repository's main checkout (`main`) or one added\n * beside it with `git worktree add` (`linked`).\n */\nexport const worktreeKindSchema = z.enum([\"main\", \"linked\"]);\nexport type WorktreeKind = z.infer<typeof worktreeKindSchema>;\n\n/**\n * The git worktree a tool event targeted. Exported; carries no path.\n *\n * `workspaceId` is derived exactly like a `git-root` workspace identity, so a\n * consumer holding the same salt can match it against one it derived itself.\n * `repositoryId` is the same derivation applied to the repository's main\n * worktree, so every worktree of one repository shares it — and for a main\n * worktree it equals `workspaceId`.\n */\nexport const workspaceTargetSchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n /** Branch checked out in that worktree; absent on a detached HEAD. */\n vcsBranchName: nonEmptyStringSchema.optional(),\n source: targetSourceSchema,\n /** `git-root` handle of the repository's main worktree; absent when there is none to name. */\n repositoryId: workspaceIdSchema.optional(),\n worktreeKind: worktreeKindSchema.optional(),\n })\n .readonly();\nexport type WorkspaceTarget = z.infer<typeof workspaceTargetSchema>;\n\n/**\n * Shape a provider's own subagent identifier must have to be exported.\n *\n * Identifier-shaped on purpose — no whitespace, no path separators — so a\n * malformed payload field cannot carry prose or a path onto the wire under an id\n * attribute. A value that does not fit is dropped, not repaired.\n */\nexport const SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;\nexport const subagentIdSchema = z.string().regex(SUBAGENT_ID_PATTERN);\nexport type SubagentId = z.infer<typeof subagentIdSchema>;\n","import { z } from \"zod\";\n\nimport { tokenCountSchema } from \"./primitives.js\";\n\n/**\n * Whether an observation reports the change since the previous observation\n * (`delta`) or the running total for the session/generation (`cumulative`).\n *\n * The canonical model keeps temporality explicit rather than assuming one:\n * summing cumulative observations double-counts, and diffing delta observations\n * silently loses tokens.\n */\nexport const usageTemporalitySchema = z.enum([\"delta\", \"cumulative\"]);\nexport type UsageTemporality = z.infer<typeof usageTemporalitySchema>;\n\n/**\n * Whether the provider counts cache-creation tokens inside its input total or\n * reports them as a disjoint bucket.\n *\n * - `included-in-input`: `cacheCreationInputTokens` is a subset of `inputTokens`.\n * - `disjoint-from-input`: cache-creation tokens are billed in addition to\n * `inputTokens` and must be added when computing a total.\n * - `not-reported`: the provider exposes no cache-creation counter; the field is\n * pinned to zero.\n */\nexport const cacheCreationAccountingSchema = z.enum([\n \"included-in-input\",\n \"disjoint-from-input\",\n \"not-reported\",\n]);\nexport type CacheCreationAccounting = z.infer<typeof cacheCreationAccountingSchema>;\n\n/** Whether a provider-reported total agrees with the canonical computation. */\nexport const providerTotalAgreementSchema = z.enum([\"unreported\", \"agrees\", \"disagrees\"]);\nexport type ProviderTotalAgreement = z.infer<typeof providerTotalAgreementSchema>;\n\n/**\n * What an adapter reports, before normalization.\n *\n * `inputTokens` is *inclusive*: it counts every input token the provider\n * attributes to the call, including cache reads (and cache creation when the\n * provider folds it in). `outputTokens` is likewise inclusive of reasoning\n * output. Subset fields describe portions of those totals, never additions.\n */\nexport const usageReportSchema = z.strictObject({\n temporality: usageTemporalitySchema,\n /** Inclusive input tokens. */\n inputTokens: tokenCountSchema.optional(),\n /** Subset of `inputTokens` served from a prompt cache. */\n cachedInputTokens: tokenCountSchema.optional(),\n /** Tokens written to a prompt cache. */\n cacheCreationInputTokens: tokenCountSchema.optional(),\n /** Required when `cacheCreationInputTokens` is present and non-zero. */\n cacheCreationAccounting: cacheCreationAccountingSchema.optional(),\n /** Inclusive output tokens. */\n outputTokens: tokenCountSchema.optional(),\n /** Subset of `outputTokens` spent on reasoning. */\n reasoningOutputTokens: tokenCountSchema.optional(),\n /** Total exactly as the provider reported it, if it reported one. */\n providerTotalTokens: tokenCountSchema.optional(),\n});\nexport type UsageReport = z.infer<typeof usageReportSchema>;\n\n/**\n * Fully normalized usage.\n *\n * Derived fields (`uncachedInputTokens`, `totalTokens`,\n * `providerTotalAgreement`) are part of the schema and are re-checked on parse,\n * so an inconsistent object cannot exist. Construct values with\n * {@link normalizeUsage} rather than by hand.\n */\nexport const canonicalUsageSchema = z\n .strictObject({\n temporality: usageTemporalitySchema,\n inputTokens: tokenCountSchema,\n cachedInputTokens: tokenCountSchema,\n cacheCreationInputTokens: tokenCountSchema,\n cacheCreationAccounting: cacheCreationAccountingSchema,\n outputTokens: tokenCountSchema,\n reasoningOutputTokens: tokenCountSchema,\n /** Derived: input tokens that were neither cache reads nor cache writes. */\n uncachedInputTokens: tokenCountSchema,\n /** Derived: canonical billable total. */\n totalTokens: tokenCountSchema,\n providerTotalTokens: tokenCountSchema.optional(),\n providerTotalAgreement: providerTotalAgreementSchema,\n })\n .check((ctx) => {\n const usage = ctx.value;\n const push = (message: string): void => {\n ctx.issues.push({ code: \"custom\", input: usage, message });\n };\n\n if (usage.cachedInputTokens > usage.inputTokens) {\n push(\"cachedInputTokens must not exceed inputTokens (it is a subset)\");\n }\n if (usage.reasoningOutputTokens > usage.outputTokens) {\n push(\"reasoningOutputTokens must not exceed outputTokens (it is a subset)\");\n }\n if (usage.cacheCreationAccounting === \"not-reported\" && usage.cacheCreationInputTokens !== 0) {\n push(\"cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported\");\n }\n const creationInsideInput =\n usage.cacheCreationAccounting === \"included-in-input\" ? usage.cacheCreationInputTokens : 0;\n if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {\n push(\n \"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input\",\n );\n }\n const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;\n if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {\n push(`uncachedInputTokens must equal ${expectedUncached}`);\n }\n const creationOutsideInput =\n usage.cacheCreationAccounting === \"disjoint-from-input\" ? usage.cacheCreationInputTokens : 0;\n const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;\n if (usage.totalTokens !== expectedTotal) {\n push(`totalTokens must equal ${expectedTotal}`);\n }\n const expectedAgreement: ProviderTotalAgreement =\n usage.providerTotalTokens === undefined\n ? \"unreported\"\n : usage.providerTotalTokens === expectedTotal\n ? \"agrees\"\n : \"disagrees\";\n if (usage.providerTotalAgreement !== expectedAgreement) {\n push(`providerTotalAgreement must be ${expectedAgreement}`);\n }\n });\nexport type CanonicalUsage = z.infer<typeof canonicalUsageSchema>;\n\nexport type UsageNormalizationIssue = {\n readonly code:\n | \"invalid-report\"\n | \"cached-exceeds-input\"\n | \"reasoning-exceeds-output\"\n | \"cache-creation-exceeds-input\"\n | \"cache-creation-accounting-missing\";\n readonly message: string;\n};\n\nexport type UsageNormalizationResult =\n | { readonly status: \"ok\"; readonly usage: CanonicalUsage; readonly notes: readonly string[] }\n | { readonly status: \"invalid\"; readonly issues: readonly UsageNormalizationIssue[] };\n\n/**\n * Normalize a provider usage report into canonical usage.\n *\n * Deterministic rules:\n * 1. Absent counters default to `0`; `providerTotalTokens` stays absent.\n * 2. Non-integer, negative, or non-finite counters are rejected.\n * 3. A subset exceeding its total is rejected — never clamped — because\n * clamping would silently invent a billing story.\n * 4. `cacheCreationAccounting` defaults to `not-reported` when no cache-creation\n * tokens are reported, and is *required* when they are: guessing whether the\n * bucket is disjoint would mis-total every downstream cost calculation.\n * 5. A provider total that disagrees with the canonical total is preserved as\n * reported and flagged `disagrees`. Both numbers survive; neither is edited.\n */\nexport const normalizeUsage = (report: unknown): UsageNormalizationResult => {\n const parsed = usageReportSchema.safeParse(report);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map((issue) => ({\n code: \"invalid-report\" as const,\n message: `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n })),\n };\n }\n\n const input = parsed.data;\n const issues: UsageNormalizationIssue[] = [];\n const notes: string[] = [];\n\n const inputTokens = input.inputTokens ?? 0;\n const cachedInputTokens = input.cachedInputTokens ?? 0;\n const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;\n const outputTokens = input.outputTokens ?? 0;\n const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;\n\n let accounting: CacheCreationAccounting;\n if (cacheCreationInputTokens === 0) {\n accounting = input.cacheCreationAccounting ?? \"not-reported\";\n if (accounting !== \"not-reported\") {\n notes.push(\n `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`,\n );\n }\n } else if (input.cacheCreationAccounting === undefined) {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message:\n \"cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred\",\n });\n accounting = \"not-reported\";\n } else if (input.cacheCreationAccounting === \"not-reported\") {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message: \"cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens\",\n });\n accounting = \"not-reported\";\n } else {\n accounting = input.cacheCreationAccounting;\n }\n\n if (cachedInputTokens > inputTokens) {\n issues.push({\n code: \"cached-exceeds-input\",\n message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n if (reasoningOutputTokens > outputTokens) {\n issues.push({\n code: \"reasoning-exceeds-output\",\n message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`,\n });\n }\n\n const creationInsideInput = accounting === \"included-in-input\" ? cacheCreationInputTokens : 0;\n if (cachedInputTokens + creationInsideInput > inputTokens) {\n issues.push({\n code: \"cache-creation-exceeds-input\",\n message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const creationOutsideInput = accounting === \"disjoint-from-input\" ? cacheCreationInputTokens : 0;\n const totalTokens = inputTokens + creationOutsideInput + outputTokens;\n const providerTotalAgreement: ProviderTotalAgreement =\n input.providerTotalTokens === undefined\n ? \"unreported\"\n : input.providerTotalTokens === totalTokens\n ? \"agrees\"\n : \"disagrees\";\n\n if (providerTotalAgreement === \"disagrees\") {\n notes.push(\n `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`,\n );\n }\n\n const usage: CanonicalUsage = {\n temporality: input.temporality,\n inputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens,\n reasoningOutputTokens,\n uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,\n totalTokens,\n ...(input.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: input.providerTotalTokens }),\n providerTotalAgreement,\n };\n\n return { status: \"ok\", usage, notes };\n};\n\nexport class UsageNormalizationError extends Error {\n public readonly issues: readonly UsageNormalizationIssue[];\n\n public constructor(issues: readonly UsageNormalizationIssue[]) {\n super(`invalid usage report: ${issues.map((issue) => issue.message).join(\"; \")}`);\n this.name = \"UsageNormalizationError\";\n this.issues = issues;\n }\n}\n\n/** Convenience wrapper for call sites that treat invalid usage as a bug. */\nexport const normalizeUsageOrThrow = (report: unknown): CanonicalUsage => {\n const result = normalizeUsage(report);\n if (result.status === \"invalid\") {\n throw new UsageNormalizationError(result.issues);\n }\n return result.usage;\n};\n\nexport const EMPTY_DELTA_USAGE: CanonicalUsage = Object.freeze(\n normalizeUsageOrThrow({ temporality: \"delta\" }),\n);\n\nexport type UsageDeltaResult = {\n readonly usage: CanonicalUsage;\n /**\n * True when the current snapshot is smaller than the previous one on any\n * counter. That means the cumulative series restarted (new session, replayed\n * transcript, provider reset), so the current snapshot is emitted as the delta\n * instead of a negative difference.\n */\n readonly resetDetected: boolean;\n};\n\nconst requireCumulative = (usage: CanonicalUsage, label: string): void => {\n if (usage.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: `${label} must have cumulative temporality` },\n ]);\n }\n};\n\n/**\n * Convert two cumulative snapshots into a delta observation.\n *\n * Replay safety: re-processing the same snapshot yields an all-zero delta, and a\n * decreasing series is reported as a reset rather than a negative delta.\n * Accounting mode must match; mixing modes would make the subtraction meaningless.\n */\nexport const cumulativeToDelta = (\n previous: CanonicalUsage,\n current: CanonicalUsage,\n): UsageDeltaResult => {\n requireCumulative(previous, \"previous usage\");\n requireCumulative(current, \"current usage\");\n\n if (\n previous.cacheCreationAccounting !== current.cacheCreationAccounting &&\n previous.cacheCreationInputTokens !== 0 &&\n current.cacheCreationInputTokens !== 0\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot diff cumulative usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const resetDetected =\n current.inputTokens < previous.inputTokens ||\n current.cachedInputTokens < previous.cachedInputTokens ||\n current.cacheCreationInputTokens < previous.cacheCreationInputTokens ||\n current.outputTokens < previous.outputTokens ||\n current.reasoningOutputTokens < previous.reasoningOutputTokens;\n\n if (resetDetected) {\n return {\n usage: normalizeUsageOrThrow({ ...toReport(current), temporality: \"delta\" }),\n resetDetected: true,\n };\n }\n\n const usage = normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: current.inputTokens - previous.inputTokens,\n cachedInputTokens: current.cachedInputTokens - previous.cachedInputTokens,\n cacheCreationInputTokens:\n current.cacheCreationInputTokens - previous.cacheCreationInputTokens,\n cacheCreationAccounting: current.cacheCreationAccounting,\n outputTokens: current.outputTokens - previous.outputTokens,\n reasoningOutputTokens: current.reasoningOutputTokens - previous.reasoningOutputTokens,\n });\n\n return { usage, resetDetected: false };\n};\n\n/** Project canonical usage back onto the reported shape. */\nexport const toReport = (usage: CanonicalUsage): UsageReport => ({\n temporality: usage.temporality,\n inputTokens: usage.inputTokens,\n cachedInputTokens: usage.cachedInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n cacheCreationAccounting: usage.cacheCreationAccounting,\n outputTokens: usage.outputTokens,\n reasoningOutputTokens: usage.reasoningOutputTokens,\n ...(usage.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: usage.providerTotalTokens }),\n});\n\n/**\n * Add two delta observations. Cumulative usage is never summed, because two\n * running totals do not compose.\n */\nexport const addUsage = (a: CanonicalUsage, b: CanonicalUsage): CanonicalUsage => {\n if (a.temporality !== \"delta\" || b.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"only delta usage may be summed\" },\n ]);\n }\n const accounting =\n a.cacheCreationInputTokens === 0 && a.cacheCreationAccounting === \"not-reported\"\n ? b.cacheCreationAccounting\n : b.cacheCreationInputTokens === 0 && b.cacheCreationAccounting === \"not-reported\"\n ? a.cacheCreationAccounting\n : a.cacheCreationAccounting;\n\n if (\n a.cacheCreationInputTokens !== 0 &&\n b.cacheCreationInputTokens !== 0 &&\n a.cacheCreationAccounting !== b.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot sum usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n a.providerTotalTokens === undefined && b.providerTotalTokens === undefined\n ? undefined\n : (a.providerTotalTokens ?? 0) + (b.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: a.inputTokens + b.inputTokens,\n cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,\n cacheCreationInputTokens: a.cacheCreationInputTokens + b.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: a.outputTokens + b.outputTokens,\n reasoningOutputTokens: a.reasoningOutputTokens + b.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n","import { z } from \"zod\";\n\n/**\n * Version of the canonical event model.\n *\n * Every emitted event carries this value. Consumers must treat an unknown\n * version as unreadable rather than guessing field semantics.\n *\n * Compatibility rules:\n * - Additive optional fields do not change the version.\n * - Renaming, removing, or re-interpreting a field increments the version.\n */\nexport const CANONICAL_SCHEMA_VERSION = 1 as const;\n\nexport type CanonicalSchemaVersion = typeof CANONICAL_SCHEMA_VERSION;\n\nexport const canonicalSchemaVersionSchema = z.literal(CANONICAL_SCHEMA_VERSION);\n","import type { Clock, StateRecord, StateValue } from \"../runtime/ports.js\";\nimport { stateRecordSchema } from \"../runtime/ports.js\";\nimport { createAsyncLock } from \"./async-lock.js\";\nimport type { LockingStateStore } from \"./store.js\";\n\nexport type BoundedMemoryStateStoreOptions = {\n readonly clock: Clock;\n /** Oldest entry is evicted once this many keys are held. Default 10,000. */\n readonly maxEntries?: number;\n /** When set, a record older than this is treated as absent and dropped lazily. */\n readonly ttlMillis?: number;\n /** Bounds how long a `withSessionLock` call waits before rejecting. Default 5,000ms. */\n readonly lockTimeoutMillis?: number;\n};\n\nexport interface BoundedMemoryStateStore extends LockingStateStore {\n size(): number;\n /** Actively removes expired entries; returns the count removed. */\n pruneExpired(now?: number): number;\n}\n\n/**\n * Production in-memory {@link StateStore}.\n *\n * Unlike the unbounded test double in `runtime/memory.ts`, this store is\n * meant to back a long-lived host process: it bounds its own size and can\n * expire entries by age, so a process that embeds many sessions over its\n * lifetime cannot grow without limit. State does not survive a process\n * restart; hosts that need it to should use the filesystem store instead.\n */\nexport const createBoundedMemoryStateStore = (\n options: BoundedMemoryStateStoreOptions,\n): BoundedMemoryStateStore => {\n const records = new Map<string, StateRecord>();\n const keyLock = createAsyncLock();\n const sessionLock = createAsyncLock();\n const maxEntries = options.maxEntries ?? 10_000;\n const lockTimeoutMillis = options.lockTimeoutMillis ?? 5_000;\n\n const isExpired = (record: StateRecord, now: number): boolean =>\n options.ttlMillis !== undefined && now - record.updatedAt > options.ttlMillis;\n\n const evictOldestIfOverCapacity = (): void => {\n while (records.size > maxEntries) {\n let oldestKey: string | undefined;\n let oldestAt = Number.POSITIVE_INFINITY;\n for (const [key, record] of records) {\n if (record.updatedAt < oldestAt) {\n oldestAt = record.updatedAt;\n oldestKey = key;\n }\n }\n if (oldestKey === undefined) {\n break;\n }\n records.delete(oldestKey);\n }\n };\n\n return {\n read: (key: string): Promise<StateRecord | undefined> =>\n keyLock.run(key, (): Promise<StateRecord | undefined> => {\n const record = records.get(key);\n if (record === undefined) {\n return Promise.resolve(undefined);\n }\n if (isExpired(record, options.clock.now())) {\n records.delete(key);\n return Promise.resolve(undefined);\n }\n return Promise.resolve(record);\n }),\n write: (key: string, value: StateValue): Promise<StateRecord> =>\n keyLock.run(key, (): Promise<StateRecord> => {\n const previous = records.get(key);\n const record = stateRecordSchema.parse({\n revision: (previous?.revision ?? 0) + 1,\n updatedAt: options.clock.now(),\n value,\n });\n records.set(key, record);\n evictOldestIfOverCapacity();\n return Promise.resolve(record);\n }),\n delete: (key: string): Promise<void> =>\n keyLock.run(key, (): Promise<void> => {\n records.delete(key);\n return Promise.resolve();\n }),\n keys: (prefix: string): Promise<readonly string[]> =>\n Promise.resolve([...records.keys()].filter((key) => key.startsWith(prefix)).sort()),\n withSessionLock: <T>(\n sessionId: string,\n fn: () => Promise<T>,\n lockOptions?: { readonly timeoutMillis?: number },\n ): Promise<T> => sessionLock.run(sessionId, fn, lockOptions?.timeoutMillis ?? lockTimeoutMillis),\n size: (): number => records.size,\n pruneExpired: (now?: number): number => {\n const cutoff = now ?? options.clock.now();\n let removed = 0;\n for (const [key, record] of records) {\n if (isExpired(record, cutoff)) {\n records.delete(key);\n removed += 1;\n }\n }\n return removed;\n },\n };\n};\n","import { randomBytes } from \"node:crypto\";\nimport { mkdir, open, readFile, readdir, rename, stat, unlink, writeFile } from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport type { Clock, Logger, StateRecord, StateValue } from \"../runtime/ports.js\";\nimport { stateRecordSchema } from \"../runtime/ports.js\";\nimport { createAsyncLock } from \"./async-lock.js\";\nimport { keyDigest, namespaceSegments, sanitizeSegment, type StoreNamespace } from \"./keys.js\";\nimport { StateLockTimeoutError, type LockingStateStore } from \"./store.js\";\n\nexport type FilesystemStateStoreOptions = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Bounds how long a write, read, or session lock waits. Default 5,000ms. */\n readonly lockTimeoutMillis?: number;\n /** A lock file older than this is assumed to belong to a crashed process and is reclaimed. Default 30,000ms. */\n readonly lockStaleMillis?: number;\n /** Delay between lock acquisition attempts. Default 25ms. */\n readonly lockPollIntervalMillis?: number;\n};\n\nexport interface FilesystemStateStore extends LockingStateStore {\n readonly recordsDir: string;\n readonly quarantineDir: string;\n /** Bounded sweep: removes records untouched for longer than `maxAgeMillis`. */\n pruneStale(\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number },\n ): Promise<{ readonly removed: number; readonly scanned: number }>;\n}\n\ntype Envelope = { readonly key: string; readonly record: StateRecord };\n\nconst isErrnoException = (thrown: unknown, code: string): boolean =>\n thrown instanceof Error && (thrown as NodeJS.ErrnoException).code === code;\n\n/**\n * Deliberately *not* `unref`'d (see `src/install/file-lock.ts`). A hook process\n * waiting for a session lock a peer holds has nothing else on its event loop: an\n * unref'd poll timer lets Node exit mid-wait (\"unsettled top-level await\") and\n * the waiting event is lost. Seen live when Claude Code fired `SubagentStart`\n * and `PostToolUse` for the same session at once.\n */\nconst sleep = (millis: number): Promise<void> =>\n new Promise((resolve) => {\n setTimeout(resolve, millis);\n });\n\nconst wrapFsError = (thrown: unknown, operation: string): Error => {\n if (thrown instanceof Error) {\n return new Error(`filesystem state store ${operation} failed: ${thrown.name}`, { cause: thrown });\n }\n return new Error(`filesystem state store ${operation} failed`);\n};\n\n/**\n * Crash-safe filesystem {@link StateStore}.\n *\n * Every write lands via a temp file plus `rename`, which POSIX guarantees is\n * atomic within one directory: a reader never observes a half-written record,\n * and a process killed mid-write leaves only an orphaned temp file, never a\n * corrupt one. A record that still fails to parse (disk corruption, a manual\n * edit, a future incompatible version) is quarantined rather than thrown from\n * `read`, so a single bad file degrades one key instead of the whole store.\n *\n * Locking is layered: an in-process {@link createAsyncLock} orders same-process\n * callers, and a lock file with a staleness timeout orders across processes\n * and recovers automatically if the holder crashed while holding it.\n */\nexport const createFilesystemStateStore = (\n options: FilesystemStateStoreOptions,\n): FilesystemStateStore => {\n const [providerSegment, installationSegment] = namespaceSegments(options);\n const baseDir = path.join(options.rootDir, providerSegment, installationSegment);\n const recordsDir = path.join(baseDir, \"records\");\n const quarantineDir = path.join(baseDir, \"quarantine\");\n const locksDir = path.join(baseDir, \"locks\");\n\n const lockTimeoutMillis = options.lockTimeoutMillis ?? 5_000;\n const lockStaleMillis = options.lockStaleMillis ?? 30_000;\n const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;\n\n const keyLock = createAsyncLock();\n const sessionLock = createAsyncLock();\n\n let dirsReady: Promise<void> | undefined;\n const ensureDirs = async (): Promise<void> => {\n if (dirsReady !== undefined) {\n return dirsReady;\n }\n const promise = (async (): Promise<void> => {\n await mkdir(recordsDir, { recursive: true });\n await mkdir(quarantineDir, { recursive: true });\n await mkdir(locksDir, { recursive: true });\n })();\n dirsReady = promise;\n try {\n await promise;\n } catch (thrown) {\n dirsReady = undefined;\n throw wrapFsError(thrown, \"ensure-dirs\");\n }\n };\n\n const recordPath = (key: string): string => path.join(recordsDir, `${keyDigest(key)}.json`);\n const tempPath = (key: string): string =>\n path.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes(6).toString(\"hex\")}.json`);\n const lockPath = (sessionId: string): string =>\n path.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);\n\n const quarantine = async (filePath: string, key: string, reason: string): Promise<void> => {\n const dest = path.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);\n try {\n await rename(filePath, dest);\n } catch {\n await unlink(filePath).catch(() => undefined);\n }\n options.logger?.warn(\"filesystem state record quarantined\", { \"state.reason\": reason });\n };\n\n const readUnlocked = async (key: string): Promise<StateRecord | undefined> => {\n await ensureDirs();\n const filePath = recordPath(key);\n let raw: string;\n try {\n raw = await readFile(filePath, \"utf8\");\n } catch (thrown) {\n if (isErrnoException(thrown, \"ENOENT\")) {\n return undefined;\n }\n throw wrapFsError(thrown, \"read\");\n }\n\n let parsedJson: unknown;\n try {\n parsedJson = JSON.parse(raw);\n } catch {\n await quarantine(filePath, key, \"invalid-json\");\n return undefined;\n }\n\n const envelope = parsedJson as Partial<Envelope>;\n if (envelope.key !== key) {\n await quarantine(filePath, key, \"key-mismatch\");\n return undefined;\n }\n const parsed = stateRecordSchema.safeParse(envelope.record);\n if (!parsed.success) {\n await quarantine(filePath, key, \"schema-invalid\");\n return undefined;\n }\n return parsed.data;\n };\n\n const writeUnlocked = async (key: string, value: StateValue): Promise<StateRecord> => {\n await ensureDirs();\n const previous = await readUnlocked(key);\n const record = stateRecordSchema.parse({\n revision: (previous?.revision ?? 0) + 1,\n updatedAt: options.clock.now(),\n value,\n });\n const envelope: Envelope = { key, record };\n const tmp = tempPath(key);\n try {\n await writeFile(tmp, JSON.stringify(envelope), \"utf8\");\n await rename(tmp, recordPath(key));\n } catch (thrown) {\n await unlink(tmp).catch(() => undefined);\n throw wrapFsError(thrown, \"write\");\n }\n return record;\n };\n\n const acquireFileLock = async (\n sessionId: string,\n timeoutMillis: number,\n ): Promise<() => Promise<void>> => {\n await ensureDirs();\n const filePath = lockPath(sessionId);\n const startedAt = options.clock.monotonicMillis();\n\n for (;;) {\n try {\n const handle = await open(filePath, \"wx\");\n try {\n await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));\n } finally {\n await handle.close();\n }\n return async (): Promise<void> => {\n await unlink(filePath).catch(() => undefined);\n };\n } catch (thrown) {\n if (!isErrnoException(thrown, \"EEXIST\")) {\n throw wrapFsError(thrown, \"lock\");\n }\n }\n\n const stale = await (async (): Promise<boolean | \"gone\"> => {\n let raw: string;\n try {\n raw = await readFile(filePath, \"utf8\");\n } catch (thrown) {\n // Released between our `open` and this read: just try again.\n return isErrnoException(thrown, \"ENOENT\") ? \"gone\" : true;\n }\n try {\n const parsed = JSON.parse(raw) as { acquiredAt?: unknown };\n if (typeof parsed.acquiredAt === \"number\") {\n return options.clock.now() - parsed.acquiredAt > lockStaleMillis;\n }\n } catch {\n // fall through to the file's age\n }\n // Empty or partial: a peer created the file (`wx`) and has not written its\n // stamp yet. Reclaiming it now would put two holders in the lock, so an\n // unreadable lock is only stale once the file itself is old.\n try {\n const stats = await stat(filePath);\n return Date.now() - stats.mtimeMs > lockStaleMillis;\n } catch {\n return \"gone\";\n }\n })();\n if (stale === \"gone\") {\n continue;\n }\n if (stale) {\n await unlink(filePath).catch(() => undefined);\n continue;\n }\n\n if (options.clock.monotonicMillis() - startedAt >= timeoutMillis) {\n // A typed error, so a caller can tell \"a peer holds this\" apart from \"the\n // store is unusable\" — the two demand opposite responses.\n throw new StateLockTimeoutError(sessionId, timeoutMillis);\n }\n await sleep(lockPollIntervalMillis);\n }\n };\n\n return {\n recordsDir,\n quarantineDir,\n read: (key: string): Promise<StateRecord | undefined> =>\n keyLock.run(key, () => readUnlocked(key), lockTimeoutMillis),\n write: (key: string, value: StateValue): Promise<StateRecord> =>\n keyLock.run(key, () => writeUnlocked(key, value), lockTimeoutMillis),\n delete: (key: string): Promise<void> =>\n keyLock.run(\n key,\n async (): Promise<void> => {\n await ensureDirs();\n await unlink(recordPath(key)).catch((thrown: unknown) => {\n if (!isErrnoException(thrown, \"ENOENT\")) {\n throw wrapFsError(thrown, \"delete\");\n }\n });\n },\n lockTimeoutMillis,\n ),\n keys: async (prefix: string): Promise<readonly string[]> => {\n await ensureDirs();\n let entries: string[];\n try {\n entries = await readdir(recordsDir);\n } catch (thrown) {\n if (isErrnoException(thrown, \"ENOENT\")) {\n return [];\n }\n throw wrapFsError(thrown, \"keys\");\n }\n const found: string[] = [];\n for (const entry of entries) {\n if (!entry.endsWith(\".json\") || entry.startsWith(\".tmp-\")) {\n continue;\n }\n let raw: string;\n try {\n raw = await readFile(path.join(recordsDir, entry), \"utf8\");\n } catch {\n continue;\n }\n try {\n const envelope = JSON.parse(raw) as Partial<Envelope>;\n if (typeof envelope.key === \"string\" && envelope.key.startsWith(prefix)) {\n found.push(envelope.key);\n }\n } catch {\n continue;\n }\n }\n return found.sort();\n },\n withSessionLock: async <T>(\n sessionId: string,\n fn: () => Promise<T>,\n lockOptions?: { readonly timeoutMillis?: number },\n ): Promise<T> => {\n const timeoutMillis = lockOptions?.timeoutMillis ?? lockTimeoutMillis;\n return sessionLock.run(\n sessionId,\n async (): Promise<T> => {\n const release = await acquireFileLock(sessionId, timeoutMillis);\n try {\n return await fn();\n } finally {\n await release();\n }\n },\n timeoutMillis,\n );\n },\n pruneStale: async (\n maxAgeMillis: number,\n pruneOptions?: { readonly maxEntries?: number },\n ): Promise<{ readonly removed: number; readonly scanned: number }> => {\n await ensureDirs();\n const cap = pruneOptions?.maxEntries ?? 5_000;\n const now = options.clock.now();\n let removed = 0;\n let scanned = 0;\n\n let entries: string[];\n try {\n entries = await readdir(recordsDir);\n } catch (thrown) {\n if (!isErrnoException(thrown, \"ENOENT\")) {\n throw wrapFsError(thrown, \"prune\");\n }\n entries = [];\n }\n for (const entry of entries) {\n if (scanned >= cap) {\n break;\n }\n if (!entry.endsWith(\".json\") || entry.startsWith(\".tmp-\")) {\n continue;\n }\n scanned += 1;\n const filePath = path.join(recordsDir, entry);\n try {\n // Ages are measured against the record's own `updatedAt`, taken from\n // the injected clock at write time, never the OS mtime: a test (or a\n // host) using a clock other than the wall clock would otherwise be\n // compared against a completely unrelated time source.\n const raw = await readFile(filePath, \"utf8\");\n const envelope = JSON.parse(raw) as Partial<Envelope>;\n const updatedAt = envelope.record?.updatedAt;\n if (typeof updatedAt === \"number\" && now - updatedAt > maxAgeMillis) {\n await unlink(filePath).catch(() => undefined);\n removed += 1;\n }\n } catch {\n continue;\n }\n }\n\n let lockEntries: string[];\n try {\n lockEntries = await readdir(locksDir);\n } catch {\n lockEntries = [];\n }\n for (const entry of lockEntries) {\n const filePath = path.join(locksDir, entry);\n try {\n const raw = await readFile(filePath, \"utf8\");\n const parsed = JSON.parse(raw) as { acquiredAt?: unknown };\n if (typeof parsed.acquiredAt === \"number\" && now - parsed.acquiredAt > lockStaleMillis) {\n await unlink(filePath).catch(() => undefined);\n }\n } catch {\n continue;\n }\n }\n\n return { removed, scanned };\n },\n };\n};\n","import { createHash } from \"node:crypto\";\n\n/**\n * Segments derived from arbitrary strings must be safe path components on any\n * filesystem: no separators, no traversal, no reserved characters. Anything\n * that already looks safe is kept as-is (for readable directory names);\n * anything else is replaced by a stable hash so no input can escape its\n * namespace directory or collide with a sibling by accident.\n */\nconst SAFE_SEGMENT_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;\n\nexport const isSafeSegment = (segment: string): boolean => SAFE_SEGMENT_PATTERN.test(segment);\n\nexport const sanitizeSegment = (segment: string): string => {\n if (isSafeSegment(segment)) {\n return segment;\n }\n return `h_${createHash(\"sha256\").update(segment, \"utf8\").digest(\"hex\").slice(0, 32)}`;\n};\n\n/** Scopes a state store to one provider deployed under one installation. */\nexport type StoreNamespace = {\n readonly providerId: string;\n readonly installationId: string;\n};\n\nexport const namespaceSegments = (namespace: StoreNamespace): readonly [string, string] => [\n sanitizeSegment(namespace.providerId),\n sanitizeSegment(namespace.installationId),\n];\n\n/** Stable, collision-resistant digest of a logical state key. */\nexport const keyDigest = (key: string): string =>\n createHash(\"sha256\").update(key, \"utf8\").digest(\"hex\");\n"],"mappings":";AAmCO,IAAM,uBAAN,cAAmC,MAAM;AAAA,EAC9B;AAAA,EAET,YAAY,KAAa,eAAuB;AACrD,UAAM,sBAAsB,aAAa,IAAI;AAC7C,SAAK,OAAO;AACZ,SAAK,UAAU;AAAA,EACjB;AACF;AAEO,IAAM,kBAAkB,MAAiB;AAC9C,QAAM,OAAO,oBAAI,IAA2B;AAE5C,QAAM,MAAM,OAAU,KAAa,IAAsB,kBAAuC;AAC9F,UAAM,WAAW,KAAK,IAAI,GAAG,KAAK,QAAQ,QAAQ;AAClD,UAAM,SAAS,SAAS;AAAA,MACtB,MAAM;AAAA,MACN,MAAM;AAAA,IACR;AAYA,QAAI,YAAY;AAChB,QAAI,UAAU;AAEd,UAAM,UAAU,OAAO,KAAK,MAAsB;AAChD,UAAI,WAAW;AAGb,cAAM,IAAI,qBAAqB,KAAK,iBAAiB,CAAC;AAAA,MACxD;AACA,gBAAU;AACV,aAAO,GAAG;AAAA,IACZ,CAAC;AAED,UAAM,YAAY,QAAQ;AAAA,MACxB,MAAM;AAAA,MACN,MAAM;AAAA,IACR;AACA,SAAK,IAAI,KAAK,SAAS;AACvB,SAAK,UAAU,KAAK,MAAM;AACxB,UAAI,KAAK,IAAI,GAAG,MAAM,WAAW;AAC/B,aAAK,OAAO,GAAG;AAAA,MACjB;AAAA,IACF,CAAC;AAED,QAAI,kBAAkB,QAAW;AAC/B,aAAO;AAAA,IACT;AAEA,QAAI;AACJ,UAAM,UAAU,IAAI,QAAe,CAAC,UAAU,WAAW;AACvD,cAAQ,WAAW,MAAM;AACvB,YAAI,CAAC,SAAS;AACZ,sBAAY;AAAA,QACd;AACA,eAAO,IAAI,qBAAqB,KAAK,aAAa,CAAC;AAAA,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5C,YAAI;AAKF,gBAAM,MAAM,MAAM,SAAS,UAAU,MAAM;AAC3C,gBAAM,WAAW,KAAK,MAAM,GAAG;AAC/B,gBAAM,YAAY,SAAS,QAAQ;AACnC,cAAI,OAAO,cAAc,YAAY,MAAM,YAAY,cAAc;AACnE,kBAAM,OAAO,QAAQ,EAAE,MAAM,MAAM,MAAS;AAC5C,uBAAW;AAAA,UACb;AAAA,QACF,QAAQ;AACN;AAAA,QACF;AAAA,MACF;AAEA,UAAI;AACJ,UAAI;AACF,sBAAc,MAAM,QAAQ,QAAQ;AAAA,MACtC,QAAQ;AACN,sBAAc,CAAC;AAAA,MACjB;AACA,iBAAW,SAAS,aAAa;AAC/B,cAAM,WAAgB,UAAK,UAAU,KAAK;AAC1C,YAAI;AACF,gBAAM,MAAM,MAAM,SAAS,UAAU,MAAM;AAC3C,gBAAM,SAAS,KAAK,MAAM,GAAG;AAC7B,cAAI,OAAO,OAAO,eAAe,YAAY,MAAM,OAAO,aAAa,iBAAiB;AACtF,kBAAM,OAAO,QAAQ,EAAE,MAAM,MAAM,MAAS;AAAA,UAC9C;AAAA,QACF,QAAQ;AACN;AAAA,QACF;AAAA,MACF;AAEA,aAAO,EAAE,SAAS,QAAQ;AAAA,IAC5B;AAAA,EACF;AACF;","names":["z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z"]}
|
|
1
|
+
{"version":3,"sources":["../src/state/async-lock.ts","../src/state/store.ts","../src/runtime/ports.ts","../src/model/events.ts","../src/errors/taxonomy.ts","../src/model/content.ts","../src/model/primitives.ts","../src/model/extensions.ts","../src/model/identity.ts","../src/model/target.ts","../src/model/usage.ts","../src/model/version.ts","../src/state/memory-store.ts","../src/state/filesystem-store.ts","../src/state/keys.ts"],"sourcesContent":["/**\n * Per-key async mutex.\n *\n * Ordinary promises already serialize a single caller's `await`s, but two\n * concurrent callers racing a read-modify-write against the same key (two\n * hook invocations updating the same session, in the same process) are not\n * serialized by anything. This chains each key's operations through a promise\n * tail so they run one at a time, in arrival order, without blocking unrelated\n * keys.\n */\nexport interface AsyncLock {\n /**\n * `timeoutMillis` bounds how long the caller waits to *acquire* the key.\n *\n * Two guarantees, and the boundary between them is the whole contract:\n *\n * - **A timed-out caller's `fn` never runs.** Giving up on the wait cancels the\n * queued operation. It has to: a caller that has been told \"I could not take\n * the lock\" will report contention and move on, and if `fn` then ran anyway it\n * would mutate state after the caller had already declared that nothing\n * happened. That is worse than either outcome on its own — the state changes\n * and nobody is watching.\n * - **Work is never cancelled after acquisition.** Once `fn` has started the\n * timeout is irrelevant; interrupting a read-modify-write partway through is\n * exactly the corruption a mutex exists to prevent. So the timeout bounds\n * *waiting*, never *exclusivity* and never *completion*.\n *\n * Cancellation does not let a waiter skip the queue: the cancelled slot still\n * settles in order, so everyone behind it keeps its place. A cancelled call\n * rejects with {@link LockWaitTimeoutError}, the same error a timed-out wait\n * produces, because from the caller's side they are one condition.\n */\n run<T>(key: string, fn: () => Promise<T>, timeoutMillis?: number): Promise<T>;\n}\n\nexport class LockWaitTimeoutError extends Error {\n public readonly lockKey: string;\n\n public constructor(key: string, timeoutMillis: number) {\n super(`lock wait exceeded ${timeoutMillis}ms`);\n this.name = \"LockWaitTimeoutError\";\n this.lockKey = key;\n }\n}\n\nexport const createAsyncLock = (): AsyncLock => {\n const tail = new Map<string, Promise<void>>();\n\n const run = async <T>(key: string, fn: () => Promise<T>, timeoutMillis?: number): Promise<T> => {\n const previous = tail.get(key) ?? Promise.resolve();\n const queued = previous.then(\n () => undefined,\n () => undefined,\n );\n\n /**\n * `entered` flips synchronously, immediately before `fn` is invoked, and\n * `cancelled` is only ever set from the timer while `entered` is false.\n *\n * That ordering is what makes the two guarantees exclusive rather than racy.\n * Microtasks drain before timers, so if this slot's turn has arrived at all,\n * the callback below has already run and set `entered` before any timer\n * callback can observe it — there is no window in which the timer sees a\n * not-yet-entered slot that is in fact about to run.\n */\n let cancelled = false;\n let entered = false;\n\n const current = queued.then((): T | Promise<T> => {\n if (cancelled) {\n // The waiter gave up before its turn came, so `fn` is skipped entirely.\n // The slot still settles here, in order, so nothing behind it is reordered.\n throw new LockWaitTimeoutError(key, timeoutMillis ?? 0);\n }\n entered = true;\n return fn();\n });\n\n const swallowed = current.then(\n () => undefined,\n () => undefined,\n );\n tail.set(key, swallowed);\n void swallowed.then(() => {\n if (tail.get(key) === swallowed) {\n tail.delete(key);\n }\n });\n\n if (timeoutMillis === undefined) {\n return current;\n }\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n if (!entered) {\n cancelled = true;\n }\n reject(new LockWaitTimeoutError(key, timeoutMillis));\n }, timeoutMillis);\n timer.unref?.();\n });\n try {\n // Raced against the queue gate, not against `current`: once the slot is\n // entered the caller waits for `fn` however long it takes.\n await Promise.race([queued, timeout]);\n } finally {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n }\n return current;\n };\n\n return { run };\n};\n","import type { Clock, StateStore } from \"../runtime/ports.js\";\nimport { LockWaitTimeoutError } from \"./async-lock.js\";\n\n/**\n * A lock could not be acquired within its wait bound because somebody else holds\n * it.\n *\n * Distinct from \"the store is broken\" on purpose, and the distinction is\n * load-bearing for callers that guard a read-modify-write with it. Contention\n * means a peer is plausibly *inside* the critical section right now, so\n * proceeding unlocked would produce exactly the lost update the lock exists to\n * prevent. A store that cannot lock at all — an unwritable directory, a full\n * disk — protects nothing, because the state the lock guards is equally\n * unreachable; there proceeding is the fail-open answer and costs nothing.\n */\nexport class StateLockTimeoutError extends Error {\n public readonly lockKey: string;\n\n public constructor(key: string, timeoutMillis: number) {\n super(`state store lock wait for \"${key}\" exceeded ${String(timeoutMillis)}ms`);\n this.name = \"StateLockTimeoutError\";\n this.lockKey = key;\n }\n}\n\n/**\n * Whether a thrown value means \"somebody else holds the lock\".\n *\n * Also true for {@link LockWaitTimeoutError}, the in-process variant, which\n * carries a second warning for callers: a timed-out wait does not cancel the\n * queued critical section, so it may still run afterwards. A caller that treats\n * contention as \"retry unlocked\" would therefore risk running the section twice.\n */\nexport const isStateLockContention = (thrown: unknown): boolean =>\n thrown instanceof StateLockTimeoutError || thrown instanceof LockWaitTimeoutError;\n\n/**\n * Optional capability beyond the frozen {@link StateStore} contract: a\n * session-scoped lock a caller can use to make a multi-step read-modify-write\n * atomic across an entire session, not just a single key.\n *\n * Deliberately keyed by an explicit `sessionId` the caller already knows,\n * rather than derived by parsing the store's own keys, so a store never has\n * to understand any particular key scheme.\n */\nexport interface LockingStateStore extends StateStore {\n withSessionLock<T>(\n sessionId: string,\n fn: () => Promise<T>,\n options?: { readonly timeoutMillis?: number },\n ): Promise<T>;\n}\n\nexport const isLockingStateStore = (store: StateStore): store is LockingStateStore =>\n typeof (store as Partial<LockingStateStore>).withSessionLock === \"function\";\n\n/** Runs `fn` under the store's session lock when it has one; otherwise runs it directly. */\nexport const withOptionalSessionLock = async <T>(\n store: StateStore,\n sessionId: string,\n fn: () => Promise<T>,\n options?: { readonly timeoutMillis?: number },\n): Promise<T> => {\n if (isLockingStateStore(store)) {\n return store.withSessionLock(sessionId, fn, options);\n }\n return fn();\n};\n\nexport type StateStoreDependencies = {\n readonly clock: Clock;\n};\n","import { z } from \"zod\";\n\nimport type { OtelHookErrorInfo } from \"../errors/index.js\";\nimport { modelDescriptorSchema, type CanonicalEvent } from \"../model/events.js\";\nimport {\n attributesSchema,\n epochMillisSchema,\n sequenceNumberSchema,\n type Attributes,\n type EpochMillis,\n type EventId,\n type InvocationId,\n} from \"../model/primitives.js\";\nimport type { WorktreeKind } from \"../model/target.js\";\nimport { canonicalUsageSchema } from \"../model/usage.js\";\n\n/**\n * Time source.\n *\n * Injected rather than read from `Date.now()` so tests are deterministic and so\n * a host with its own time authority can supply it.\n */\nexport interface Clock {\n /** Wall-clock time in whole milliseconds since the Unix epoch. */\n now(): EpochMillis;\n /** Monotonic reading for durations; unrelated to wall clock. */\n monotonicMillis(): number;\n}\n\n/** Stable inputs from which an invocation id is derived. */\nexport type InvocationIdSeed = {\n readonly providerId: string;\n readonly sessionId: string;\n readonly sourceEventName?: string;\n readonly occurredAt: number;\n /** Provider-supplied uniqueness, e.g. a request id. */\n readonly discriminator?: string;\n};\n\n/** Stable inputs from which an event id is derived. */\nexport type EventIdSeed = {\n readonly invocationId: string;\n readonly sequence: number;\n readonly eventType: string;\n readonly discriminator?: string;\n};\n\n/**\n * Identifier factory.\n *\n * Seeds are structured rather than free-form so the default implementation can\n * be a pure function of its inputs: replaying the same source data produces the\n * same ids, which lets a collector dedupe instead of double-counting.\n */\nexport interface IdGenerator {\n newInvocationId(seed: InvocationIdSeed): InvocationId;\n newEventId(seed: EventIdSeed): EventId;\n /** Short opaque id for spans and generations, derived from its parts. */\n newOpaqueId(parts: readonly string[]): string;\n}\n\n/**\n * Which delivery's observations are already folded into a stored total.\n *\n * The reason this rides *inside* the total's own record rather than beside it: the\n * store has no multi-key transaction, so a marker in a second key could be written\n * without the total or the other way round, and a marker that can disagree with\n * what it describes is worse than none. In one record the two move together under a\n * single write, which is what makes re-applying a redelivered callback's usage a\n * no-op instead of a double count.\n *\n * `callbackId` is an opaque digest supplied by the caller, never a host's raw\n * delivery id: a state record is somewhere a raw provider or host identifier must\n * not appear as a side effect of deduplicating on it.\n */\nexport const appliedDeliverySchema = z.strictObject({\n callbackId: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/),\n /** How many of that delivery's observations are folded in, counted from one. */\n applications: z.number().int().min(1).max(4_096),\n});\nexport type AppliedDelivery = z.infer<typeof appliedDeliverySchema>;\n\n/** Values the state store may hold. Restricted so state stays inspectable. */\nexport const stateValueSchema = z.discriminatedUnion(\"kind\", [\n z.strictObject({\n kind: z.literal(\"usage-cumulative\"),\n usage: canonicalUsageSchema,\n /**\n * Optional: absent on every record written before this field existed, which\n * reads as \"unknown provenance\" and simply forgoes the idempotency check\n * rather than resetting a baseline to gain it.\n */\n appliedDelivery: appliedDeliverySchema.optional(),\n }),\n z.strictObject({\n kind: z.literal(\"sequence\"),\n next: sequenceNumberSchema,\n }),\n z.strictObject({\n kind: z.literal(\"attributes\"),\n attributes: attributesSchema,\n }),\n /**\n * The model a session last reported, so a later invocation whose payload names\n * none (Claude Code's `Stop`) can still say which model it was. A model id is\n * not sensitive (`modelDescriptorSchema`), and the descriptor is the strict,\n * bounded canonical shape, never a payload fragment.\n */\n z.strictObject({\n kind: z.literal(\"session-model\"),\n model: modelDescriptorSchema,\n }),\n /**\n * How far a {@link PayloadEnricher} has read a session's append-only source\n * (Claude Code's transcript), so the next read starts where the last ended.\n * `source` is an opaque digest of what was read, never a path.\n */\n /**\n * Running state of one metric series (issue #69), so a cumulative data point\n * exported by a later hook process continues the same total. Holds numbers and\n * a series digest only; the series' attributes are re-supplied by the caller\n * and never read back from disk.\n */\n z.strictObject({\n kind: z.literal(\"metric-series\"),\n /** Start of the cumulative interval. */\n startTimeMillis: epochMillisSchema,\n /** Counters: the running total. */\n value: z.number().finite().min(0).optional(),\n /** Histograms: the running aggregation. */\n histogram: z\n .strictObject({\n count: z.number().int().min(0),\n sum: z.number().finite().min(0),\n min: z.number().finite(),\n max: z.number().finite(),\n bucketCounts: z.array(z.number().int().min(0)).max(64),\n })\n .optional(),\n /** Opaque digest of the last delivery folded in; makes a replay a no-op. */\n appliedDelivery: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional(),\n }),\n z.strictObject({\n kind: z.literal(\"read-cursor\"),\n source: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/),\n offset: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),\n }),\n]);\nexport type StateValue = z.infer<typeof stateValueSchema>;\n\nexport const stateRecordSchema = z.strictObject({\n /** Incremented on each write; lets callers detect lost updates. */\n revision: z.number().int().min(0),\n updatedAt: epochMillisSchema,\n value: stateValueSchema,\n});\nexport type StateRecord = z.infer<typeof stateRecordSchema>;\n\n/**\n * Durable-ish key/value state.\n *\n * Needed because a hook process is short-lived but usage accounting spans an\n * entire session. The interface is intentionally minimal: no transactions, no\n * queries, nothing a file or a KV row cannot provide.\n */\nexport interface StateStore {\n read(key: string): Promise<StateRecord | undefined>;\n /** Writes unconditionally, returning the stored record. */\n write(key: string, value: StateValue): Promise<StateRecord>;\n delete(key: string): Promise<void>;\n keys(prefix: string): Promise<readonly string[]>;\n}\n\nexport type TelemetryEmitResult = {\n readonly accepted: number;\n readonly rejected: number;\n readonly errors: readonly OtelHookErrorInfo[];\n};\n\n/**\n * Destination for canonical events.\n *\n * The sink receives canonical events only — never provider payloads — so an\n * exporter cannot become a second, unaudited disclosure path.\n */\n/**\n * What a sink may know about a batch beyond its events, for routing only.\n * Nothing here is exported: it decides where a record may go, never what it says.\n */\nexport type TelemetryEmitOptions = {\n /**\n * Repository key of the session workspace's `origin` remote. Scoped\n * destinations route an event without a context stamp of its own by it,\n * ahead of the exporter Resource's repository.\n */\n readonly workspaceRepositoryKey?: string;\n};\n\nexport interface TelemetrySink {\n emit(events: readonly CanonicalEvent[], options?: TelemetryEmitOptions): Promise<TelemetryEmitResult>;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nexport const logLevelSchema = z.enum([\"silent\", \"error\", \"warn\", \"info\", \"debug\"]);\nexport type LogLevel = z.infer<typeof logLevelSchema>;\n\nexport const LOG_LEVEL_RANK: Readonly<Record<LogLevel, number>> = Object.freeze({\n silent: 0,\n error: 1,\n warn: 2,\n info: 3,\n debug: 4,\n});\n\n/**\n * Diagnostic logger.\n *\n * Fields are attribute values, not arbitrary objects, so a log line cannot\n * become a way to print a provider payload. Implementations must never write to\n * stdout (ADR 0004).\n */\nexport interface Logger {\n error(message: string, fields?: Attributes): void;\n warn(message: string, fields?: Attributes): void;\n info(message: string, fields?: Attributes): void;\n debug(message: string, fields?: Attributes): void;\n}\n\n/** A git worktree found on the local filesystem. Holds a path: never exported. */\nexport type LocatedWorktree = {\n /** Absolute path of the worktree's top-level directory (the one holding `.git`). */\n readonly root: string;\n /** Branch checked out there, from `HEAD`; absent when HEAD is detached. */\n readonly branch?: string;\n /** Main checkout or linked worktree; absent when the locator does not tell. */\n readonly kind?: WorktreeKind;\n /**\n * Absolute path of the repository's main worktree — `root` itself for a main\n * worktree. Absent when there is none to name: a bare repository, a main\n * checkout that is gone, or a layout the locator cannot read.\n */\n readonly mainRoot?: string;\n};\n\n/**\n * Finds the git worktree containing a local path (ADR 0008).\n *\n * The only port that reads the filesystem on behalf of event content, which is\n * why it is a port: the core decides *when* to ask and what of the answer may be\n * exported, the implementation only answers. Implementations must never throw or\n * reject — any failure is `undefined` — and must not spawn processes.\n */\nexport interface WorktreeLocator {\n locate(absolutePath: string): Promise<LocatedWorktree | undefined>;\n /**\n * The repository key (`normalizeRepositoryKey`) of the `origin` remote of the\n * repository whose worktree contains the path, or `undefined` when there is\n * none, it is a local path, or it cannot be read. Used for routing only: the\n * key decides which scoped destinations may receive a record and is never\n * exported. Optional: a locator without it routes nothing by remote.\n */\n originRepositoryKey?(absolutePath: string): Promise<string | undefined>;\n}\n\n/** Where an enricher stopped reading a session's source; see the `read-cursor` state value. */\nexport type ReadCursor = {\n /** Opaque digest naming the source, so a cursor never applies to another file. */\n readonly source: string;\n /** Byte offset the next read starts at. */\n readonly offset: number;\n};\n\nexport type PayloadEnrichmentInput = {\n readonly payload: unknown;\n readonly sessionId: string;\n /** The cursor this enricher stored for this session (and cursor scope) last time, if any. */\n readonly cursor?: ReadCursor;\n};\n\nexport type PayloadEnrichment = {\n /** The payload the adapter parses: the input, or a copy with fields attached. */\n readonly payload: unknown;\n /** A cursor to store for this session; absent leaves the stored one as it is. */\n readonly cursor?: ReadCursor;\n /** Short, non-sensitive notes for the debug log (why a read fell back, ...). */\n readonly notes?: readonly string[];\n};\n\n/**\n * Host-side step that attaches facts to a provider payload before its adapter\n * parses it — for facts the provider writes somewhere other than the hook\n * payload, such as Claude Code's transcript.\n *\n * Not an adapter capability, on purpose: adapters get no filesystem handle (ADR\n * 0003). An enricher is configured by the host, runs inside the session lock so\n * its cursor is read and written atomically, and must be bounded and never throw\n * (a throw is contained and the original payload is parsed). It never runs for a\n * redelivered callback, which is not a new observation.\n */\nexport interface PayloadEnricher {\n /** Stable id; namespaces the enricher's cursor in the state store. */\n readonly id: string;\n /** The provider whose payloads it enriches. Others are never passed to it. */\n readonly providerId: string;\n /**\n * Which of the session's cursors this payload reads, when a session has more\n * than one source (Claude Code writes each subagent to its own transcript).\n * `undefined`, or no function, selects the session's own cursor. A scope is\n * part of a state key, never exported; it must not hold a path.\n */\n cursorScope?(payload: unknown): string | undefined;\n enrich(input: PayloadEnrichmentInput): Promise<PayloadEnrichment>;\n}\n\n/**\n * One window of a session's context: the attributes in force from `from`\n * (inclusive) until `to` (exclusive), or open-ended when `to` is `null`.\n * Attributes are already screened (see `sanitizeSessionContextAttributes`).\n */\nexport type SessionContextSegment = {\n readonly from: EpochMillis;\n readonly to: EpochMillis | null;\n readonly attributes: Readonly<Record<string, string | number | boolean>>;\n};\n\nexport type SessionContextRequest = {\n /** The detected provider, e.g. `claude-code`. The reader maps it to its directory name. */\n readonly providerId: string;\n /**\n * The session whose context applies: always the invocation's session, which\n * for a subagent event is its parent's — never the subagent's own id.\n */\n readonly sessionId: string;\n};\n\n/**\n * Reads the session context a harness wrote for one agent session.\n *\n * A port for the same reason {@link WorktreeLocator} is one: the core decides\n * when to ask and what of the answer reaches a record; the implementation only\n * reads. Adapters never see it (ADR 0003). Implementations must never throw or\n * reject: no file, an unreadable file, an invalid one, or one of an unknown\n * version are all `undefined`, and the core then stamps nothing.\n */\nexport interface SessionContextReader {\n read(request: SessionContextRequest): Promise<readonly SessionContextSegment[] | undefined>;\n}\n","import { z } from \"zod\";\n\nimport {\n errorPhaseSchema,\n errorSeveritySchema,\n otelHookErrorCodeSchema,\n} from \"../errors/taxonomy.js\";\nimport { contentFactSchema, contentFactsSchema } from \"./content.js\";\nimport { extensionsSchema, emptyExtensions } from \"./extensions.js\";\nimport { sourceProvenanceSchema, workspaceIdentitySchema } from \"./identity.js\";\nimport { subagentIdSchema, workspaceTargetSchema } from \"./target.js\";\nimport {\n durationMillisSchema,\n epochMillisSchema,\n eventIdSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n sequenceNumberSchema,\n sessionIdSchema,\n tokenCountSchema,\n} from \"./primitives.js\";\nimport { canonicalUsageSchema, type CanonicalUsage } from \"./usage.js\";\nimport { canonicalSchemaVersionSchema } from \"./version.js\";\n\n/** Model being invoked. Model identifiers are not treated as sensitive. */\nexport const modelDescriptorSchema = z.strictObject({\n modelId: nonEmptyStringSchema,\n /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */\n vendor: nonEmptyStringSchema.optional(),\n family: nonEmptyStringSchema.optional(),\n});\nexport type ModelDescriptor = z.infer<typeof modelDescriptorSchema>;\n\nexport const costFactsSchema = z.strictObject({\n /** ISO 4217 code. */\n currency: z.string().length(3),\n amount: z.number().min(0).finite(),\n source: z.enum([\"provider-reported\", \"computed\"]),\n});\nexport type CostFacts = z.infer<typeof costFactsSchema>;\n\nexport const canonicalEventTypeSchema = z.enum([\n \"session.start\",\n \"session.end\",\n \"prompt.submitted\",\n \"generation.start\",\n \"generation.end\",\n \"tool.start\",\n \"tool.end\",\n \"subagent.start\",\n \"subagent.end\",\n \"compaction.performed\",\n \"error.raised\",\n]);\nexport type CanonicalEventType = z.infer<typeof canonicalEventTypeSchema>;\n\nexport const CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;\n\nconst outcomeSchema = z.enum([\"ok\", \"error\", \"cancelled\", \"timeout\", \"denied\", \"unknown\"]);\nexport type EventOutcome = z.infer<typeof outcomeSchema>;\n\n/**\n * Fields present on every canonical event.\n *\n * Identity fields are duplicated onto each event rather than referenced through\n * shared state, so an event is self-describing once it leaves the process.\n */\nconst baseEventFields = {\n schemaVersion: canonicalSchemaVersionSchema,\n eventId: eventIdSchema,\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Per-invocation ordering key. Stable across replays of the same input. */\n sequence: sequenceNumberSchema,\n occurredAt: epochMillisSchema,\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n /**\n * The provider's own id for the subagent this event was emitted inside (e.g.\n * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event\n * factory, never by hand.\n */\n subagentId: subagentIdSchema.optional(),\n extensions: extensionsSchema.default(emptyExtensions),\n /**\n * Attributes of the session context segment in force when the event\n * occurred (`docs/session-context.md`), stamped by the core from a file a\n * harness wrote. Exported on every record of the event, over the same keys\n * from the Resource. Absent when no context applies. Set by the core only,\n * never by an adapter.\n */\n contextAttributes: z.record(z.string().min(1).max(255), z.union([z.string(), z.number(), z.boolean()])).optional(),\n} as const;\n\nconst event = <TShape extends z.ZodRawShape>(shape: TShape) =>\n z.strictObject({ ...baseEventFields, ...shape });\n\nexport const sessionStartEventSchema = event({\n type: z.literal(\"session.start\"),\n sessionKind: z.enum([\"interactive\", \"non-interactive\", \"unknown\"]),\n agentName: nonEmptyStringSchema.optional(),\n agentVersion: nonEmptyStringSchema.optional(),\n model: modelDescriptorSchema.optional(),\n /** The git worktree the session runs in, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const sessionEndEventSchema = event({\n type: z.literal(\"session.end\"),\n reason: z.enum([\"completed\", \"aborted\", \"error\", \"timeout\", \"unknown\"]),\n durationMillis: durationMillisSchema.optional(),\n /** Session totals, typically cumulative. */\n usage: canonicalUsageSchema.optional(),\n cost: costFactsSchema.optional(),\n});\n\nexport const promptSubmittedEventSchema = event({\n type: z.literal(\"prompt.submitted\"),\n promptSource: z.enum([\"user\", \"automation\", \"resumed\", \"unknown\"]),\n content: contentFactSchema.optional(),\n turnIndex: z.number().int().min(0).optional(),\n /** The git worktree the session runs in, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const generationStartEventSchema = event({\n type: z.literal(\"generation.start\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n requestedMaxOutputTokens: tokenCountSchema.optional(),\n inputContent: contentFactsSchema.optional(),\n});\n\nexport const generationEndEventSchema = event({\n type: z.literal(\"generation.end\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n outcome: outcomeSchema,\n stopReason: nonEmptyStringSchema.optional(),\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n /**\n * True when `usage` is known to cover only part of the generation (for\n * example the last model request of a multi-request turn); false when the\n * provider or harness said it is the whole. Absent: not stated. Meaningless\n * without `usage`.\n */\n usagePartial: z.boolean().optional(),\n cost: costFactsSchema.optional(),\n outputContent: contentFactsSchema.optional(),\n});\n\nexport const toolKindSchema = z.enum([\n \"read\",\n \"write\",\n \"execute\",\n \"search\",\n \"network\",\n \"delegate\",\n \"other\",\n \"unknown\",\n]);\nexport type ToolKind = z.infer<typeof toolKindSchema>;\n\nexport const toolStartEventSchema = event({\n type: z.literal(\"tool.start\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n toolKind: toolKindSchema,\n generationId: nonEmptyStringSchema.optional(),\n input: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const toolEndEventSchema = event({\n type: z.literal(\"tool.end\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n /** Present when the host asked for or recorded a permission decision. */\n permissionDecision: z.enum([\"allowed\", \"denied\", \"deferred\", \"not-required\"]).optional(),\n output: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const subagentStartEventSchema = event({\n type: z.literal(\"subagent.start\"),\n subagentInvocationId: invocationIdSchema,\n subagentType: nonEmptyStringSchema.optional(),\n /** 0 for the top-level agent; 1 for its direct children. */\n delegationDepth: z.number().int().min(0).max(64),\n model: modelDescriptorSchema.optional(),\n});\n\nexport const subagentEndEventSchema = event({\n type: z.literal(\"subagent.end\"),\n subagentInvocationId: invocationIdSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const compactionPerformedEventSchema = event({\n type: z.literal(\"compaction.performed\"),\n trigger: z.enum([\"automatic\", \"manual\", \"unknown\"]),\n /** Provider-reported context size before and after compaction, if known. */\n contextTokensBefore: tokenCountSchema.optional(),\n contextTokensAfter: tokenCountSchema.optional(),\n droppedMessageCount: z.number().int().min(0).optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const errorRaisedEventSchema = event({\n type: z.literal(\"error.raised\"),\n errorCode: otelHookErrorCodeSchema,\n severity: errorSeveritySchema,\n phase: errorPhaseSchema,\n retryable: z.boolean(),\n /** Error text is content: it is described, never embedded verbatim by default. */\n message: contentFactSchema.optional(),\n /** Non-sensitive, provider-agnostic short label. */\n detail: nonEmptyStringSchema.optional(),\n});\n\nexport const canonicalEventSchema = z.discriminatedUnion(\"type\", [\n sessionStartEventSchema,\n sessionEndEventSchema,\n promptSubmittedEventSchema,\n generationStartEventSchema,\n generationEndEventSchema,\n toolStartEventSchema,\n toolEndEventSchema,\n subagentStartEventSchema,\n subagentEndEventSchema,\n compactionPerformedEventSchema,\n errorRaisedEventSchema,\n]);\n\nexport type CanonicalEvent = z.infer<typeof canonicalEventSchema>;\nexport type CanonicalEventInput = z.input<typeof canonicalEventSchema>;\n\nexport type SessionStartEvent = z.infer<typeof sessionStartEventSchema>;\nexport type SessionEndEvent = z.infer<typeof sessionEndEventSchema>;\nexport type PromptSubmittedEvent = z.infer<typeof promptSubmittedEventSchema>;\nexport type GenerationStartEvent = z.infer<typeof generationStartEventSchema>;\nexport type GenerationEndEvent = z.infer<typeof generationEndEventSchema>;\nexport type ToolStartEvent = z.infer<typeof toolStartEventSchema>;\nexport type ToolEndEvent = z.infer<typeof toolEndEventSchema>;\nexport type SubagentStartEvent = z.infer<typeof subagentStartEventSchema>;\nexport type SubagentEndEvent = z.infer<typeof subagentEndEventSchema>;\nexport type CompactionPerformedEvent = z.infer<typeof compactionPerformedEventSchema>;\nexport type ErrorRaisedEvent = z.infer<typeof errorRaisedEventSchema>;\n\nexport type CanonicalEventOfType<TType extends CanonicalEventType> = Extract<\n CanonicalEvent,\n { type: TType }\n>;\n\n/**\n * The event types that may carry a resolved `target` (ADR 0008): a tool call\n * names the worktree it touched; a session start and a prompt name the one the\n * session runs in, so a consumer knows the session's place before its first\n * tool call.\n */\nexport const TARGETED_EVENT_TYPES = [\"session.start\", \"prompt.submitted\", \"tool.start\", \"tool.end\"] as const;\nexport type TargetedEventType = (typeof TARGETED_EVENT_TYPES)[number];\nexport type TargetedEvent = CanonicalEventOfType<TargetedEventType>;\n\nconst TARGETED: ReadonlySet<string> = new Set(TARGETED_EVENT_TYPES);\nexport const isTargetedEvent = (event: CanonicalEvent): event is TargetedEvent => TARGETED.has(event.type);\n\nexport type EventValidationResult =\n | { readonly status: \"ok\"; readonly event: CanonicalEvent }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nexport const validateCanonicalEvent = (value: unknown): EventValidationResult => {\n const parsed = canonicalEventSchema.safeParse(value);\n if (parsed.success) {\n return { status: \"ok\", event: parsed.data };\n }\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n};\n\n/** Parse or throw. Intended for fixtures and tests, not the hook path. */\nexport const parseCanonicalEvent = (value: unknown): CanonicalEvent =>\n canonicalEventSchema.parse(value);\n\n/** Usage carried by an event, if the event type can carry any. */\nexport const eventUsage = (event: CanonicalEvent): CanonicalUsage | undefined =>\n \"usage\" in event ? event.usage : undefined;\n\n/** Stable ordering: by sequence, then by timestamp, then by event id. */\nexport const compareEvents = (a: CanonicalEvent, b: CanonicalEvent): number =>\n a.sequence - b.sequence || a.occurredAt - b.occurredAt || a.eventId.localeCompare(b.eventId);\n","import { z } from \"zod\";\n\n/**\n * Closed set of error codes. Adding a code is a minor change; changing what a\n * code means is a breaking change.\n */\nexport const otelHookErrorCodeSchema = z.enum([\n /** Input was not usable at all (empty stdin, unparsable JSON). */\n \"invalid-input\",\n /** Input parsed but failed canonical schema validation. */\n \"schema-validation-failed\",\n /** No adapter claimed the input with sufficient confidence. */\n \"provider-unknown\",\n /** Several adapters claimed the input at the same confidence. */\n \"provider-detection-ambiguous\",\n /** An adapter threw or returned a malformed result. */\n \"provider-adapter-failure\",\n /** Two identity claims disagreed at equal confidence. */\n \"identity-conflict\",\n /** Required identity fields were absent. */\n \"identity-incomplete\",\n /** A usage report violated the canonical usage invariants. */\n \"usage-invalid\",\n /** The state store could not be read or written. */\n \"state-store-failure\",\n /** The telemetry sink rejected or could not deliver a batch. */\n \"telemetry-export-failure\",\n /** Content reached the sink boundary in a state the policy forbids. */\n \"privacy-policy-violation\",\n /** Configuration could not be resolved. */\n \"configuration-invalid\",\n /** A configured bound (events, batch size) dropped data. */\n \"limit-exceeded\",\n /**\n * No replay-stable delivery identifier was available for a callback while\n * deduplication was required.\n */\n \"delivery-identifier-unavailable\",\n \"delivery-claim-superseded\",\n /** Anything unanticipated. Always reported, never fatal to the host. */\n \"internal-error\",\n]);\nexport type OtelHookErrorCode = z.infer<typeof otelHookErrorCodeSchema>;\n\nexport const errorSeveritySchema = z.enum([\"warning\", \"error\"]);\nexport type ErrorSeverity = z.infer<typeof errorSeveritySchema>;\n\n/** Pipeline stage where a failure occurred. */\nexport const errorPhaseSchema = z.enum([\n \"configuration\",\n \"detection\",\n \"identity\",\n \"parsing\",\n \"normalization\",\n \"privacy\",\n \"state\",\n \"export\",\n \"shutdown\",\n]);\nexport type ErrorPhase = z.infer<typeof errorPhaseSchema>;\n\n/**\n * Which of the two safety postures a code participates in.\n *\n * - `fail-open`: the hook still reports success to the host agent. Telemetry may\n * be incomplete; the coding agent is never blocked.\n * - `fail-closed-attribution`: the observation is not attributed to a session or\n * provider. Data is dropped rather than labelled with a guess.\n */\nexport const failurePostureSchema = z.enum([\"fail-open\", \"fail-closed-attribution\"]);\nexport type FailurePosture = z.infer<typeof failurePostureSchema>;\n\nexport type ErrorCodeDescriptor = {\n readonly code: OtelHookErrorCode;\n readonly severity: ErrorSeverity;\n readonly posture: FailurePosture;\n /** Whether retrying the same input could succeed. */\n readonly retryable: boolean;\n readonly summary: string;\n};\n\nexport const ERROR_TAXONOMY: Readonly<Record<OtelHookErrorCode, ErrorCodeDescriptor>> =\n Object.freeze({\n \"invalid-input\": {\n code: \"invalid-input\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Input could not be read or decoded.\",\n },\n \"schema-validation-failed\": {\n code: \"schema-validation-failed\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"A canonical event failed schema validation and was dropped.\",\n },\n \"provider-unknown\": {\n code: \"provider-unknown\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"No adapter recognized the source provider; the input stays unattributed.\",\n },\n \"provider-detection-ambiguous\": {\n code: \"provider-detection-ambiguous\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Multiple adapters claimed the input at equal confidence.\",\n },\n \"provider-adapter-failure\": {\n code: \"provider-adapter-failure\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A provider adapter failed while parsing.\",\n },\n \"identity-conflict\": {\n code: \"identity-conflict\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Identity claims disagreed; attribution was declined.\",\n },\n \"identity-incomplete\": {\n code: \"identity-incomplete\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Required identity fields were missing; attribution was declined.\",\n },\n \"usage-invalid\": {\n code: \"usage-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A usage report violated the canonical usage invariants.\",\n },\n \"state-store-failure\": {\n code: \"state-store-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"State could not be read or written; derived values may be incomplete.\",\n },\n \"telemetry-export-failure\": {\n code: \"telemetry-export-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"The telemetry sink could not accept a batch.\",\n },\n \"privacy-policy-violation\": {\n code: \"privacy-policy-violation\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Content violated the resolved privacy policy and was dropped.\",\n },\n \"configuration-invalid\": {\n code: \"configuration-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Configuration could not be resolved; defaults apply.\",\n },\n \"limit-exceeded\": {\n code: \"limit-exceeded\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A configured bound was reached and data was dropped.\",\n },\n \"delivery-identifier-unavailable\": {\n code: \"delivery-identifier-unavailable\",\n severity: \"warning\",\n // Fail-open: the observation is still attributed and exported. Only the\n // at-most-once guarantee is missing, and refusing the telemetry to protect\n // a duplicate count would trade a certain loss for a possible one.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"No replay-stable delivery identifier was available; this callback was exported without deduplication.\",\n },\n \"delivery-claim-superseded\": {\n code: \"delivery-claim-superseded\",\n severity: \"warning\",\n // Fail-open, and specifically *not* silent. A peer reclaimed this callback's\n // claim while this process was still working on it, which means the\n // configured stale window is shorter than this installation's real worst\n // case. Both processes may now have exported the callback, so the\n // at-most-once guarantee did not hold for it — the only honest response is\n // to say so and let the operator raise the window.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"A delivery claim was reclaimed by another process before this one committed; the callback may have been exported twice.\",\n },\n \"internal-error\": {\n code: \"internal-error\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"An unexpected failure was contained.\",\n },\n });\n\nexport const describeErrorCode = (code: OtelHookErrorCode): ErrorCodeDescriptor =>\n ERROR_TAXONOMY[code];\n\n/** Outcome of attributing an observation to a provider and session. */\nexport const attributionOutcomeSchema = z.enum([\n /** Identity resolved; events carry provider and session identity. */\n \"attributed\",\n /** Identity could not be established safely; nothing was attributed. */\n \"declined\",\n /** Attribution was attempted and failed unexpectedly. */\n \"failed\",\n /** Input was recognized but intentionally carried no telemetry. */\n \"not-applicable\",\n]);\nexport type AttributionOutcome = z.infer<typeof attributionOutcomeSchema>;\n\nexport const attributionReasonSchema = z.enum([\n \"provider-unknown\",\n \"provider-detection-ambiguous\",\n \"identity-conflict\",\n \"identity-incomplete\",\n \"adapter-ignored-input\",\n \"adapter-failure\",\n \"invalid-input\",\n \"internal-error\",\n]);\nexport type AttributionReason = z.infer<typeof attributionReasonSchema>;\n","import { z } from \"zod\";\n\nimport { nonEmptyStringSchema } from \"./primitives.js\";\n\n/** What kind of conversational or tool content a fact describes. */\nexport const contentKindSchema = z.enum([\n \"prompt\",\n \"response\",\n \"reasoning\",\n \"tool-input\",\n \"tool-output\",\n \"error-message\",\n \"system-instruction\",\n \"attachment\",\n]);\nexport type ContentKind = z.infer<typeof contentKindSchema>;\n\nexport const contentRoleSchema = z.enum([\"user\", \"assistant\", \"system\", \"tool\", \"unknown\"]);\nexport type ContentRole = z.infer<typeof contentRoleSchema>;\n\n/**\n * How much of the original content this fact discloses.\n *\n * - `omitted`: no text at all (the default posture).\n * - `masked`: a shape-preserving mask; non-whitespace characters replaced.\n * - `redacted`: text with secret-looking spans replaced by a placeholder.\n * - `raw`: verbatim text. Only reachable through explicit opt-in.\n */\nexport const contentDisclosureSchema = z.enum([\"omitted\", \"masked\", \"redacted\", \"raw\"]);\nexport type ContentDisclosure = z.infer<typeof contentDisclosureSchema>;\n\nexport const CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;\n\n/**\n * A privacy-safe description of content.\n *\n * Lengths and a stable hash are always present so consumers can measure and\n * correlate volume without receiving the content itself. `text` is present only\n * when the resolved privacy policy allows disclosure, and is produced solely by\n * the central privacy service.\n */\nexport const contentFactSchema = z.strictObject({\n kind: contentKindSchema,\n role: contentRoleSchema.optional(),\n /** Unicode code point count of the original content. */\n characterLength: z.number().int().min(0),\n /** UTF-8 byte length of the original content. */\n byteLength: z.number().int().min(0),\n /** Stable salted digest of the original content. */\n contentHash: z.string().regex(CONTENT_HASH_PATTERN),\n disclosure: contentDisclosureSchema,\n /** Disclosed text, bounded by the privacy policy. Absent when omitted. */\n text: z.string().optional(),\n /** True when `text` was cut short by the configured string bound. */\n truncated: z.boolean(),\n /** Number of secret-looking spans replaced while producing `text`. */\n secretsRedacted: z.number().int().min(0),\n /** Optional non-sensitive label, e.g. a MIME type or tool name. */\n label: nonEmptyStringSchema.optional(),\n});\nexport type ContentFact = z.infer<typeof contentFactSchema>;\n\nexport const contentFactsSchema = z.array(contentFactSchema).max(64);\n\n/**\n * Guard used in tests and at the sink boundary: an omitted fact must not carry\n * text, and a disclosing fact must carry it.\n */\nexport const isContentFactConsistent = (fact: ContentFact): boolean =>\n fact.disclosure === \"omitted\" ? fact.text === undefined : fact.text !== undefined;\n\n/**\n * A fact for a content kind the event can carry when the provider sent no text.\n *\n * Always `omitted` with zero length, regardless of the installation's content\n * mode: there is nothing to mask, redact, or export.\n */\nexport const isUnavailableContentFact = (fact: ContentFact): boolean =>\n fact.disclosure === \"omitted\" &&\n fact.text === undefined &&\n fact.characterLength === 0 &&\n fact.byteLength === 0;\n","import { z } from \"zod\";\n\n/** Maximum length accepted for short identifier-like strings. */\nexport const MAX_IDENTIFIER_LENGTH = 256;\n\n/** Maximum length accepted for a single string attribute value. */\nexport const MAX_ATTRIBUTE_STRING_LENGTH = 4096;\n\n/** Maximum number of entries accepted in an attribute array value. */\nexport const MAX_ATTRIBUTE_ARRAY_LENGTH = 128;\n\nexport const nonEmptyStringSchema = z.string().min(1).max(MAX_IDENTIFIER_LENGTH);\n\n/** Wall-clock time as whole milliseconds since the Unix epoch. */\nexport const epochMillisSchema = z.number().int().min(0).max(8_640_000_000_000_000);\nexport type EpochMillis = z.infer<typeof epochMillisSchema>;\n\n/** Non-negative duration in milliseconds; may be fractional. */\nexport const durationMillisSchema = z.number().min(0).finite();\n\n/** Token counts are always non-negative integers. */\nexport const tokenCountSchema = z.number().int().min(0);\n\n/** Monotonically increasing per-invocation ordering key. */\nexport const sequenceNumberSchema = z.number().int().min(0);\n\nconst brandedIdSchema = (): z.ZodString => z.string().min(1).max(MAX_IDENTIFIER_LENGTH);\n\nexport const invocationIdSchema = brandedIdSchema().brand<\"InvocationId\">();\nexport type InvocationId = z.infer<typeof invocationIdSchema>;\n\nexport const sessionIdSchema = brandedIdSchema().brand<\"SessionId\">();\nexport type SessionId = z.infer<typeof sessionIdSchema>;\n\nexport const eventIdSchema = brandedIdSchema().brand<\"EventId\">();\nexport type EventId = z.infer<typeof eventIdSchema>;\n\n/**\n * Workspace identifiers are opaque, privacy-safe handles of the form\n * `<scheme>:<token>`. Filesystem paths cannot satisfy this pattern, which keeps\n * home directories and repository paths out of telemetry by construction.\n */\nexport const WORKSPACE_ID_PATTERN = /^[a-z][a-z0-9]{0,15}:[A-Za-z0-9_-]{8,128}$/;\nexport const workspaceIdSchema = z\n .string()\n .regex(WORKSPACE_ID_PATTERN, \"workspace id must be an opaque `<scheme>:<token>` handle\")\n .brand<\"WorkspaceId\">();\nexport type WorkspaceId = z.infer<typeof workspaceIdSchema>;\n\n/** Provider ids are lowercase, hyphenated, and stable across releases. */\nexport const PROVIDER_ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\nexport const providerIdSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(PROVIDER_ID_PATTERN, \"provider id must be lowercase and hyphenated\")\n .brand<\"ProviderId\">();\nexport type ProviderId = z.infer<typeof providerIdSchema>;\n\n/** Sentinel used whenever the source provider could not be established. */\nexport const UNKNOWN_PROVIDER_ID = \"unknown\" as const;\nexport type UnknownProviderId = typeof UNKNOWN_PROVIDER_ID;\n\nexport const resolvedProviderIdSchema = z.union([\n providerIdSchema,\n z.literal(UNKNOWN_PROVIDER_ID),\n]);\nexport type ResolvedProviderId = z.infer<typeof resolvedProviderIdSchema>;\n\nexport const isUnknownProvider = (value: ResolvedProviderId): value is UnknownProviderId =>\n value === UNKNOWN_PROVIDER_ID;\n\n/**\n * Attribute values are restricted to OpenTelemetry-compatible primitives.\n *\n * This restriction is a containment boundary, not a convenience: because no\n * nested object can be represented, a raw provider payload cannot be smuggled\n * out of an adapter through attributes or extensions.\n */\nexport const attributePrimitiveSchema = z.union([\n z.string().max(MAX_ATTRIBUTE_STRING_LENGTH),\n z.number().finite(),\n z.boolean(),\n]);\nexport type AttributePrimitive = z.infer<typeof attributePrimitiveSchema>;\n\nexport const attributeValueSchema = z.union([\n attributePrimitiveSchema,\n z.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH),\n]);\nexport type AttributeValue = z.infer<typeof attributeValueSchema>;\n\nexport const attributesSchema = z.record(z.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);\nexport type Attributes = z.infer<typeof attributesSchema>;\n\n/** Ordered confidence ladder for provider detection. */\nexport const detectionConfidenceSchema = z.enum([\"none\", \"weak\", \"strong\", \"exact\"]);\nexport type DetectionConfidence = z.infer<typeof detectionConfidenceSchema>;\n\nexport const DETECTION_CONFIDENCE_RANK: Readonly<Record<DetectionConfidence, number>> =\n Object.freeze({\n none: 0,\n weak: 1,\n strong: 2,\n exact: 3,\n });\n\nexport const compareDetectionConfidence = (a: DetectionConfidence, b: DetectionConfidence): number =>\n DETECTION_CONFIDENCE_RANK[a] - DETECTION_CONFIDENCE_RANK[b];\n\n/** How the observed data reached this process. */\nexport const sourceTransportSchema = z.enum([\n \"hook-stdin\",\n \"cli-argument\",\n \"library-call\",\n \"test-fixture\",\n]);\nexport type SourceTransport = z.infer<typeof sourceTransportSchema>;\n","import { z } from \"zod\";\n\nimport { attributeValueSchema, type AttributeValue } from \"./primitives.js\";\n\n/**\n * Extension keys must be namespaced: at least one dot-separated segment before\n * the leaf, e.g. `acme.deployment-tier`. Namespacing keeps provider- and\n * consumer-specific fields from colliding with core fields or each other.\n */\nexport const EXTENSION_KEY_PATTERN =\n /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;\n\n/** Namespaces owned by the core model; extensions may not use them. */\nexport const RESERVED_EXTENSION_NAMESPACES: readonly string[] = Object.freeze([\n \"otelhook\",\n \"otel\",\n \"telemetry\",\n]);\n\nexport const MAX_EXTENSION_ENTRIES = 64;\n\nexport const extensionKeyNamespace = (key: string): string => key.slice(0, key.indexOf(\".\"));\n\nexport const isReservedExtensionNamespace = (key: string): boolean =>\n RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));\n\nexport const isValidExtensionKey = (key: string): boolean =>\n EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);\n\n/**\n * Namespaced extension bag.\n *\n * Values are restricted to attribute primitives, so extensions cannot carry\n * nested provider payloads.\n */\nexport const extensionsSchema = z\n .record(z.string(), attributeValueSchema)\n .check((ctx) => {\n const keys = Object.keys(ctx.value);\n if (keys.length > MAX_EXTENSION_ENTRIES) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`,\n });\n }\n for (const key of keys) {\n if (!EXTENSION_KEY_PATTERN.test(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. \"acme.tier\"`,\n });\n continue;\n }\n if (isReservedExtensionNamespace(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`,\n });\n }\n }\n });\n\nexport type Extensions = Record<string, AttributeValue>;\n\nexport const EMPTY_EXTENSIONS: Extensions = Object.freeze({});\n\nexport const emptyExtensions = (): Extensions => ({});\n","import { z } from \"zod\";\n\nimport {\n attributesSchema,\n detectionConfidenceSchema,\n DETECTION_CONFIDENCE_RANK,\n epochMillisSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n resolvedProviderIdSchema,\n sessionIdSchema,\n sourceTransportSchema,\n workspaceIdSchema,\n type DetectionConfidence,\n type InvocationId,\n type SessionId,\n type WorkspaceId,\n} from \"./primitives.js\";\n\n/**\n * Where a workspace identifier came from.\n *\n * Ordered from most to least stable. The source is recorded so consumers can\n * tell a repository-scoped identity from a directory-scoped one instead of\n * assuming they are comparable.\n */\nexport const workspaceKeySourceSchema = z.enum([\n \"git-remote\",\n \"git-root\",\n \"working-directory\",\n \"explicit\",\n \"unknown\",\n]);\nexport type WorkspaceKeySource = z.infer<typeof workspaceKeySourceSchema>;\n\n/**\n * Privacy-safe workspace identity.\n *\n * Only opaque handles and explicitly allowed labels are modelled. There is no\n * field for a filesystem path, so paths cannot be exported through this type.\n */\nexport const workspaceIdentitySchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n keySource: workspaceKeySourceSchema,\n /** Repository name only; never an owner path or URL with credentials. */\n repositoryName: nonEmptyStringSchema.optional(),\n vcsBranchName: nonEmptyStringSchema.optional(),\n /** Opaque handle for the checked-out revision. */\n vcsRevisionId: nonEmptyStringSchema.optional(),\n })\n .readonly();\nexport type WorkspaceIdentity = z.infer<typeof workspaceIdentitySchema>;\n\nexport const UNKNOWN_WORKSPACE_ID = \"unknown:0000000000000000\" as WorkspaceId;\n\nexport const unknownWorkspaceIdentity = (): WorkspaceIdentity =>\n workspaceIdentitySchema.parse({\n workspaceId: UNKNOWN_WORKSPACE_ID,\n keySource: \"unknown\",\n });\n\n/**\n * Provenance of an observation: which provider produced it and which adapter\n * interpreted it, with the confidence of that attribution.\n */\nexport const sourceProvenanceSchema = z\n .strictObject({\n providerId: resolvedProviderIdSchema,\n providerVersion: nonEmptyStringSchema.optional(),\n adapterId: nonEmptyStringSchema,\n adapterVersion: nonEmptyStringSchema,\n detectionConfidence: detectionConfidenceSchema,\n /** The provider's own name for the source event, e.g. a hook event name. */\n sourceEventName: nonEmptyStringSchema.optional(),\n transport: sourceTransportSchema,\n })\n .readonly();\nexport type SourceProvenance = z.infer<typeof sourceProvenanceSchema>;\n\n/**\n * Opaque, immutable metadata supplied by the embedding consumer.\n *\n * The library never interprets these values; it only carries and exports them.\n */\nexport const consumerAttributesSchema = attributesSchema.readonly();\nexport type ConsumerAttributes = z.infer<typeof consumerAttributesSchema>;\n\n/**\n * Immutable identity of a single hook invocation.\n *\n * Frozen on parse. There is deliberately no setter, no builder that mutates in\n * place, and no module-level instance: identity is passed explicitly so two\n * concurrent invocations can never observe each other's fields.\n */\nexport const invocationIdentitySchema = z\n .strictObject({\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Set when this invocation runs beneath another agent invocation. */\n parentInvocationId: invocationIdSchema.optional(),\n /** Root of the session tree when the provider exposes one. */\n rootSessionId: sessionIdSchema.optional(),\n /** Stable handle for the agent process/instance, when available. */\n agentInstanceId: nonEmptyStringSchema.optional(),\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n startedAt: epochMillisSchema,\n consumerAttributes: consumerAttributesSchema,\n })\n .readonly();\nexport type InvocationIdentity = z.infer<typeof invocationIdentitySchema>;\n\n/** Fields an identity claim may contribute. */\nexport const identityClaimFieldsSchema = z.strictObject({\n invocationId: invocationIdSchema.optional(),\n sessionId: sessionIdSchema.optional(),\n parentInvocationId: invocationIdSchema.optional(),\n rootSessionId: sessionIdSchema.optional(),\n agentInstanceId: nonEmptyStringSchema.optional(),\n workspace: workspaceIdentitySchema.optional(),\n startedAt: epochMillisSchema.optional(),\n});\nexport type IdentityClaimFields = z.infer<typeof identityClaimFieldsSchema>;\n\n/**\n * A claim about invocation identity from one source.\n *\n * Claims are evidence, not truth. Resolution keeps the highest-confidence claim\n * per field and refuses to merge disagreeing peers.\n */\nexport const identityClaimSchema = z.strictObject({\n /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */\n source: nonEmptyStringSchema,\n confidence: detectionConfidenceSchema,\n fields: identityClaimFieldsSchema,\n});\nexport type IdentityClaim = z.infer<typeof identityClaimSchema>;\n\nexport type IdentityConflict = {\n readonly field: keyof IdentityClaimFields;\n readonly confidence: DetectionConfidence;\n /** Rendered, non-sensitive representations of the disagreeing values. */\n readonly values: readonly string[];\n readonly sources: readonly string[];\n};\n\nexport type IdentityResolution =\n | { readonly status: \"resolved\"; readonly identity: InvocationIdentity }\n | {\n readonly status: \"conflict\";\n readonly conflicts: readonly IdentityConflict[];\n }\n | {\n readonly status: \"incomplete\";\n readonly missing: readonly (keyof IdentityClaimFields)[];\n }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nconst CLAIM_FIELDS = [\n \"invocationId\",\n \"sessionId\",\n \"parentInvocationId\",\n \"rootSessionId\",\n \"agentInstanceId\",\n \"workspace\",\n \"startedAt\",\n] as const satisfies readonly (keyof IdentityClaimFields)[];\n\nconst renderClaimValue = (value: unknown): string => {\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (value !== null && typeof value === \"object\" && \"workspaceId\" in value) {\n const { workspaceId } = value;\n return typeof workspaceId === \"string\" ? workspaceId : \"<workspace>\";\n }\n return \"<opaque>\";\n};\n\nexport type ResolveIdentityInput = {\n readonly claims: readonly IdentityClaim[];\n readonly provenance: SourceProvenance;\n /** Used only for fields no claim provides and that have a safe default. */\n readonly fallback?: {\n readonly startedAt?: number;\n readonly workspace?: WorkspaceIdentity;\n };\n readonly consumerAttributes?: Readonly<Record<string, unknown>>;\n};\n\n/**\n * Resolve identity from claims, failing closed.\n *\n * Rules:\n * 1. For each field, only claims at the highest confidence that provided it are\n * considered. Lower-confidence claims never fill in or override.\n * 2. Two distinct values at that highest confidence produce a `conflict`. The\n * invocation is then not attributed at all — a mislabelled session is worse\n * than a missing one.\n * 3. `invocationId` and `sessionId` are mandatory. Missing either yields\n * `incomplete`; neither is invented here.\n * 4. `startedAt` and `workspace` may come from an explicit fallback, because a\n * clock reading and an `unknown` workspace handle assert nothing false.\n */\nexport const resolveInvocationIdentity = (input: ResolveIdentityInput): IdentityResolution => {\n const parsedClaims: IdentityClaim[] = [];\n const issues: string[] = [];\n for (const [index, claim] of input.claims.entries()) {\n const parsed = identityClaimSchema.safeParse(claim);\n if (parsed.success) {\n parsedClaims.push(parsed.data);\n } else {\n issues.push(\n `claim[${index}]: ${parsed.error.issues.map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`).join(\", \")}`,\n );\n }\n }\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const conflicts: IdentityConflict[] = [];\n const selected: Record<string, unknown> = {};\n\n for (const field of CLAIM_FIELDS) {\n const contributors = parsedClaims.filter((claim) => claim.fields[field] !== undefined);\n if (contributors.length === 0) {\n continue;\n }\n const bestRank = Math.max(\n ...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence]),\n );\n const best = contributors.filter(\n (claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank,\n );\n const rendered = new Map<string, string[]>();\n for (const claim of best) {\n const key = JSON.stringify(claim.fields[field]);\n const sources = rendered.get(key) ?? [];\n sources.push(claim.source);\n rendered.set(key, sources);\n }\n if (rendered.size > 1) {\n const [firstBest] = best;\n conflicts.push({\n field,\n confidence: firstBest?.confidence ?? \"none\",\n values: best.map((claim) => renderClaimValue(claim.fields[field])),\n sources: best.map((claim) => claim.source),\n });\n continue;\n }\n const [winner] = best;\n if (winner !== undefined) {\n selected[field] = winner.fields[field];\n }\n }\n\n if (conflicts.length > 0) {\n return { status: \"conflict\", conflicts };\n }\n\n const missing: (keyof IdentityClaimFields)[] = [];\n if (selected.invocationId === undefined) {\n missing.push(\"invocationId\");\n }\n if (selected.sessionId === undefined) {\n missing.push(\"sessionId\");\n }\n if (missing.length > 0) {\n return { status: \"incomplete\", missing };\n }\n\n const startedAt = (selected.startedAt as number | undefined) ?? input.fallback?.startedAt;\n if (startedAt === undefined) {\n return { status: \"incomplete\", missing: [\"startedAt\"] };\n }\n const workspace =\n (selected.workspace as WorkspaceIdentity | undefined) ??\n input.fallback?.workspace ??\n unknownWorkspaceIdentity();\n\n const candidate = {\n invocationId: selected.invocationId as InvocationId,\n sessionId: selected.sessionId as SessionId,\n ...(selected.parentInvocationId === undefined\n ? {}\n : { parentInvocationId: selected.parentInvocationId as InvocationId }),\n ...(selected.rootSessionId === undefined\n ? {}\n : { rootSessionId: selected.rootSessionId as SessionId }),\n ...(selected.agentInstanceId === undefined\n ? {}\n : { agentInstanceId: selected.agentInstanceId as string }),\n provenance: input.provenance,\n workspace,\n startedAt,\n consumerAttributes: input.consumerAttributes ?? {},\n };\n\n const parsed = invocationIdentitySchema.safeParse(candidate);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n }\n return { status: \"resolved\", identity: parsed.data };\n};\n","import { z } from \"zod\";\n\nimport { nonEmptyStringSchema, workspaceIdSchema } from \"./primitives.js\";\n\n/**\n * Per-event workspace targeting (ADR 0008).\n *\n * A session's `workspace` is where the agent was *started*. An agent routinely\n * works somewhere else — in a linked git worktree beside the checkout it was\n * launched from — and the session-level identity cannot show that. A tool event\n * can: the file it edited, or the directory its shell command ran in, names the\n * worktree it actually touched.\n *\n * Two values model that, and the split between them is the privacy boundary:\n *\n * - {@link TargetHint} is what an adapter observed — local paths. It is an\n * in-process value only: it is never part of a {@link CanonicalEvent}, never\n * persisted, never exported. The core resolves it and drops it.\n * - {@link WorkspaceTarget} is what the core resolved — salted handles of the\n * worktree and its repository, the worktree's kind, the checked-out branch, and\n * what the evidence was. It travels on the event.\n */\n\n/**\n * What a target was derived from, strongest evidence first.\n *\n * - `tool-path` — a path the tool call itself named (an edited or read file, a\n * patch header).\n * - `shell-cwd` — the working directory the provider reports a shell command ran in.\n * - `session-cwd` — only the session's own directory was known; the event may\n * have reached elsewhere (e.g. a shell `cd`) without the provider saying so.\n */\nexport const targetSourceSchema = z.enum([\"tool-path\", \"shell-cwd\", \"session-cwd\"]);\nexport type TargetSource = z.infer<typeof targetSourceSchema>;\n\n/** Most paths one hint may name; a bound, not a sampling rule (all must agree). */\nexport const MAX_TARGET_HINT_PATHS = 8;\n\n/** Longest local path a hint may carry. Longer input is dropped, never truncated. */\nexport const MAX_TARGET_PATH_LENGTH = 4096;\n\nconst localPathSchema = z\n .string()\n .min(1)\n .max(MAX_TARGET_PATH_LENGTH)\n .refine((value) => !value.includes(\"\\u0000\"), \"path must not contain NUL\");\n\n/**\n * An adapter's observation of where a tool event pointed. **Carries local paths**\n * — in-process only, see the module note.\n *\n * Every path in one hint must resolve to the same worktree, or the event gets no\n * target at all: a patch touching two worktrees did not target either of them.\n */\nexport const targetHintSchema = z\n .strictObject({\n source: targetSourceSchema,\n paths: z.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),\n /** Absolute directory that relative `paths` resolve against. */\n baseDirectory: localPathSchema.optional(),\n })\n .readonly();\nexport type TargetHint = z.infer<typeof targetHintSchema>;\n\n/**\n * The weakest hint: the session's own directory. Every adapter gives it to a\n * session start and a prompt, and to a tool call that names no path.\n */\nexport const sessionCwdHint = (cwd: string | undefined): TargetHint | undefined =>\n cwd === undefined || cwd.length === 0 ? undefined : { source: \"session-cwd\", paths: [cwd] };\n\n/**\n * Whether a worktree is its repository's main checkout (`main`) or one added\n * beside it with `git worktree add` (`linked`).\n */\nexport const worktreeKindSchema = z.enum([\"main\", \"linked\"]);\nexport type WorktreeKind = z.infer<typeof worktreeKindSchema>;\n\n/**\n * The git worktree a tool event targeted. Exported; carries no path.\n *\n * `workspaceId` is derived exactly like a `git-root` workspace identity, so a\n * consumer holding the same salt can match it against one it derived itself.\n * `repositoryId` is the same derivation applied to the repository's main\n * worktree, so every worktree of one repository shares it — and for a main\n * worktree it equals `workspaceId`.\n */\nexport const workspaceTargetSchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n /** Branch checked out in that worktree; absent on a detached HEAD. */\n vcsBranchName: nonEmptyStringSchema.optional(),\n source: targetSourceSchema,\n /** `git-root` handle of the repository's main worktree; absent when there is none to name. */\n repositoryId: workspaceIdSchema.optional(),\n worktreeKind: worktreeKindSchema.optional(),\n })\n .readonly();\nexport type WorkspaceTarget = z.infer<typeof workspaceTargetSchema>;\n\n/**\n * Shape a provider's own subagent identifier must have to be exported.\n *\n * Identifier-shaped on purpose — no whitespace, no path separators — so a\n * malformed payload field cannot carry prose or a path onto the wire under an id\n * attribute. A value that does not fit is dropped, not repaired.\n */\nexport const SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;\nexport const subagentIdSchema = z.string().regex(SUBAGENT_ID_PATTERN);\nexport type SubagentId = z.infer<typeof subagentIdSchema>;\n","import { z } from \"zod\";\n\nimport { tokenCountSchema } from \"./primitives.js\";\n\n/**\n * Whether an observation reports the change since the previous observation\n * (`delta`) or the running total for the session/generation (`cumulative`).\n *\n * The canonical model keeps temporality explicit rather than assuming one:\n * summing cumulative observations double-counts, and diffing delta observations\n * silently loses tokens.\n */\nexport const usageTemporalitySchema = z.enum([\"delta\", \"cumulative\"]);\nexport type UsageTemporality = z.infer<typeof usageTemporalitySchema>;\n\n/**\n * Whether the provider counts cache-creation tokens inside its input total or\n * reports them as a disjoint bucket.\n *\n * - `included-in-input`: `cacheCreationInputTokens` is a subset of `inputTokens`.\n * - `disjoint-from-input`: cache-creation tokens are billed in addition to\n * `inputTokens` and must be added when computing a total.\n * - `not-reported`: the provider exposes no cache-creation counter; the field is\n * pinned to zero.\n */\nexport const cacheCreationAccountingSchema = z.enum([\n \"included-in-input\",\n \"disjoint-from-input\",\n \"not-reported\",\n]);\nexport type CacheCreationAccounting = z.infer<typeof cacheCreationAccountingSchema>;\n\n/** Whether a provider-reported total agrees with the canonical computation. */\nexport const providerTotalAgreementSchema = z.enum([\"unreported\", \"agrees\", \"disagrees\"]);\nexport type ProviderTotalAgreement = z.infer<typeof providerTotalAgreementSchema>;\n\n/**\n * What an adapter reports, before normalization.\n *\n * `inputTokens` is *inclusive*: it counts every input token the provider\n * attributes to the call, including cache reads (and cache creation when the\n * provider folds it in). `outputTokens` is likewise inclusive of reasoning\n * output. Subset fields describe portions of those totals, never additions.\n */\nexport const usageReportSchema = z.strictObject({\n temporality: usageTemporalitySchema,\n /** Inclusive input tokens. */\n inputTokens: tokenCountSchema.optional(),\n /** Subset of `inputTokens` served from a prompt cache. */\n cachedInputTokens: tokenCountSchema.optional(),\n /** Tokens written to a prompt cache. */\n cacheCreationInputTokens: tokenCountSchema.optional(),\n /** Required when `cacheCreationInputTokens` is present and non-zero. */\n cacheCreationAccounting: cacheCreationAccountingSchema.optional(),\n /** Inclusive output tokens. */\n outputTokens: tokenCountSchema.optional(),\n /** Subset of `outputTokens` spent on reasoning. */\n reasoningOutputTokens: tokenCountSchema.optional(),\n /** Total exactly as the provider reported it, if it reported one. */\n providerTotalTokens: tokenCountSchema.optional(),\n});\nexport type UsageReport = z.infer<typeof usageReportSchema>;\n\n/**\n * Fully normalized usage.\n *\n * Derived fields (`uncachedInputTokens`, `totalTokens`,\n * `providerTotalAgreement`) are part of the schema and are re-checked on parse,\n * so an inconsistent object cannot exist. Construct values with\n * {@link normalizeUsage} rather than by hand.\n */\nexport const canonicalUsageSchema = z\n .strictObject({\n temporality: usageTemporalitySchema,\n inputTokens: tokenCountSchema,\n cachedInputTokens: tokenCountSchema,\n cacheCreationInputTokens: tokenCountSchema,\n cacheCreationAccounting: cacheCreationAccountingSchema,\n outputTokens: tokenCountSchema,\n reasoningOutputTokens: tokenCountSchema,\n /** Derived: input tokens that were neither cache reads nor cache writes. */\n uncachedInputTokens: tokenCountSchema,\n /** Derived: canonical billable total. */\n totalTokens: tokenCountSchema,\n providerTotalTokens: tokenCountSchema.optional(),\n providerTotalAgreement: providerTotalAgreementSchema,\n })\n .check((ctx) => {\n const usage = ctx.value;\n const push = (message: string): void => {\n ctx.issues.push({ code: \"custom\", input: usage, message });\n };\n\n if (usage.cachedInputTokens > usage.inputTokens) {\n push(\"cachedInputTokens must not exceed inputTokens (it is a subset)\");\n }\n if (usage.reasoningOutputTokens > usage.outputTokens) {\n push(\"reasoningOutputTokens must not exceed outputTokens (it is a subset)\");\n }\n if (usage.cacheCreationAccounting === \"not-reported\" && usage.cacheCreationInputTokens !== 0) {\n push(\"cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported\");\n }\n const creationInsideInput =\n usage.cacheCreationAccounting === \"included-in-input\" ? usage.cacheCreationInputTokens : 0;\n if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {\n push(\n \"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input\",\n );\n }\n const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;\n if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {\n push(`uncachedInputTokens must equal ${expectedUncached}`);\n }\n const creationOutsideInput =\n usage.cacheCreationAccounting === \"disjoint-from-input\" ? usage.cacheCreationInputTokens : 0;\n const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;\n if (usage.totalTokens !== expectedTotal) {\n push(`totalTokens must equal ${expectedTotal}`);\n }\n const expectedAgreement: ProviderTotalAgreement =\n usage.providerTotalTokens === undefined\n ? \"unreported\"\n : usage.providerTotalTokens === expectedTotal\n ? \"agrees\"\n : \"disagrees\";\n if (usage.providerTotalAgreement !== expectedAgreement) {\n push(`providerTotalAgreement must be ${expectedAgreement}`);\n }\n });\nexport type CanonicalUsage = z.infer<typeof canonicalUsageSchema>;\n\nexport type UsageNormalizationIssue = {\n readonly code:\n | \"invalid-report\"\n | \"cached-exceeds-input\"\n | \"reasoning-exceeds-output\"\n | \"cache-creation-exceeds-input\"\n | \"cache-creation-accounting-missing\";\n readonly message: string;\n};\n\nexport type UsageNormalizationResult =\n | { readonly status: \"ok\"; readonly usage: CanonicalUsage; readonly notes: readonly string[] }\n | { readonly status: \"invalid\"; readonly issues: readonly UsageNormalizationIssue[] };\n\n/**\n * Normalize a provider usage report into canonical usage.\n *\n * Deterministic rules:\n * 1. Absent counters default to `0`; `providerTotalTokens` stays absent.\n * 2. Non-integer, negative, or non-finite counters are rejected.\n * 3. A subset exceeding its total is rejected — never clamped — because\n * clamping would silently invent a billing story.\n * 4. `cacheCreationAccounting` defaults to `not-reported` when no cache-creation\n * tokens are reported, and is *required* when they are: guessing whether the\n * bucket is disjoint would mis-total every downstream cost calculation.\n * 5. A provider total that disagrees with the canonical total is preserved as\n * reported and flagged `disagrees`. Both numbers survive; neither is edited.\n */\nexport const normalizeUsage = (report: unknown): UsageNormalizationResult => {\n const parsed = usageReportSchema.safeParse(report);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map((issue) => ({\n code: \"invalid-report\" as const,\n message: `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n })),\n };\n }\n\n const input = parsed.data;\n const issues: UsageNormalizationIssue[] = [];\n const notes: string[] = [];\n\n const inputTokens = input.inputTokens ?? 0;\n const cachedInputTokens = input.cachedInputTokens ?? 0;\n const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;\n const outputTokens = input.outputTokens ?? 0;\n const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;\n\n let accounting: CacheCreationAccounting;\n if (cacheCreationInputTokens === 0) {\n accounting = input.cacheCreationAccounting ?? \"not-reported\";\n if (accounting !== \"not-reported\") {\n notes.push(\n `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`,\n );\n }\n } else if (input.cacheCreationAccounting === undefined) {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message:\n \"cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred\",\n });\n accounting = \"not-reported\";\n } else if (input.cacheCreationAccounting === \"not-reported\") {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message: \"cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens\",\n });\n accounting = \"not-reported\";\n } else {\n accounting = input.cacheCreationAccounting;\n }\n\n if (cachedInputTokens > inputTokens) {\n issues.push({\n code: \"cached-exceeds-input\",\n message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n if (reasoningOutputTokens > outputTokens) {\n issues.push({\n code: \"reasoning-exceeds-output\",\n message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`,\n });\n }\n\n const creationInsideInput = accounting === \"included-in-input\" ? cacheCreationInputTokens : 0;\n if (cachedInputTokens + creationInsideInput > inputTokens) {\n issues.push({\n code: \"cache-creation-exceeds-input\",\n message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const creationOutsideInput = accounting === \"disjoint-from-input\" ? cacheCreationInputTokens : 0;\n const totalTokens = inputTokens + creationOutsideInput + outputTokens;\n const providerTotalAgreement: ProviderTotalAgreement =\n input.providerTotalTokens === undefined\n ? \"unreported\"\n : input.providerTotalTokens === totalTokens\n ? \"agrees\"\n : \"disagrees\";\n\n if (providerTotalAgreement === \"disagrees\") {\n notes.push(\n `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`,\n );\n }\n\n const usage: CanonicalUsage = {\n temporality: input.temporality,\n inputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens,\n reasoningOutputTokens,\n uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,\n totalTokens,\n ...(input.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: input.providerTotalTokens }),\n providerTotalAgreement,\n };\n\n return { status: \"ok\", usage, notes };\n};\n\nexport class UsageNormalizationError extends Error {\n public readonly issues: readonly UsageNormalizationIssue[];\n\n public constructor(issues: readonly UsageNormalizationIssue[]) {\n super(`invalid usage report: ${issues.map((issue) => issue.message).join(\"; \")}`);\n this.name = \"UsageNormalizationError\";\n this.issues = issues;\n }\n}\n\n/** Convenience wrapper for call sites that treat invalid usage as a bug. */\nexport const normalizeUsageOrThrow = (report: unknown): CanonicalUsage => {\n const result = normalizeUsage(report);\n if (result.status === \"invalid\") {\n throw new UsageNormalizationError(result.issues);\n }\n return result.usage;\n};\n\nexport const EMPTY_DELTA_USAGE: CanonicalUsage = Object.freeze(\n normalizeUsageOrThrow({ temporality: \"delta\" }),\n);\n\nexport type UsageDeltaResult = {\n readonly usage: CanonicalUsage;\n /**\n * True when the current snapshot is smaller than the previous one on any\n * counter. That means the cumulative series restarted (new session, replayed\n * transcript, provider reset), so the current snapshot is emitted as the delta\n * instead of a negative difference.\n */\n readonly resetDetected: boolean;\n};\n\nconst requireCumulative = (usage: CanonicalUsage, label: string): void => {\n if (usage.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: `${label} must have cumulative temporality` },\n ]);\n }\n};\n\n/**\n * Convert two cumulative snapshots into a delta observation.\n *\n * Replay safety: re-processing the same snapshot yields an all-zero delta, and a\n * decreasing series is reported as a reset rather than a negative delta.\n * Accounting mode must match; mixing modes would make the subtraction meaningless.\n */\nexport const cumulativeToDelta = (\n previous: CanonicalUsage,\n current: CanonicalUsage,\n): UsageDeltaResult => {\n requireCumulative(previous, \"previous usage\");\n requireCumulative(current, \"current usage\");\n\n if (\n previous.cacheCreationAccounting !== current.cacheCreationAccounting &&\n previous.cacheCreationInputTokens !== 0 &&\n current.cacheCreationInputTokens !== 0\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot diff cumulative usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const resetDetected =\n current.inputTokens < previous.inputTokens ||\n current.cachedInputTokens < previous.cachedInputTokens ||\n current.cacheCreationInputTokens < previous.cacheCreationInputTokens ||\n current.outputTokens < previous.outputTokens ||\n current.reasoningOutputTokens < previous.reasoningOutputTokens;\n\n if (resetDetected) {\n return {\n usage: normalizeUsageOrThrow({ ...toReport(current), temporality: \"delta\" }),\n resetDetected: true,\n };\n }\n\n const usage = normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: current.inputTokens - previous.inputTokens,\n cachedInputTokens: current.cachedInputTokens - previous.cachedInputTokens,\n cacheCreationInputTokens:\n current.cacheCreationInputTokens - previous.cacheCreationInputTokens,\n cacheCreationAccounting: current.cacheCreationAccounting,\n outputTokens: current.outputTokens - previous.outputTokens,\n reasoningOutputTokens: current.reasoningOutputTokens - previous.reasoningOutputTokens,\n });\n\n return { usage, resetDetected: false };\n};\n\n/** Project canonical usage back onto the reported shape. */\nexport const toReport = (usage: CanonicalUsage): UsageReport => ({\n temporality: usage.temporality,\n inputTokens: usage.inputTokens,\n cachedInputTokens: usage.cachedInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n cacheCreationAccounting: usage.cacheCreationAccounting,\n outputTokens: usage.outputTokens,\n reasoningOutputTokens: usage.reasoningOutputTokens,\n ...(usage.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: usage.providerTotalTokens }),\n});\n\n/**\n * Add two delta observations. Cumulative usage is never summed, because two\n * running totals do not compose.\n */\nexport const addUsage = (a: CanonicalUsage, b: CanonicalUsage): CanonicalUsage => {\n if (a.temporality !== \"delta\" || b.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"only delta usage may be summed\" },\n ]);\n }\n const accounting =\n a.cacheCreationInputTokens === 0 && a.cacheCreationAccounting === \"not-reported\"\n ? b.cacheCreationAccounting\n : b.cacheCreationInputTokens === 0 && b.cacheCreationAccounting === \"not-reported\"\n ? a.cacheCreationAccounting\n : a.cacheCreationAccounting;\n\n if (\n a.cacheCreationInputTokens !== 0 &&\n b.cacheCreationInputTokens !== 0 &&\n a.cacheCreationAccounting !== b.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot sum usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n a.providerTotalTokens === undefined && b.providerTotalTokens === undefined\n ? undefined\n : (a.providerTotalTokens ?? 0) + (b.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: a.inputTokens + b.inputTokens,\n cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,\n cacheCreationInputTokens: a.cacheCreationInputTokens + b.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: a.outputTokens + b.outputTokens,\n reasoningOutputTokens: a.reasoningOutputTokens + b.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n","import { z } from \"zod\";\n\n/**\n * Version of the canonical event model.\n *\n * Every emitted event carries this value. Consumers must treat an unknown\n * version as unreadable rather than guessing field semantics.\n *\n * Compatibility rules:\n * - Additive optional fields do not change the version.\n * - Renaming, removing, or re-interpreting a field increments the version.\n */\nexport const CANONICAL_SCHEMA_VERSION = 1 as const;\n\nexport type CanonicalSchemaVersion = typeof CANONICAL_SCHEMA_VERSION;\n\nexport const canonicalSchemaVersionSchema = z.literal(CANONICAL_SCHEMA_VERSION);\n","import type { Clock, StateRecord, StateValue } from \"../runtime/ports.js\";\nimport { stateRecordSchema } from \"../runtime/ports.js\";\nimport { createAsyncLock } from \"./async-lock.js\";\nimport type { LockingStateStore } from \"./store.js\";\n\nexport type BoundedMemoryStateStoreOptions = {\n readonly clock: Clock;\n /** Oldest entry is evicted once this many keys are held. Default 10,000. */\n readonly maxEntries?: number;\n /** When set, a record older than this is treated as absent and dropped lazily. */\n readonly ttlMillis?: number;\n /** Bounds how long a `withSessionLock` call waits before rejecting. Default 5,000ms. */\n readonly lockTimeoutMillis?: number;\n};\n\nexport interface BoundedMemoryStateStore extends LockingStateStore {\n size(): number;\n /** Actively removes expired entries; returns the count removed. */\n pruneExpired(now?: number): number;\n}\n\n/**\n * Production in-memory {@link StateStore}.\n *\n * Unlike the unbounded test double in `runtime/memory.ts`, this store is\n * meant to back a long-lived host process: it bounds its own size and can\n * expire entries by age, so a process that embeds many sessions over its\n * lifetime cannot grow without limit. State does not survive a process\n * restart; hosts that need it to should use the filesystem store instead.\n */\nexport const createBoundedMemoryStateStore = (\n options: BoundedMemoryStateStoreOptions,\n): BoundedMemoryStateStore => {\n const records = new Map<string, StateRecord>();\n const keyLock = createAsyncLock();\n const sessionLock = createAsyncLock();\n const maxEntries = options.maxEntries ?? 10_000;\n const lockTimeoutMillis = options.lockTimeoutMillis ?? 5_000;\n\n const isExpired = (record: StateRecord, now: number): boolean =>\n options.ttlMillis !== undefined && now - record.updatedAt > options.ttlMillis;\n\n const evictOldestIfOverCapacity = (): void => {\n while (records.size > maxEntries) {\n let oldestKey: string | undefined;\n let oldestAt = Number.POSITIVE_INFINITY;\n for (const [key, record] of records) {\n if (record.updatedAt < oldestAt) {\n oldestAt = record.updatedAt;\n oldestKey = key;\n }\n }\n if (oldestKey === undefined) {\n break;\n }\n records.delete(oldestKey);\n }\n };\n\n return {\n read: (key: string): Promise<StateRecord | undefined> =>\n keyLock.run(key, (): Promise<StateRecord | undefined> => {\n const record = records.get(key);\n if (record === undefined) {\n return Promise.resolve(undefined);\n }\n if (isExpired(record, options.clock.now())) {\n records.delete(key);\n return Promise.resolve(undefined);\n }\n return Promise.resolve(record);\n }),\n write: (key: string, value: StateValue): Promise<StateRecord> =>\n keyLock.run(key, (): Promise<StateRecord> => {\n const previous = records.get(key);\n const record = stateRecordSchema.parse({\n revision: (previous?.revision ?? 0) + 1,\n updatedAt: options.clock.now(),\n value,\n });\n records.set(key, record);\n evictOldestIfOverCapacity();\n return Promise.resolve(record);\n }),\n delete: (key: string): Promise<void> =>\n keyLock.run(key, (): Promise<void> => {\n records.delete(key);\n return Promise.resolve();\n }),\n keys: (prefix: string): Promise<readonly string[]> =>\n Promise.resolve([...records.keys()].filter((key) => key.startsWith(prefix)).sort()),\n withSessionLock: <T>(\n sessionId: string,\n fn: () => Promise<T>,\n lockOptions?: { readonly timeoutMillis?: number },\n ): Promise<T> => sessionLock.run(sessionId, fn, lockOptions?.timeoutMillis ?? lockTimeoutMillis),\n size: (): number => records.size,\n pruneExpired: (now?: number): number => {\n const cutoff = now ?? options.clock.now();\n let removed = 0;\n for (const [key, record] of records) {\n if (isExpired(record, cutoff)) {\n records.delete(key);\n removed += 1;\n }\n }\n return removed;\n },\n };\n};\n","import { randomBytes } from \"node:crypto\";\nimport { mkdir, open, readFile, readdir, rename, stat, unlink, writeFile } from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport type { Clock, Logger, StateRecord, StateValue } from \"../runtime/ports.js\";\nimport { stateRecordSchema } from \"../runtime/ports.js\";\nimport { createAsyncLock } from \"./async-lock.js\";\nimport { keyDigest, namespaceSegments, sanitizeSegment, type StoreNamespace } from \"./keys.js\";\nimport { StateLockTimeoutError, type LockingStateStore } from \"./store.js\";\n\nexport type FilesystemStateStoreOptions = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Bounds how long a write, read, or session lock waits. Default 5,000ms. */\n readonly lockTimeoutMillis?: number;\n /** A lock file older than this is assumed to belong to a crashed process and is reclaimed. Default 30,000ms. */\n readonly lockStaleMillis?: number;\n /** Delay between lock acquisition attempts. Default 25ms. */\n readonly lockPollIntervalMillis?: number;\n};\n\nexport interface FilesystemStateStore extends LockingStateStore {\n readonly recordsDir: string;\n readonly quarantineDir: string;\n /** Bounded sweep: removes records untouched for longer than `maxAgeMillis`. */\n pruneStale(\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number },\n ): Promise<{ readonly removed: number; readonly scanned: number }>;\n}\n\ntype Envelope = { readonly key: string; readonly record: StateRecord };\n\nconst isErrnoException = (thrown: unknown, code: string): boolean =>\n thrown instanceof Error && (thrown as NodeJS.ErrnoException).code === code;\n\n/**\n * Deliberately *not* `unref`'d (see `src/install/file-lock.ts`). A hook process\n * waiting for a session lock a peer holds has nothing else on its event loop: an\n * unref'd poll timer lets Node exit mid-wait (\"unsettled top-level await\") and\n * the waiting event is lost. Seen live when Claude Code fired `SubagentStart`\n * and `PostToolUse` for the same session at once.\n */\nconst sleep = (millis: number): Promise<void> =>\n new Promise((resolve) => {\n setTimeout(resolve, millis);\n });\n\nconst wrapFsError = (thrown: unknown, operation: string): Error => {\n if (thrown instanceof Error) {\n return new Error(`filesystem state store ${operation} failed: ${thrown.name}`, { cause: thrown });\n }\n return new Error(`filesystem state store ${operation} failed`);\n};\n\n/**\n * Crash-safe filesystem {@link StateStore}.\n *\n * Every write lands via a temp file plus `rename`, which POSIX guarantees is\n * atomic within one directory: a reader never observes a half-written record,\n * and a process killed mid-write leaves only an orphaned temp file, never a\n * corrupt one. A record that still fails to parse (disk corruption, a manual\n * edit, a future incompatible version) is quarantined rather than thrown from\n * `read`, so a single bad file degrades one key instead of the whole store.\n *\n * Locking is layered: an in-process {@link createAsyncLock} orders same-process\n * callers, and a lock file with a staleness timeout orders across processes\n * and recovers automatically if the holder crashed while holding it.\n */\nexport const createFilesystemStateStore = (\n options: FilesystemStateStoreOptions,\n): FilesystemStateStore => {\n const [providerSegment, installationSegment] = namespaceSegments(options);\n const baseDir = path.join(options.rootDir, providerSegment, installationSegment);\n const recordsDir = path.join(baseDir, \"records\");\n const quarantineDir = path.join(baseDir, \"quarantine\");\n const locksDir = path.join(baseDir, \"locks\");\n\n const lockTimeoutMillis = options.lockTimeoutMillis ?? 5_000;\n const lockStaleMillis = options.lockStaleMillis ?? 30_000;\n const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;\n\n const keyLock = createAsyncLock();\n const sessionLock = createAsyncLock();\n\n let dirsReady: Promise<void> | undefined;\n const ensureDirs = async (): Promise<void> => {\n if (dirsReady !== undefined) {\n return dirsReady;\n }\n const promise = (async (): Promise<void> => {\n await mkdir(recordsDir, { recursive: true });\n await mkdir(quarantineDir, { recursive: true });\n await mkdir(locksDir, { recursive: true });\n })();\n dirsReady = promise;\n try {\n await promise;\n } catch (thrown) {\n dirsReady = undefined;\n throw wrapFsError(thrown, \"ensure-dirs\");\n }\n };\n\n const recordPath = (key: string): string => path.join(recordsDir, `${keyDigest(key)}.json`);\n const tempPath = (key: string): string =>\n path.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes(6).toString(\"hex\")}.json`);\n const lockPath = (sessionId: string): string =>\n path.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);\n\n const quarantine = async (filePath: string, key: string, reason: string): Promise<void> => {\n const dest = path.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);\n try {\n await rename(filePath, dest);\n } catch {\n await unlink(filePath).catch(() => undefined);\n }\n options.logger?.warn(\"filesystem state record quarantined\", { \"state.reason\": reason });\n };\n\n const readUnlocked = async (key: string): Promise<StateRecord | undefined> => {\n await ensureDirs();\n const filePath = recordPath(key);\n let raw: string;\n try {\n raw = await readFile(filePath, \"utf8\");\n } catch (thrown) {\n if (isErrnoException(thrown, \"ENOENT\")) {\n return undefined;\n }\n throw wrapFsError(thrown, \"read\");\n }\n\n let parsedJson: unknown;\n try {\n parsedJson = JSON.parse(raw);\n } catch {\n await quarantine(filePath, key, \"invalid-json\");\n return undefined;\n }\n\n const envelope = parsedJson as Partial<Envelope>;\n if (envelope.key !== key) {\n await quarantine(filePath, key, \"key-mismatch\");\n return undefined;\n }\n const parsed = stateRecordSchema.safeParse(envelope.record);\n if (!parsed.success) {\n await quarantine(filePath, key, \"schema-invalid\");\n return undefined;\n }\n return parsed.data;\n };\n\n const writeUnlocked = async (key: string, value: StateValue): Promise<StateRecord> => {\n await ensureDirs();\n const previous = await readUnlocked(key);\n const record = stateRecordSchema.parse({\n revision: (previous?.revision ?? 0) + 1,\n updatedAt: options.clock.now(),\n value,\n });\n const envelope: Envelope = { key, record };\n const tmp = tempPath(key);\n try {\n await writeFile(tmp, JSON.stringify(envelope), \"utf8\");\n await rename(tmp, recordPath(key));\n } catch (thrown) {\n await unlink(tmp).catch(() => undefined);\n throw wrapFsError(thrown, \"write\");\n }\n return record;\n };\n\n const acquireFileLock = async (\n sessionId: string,\n timeoutMillis: number,\n ): Promise<() => Promise<void>> => {\n await ensureDirs();\n const filePath = lockPath(sessionId);\n const startedAt = options.clock.monotonicMillis();\n\n for (;;) {\n try {\n const handle = await open(filePath, \"wx\");\n try {\n await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));\n } finally {\n await handle.close();\n }\n return async (): Promise<void> => {\n await unlink(filePath).catch(() => undefined);\n };\n } catch (thrown) {\n if (!isErrnoException(thrown, \"EEXIST\")) {\n throw wrapFsError(thrown, \"lock\");\n }\n }\n\n const stale = await (async (): Promise<boolean | \"gone\"> => {\n let raw: string;\n try {\n raw = await readFile(filePath, \"utf8\");\n } catch (thrown) {\n // Released between our `open` and this read: just try again.\n return isErrnoException(thrown, \"ENOENT\") ? \"gone\" : true;\n }\n try {\n const parsed = JSON.parse(raw) as { acquiredAt?: unknown };\n if (typeof parsed.acquiredAt === \"number\") {\n return options.clock.now() - parsed.acquiredAt > lockStaleMillis;\n }\n } catch {\n // fall through to the file's age\n }\n // Empty or partial: a peer created the file (`wx`) and has not written its\n // stamp yet. Reclaiming it now would put two holders in the lock, so an\n // unreadable lock is only stale once the file itself is old.\n try {\n const stats = await stat(filePath);\n return Date.now() - stats.mtimeMs > lockStaleMillis;\n } catch {\n return \"gone\";\n }\n })();\n if (stale === \"gone\") {\n continue;\n }\n if (stale) {\n await unlink(filePath).catch(() => undefined);\n continue;\n }\n\n if (options.clock.monotonicMillis() - startedAt >= timeoutMillis) {\n // A typed error, so a caller can tell \"a peer holds this\" apart from \"the\n // store is unusable\" — the two demand opposite responses.\n throw new StateLockTimeoutError(sessionId, timeoutMillis);\n }\n await sleep(lockPollIntervalMillis);\n }\n };\n\n return {\n recordsDir,\n quarantineDir,\n read: (key: string): Promise<StateRecord | undefined> =>\n keyLock.run(key, () => readUnlocked(key), lockTimeoutMillis),\n write: (key: string, value: StateValue): Promise<StateRecord> =>\n keyLock.run(key, () => writeUnlocked(key, value), lockTimeoutMillis),\n delete: (key: string): Promise<void> =>\n keyLock.run(\n key,\n async (): Promise<void> => {\n await ensureDirs();\n await unlink(recordPath(key)).catch((thrown: unknown) => {\n if (!isErrnoException(thrown, \"ENOENT\")) {\n throw wrapFsError(thrown, \"delete\");\n }\n });\n },\n lockTimeoutMillis,\n ),\n keys: async (prefix: string): Promise<readonly string[]> => {\n await ensureDirs();\n let entries: string[];\n try {\n entries = await readdir(recordsDir);\n } catch (thrown) {\n if (isErrnoException(thrown, \"ENOENT\")) {\n return [];\n }\n throw wrapFsError(thrown, \"keys\");\n }\n const found: string[] = [];\n for (const entry of entries) {\n if (!entry.endsWith(\".json\") || entry.startsWith(\".tmp-\")) {\n continue;\n }\n let raw: string;\n try {\n raw = await readFile(path.join(recordsDir, entry), \"utf8\");\n } catch {\n continue;\n }\n try {\n const envelope = JSON.parse(raw) as Partial<Envelope>;\n if (typeof envelope.key === \"string\" && envelope.key.startsWith(prefix)) {\n found.push(envelope.key);\n }\n } catch {\n continue;\n }\n }\n return found.sort();\n },\n withSessionLock: async <T>(\n sessionId: string,\n fn: () => Promise<T>,\n lockOptions?: { readonly timeoutMillis?: number },\n ): Promise<T> => {\n const timeoutMillis = lockOptions?.timeoutMillis ?? lockTimeoutMillis;\n return sessionLock.run(\n sessionId,\n async (): Promise<T> => {\n const release = await acquireFileLock(sessionId, timeoutMillis);\n try {\n return await fn();\n } finally {\n await release();\n }\n },\n timeoutMillis,\n );\n },\n pruneStale: async (\n maxAgeMillis: number,\n pruneOptions?: { readonly maxEntries?: number },\n ): Promise<{ readonly removed: number; readonly scanned: number }> => {\n await ensureDirs();\n const cap = pruneOptions?.maxEntries ?? 5_000;\n const now = options.clock.now();\n let removed = 0;\n let scanned = 0;\n\n let entries: string[];\n try {\n entries = await readdir(recordsDir);\n } catch (thrown) {\n if (!isErrnoException(thrown, \"ENOENT\")) {\n throw wrapFsError(thrown, \"prune\");\n }\n entries = [];\n }\n for (const entry of entries) {\n if (scanned >= cap) {\n break;\n }\n if (!entry.endsWith(\".json\") || entry.startsWith(\".tmp-\")) {\n continue;\n }\n scanned += 1;\n const filePath = path.join(recordsDir, entry);\n try {\n // Ages are measured against the record's own `updatedAt`, taken from\n // the injected clock at write time, never the OS mtime: a test (or a\n // host) using a clock other than the wall clock would otherwise be\n // compared against a completely unrelated time source.\n const raw = await readFile(filePath, \"utf8\");\n const envelope = JSON.parse(raw) as Partial<Envelope>;\n const updatedAt = envelope.record?.updatedAt;\n if (typeof updatedAt === \"number\" && now - updatedAt > maxAgeMillis) {\n await unlink(filePath).catch(() => undefined);\n removed += 1;\n }\n } catch {\n continue;\n }\n }\n\n let lockEntries: string[];\n try {\n lockEntries = await readdir(locksDir);\n } catch {\n lockEntries = [];\n }\n for (const entry of lockEntries) {\n const filePath = path.join(locksDir, entry);\n try {\n const raw = await readFile(filePath, \"utf8\");\n const parsed = JSON.parse(raw) as { acquiredAt?: unknown };\n if (typeof parsed.acquiredAt === \"number\" && now - parsed.acquiredAt > lockStaleMillis) {\n await unlink(filePath).catch(() => undefined);\n }\n } catch {\n continue;\n }\n }\n\n return { removed, scanned };\n },\n };\n};\n","import { createHash } from \"node:crypto\";\n\n/**\n * Segments derived from arbitrary strings must be safe path components on any\n * filesystem: no separators, no traversal, no reserved characters. Anything\n * that already looks safe is kept as-is (for readable directory names);\n * anything else is replaced by a stable hash so no input can escape its\n * namespace directory or collide with a sibling by accident.\n */\nconst SAFE_SEGMENT_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;\n\nexport const isSafeSegment = (segment: string): boolean => SAFE_SEGMENT_PATTERN.test(segment);\n\nexport const sanitizeSegment = (segment: string): string => {\n if (isSafeSegment(segment)) {\n return segment;\n }\n return `h_${createHash(\"sha256\").update(segment, \"utf8\").digest(\"hex\").slice(0, 32)}`;\n};\n\n/** Scopes a state store to one provider deployed under one installation. */\nexport type StoreNamespace = {\n readonly providerId: string;\n readonly installationId: string;\n};\n\nexport const namespaceSegments = (namespace: StoreNamespace): readonly [string, string] => [\n sanitizeSegment(namespace.providerId),\n sanitizeSegment(namespace.installationId),\n];\n\n/** Stable, collision-resistant digest of a logical state key. */\nexport const keyDigest = (key: string): string =>\n createHash(\"sha256\").update(key, \"utf8\").digest(\"hex\");\n"],"mappings":";AAmCO,IAAM,uBAAN,cAAmC,MAAM;AAAA,EAC9B;AAAA,EAET,YAAY,KAAa,eAAuB;AACrD,UAAM,sBAAsB,aAAa,IAAI;AAC7C,SAAK,OAAO;AACZ,SAAK,UAAU;AAAA,EACjB;AACF;AAEO,IAAM,kBAAkB,MAAiB;AAC9C,QAAM,OAAO,oBAAI,IAA2B;AAE5C,QAAM,MAAM,OAAU,KAAa,IAAsB,kBAAuC;AAC9F,UAAM,WAAW,KAAK,IAAI,GAAG,KAAK,QAAQ,QAAQ;AAClD,UAAM,SAAS,SAAS;AAAA,MACtB,MAAM;AAAA,MACN,MAAM;AAAA,IACR;AAYA,QAAI,YAAY;AAChB,QAAI,UAAU;AAEd,UAAM,UAAU,OAAO,KAAK,MAAsB;AAChD,UAAI,WAAW;AAGb,cAAM,IAAI,qBAAqB,KAAK,iBAAiB,CAAC;AAAA,MACxD;AACA,gBAAU;AACV,aAAO,GAAG;AAAA,IACZ,CAAC;AAED,UAAM,YAAY,QAAQ;AAAA,MACxB,MAAM;AAAA,MACN,MAAM;AAAA,IACR;AACA,SAAK,IAAI,KAAK,SAAS;AACvB,SAAK,UAAU,KAAK,MAAM;AACxB,UAAI,KAAK,IAAI,GAAG,MAAM,WAAW;AAC/B,aAAK,OAAO,GAAG;AAAA,MACjB;AAAA,IACF,CAAC;AAED,QAAI,kBAAkB,QAAW;AAC/B,aAAO;AAAA,IACT;AAEA,QAAI;AACJ,UAAM,UAAU,IAAI,QAAe,CAAC,UAAU,WAAW;AACvD,cAAQ,WAAW,MAAM;AACvB,YAAI,CAAC,SAAS;AACZ,sBAAY;AAAA,QACd;AACA,eAAO,IAAI,qBA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