@osfactory/otel-hook 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/{adapter-DXpNtnaf.d.ts → adapter-BS7xHKGQ.d.ts} +9 -3
  2. package/dist/cli.js +1043 -487
  3. package/dist/cli.js.map +1 -1
  4. package/dist/{events-VxBnDFaO.d.ts → events-CzZ5kukS.d.ts} +177 -1
  5. package/dist/{filesystem-store-J8jjDMTh.d.ts → filesystem-store-BcOveJYY.d.ts} +1 -1
  6. package/dist/{hook-_mlO3akA.d.ts → hook-DxTakjAD.d.ts} +12 -4
  7. package/dist/index.d.ts +12 -12
  8. package/dist/index.js +1171 -599
  9. package/dist/index.js.map +1 -1
  10. package/dist/install.d.ts +4 -4
  11. package/dist/install.js +103 -68
  12. package/dist/install.js.map +1 -1
  13. package/dist/integration.d.ts +14 -8
  14. package/dist/integration.js +547 -121
  15. package/dist/integration.js.map +1 -1
  16. package/dist/lifecycle.d.ts +3 -3
  17. package/dist/lifecycle.js +27 -2
  18. package/dist/lifecycle.js.map +1 -1
  19. package/dist/{memory-DXVBc8V9.d.ts → memory-DkTohdIa.d.ts} +2 -2
  20. package/dist/model.d.ts +1 -1
  21. package/dist/model.js +84 -41
  22. package/dist/model.js.map +1 -1
  23. package/dist/{otlp-log-sink-DTSa0KRF.d.ts → otlp-log-sink-DaZDPKnR.d.ts} +3 -3
  24. package/dist/{payload-BWV5-4n3.d.ts → payload-2lnpKodw.d.ts} +1 -1
  25. package/dist/{ports-Q8x0ODhs.d.ts → ports-B0rC49b3.d.ts} +28 -2
  26. package/dist/providers.d.ts +26 -9
  27. package/dist/providers.js +668 -452
  28. package/dist/providers.js.map +1 -1
  29. package/dist/{registry-Dqr3VNmT.d.ts → registry-DVnPA_b6.d.ts} +1 -1
  30. package/dist/runtime.d.ts +103 -11
  31. package/dist/runtime.js +416 -67
  32. package/dist/runtime.js.map +1 -1
  33. package/dist/{semconv-CIU-2kGO.d.ts → semconv-CtnDdsPk.d.ts} +1 -1
  34. package/dist/state.d.ts +4 -4
  35. package/dist/state.js.map +1 -1
  36. package/dist/telemetry.d.ts +6 -6
  37. package/dist/telemetry.js +92 -10
  38. package/dist/telemetry.js.map +1 -1
  39. package/dist/testing.d.ts +13 -7
  40. package/dist/testing.js +821 -492
  41. package/dist/testing.js.map +1 -1
  42. package/package.json +4 -1
@@ -2,7 +2,7 @@ import { Attributes } from '@opentelemetry/api';
2
2
  import { InstrumentationScope } from '@opentelemetry/core';
3
3
  import { Resource } from '@opentelemetry/resources';
4
4
  import { ReadableSpan } from '@opentelemetry/sdk-trace';
5
- import { b as CanonicalEvent } from './events-VxBnDFaO.js';
5
+ import { b as CanonicalEvent } from './events-CzZ5kukS.js';
6
6
 
7
7
  declare const DEFAULT_INSTRUMENTATION_SCOPE: InstrumentationScope;
8
8
  /** Lifecycle scopes that pair a `*.start` edge with a later `*.end` edge. */
package/dist/state.d.ts CHANGED
@@ -1,12 +1,12 @@
1
1
  export { S as StoreNamespace } from './keys-Dej5bN3L.js';
2
- import { L as LockingStateStore } from './filesystem-store-J8jjDMTh.js';
3
- export { F as FilesystemStateStore, a as FilesystemStateStoreOptions, S as StateStoreDependencies, c as createFilesystemStateStore, i as isLockingStateStore, w as withOptionalSessionLock } from './filesystem-store-J8jjDMTh.js';
4
- import { C as Clock } from './ports-Q8x0ODhs.js';
2
+ import { L as LockingStateStore } from './filesystem-store-BcOveJYY.js';
3
+ export { F as FilesystemStateStore, a as FilesystemStateStoreOptions, S as StateStoreDependencies, c as createFilesystemStateStore, i as isLockingStateStore, w as withOptionalSessionLock } from './filesystem-store-BcOveJYY.js';
4
+ import { C as Clock } from './ports-B0rC49b3.js';
5
5
  import 'zod';
6
6
  import './errors.js';
7
7
  import './primitives-CJ8-rn-f.js';
8
8
  import './taxonomy-DwhTtuWd.js';
9
- import './events-VxBnDFaO.js';
9
+ import './events-CzZ5kukS.js';
10
10
 
11
11
  type BoundedMemoryStateStoreOptions = {
12
12
  readonly clock: Clock;
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/primitives.ts","../src/model/usage.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 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 { 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]);\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","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 { 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 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, unlink, writeFile } from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport type { Clock, Logger, StateRecord, StateValue } from \"../runtime/ports.js\";\nimport { stateRecordSchema } from \"../runtime/ports.js\";\nimport { createAsyncLock } from \"./async-lock.js\";\nimport { keyDigest, namespaceSegments, sanitizeSegment, type StoreNamespace } from \"./keys.js\";\nimport { StateLockTimeoutError, type LockingStateStore } from \"./store.js\";\n\nexport type FilesystemStateStoreOptions = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Bounds how long a write, read, or session lock waits. Default 5,000ms. */\n readonly lockTimeoutMillis?: number;\n /** A lock file older than this is assumed to belong to a crashed process and is reclaimed. Default 30,000ms. */\n readonly lockStaleMillis?: number;\n /** Delay between lock acquisition attempts. Default 25ms. */\n readonly lockPollIntervalMillis?: number;\n};\n\nexport interface FilesystemStateStore extends LockingStateStore {\n readonly recordsDir: string;\n readonly quarantineDir: string;\n /** Bounded sweep: removes records untouched for longer than `maxAgeMillis`. */\n pruneStale(\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number },\n ): Promise<{ readonly removed: number; readonly scanned: number }>;\n}\n\ntype Envelope = { readonly key: string; readonly record: StateRecord };\n\nconst isErrnoException = (thrown: unknown, code: string): boolean =>\n thrown instanceof Error && (thrown as NodeJS.ErrnoException).code === code;\n\nconst sleep = (millis: number): Promise<void> =>\n new Promise((resolve) => {\n const timer = setTimeout(resolve, millis);\n timer.unref?.();\n });\n\nconst wrapFsError = (thrown: unknown, operation: string): Error => {\n if (thrown instanceof Error) {\n return new Error(`filesystem state store ${operation} failed: ${thrown.name}`, { cause: thrown });\n }\n return new Error(`filesystem state store ${operation} failed`);\n};\n\n/**\n * Crash-safe filesystem {@link StateStore}.\n *\n * Every write lands via a temp file plus `rename`, which POSIX guarantees is\n * atomic within one directory: a reader never observes a half-written record,\n * and a process killed mid-write leaves only an orphaned temp file, never a\n * corrupt one. A record that still fails to parse (disk corruption, a manual\n * edit, a future incompatible version) is quarantined rather than thrown from\n * `read`, so a single bad file degrades one key instead of the whole store.\n *\n * Locking is layered: an in-process {@link createAsyncLock} orders same-process\n * callers, and a lock file with a staleness timeout orders across processes\n * and recovers automatically if the holder crashed while holding it.\n */\nexport const createFilesystemStateStore = (\n options: FilesystemStateStoreOptions,\n): FilesystemStateStore => {\n const [providerSegment, installationSegment] = namespaceSegments(options);\n const baseDir = path.join(options.rootDir, providerSegment, installationSegment);\n const recordsDir = path.join(baseDir, \"records\");\n const quarantineDir = path.join(baseDir, \"quarantine\");\n const locksDir = path.join(baseDir, \"locks\");\n\n const lockTimeoutMillis = options.lockTimeoutMillis ?? 5_000;\n const lockStaleMillis = options.lockStaleMillis ?? 30_000;\n const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;\n\n const keyLock = createAsyncLock();\n const sessionLock = createAsyncLock();\n\n let dirsReady: Promise<void> | undefined;\n const ensureDirs = async (): Promise<void> => {\n if (dirsReady !== undefined) {\n return dirsReady;\n }\n const promise = (async (): Promise<void> => {\n await mkdir(recordsDir, { recursive: true });\n await mkdir(quarantineDir, { recursive: true });\n await mkdir(locksDir, { recursive: true });\n })();\n dirsReady = promise;\n try {\n await promise;\n } catch (thrown) {\n dirsReady = undefined;\n throw wrapFsError(thrown, \"ensure-dirs\");\n }\n };\n\n const recordPath = (key: string): string => path.join(recordsDir, `${keyDigest(key)}.json`);\n const tempPath = (key: string): string =>\n path.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes(6).toString(\"hex\")}.json`);\n const lockPath = (sessionId: string): string =>\n path.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);\n\n const quarantine = async (filePath: string, key: string, reason: string): Promise<void> => {\n const dest = path.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);\n try {\n await rename(filePath, dest);\n } catch {\n await unlink(filePath).catch(() => undefined);\n }\n options.logger?.warn(\"filesystem state record quarantined\", { \"state.reason\": reason });\n };\n\n const readUnlocked = async (key: string): Promise<StateRecord | undefined> => {\n await ensureDirs();\n const filePath = recordPath(key);\n let raw: string;\n try {\n raw = await readFile(filePath, \"utf8\");\n } catch (thrown) {\n if (isErrnoException(thrown, \"ENOENT\")) {\n return undefined;\n }\n throw wrapFsError(thrown, \"read\");\n }\n\n let parsedJson: unknown;\n try {\n parsedJson = JSON.parse(raw);\n } catch {\n await quarantine(filePath, key, \"invalid-json\");\n return undefined;\n }\n\n const envelope = parsedJson as Partial<Envelope>;\n if (envelope.key !== key) {\n await quarantine(filePath, key, \"key-mismatch\");\n return undefined;\n }\n const parsed = stateRecordSchema.safeParse(envelope.record);\n if (!parsed.success) {\n await quarantine(filePath, key, \"schema-invalid\");\n return undefined;\n }\n return parsed.data;\n };\n\n const writeUnlocked = async (key: string, value: StateValue): Promise<StateRecord> => {\n await ensureDirs();\n const previous = await readUnlocked(key);\n const record = stateRecordSchema.parse({\n revision: (previous?.revision ?? 0) + 1,\n updatedAt: options.clock.now(),\n value,\n });\n const envelope: Envelope = { key, record };\n const tmp = tempPath(key);\n try {\n await writeFile(tmp, JSON.stringify(envelope), \"utf8\");\n await rename(tmp, recordPath(key));\n } catch (thrown) {\n await unlink(tmp).catch(() => undefined);\n throw wrapFsError(thrown, \"write\");\n }\n return record;\n };\n\n const acquireFileLock = async (\n sessionId: string,\n timeoutMillis: number,\n ): Promise<() => Promise<void>> => {\n await ensureDirs();\n const filePath = lockPath(sessionId);\n const startedAt = options.clock.monotonicMillis();\n\n for (;;) {\n try {\n const handle = await open(filePath, \"wx\");\n try {\n await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));\n } finally {\n await handle.close();\n }\n return async (): Promise<void> => {\n await unlink(filePath).catch(() => undefined);\n };\n } catch (thrown) {\n if (!isErrnoException(thrown, \"EEXIST\")) {\n throw wrapFsError(thrown, \"lock\");\n }\n }\n\n const stale = await (async (): Promise<boolean> => {\n try {\n const raw = await readFile(filePath, \"utf8\");\n const parsed = JSON.parse(raw) as { acquiredAt?: unknown };\n return (\n typeof parsed.acquiredAt !== \"number\" ||\n options.clock.now() - parsed.acquiredAt > lockStaleMillis\n );\n } catch {\n return true;\n }\n })();\n if (stale) {\n await unlink(filePath).catch(() => undefined);\n continue;\n }\n\n if (options.clock.monotonicMillis() - startedAt >= timeoutMillis) {\n // A typed error, so a caller can tell \"a peer holds this\" apart from \"the\n // store is unusable\" — the two demand opposite responses.\n throw new StateLockTimeoutError(sessionId, timeoutMillis);\n }\n await sleep(lockPollIntervalMillis);\n }\n };\n\n return {\n recordsDir,\n quarantineDir,\n read: (key: string): Promise<StateRecord | undefined> =>\n keyLock.run(key, () => readUnlocked(key), lockTimeoutMillis),\n write: (key: string, value: StateValue): Promise<StateRecord> =>\n keyLock.run(key, () => writeUnlocked(key, value), lockTimeoutMillis),\n delete: (key: string): Promise<void> =>\n keyLock.run(\n key,\n async (): Promise<void> => {\n await ensureDirs();\n await unlink(recordPath(key)).catch((thrown: unknown) => {\n if (!isErrnoException(thrown, \"ENOENT\")) {\n throw wrapFsError(thrown, \"delete\");\n }\n });\n },\n lockTimeoutMillis,\n ),\n keys: async (prefix: string): Promise<readonly string[]> => {\n await ensureDirs();\n let entries: string[];\n try {\n entries = await readdir(recordsDir);\n } catch (thrown) {\n if (isErrnoException(thrown, \"ENOENT\")) {\n return [];\n }\n throw wrapFsError(thrown, \"keys\");\n }\n const found: string[] = [];\n for (const entry of entries) {\n if (!entry.endsWith(\".json\") || entry.startsWith(\".tmp-\")) {\n continue;\n }\n let raw: string;\n try {\n raw = await readFile(path.join(recordsDir, entry), \"utf8\");\n } catch {\n continue;\n }\n try {\n const envelope = JSON.parse(raw) as Partial<Envelope>;\n if (typeof envelope.key === \"string\" && envelope.key.startsWith(prefix)) {\n found.push(envelope.key);\n }\n } catch {\n continue;\n }\n }\n return found.sort();\n },\n withSessionLock: async <T>(\n sessionId: string,\n fn: () => Promise<T>,\n lockOptions?: { readonly timeoutMillis?: number },\n ): Promise<T> => {\n const timeoutMillis = lockOptions?.timeoutMillis ?? lockTimeoutMillis;\n return sessionLock.run(\n sessionId,\n async (): Promise<T> => {\n const release = await acquireFileLock(sessionId, timeoutMillis);\n try {\n return await fn();\n } finally {\n await release();\n }\n },\n timeoutMillis,\n );\n },\n pruneStale: async (\n maxAgeMillis: number,\n pruneOptions?: { readonly maxEntries?: number },\n ): Promise<{ readonly removed: number; readonly scanned: number }> => {\n await ensureDirs();\n const cap = pruneOptions?.maxEntries ?? 5_000;\n const now = options.clock.now();\n let removed = 0;\n let scanned = 0;\n\n let entries: string[];\n try {\n entries = await readdir(recordsDir);\n } catch (thrown) {\n if (!isErrnoException(thrown, \"ENOENT\")) {\n throw wrapFsError(thrown, \"prune\");\n }\n entries = [];\n }\n for (const entry of entries) {\n if (scanned >= cap) {\n break;\n }\n if (!entry.endsWith(\".json\") || entry.startsWith(\".tmp-\")) {\n continue;\n }\n scanned += 1;\n const filePath = path.join(recordsDir, entry);\n try {\n // Ages are measured against the record's own `updatedAt`, taken from\n // the injected clock at write time, never the OS mtime: a test (or a\n // host) using a clock other than the wall clock would otherwise be\n // compared against a completely unrelated time source.\n const raw = await readFile(filePath, \"utf8\");\n const envelope = JSON.parse(raw) as Partial<Envelope>;\n const updatedAt = envelope.record?.updatedAt;\n if (typeof updatedAt === \"number\" && now - updatedAt > maxAgeMillis) {\n await unlink(filePath).catch(() => undefined);\n removed += 1;\n }\n } catch {\n continue;\n }\n }\n\n let lockEntries: string[];\n try {\n lockEntries = await readdir(locksDir);\n } catch {\n lockEntries = [];\n }\n for (const entry of lockEntries) {\n const filePath = path.join(locksDir, entry);\n try {\n const raw = await readFile(filePath, \"utf8\");\n const parsed = JSON.parse(raw) as { acquiredAt?: unknown };\n if (typeof parsed.acquiredAt === \"number\" && now - parsed.acquiredAt > lockStaleMillis) {\n await unlink(filePath).catch(() => undefined);\n }\n } catch {\n continue;\n }\n }\n\n return { removed, scanned };\n },\n };\n};\n","import { createHash } from \"node:crypto\";\n\n/**\n * Segments derived from arbitrary strings must be safe path components on any\n * filesystem: no separators, no traversal, no reserved characters. Anything\n * that already looks safe is kept as-is (for readable directory names);\n * anything else is replaced by a stable hash so no input can escape its\n * namespace directory or collide with a sibling by accident.\n */\nconst SAFE_SEGMENT_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;\n\nexport const isSafeSegment = (segment: string): boolean => SAFE_SEGMENT_PATTERN.test(segment);\n\nexport const sanitizeSegment = (segment: string): string => {\n if (isSafeSegment(segment)) {\n return segment;\n }\n return `h_${createHash(\"sha256\").update(segment, \"utf8\").digest(\"hex\").slice(0, 32)}`;\n};\n\n/** Scopes a state store to one provider deployed under one installation. */\nexport type StoreNamespace = {\n readonly providerId: string;\n readonly installationId: string;\n};\n\nexport const namespaceSegments = (namespace: StoreNamespace): readonly [string, string] => [\n sanitizeSegment(namespace.providerId),\n sanitizeSegment(namespace.installationId),\n];\n\n/** Stable, collision-resistant digest of a logical state key. */\nexport const keyDigest = (key: string): string =>\n createHash(\"sha256\").update(key, \"utf8\").digest(\"hex\");\n"],"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,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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"]}
1
+ {"version":3,"sources":["../src/state/async-lock.ts","../src/state/store.ts","../src/runtime/ports.ts","../src/model/primitives.ts","../src/model/usage.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 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]);\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","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 { 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 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, unlink, writeFile } from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport type { Clock, Logger, StateRecord, StateValue } from \"../runtime/ports.js\";\nimport { stateRecordSchema } from \"../runtime/ports.js\";\nimport { createAsyncLock } from \"./async-lock.js\";\nimport { keyDigest, namespaceSegments, sanitizeSegment, type StoreNamespace } from \"./keys.js\";\nimport { StateLockTimeoutError, type LockingStateStore } from \"./store.js\";\n\nexport type FilesystemStateStoreOptions = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Bounds how long a write, read, or session lock waits. Default 5,000ms. */\n readonly lockTimeoutMillis?: number;\n /** A lock file older than this is assumed to belong to a crashed process and is reclaimed. Default 30,000ms. */\n readonly lockStaleMillis?: number;\n /** Delay between lock acquisition attempts. Default 25ms. */\n readonly lockPollIntervalMillis?: number;\n};\n\nexport interface FilesystemStateStore extends LockingStateStore {\n readonly recordsDir: string;\n readonly quarantineDir: string;\n /** Bounded sweep: removes records untouched for longer than `maxAgeMillis`. */\n pruneStale(\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number },\n ): Promise<{ readonly removed: number; readonly scanned: number }>;\n}\n\ntype Envelope = { readonly key: string; readonly record: StateRecord };\n\nconst isErrnoException = (thrown: unknown, code: string): boolean =>\n thrown instanceof Error && (thrown as NodeJS.ErrnoException).code === code;\n\nconst sleep = (millis: number): Promise<void> =>\n new Promise((resolve) => {\n const timer = setTimeout(resolve, millis);\n timer.unref?.();\n });\n\nconst wrapFsError = (thrown: unknown, operation: string): Error => {\n if (thrown instanceof Error) {\n return new Error(`filesystem state store ${operation} failed: ${thrown.name}`, { cause: thrown });\n }\n return new Error(`filesystem state store ${operation} failed`);\n};\n\n/**\n * Crash-safe filesystem {@link StateStore}.\n *\n * Every write lands via a temp file plus `rename`, which POSIX guarantees is\n * atomic within one directory: a reader never observes a half-written record,\n * and a process killed mid-write leaves only an orphaned temp file, never a\n * corrupt one. A record that still fails to parse (disk corruption, a manual\n * edit, a future incompatible version) is quarantined rather than thrown from\n * `read`, so a single bad file degrades one key instead of the whole store.\n *\n * Locking is layered: an in-process {@link createAsyncLock} orders same-process\n * callers, and a lock file with a staleness timeout orders across processes\n * and recovers automatically if the holder crashed while holding it.\n */\nexport const createFilesystemStateStore = (\n options: FilesystemStateStoreOptions,\n): FilesystemStateStore => {\n const [providerSegment, installationSegment] = namespaceSegments(options);\n const baseDir = path.join(options.rootDir, providerSegment, installationSegment);\n const recordsDir = path.join(baseDir, \"records\");\n const quarantineDir = path.join(baseDir, \"quarantine\");\n const locksDir = path.join(baseDir, \"locks\");\n\n const lockTimeoutMillis = options.lockTimeoutMillis ?? 5_000;\n const lockStaleMillis = options.lockStaleMillis ?? 30_000;\n const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;\n\n const keyLock = createAsyncLock();\n const sessionLock = createAsyncLock();\n\n let dirsReady: Promise<void> | undefined;\n const ensureDirs = async (): Promise<void> => {\n if (dirsReady !== undefined) {\n return dirsReady;\n }\n const promise = (async (): Promise<void> => {\n await mkdir(recordsDir, { recursive: true });\n await mkdir(quarantineDir, { recursive: true });\n await mkdir(locksDir, { recursive: true });\n })();\n dirsReady = promise;\n try {\n await promise;\n } catch (thrown) {\n dirsReady = undefined;\n throw wrapFsError(thrown, \"ensure-dirs\");\n }\n };\n\n const recordPath = (key: string): string => path.join(recordsDir, `${keyDigest(key)}.json`);\n const tempPath = (key: string): string =>\n path.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes(6).toString(\"hex\")}.json`);\n const lockPath = (sessionId: string): string =>\n path.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);\n\n const quarantine = async (filePath: string, key: string, reason: string): Promise<void> => {\n const dest = path.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);\n try {\n await rename(filePath, dest);\n } catch {\n await unlink(filePath).catch(() => undefined);\n }\n options.logger?.warn(\"filesystem state record quarantined\", { \"state.reason\": reason });\n };\n\n const readUnlocked = async (key: string): Promise<StateRecord | undefined> => {\n await ensureDirs();\n const filePath = recordPath(key);\n let raw: string;\n try {\n raw = await readFile(filePath, \"utf8\");\n } catch (thrown) {\n if (isErrnoException(thrown, \"ENOENT\")) {\n return undefined;\n }\n throw wrapFsError(thrown, \"read\");\n }\n\n let parsedJson: unknown;\n try {\n parsedJson = JSON.parse(raw);\n } catch {\n await quarantine(filePath, key, \"invalid-json\");\n return undefined;\n }\n\n const envelope = parsedJson as Partial<Envelope>;\n if (envelope.key !== key) {\n await quarantine(filePath, key, \"key-mismatch\");\n return undefined;\n }\n const parsed = stateRecordSchema.safeParse(envelope.record);\n if (!parsed.success) {\n await quarantine(filePath, key, \"schema-invalid\");\n return undefined;\n }\n return parsed.data;\n };\n\n const writeUnlocked = async (key: string, value: StateValue): Promise<StateRecord> => {\n await ensureDirs();\n const previous = await readUnlocked(key);\n const record = stateRecordSchema.parse({\n revision: (previous?.revision ?? 0) + 1,\n updatedAt: options.clock.now(),\n value,\n });\n const envelope: Envelope = { key, record };\n const tmp = tempPath(key);\n try {\n await writeFile(tmp, JSON.stringify(envelope), \"utf8\");\n await rename(tmp, recordPath(key));\n } catch (thrown) {\n await unlink(tmp).catch(() => undefined);\n throw wrapFsError(thrown, \"write\");\n }\n return record;\n };\n\n const acquireFileLock = async (\n sessionId: string,\n timeoutMillis: number,\n ): Promise<() => Promise<void>> => {\n await ensureDirs();\n const filePath = lockPath(sessionId);\n const startedAt = options.clock.monotonicMillis();\n\n for (;;) {\n try {\n const handle = await open(filePath, \"wx\");\n try {\n await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));\n } finally {\n await handle.close();\n }\n return async (): Promise<void> => {\n await unlink(filePath).catch(() => undefined);\n };\n } catch (thrown) {\n if (!isErrnoException(thrown, \"EEXIST\")) {\n throw wrapFsError(thrown, \"lock\");\n }\n }\n\n const stale = await (async (): Promise<boolean> => {\n try {\n const raw = await readFile(filePath, \"utf8\");\n const parsed = JSON.parse(raw) as { acquiredAt?: unknown };\n return (\n typeof parsed.acquiredAt !== \"number\" ||\n options.clock.now() - parsed.acquiredAt > lockStaleMillis\n );\n } catch {\n return true;\n }\n })();\n if (stale) {\n await unlink(filePath).catch(() => undefined);\n continue;\n }\n\n if (options.clock.monotonicMillis() - startedAt >= timeoutMillis) {\n // A typed error, so a caller can tell \"a peer holds this\" apart from \"the\n // store is unusable\" — the two demand opposite responses.\n throw new StateLockTimeoutError(sessionId, timeoutMillis);\n }\n await sleep(lockPollIntervalMillis);\n }\n };\n\n return {\n recordsDir,\n quarantineDir,\n read: (key: string): Promise<StateRecord | undefined> =>\n keyLock.run(key, () => readUnlocked(key), lockTimeoutMillis),\n write: (key: string, value: StateValue): Promise<StateRecord> =>\n keyLock.run(key, () => writeUnlocked(key, value), lockTimeoutMillis),\n delete: (key: string): Promise<void> =>\n keyLock.run(\n key,\n async (): Promise<void> => {\n await ensureDirs();\n await unlink(recordPath(key)).catch((thrown: unknown) => {\n if (!isErrnoException(thrown, \"ENOENT\")) {\n throw wrapFsError(thrown, \"delete\");\n }\n });\n },\n lockTimeoutMillis,\n ),\n keys: async (prefix: string): Promise<readonly string[]> => {\n await ensureDirs();\n let entries: string[];\n try {\n entries = await readdir(recordsDir);\n } catch (thrown) {\n if (isErrnoException(thrown, \"ENOENT\")) {\n return [];\n }\n throw wrapFsError(thrown, \"keys\");\n }\n const found: string[] = [];\n for (const entry of entries) {\n if (!entry.endsWith(\".json\") || entry.startsWith(\".tmp-\")) {\n continue;\n }\n let raw: string;\n try {\n raw = await readFile(path.join(recordsDir, entry), \"utf8\");\n } catch {\n continue;\n }\n try {\n const envelope = JSON.parse(raw) as Partial<Envelope>;\n if (typeof envelope.key === \"string\" && envelope.key.startsWith(prefix)) {\n found.push(envelope.key);\n }\n } catch {\n continue;\n }\n }\n return found.sort();\n },\n withSessionLock: async <T>(\n sessionId: string,\n fn: () => Promise<T>,\n lockOptions?: { readonly timeoutMillis?: number },\n ): Promise<T> => {\n const timeoutMillis = lockOptions?.timeoutMillis ?? lockTimeoutMillis;\n return sessionLock.run(\n sessionId,\n async (): Promise<T> => {\n const release = await acquireFileLock(sessionId, timeoutMillis);\n try {\n return await fn();\n } finally {\n await release();\n }\n },\n timeoutMillis,\n );\n },\n pruneStale: async (\n maxAgeMillis: number,\n pruneOptions?: { readonly maxEntries?: number },\n ): Promise<{ readonly removed: number; readonly scanned: number }> => {\n await ensureDirs();\n const cap = pruneOptions?.maxEntries ?? 5_000;\n const now = options.clock.now();\n let removed = 0;\n let scanned = 0;\n\n let entries: string[];\n try {\n entries = await readdir(recordsDir);\n } catch (thrown) {\n if (!isErrnoException(thrown, \"ENOENT\")) {\n throw wrapFsError(thrown, \"prune\");\n }\n entries = [];\n }\n for (const entry of entries) {\n if (scanned >= cap) {\n break;\n }\n if (!entry.endsWith(\".json\") || entry.startsWith(\".tmp-\")) {\n continue;\n }\n scanned += 1;\n const filePath = path.join(recordsDir, entry);\n try {\n // Ages are measured against the record's own `updatedAt`, taken from\n // the injected clock at write time, never the OS mtime: a test (or a\n // host) using a clock other than the wall clock would otherwise be\n // compared against a completely unrelated time source.\n const raw = await readFile(filePath, \"utf8\");\n const envelope = JSON.parse(raw) as Partial<Envelope>;\n const updatedAt = envelope.record?.updatedAt;\n if (typeof updatedAt === \"number\" && now - updatedAt > maxAgeMillis) {\n await unlink(filePath).catch(() => undefined);\n removed += 1;\n }\n } catch {\n continue;\n }\n }\n\n let lockEntries: string[];\n try {\n lockEntries = await readdir(locksDir);\n } catch {\n lockEntries = [];\n }\n for (const entry of lockEntries) {\n const filePath = path.join(locksDir, entry);\n try {\n const raw = await readFile(filePath, \"utf8\");\n const parsed = JSON.parse(raw) as { acquiredAt?: unknown };\n if (typeof parsed.acquiredAt === \"number\" && now - parsed.acquiredAt > lockStaleMillis) {\n await unlink(filePath).catch(() => undefined);\n }\n } catch {\n continue;\n }\n }\n\n return { removed, scanned };\n },\n };\n};\n","import { createHash } from \"node:crypto\";\n\n/**\n * Segments derived from arbitrary strings must be safe path components on any\n * filesystem: no separators, no traversal, no reserved characters. Anything\n * that already looks safe is kept as-is (for readable directory names);\n * anything else is replaced by a stable hash so no input can escape its\n * namespace directory or collide with a sibling by accident.\n */\nconst SAFE_SEGMENT_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;\n\nexport const isSafeSegment = (segment: string): boolean => SAFE_SEGMENT_PATTERN.test(segment);\n\nexport const sanitizeSegment = (segment: string): string => {\n if (isSafeSegment(segment)) {\n return segment;\n }\n return `h_${createHash(\"sha256\").update(segment, \"utf8\").digest(\"hex\").slice(0, 32)}`;\n};\n\n/** Scopes a state store to one provider deployed under one installation. */\nexport type StoreNamespace = {\n readonly providerId: string;\n readonly installationId: string;\n};\n\nexport const namespaceSegments = (namespace: StoreNamespace): readonly [string, string] => [\n sanitizeSegment(namespace.providerId),\n sanitizeSegment(namespace.installationId),\n];\n\n/** Stable, collision-resistant digest of a logical state key. */\nexport const keyDigest = (key: string): string =>\n createHash(\"sha256\").update(key, \"utf8\").digest(\"hex\");\n"],"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,M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AAc,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"]}
@@ -1,14 +1,14 @@
1
- import { b as SpanCorrelationResolver } from './semconv-CIU-2kGO.js';
2
- export { D as DEFAULT_INSTRUMENTATION_SCOPE, E as EventTraceIdentity, M as MAX_RECOVERED_START_ATTRIBUTES, S as SemanticMappingOptions, a as SpanCorrelation, c as SpanDisposition, d as SpanFamily, e as SpanOrphanClassification, f as SpanPairing, g as SpanScopeRef, h as canonicalEventTraceIdentities, i as canonicalEventsToReadableSpans, p as parentScopeRefOf, s as spanScopeRefOf, j as startOnlySpanAttributes } from './semconv-CIU-2kGO.js';
3
- import { o as OtlpTelemetrySink, n as OtlpLogTelemetrySink } from './otlp-log-sink-DTSa0KRF.js';
4
- export { C as ContentWithholdingReason, D as DurableLogSpool, a as DurableLogSpoolOptions, b as DurableSpool, c as DurableSpoolOptions, L as LOG_MAPPING_VERSION, d as LOG_SIGNALS, e as LogContentPolicy, f as LogMappingOptions, g as LogMappingResult, h as LogSignal, i as LogSpoolBatch, j as LogsDeliverability, M as MAX_LOG_BODY_CHARACTERS, k as MAX_LOG_RECORDS_PER_BATCH, l as MAX_LOG_RECORDS_PER_EVENT, m as MCP_TOOL_NAME_PATTERN, N as NO_LOG_CONTENT, O as OtlpLogSinkOptions, p as OtlpTraceSinkOptions, S as SerializedLogRecord, q as SerializedSpan, r as SpoolBatch, s as SpoolDrainResult, t as SpoolEnqueueResult, u as canonicalEventsToLogRecords, v as createFileDurableLogSpool, w as createFileDurableSpool, x as createOtlpLogSink, y as createOtlpTraceSink, z as describeLogsDeliverability, A as logSignalOf, B as logSignalsForLifecycleEvents, E as resolveLogsEndpoint } from './otlp-log-sink-DTSa0KRF.js';
1
+ import { b as SpanCorrelationResolver } from './semconv-CtnDdsPk.js';
2
+ export { D as DEFAULT_INSTRUMENTATION_SCOPE, E as EventTraceIdentity, M as MAX_RECOVERED_START_ATTRIBUTES, S as SemanticMappingOptions, a as SpanCorrelation, c as SpanDisposition, d as SpanFamily, e as SpanOrphanClassification, f as SpanPairing, g as SpanScopeRef, h as canonicalEventTraceIdentities, i as canonicalEventsToReadableSpans, p as parentScopeRefOf, s as spanScopeRefOf, j as startOnlySpanAttributes } from './semconv-CtnDdsPk.js';
3
+ import { o as OtlpTelemetrySink, n as OtlpLogTelemetrySink } from './otlp-log-sink-DaZDPKnR.js';
4
+ export { C as ContentWithholdingReason, D as DurableLogSpool, a as DurableLogSpoolOptions, b as DurableSpool, c as DurableSpoolOptions, L as LOG_MAPPING_VERSION, d as LOG_SIGNALS, e as LogContentPolicy, f as LogMappingOptions, g as LogMappingResult, h as LogSignal, i as LogSpoolBatch, j as LogsDeliverability, M as MAX_LOG_BODY_CHARACTERS, k as MAX_LOG_RECORDS_PER_BATCH, l as MAX_LOG_RECORDS_PER_EVENT, m as MCP_TOOL_NAME_PATTERN, N as NO_LOG_CONTENT, O as OtlpLogSinkOptions, p as OtlpTraceSinkOptions, S as SerializedLogRecord, q as SerializedSpan, r as SpoolBatch, s as SpoolDrainResult, t as SpoolEnqueueResult, u as canonicalEventsToLogRecords, v as createFileDurableLogSpool, w as createFileDurableSpool, x as createOtlpLogSink, y as createOtlpTraceSink, z as describeLogsDeliverability, A as logSignalOf, B as logSignalsForLifecycleEvents, E as resolveLogsEndpoint } from './otlp-log-sink-DaZDPKnR.js';
5
5
  import { DeliveryHealthSnapshot } from './diagnostics.js';
6
- import { f as TelemetrySink } from './ports-Q8x0ODhs.js';
6
+ import { g as TelemetrySink } from './ports-B0rC49b3.js';
7
7
  import '@opentelemetry/api';
8
8
  import '@opentelemetry/core';
9
9
  import '@opentelemetry/resources';
10
10
  import '@opentelemetry/sdk-trace';
11
- import './events-VxBnDFaO.js';
11
+ import './events-CzZ5kukS.js';
12
12
  import 'zod';
13
13
  import './schema-Cn0-xz8L.js';
14
14
  import './keys-Dej5bN3L.js';
package/dist/telemetry.js CHANGED
@@ -38,7 +38,7 @@ import {
38
38
  } from "@opentelemetry/semantic-conventions/incubating";
39
39
 
40
40
  // src/version.ts
41
- var VERSION = "0.3.0";
41
+ var VERSION = "0.5.0";
42
42
 
43
43
  // src/telemetry/export-identity.ts
44
44
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -54,6 +54,27 @@ var ATTR_OTELHOOK_PROVIDER_ID = "otelhook.provider.id";
54
54
  var ATTR_OTELHOOK_PROVIDER_VERSION = "otelhook.provider.version";
55
55
  var ATTR_OTELHOOK_WORKSPACE_ID = "otelhook.workspace.id";
56
56
  var HAR_SESSION_KEY = "har.session_key";
57
+ var ATTR_OTELHOOK_SUBAGENT_ID = "otelhook.subagent.id";
58
+ var ATTR_VCS_REF_HEAD_NAME = "vcs.ref.head.name";
59
+ var ATTR_OTELHOOK_TARGET_WORKSPACE_ID = "otelhook.target.workspace.id";
60
+ var ATTR_OTELHOOK_TARGET_SOURCE = "otelhook.target.source";
61
+ var ATTR_OTELHOOK_TARGET_REPOSITORY_ID = "otelhook.target.repository.id";
62
+ var ATTR_OTELHOOK_TARGET_WORKTREE_KIND = "otelhook.target.worktree.kind";
63
+ var ATTR_OTELHOOK_USAGE_TEMPORALITY = "otelhook.usage.temporality";
64
+ var targetAttributes = (event) => {
65
+ if (event.type !== "tool.start" && event.type !== "tool.end" || event.target === void 0) {
66
+ return {};
67
+ }
68
+ const { target } = event;
69
+ return {
70
+ [ATTR_OTELHOOK_TARGET_WORKSPACE_ID]: target.workspaceId,
71
+ [ATTR_OTELHOOK_TARGET_SOURCE]: target.source,
72
+ ...target.vcsBranchName === void 0 ? {} : { [ATTR_VCS_REF_HEAD_NAME]: target.vcsBranchName },
73
+ ...target.repositoryId === void 0 ? {} : { [ATTR_OTELHOOK_TARGET_REPOSITORY_ID]: target.repositoryId },
74
+ ...target.worktreeKind === void 0 ? {} : { [ATTR_OTELHOOK_TARGET_WORKTREE_KIND]: target.worktreeKind }
75
+ };
76
+ };
77
+ var usageTemporalityAttributes = (usage) => usage === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_TEMPORALITY]: usage.temporality };
57
78
  var isPrimitiveAttribute = (value) => typeof value === "string" || typeof value === "number" || typeof value === "boolean";
58
79
  var passthroughHarAttributes = (resource) => {
59
80
  const attributes = {};
@@ -89,6 +110,7 @@ var exportIdentityAttributes = (event, resource, ids) => {
89
110
  [ATTR_OTELHOOK_PROVIDER_ID]: event.provenance.providerId,
90
111
  ...event.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event.provenance.providerVersion },
91
112
  [ATTR_OTELHOOK_WORKSPACE_ID]: event.workspace.workspaceId,
113
+ ...event.subagentId === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event.subagentId },
92
114
  ...passthroughHarAttributes(resource),
93
115
  ...hexTraceAttributes(ids)
94
116
  };
@@ -110,6 +132,7 @@ var ATTR_OTELHOOK_DELEGATION_DEPTH = "otelhook.delegation_depth";
110
132
  var ATTR_OTELHOOK_COMPACTION_TRIGGER = "otelhook.compaction.trigger";
111
133
  var ATTR_OTELHOOK_AGENT_NAME = "otelhook.agent.name";
112
134
  var ATTR_OTELHOOK_AGENT_VERSION = "otelhook.agent.version";
135
+ var ATTR_OTELHOOK_GENERATION_ID = "otelhook.generation.id";
113
136
  var FIELD_SEPARATOR = "\0";
114
137
  var digestHex = (parts, length) => createHash("sha256").update(parts.join(FIELD_SEPARATOR)).digest("hex").slice(0, length);
115
138
  var MAX_RECOVERED_START_ATTRIBUTES = 16;
@@ -176,8 +199,10 @@ var startOnlySpanAttributes = (event) => {
176
199
  };
177
200
  // `toolName` and `toolCallId` are on both tool edges, so they are not
178
201
  // start-only and persisting them would just pad every record.
202
+ // The target is carried forward too: an end-only process may see a payload
203
+ // with less to go on (no tool input), and the start's evidence still holds.
179
204
  case "tool.start":
180
- return { [ATTR_OTELHOOK_TOOL_KIND]: event.toolKind };
205
+ return { [ATTR_OTELHOOK_TOOL_KIND]: event.toolKind, ...targetAttributes(event) };
181
206
  case "subagent.start":
182
207
  return { [ATTR_OTELHOOK_DELEGATION_DEPTH]: event.delegationDepth };
183
208
  default:
@@ -208,9 +233,54 @@ var usageAttributes = (usage, resetDetected) => {
208
233
  [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: usage.cachedInputTokens,
209
234
  [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: usage.cacheCreationInputTokens,
210
235
  [ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]: usage.reasoningOutputTokens,
236
+ ...usageTemporalityAttributes(usage),
211
237
  ...resetDetected ? { [ATTR_OTELHOOK_RESET_DETECTED]: true } : {}
212
238
  };
213
239
  };
240
+ var TARGET_SOURCE_RANK = Object.freeze({
241
+ "tool-path": 3,
242
+ "shell-cwd": 2,
243
+ "session-cwd": 1
244
+ });
245
+ var TARGET_KEYS = [
246
+ ATTR_OTELHOOK_TARGET_WORKSPACE_ID,
247
+ ATTR_OTELHOOK_TARGET_SOURCE,
248
+ ATTR_VCS_REF_HEAD_NAME,
249
+ ATTR_OTELHOOK_TARGET_REPOSITORY_ID,
250
+ ATTR_OTELHOOK_TARGET_WORKTREE_KIND
251
+ ];
252
+ var pickTarget = (attributes) => {
253
+ const picked = {};
254
+ for (const key of TARGET_KEYS) {
255
+ if (attributes[key] !== void 0) {
256
+ picked[key] = attributes[key];
257
+ }
258
+ }
259
+ return picked;
260
+ };
261
+ var withoutTarget = (attributes) => {
262
+ const rest = { ...attributes };
263
+ for (const key of TARGET_KEYS) {
264
+ delete rest[key];
265
+ }
266
+ return rest;
267
+ };
268
+ var rankOf = (candidate) => {
269
+ const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];
270
+ return typeof source === "string" && Object.hasOwn(TARGET_SOURCE_RANK, source) ? TARGET_SOURCE_RANK[source] ?? 0 : 0;
271
+ };
272
+ var strongestTarget = (candidates) => {
273
+ let best = {};
274
+ let bestRank = 0;
275
+ for (const candidate of candidates) {
276
+ const rank = rankOf(candidate);
277
+ if (rank > 0 && rank >= bestRank) {
278
+ best = candidate;
279
+ bestRank = rank;
280
+ }
281
+ }
282
+ return best;
283
+ };
214
284
  var buildSpanContext = (traceId, spanId) => ({
215
285
  traceId,
216
286
  spanId,
@@ -321,6 +391,9 @@ var buildLifecycleSpan = (plan, resource, scope) => {
321
391
  ...model?.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM]: model.vendor },
322
392
  ...start?.model?.modelId === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL]: start.model.modelId },
323
393
  ...end?.model?.modelId === void 0 ? {} : { [ATTR_GEN_AI_RESPONSE_MODEL]: end.model.modelId },
394
+ // The provider's own id for this unit of work (Cursor generation,
395
+ // Codex turn): the key a consumer stores a usage observation under.
396
+ [ATTR_OTELHOOK_GENERATION_ID]: group.ref.scopeKey,
324
397
  ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
325
398
  ...usageAttributes(end?.usage, false)
326
399
  };
@@ -334,11 +407,17 @@ var buildLifecycleSpan = (plan, resource, scope) => {
334
407
  name = `tool ${toolName}`;
335
408
  kind = SpanKind.CLIENT;
336
409
  attributes = {
337
- ...attributes,
410
+ // Target keys are re-chosen below as one unit, never mixed across edges.
411
+ ...withoutTarget(attributes),
338
412
  [ATTR_GEN_AI_TOOL_NAME]: toolName,
339
413
  [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,
340
414
  ...start?.toolKind === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind },
341
- ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }
415
+ ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
416
+ ...strongestTarget([
417
+ pickTarget(resolved.recovered),
418
+ start === void 0 ? {} : targetAttributes(start),
419
+ end === void 0 ? {} : targetAttributes(end)
420
+ ])
342
421
  };
343
422
  status = outcomeStatus(end?.outcome);
344
423
  break;
@@ -1548,7 +1627,7 @@ var ATTR_OTELHOOK_AGENT_VERSION2 = "otelhook.agent.version";
1548
1627
  var ATTR_OTELHOOK_SESSION_KIND = "otelhook.session.kind";
1549
1628
  var ATTR_OTELHOOK_PROMPT_SOURCE = "otelhook.prompt.source";
1550
1629
  var ATTR_OTELHOOK_PROMPT_TURN_INDEX = "otelhook.prompt.turn_index";
1551
- var ATTR_OTELHOOK_GENERATION_ID = "otelhook.generation.id";
1630
+ var ATTR_OTELHOOK_GENERATION_ID2 = "otelhook.generation.id";
1552
1631
  var ATTR_OTELHOOK_STOP_REASON = "otelhook.generation.stop_reason";
1553
1632
  var ATTR_OTELHOOK_COMPACTION_TRIGGER2 = "otelhook.compaction.trigger";
1554
1633
  var ATTR_OTELHOOK_CONTEXT_TOKENS_BEFORE = "otelhook.compaction.context_tokens_before";
@@ -1707,14 +1786,14 @@ var eventAttributes = (event) => {
1707
1786
  case "generation.start":
1708
1787
  return {
1709
1788
  [ATTR_GEN_AI_OPERATION_NAME2]: "chat",
1710
- [ATTR_OTELHOOK_GENERATION_ID]: event.generationId,
1789
+ [ATTR_OTELHOOK_GENERATION_ID2]: event.generationId,
1711
1790
  [ATTR_GEN_AI_REQUEST_MODEL2]: event.model.modelId,
1712
1791
  ...event.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event.model.vendor }
1713
1792
  };
1714
1793
  case "generation.end":
1715
1794
  return {
1716
1795
  [ATTR_GEN_AI_OPERATION_NAME2]: "chat",
1717
- [ATTR_OTELHOOK_GENERATION_ID]: event.generationId,
1796
+ [ATTR_OTELHOOK_GENERATION_ID2]: event.generationId,
1718
1797
  [ATTR_GEN_AI_RESPONSE_MODEL2]: event.model.modelId,
1719
1798
  ...event.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event.model.vendor },
1720
1799
  [ATTR_OTELHOOK_OUTCOME2]: event.outcome,
@@ -1726,14 +1805,16 @@ var eventAttributes = (event) => {
1726
1805
  [ATTR_GEN_AI_TOOL_NAME2]: event.toolName,
1727
1806
  [ATTR_GEN_AI_TOOL_CALL_ID2]: event.toolCallId,
1728
1807
  [ATTR_OTELHOOK_TOOL_KIND2]: event.toolKind,
1729
- ...event.generationId === void 0 ? {} : { [ATTR_OTELHOOK_GENERATION_ID]: event.generationId }
1808
+ ...event.generationId === void 0 ? {} : { [ATTR_OTELHOOK_GENERATION_ID2]: event.generationId },
1809
+ ...targetAttributes(event)
1730
1810
  };
1731
1811
  case "tool.end":
1732
1812
  return {
1733
1813
  [ATTR_GEN_AI_TOOL_NAME2]: event.toolName,
1734
1814
  [ATTR_GEN_AI_TOOL_CALL_ID2]: event.toolCallId,
1735
1815
  [ATTR_OTELHOOK_OUTCOME2]: event.outcome,
1736
- ...event.permissionDecision === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_PERMISSION]: event.permissionDecision }
1816
+ ...event.permissionDecision === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_PERMISSION]: event.permissionDecision },
1817
+ ...targetAttributes(event)
1737
1818
  };
1738
1819
  case "subagent.start":
1739
1820
  return {
@@ -1767,7 +1848,8 @@ var usageAttributes2 = (usage) => usage === void 0 ? {} : {
1767
1848
  [ATTR_GEN_AI_USAGE_INPUT_TOKENS2]: usage.inputTokens,
1768
1849
  [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS2]: usage.outputTokens,
1769
1850
  [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS2]: usage.cachedInputTokens,
1770
- [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS2]: usage.cacheCreationInputTokens
1851
+ [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS2]: usage.cacheCreationInputTokens,
1852
+ ...usageTemporalityAttributes(usage)
1771
1853
  };
1772
1854
  var contentFactsOf = (event) => {
1773
1855
  switch (event.type) {