@osfactory/otel-hook 0.1.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.
- package/LICENSE +21 -0
- package/README.md +1020 -0
- package/dist/adapter-DIgRACtL.d.ts +303 -0
- package/dist/cli.js +12607 -0
- package/dist/cli.js.map +1 -0
- package/dist/config.d.ts +233 -0
- package/dist/config.js +996 -0
- package/dist/config.js.map +1 -0
- package/dist/content-CoB7aNP1.d.ts +118 -0
- package/dist/diagnostics.d.ts +58 -0
- package/dist/diagnostics.js +46 -0
- package/dist/diagnostics.js.map +1 -0
- package/dist/errors.d.ts +91 -0
- package/dist/errors.js +322 -0
- package/dist/errors.js.map +1 -0
- package/dist/events-VxBnDFaO.d.ts +2044 -0
- package/dist/filesystem-store-J8jjDMTh.d.ts +65 -0
- package/dist/hook-CGpo-vks.d.ts +292 -0
- package/dist/identity-BrVBs901.d.ts +227 -0
- package/dist/index.d.ts +44 -0
- package/dist/index.js +11798 -0
- package/dist/index.js.map +1 -0
- package/dist/install.d.ts +1021 -0
- package/dist/install.js +3271 -0
- package/dist/install.js.map +1 -0
- package/dist/integration.d.ts +303 -0
- package/dist/integration.js +5942 -0
- package/dist/integration.js.map +1 -0
- package/dist/keys-Dej5bN3L.d.ts +7 -0
- package/dist/lifecycle.d.ts +428 -0
- package/dist/lifecycle.js +1077 -0
- package/dist/lifecycle.js.map +1 -0
- package/dist/memory-DXVBc8V9.d.ts +94 -0
- package/dist/model.d.ts +45 -0
- package/dist/model.js +1023 -0
- package/dist/model.js.map +1 -0
- package/dist/otlp-log-sink-CeIFDDpn.d.ts +457 -0
- package/dist/payload-CHr53E_v.d.ts +201 -0
- package/dist/policy-D1CrlYn3.d.ts +73 -0
- package/dist/ports-Q8x0ODhs.d.ts +200 -0
- package/dist/primitives-CJ8-rn-f.d.ts +75 -0
- package/dist/privacy.d.ts +51 -0
- package/dist/privacy.js +633 -0
- package/dist/privacy.js.map +1 -0
- package/dist/providers.d.ts +257 -0
- package/dist/providers.js +4398 -0
- package/dist/providers.js.map +1 -0
- package/dist/registry-BzYmC9OC.d.ts +49 -0
- package/dist/runtime.d.ts +32 -0
- package/dist/runtime.js +2907 -0
- package/dist/runtime.js.map +1 -0
- package/dist/schema-Cn0-xz8L.d.ts +224 -0
- package/dist/semconv-Baoz-0OI.d.ts +188 -0
- package/dist/service-j4jEO6cZ.d.ts +68 -0
- package/dist/state.d.ts +36 -0
- package/dist/state.js +710 -0
- package/dist/state.js.map +1 -0
- package/dist/taxonomy-DwhTtuWd.d.ts +87 -0
- package/dist/telemetry.d.ts +77 -0
- package/dist/telemetry.js +2294 -0
- package/dist/telemetry.js.map +1 -0
- package/dist/testing.d.ts +155 -0
- package/dist/testing.js +6513 -0
- package/dist/testing.js.map +1 -0
- package/package.json +124 -0
|
@@ -0,0 +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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AY,QAAQ,OAAO;AAAA,QACnC;AACA,kBAAU,CAAC;AAAA,MACb;AACA,iBAAW,SAAS,SAAS;AAC3B,YAAI,WAAW,KAAK;AAClB;AAAA,QACF;AACA,YAAI,CAAC,MAAM,SAAS,OAAO,KAAK,MAAM,WAAW,OAAO,GAAG;AACzD;AAAA,QACF;AACA,mBAAW;AACX,cAAM,WAAgB,UAAK,YAAY,KAAK;AAC5C,YAAI;AAKF,gBAAM,MAAM,MAAM,SAAS,UAAU,MAAM;AAC3C,gBAAM,WAAW,KAAK,MAAM,GAAG;AAC/B,gBAAM,YAAY,SAAS,QAAQ;AACnC,cAAI,OAAO,cAAc,YAAY,MAAM,YAAY,cAAc;AACnE,kBAAM,OAAO,QAAQ,EAAE,MAAM,MAAM,MAAS;AAC5C,uBAAW;AAAA,UACb;AAAA,QACF,QAAQ;AACN;AAAA,QACF;AAAA,MACF;AAEA,UAAI;AACJ,UAAI;AACF,sBAAc,MAAM,QAAQ,QAAQ;AAAA,MACtC,QAAQ;AACN,sBAAc,CAAC;AAAA,MACjB;AACA,iBAAW,SAAS,aAAa;AAC/B,cAAM,WAAgB,UAAK,UAAU,KAAK;AAC1C,YAAI;AACF,gBAAM,MAAM,MAAM,SAAS,UAAU,MAAM;AAC3C,gBAAM,SAAS,KAAK,MAAM,GAAG;AAC7B,cAAI,OAAO,OAAO,eAAe,YAAY,MAAM,OAAO,aAAa,iBAAiB;AACtF,kBAAM,OAAO,QAAQ,EAAE,MAAM,MAAM,MAAS;AAAA,UAC9C;AAAA,QACF,QAAQ;AACN;AAAA,QACF;AAAA,MACF;AAEA,aAAO,EAAE,SAAS,QAAQ;AAAA,IAC5B;AAAA,EACF;AACF;","names":["z","z","z","z"]}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Closed set of error codes. Adding a code is a minor change; changing what a
|
|
5
|
+
* code means is a breaking change.
|
|
6
|
+
*/
|
|
7
|
+
declare const otelHookErrorCodeSchema: z.ZodEnum<{
|
|
8
|
+
"invalid-input": "invalid-input";
|
|
9
|
+
"schema-validation-failed": "schema-validation-failed";
|
|
10
|
+
"provider-unknown": "provider-unknown";
|
|
11
|
+
"provider-detection-ambiguous": "provider-detection-ambiguous";
|
|
12
|
+
"provider-adapter-failure": "provider-adapter-failure";
|
|
13
|
+
"identity-conflict": "identity-conflict";
|
|
14
|
+
"identity-incomplete": "identity-incomplete";
|
|
15
|
+
"usage-invalid": "usage-invalid";
|
|
16
|
+
"state-store-failure": "state-store-failure";
|
|
17
|
+
"telemetry-export-failure": "telemetry-export-failure";
|
|
18
|
+
"privacy-policy-violation": "privacy-policy-violation";
|
|
19
|
+
"configuration-invalid": "configuration-invalid";
|
|
20
|
+
"limit-exceeded": "limit-exceeded";
|
|
21
|
+
"delivery-identifier-unavailable": "delivery-identifier-unavailable";
|
|
22
|
+
"delivery-claim-superseded": "delivery-claim-superseded";
|
|
23
|
+
"internal-error": "internal-error";
|
|
24
|
+
}>;
|
|
25
|
+
type OtelHookErrorCode = z.infer<typeof otelHookErrorCodeSchema>;
|
|
26
|
+
declare const errorSeveritySchema: z.ZodEnum<{
|
|
27
|
+
error: "error";
|
|
28
|
+
warning: "warning";
|
|
29
|
+
}>;
|
|
30
|
+
type ErrorSeverity = z.infer<typeof errorSeveritySchema>;
|
|
31
|
+
/** Pipeline stage where a failure occurred. */
|
|
32
|
+
declare const errorPhaseSchema: z.ZodEnum<{
|
|
33
|
+
identity: "identity";
|
|
34
|
+
configuration: "configuration";
|
|
35
|
+
detection: "detection";
|
|
36
|
+
parsing: "parsing";
|
|
37
|
+
normalization: "normalization";
|
|
38
|
+
privacy: "privacy";
|
|
39
|
+
state: "state";
|
|
40
|
+
export: "export";
|
|
41
|
+
shutdown: "shutdown";
|
|
42
|
+
}>;
|
|
43
|
+
type ErrorPhase = z.infer<typeof errorPhaseSchema>;
|
|
44
|
+
/**
|
|
45
|
+
* Which of the two safety postures a code participates in.
|
|
46
|
+
*
|
|
47
|
+
* - `fail-open`: the hook still reports success to the host agent. Telemetry may
|
|
48
|
+
* be incomplete; the coding agent is never blocked.
|
|
49
|
+
* - `fail-closed-attribution`: the observation is not attributed to a session or
|
|
50
|
+
* provider. Data is dropped rather than labelled with a guess.
|
|
51
|
+
*/
|
|
52
|
+
declare const failurePostureSchema: z.ZodEnum<{
|
|
53
|
+
"fail-open": "fail-open";
|
|
54
|
+
"fail-closed-attribution": "fail-closed-attribution";
|
|
55
|
+
}>;
|
|
56
|
+
type FailurePosture = z.infer<typeof failurePostureSchema>;
|
|
57
|
+
type ErrorCodeDescriptor = {
|
|
58
|
+
readonly code: OtelHookErrorCode;
|
|
59
|
+
readonly severity: ErrorSeverity;
|
|
60
|
+
readonly posture: FailurePosture;
|
|
61
|
+
/** Whether retrying the same input could succeed. */
|
|
62
|
+
readonly retryable: boolean;
|
|
63
|
+
readonly summary: string;
|
|
64
|
+
};
|
|
65
|
+
declare const ERROR_TAXONOMY: Readonly<Record<OtelHookErrorCode, ErrorCodeDescriptor>>;
|
|
66
|
+
declare const describeErrorCode: (code: OtelHookErrorCode) => ErrorCodeDescriptor;
|
|
67
|
+
/** Outcome of attributing an observation to a provider and session. */
|
|
68
|
+
declare const attributionOutcomeSchema: z.ZodEnum<{
|
|
69
|
+
attributed: "attributed";
|
|
70
|
+
declined: "declined";
|
|
71
|
+
failed: "failed";
|
|
72
|
+
"not-applicable": "not-applicable";
|
|
73
|
+
}>;
|
|
74
|
+
type AttributionOutcome = z.infer<typeof attributionOutcomeSchema>;
|
|
75
|
+
declare const attributionReasonSchema: z.ZodEnum<{
|
|
76
|
+
"invalid-input": "invalid-input";
|
|
77
|
+
"provider-unknown": "provider-unknown";
|
|
78
|
+
"provider-detection-ambiguous": "provider-detection-ambiguous";
|
|
79
|
+
"identity-conflict": "identity-conflict";
|
|
80
|
+
"identity-incomplete": "identity-incomplete";
|
|
81
|
+
"internal-error": "internal-error";
|
|
82
|
+
"adapter-ignored-input": "adapter-ignored-input";
|
|
83
|
+
"adapter-failure": "adapter-failure";
|
|
84
|
+
}>;
|
|
85
|
+
type AttributionReason = z.infer<typeof attributionReasonSchema>;
|
|
86
|
+
|
|
87
|
+
export { type AttributionOutcome as A, ERROR_TAXONOMY as E, type FailurePosture as F, type OtelHookErrorCode as O, type AttributionReason as a, type ErrorCodeDescriptor as b, type ErrorPhase as c, type ErrorSeverity as d, attributionOutcomeSchema as e, attributionReasonSchema as f, describeErrorCode as g, errorPhaseSchema as h, errorSeveritySchema as i, failurePostureSchema as j, otelHookErrorCodeSchema as o };
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { b as SpanCorrelationResolver } from './semconv-Baoz-0OI.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-Baoz-0OI.js';
|
|
3
|
+
import { o as OtlpTelemetrySink, n as OtlpLogTelemetrySink } from './otlp-log-sink-CeIFDDpn.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-CeIFDDpn.js';
|
|
5
|
+
import { DeliveryHealthSnapshot } from './diagnostics.js';
|
|
6
|
+
import { f as TelemetrySink } from './ports-Q8x0ODhs.js';
|
|
7
|
+
import '@opentelemetry/api';
|
|
8
|
+
import '@opentelemetry/core';
|
|
9
|
+
import '@opentelemetry/resources';
|
|
10
|
+
import '@opentelemetry/sdk-trace';
|
|
11
|
+
import './events-VxBnDFaO.js';
|
|
12
|
+
import 'zod';
|
|
13
|
+
import './schema-Cn0-xz8L.js';
|
|
14
|
+
import './keys-Dej5bN3L.js';
|
|
15
|
+
import '@opentelemetry/sdk-logs';
|
|
16
|
+
import './content-CoB7aNP1.js';
|
|
17
|
+
import './primitives-CJ8-rn-f.js';
|
|
18
|
+
import './taxonomy-DwhTtuWd.js';
|
|
19
|
+
import './errors.js';
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* One canonical batch, two OTLP signals.
|
|
23
|
+
*
|
|
24
|
+
* A hook has a single {@link TelemetrySink} seam, and both signals map the *same*
|
|
25
|
+
* canonical events — so this fans one batch out rather than making the orchestrator
|
|
26
|
+
* aware that there is more than one destination.
|
|
27
|
+
*
|
|
28
|
+
* ## Durability adds up across signals
|
|
29
|
+
*
|
|
30
|
+
* The counts are summed rather than taken from the primary signal, because the
|
|
31
|
+
* caller's question is "may I commit this callback?" and the answer turns on whether
|
|
32
|
+
* *anything* reached a collector or a spool. Summing gives `classifyDurability`
|
|
33
|
+
* exactly the right inputs:
|
|
34
|
+
*
|
|
35
|
+
* - both signals delivered → `delivered`
|
|
36
|
+
* - neither delivered → `lost`, and the callback is safe to retry precisely because
|
|
37
|
+
* there is nothing to duplicate
|
|
38
|
+
* - one delivered and one did not → `partial`, which is terminal: retrying would
|
|
39
|
+
* re-export what the healthy signal already delivered, and a duplicate silently
|
|
40
|
+
* corrupts a total whereas a reported loss is a number somebody can act on
|
|
41
|
+
*
|
|
42
|
+
* A disabled sink accepts everything, so an installation with logs off behaves
|
|
43
|
+
* exactly as it did before logs existed.
|
|
44
|
+
*
|
|
45
|
+
* ## Correlation must be resolved once per batch
|
|
46
|
+
*
|
|
47
|
+
* Both sinks want the same pairing facts, and `SpanCorrelator.correlateBatch` is not
|
|
48
|
+
* a read — it records a start edge, marks a scope published, and takes the session
|
|
49
|
+
* lock to do it. Wrap the correlator in {@link shareCorrelationPerBatch} and give
|
|
50
|
+
* *the same wrapped function* to both sinks; `emit` here is sequential so the first
|
|
51
|
+
* sink resolves it and the second is served the memoized answer.
|
|
52
|
+
*/
|
|
53
|
+
type SignalFanoutOptions = {
|
|
54
|
+
readonly traces: OtlpTelemetrySink;
|
|
55
|
+
readonly logs: OtlpLogTelemetrySink;
|
|
56
|
+
};
|
|
57
|
+
interface SignalFanoutSink extends TelemetrySink {
|
|
58
|
+
/** One snapshot per wired signal, in a stable order: traces, then logs. */
|
|
59
|
+
health(): readonly DeliveryHealthSnapshot[];
|
|
60
|
+
}
|
|
61
|
+
declare const createSignalFanout: (options: SignalFanoutOptions) => SignalFanoutSink;
|
|
62
|
+
/**
|
|
63
|
+
* Wrap a correlation resolver so one batch resolves at most once.
|
|
64
|
+
*
|
|
65
|
+
* Memoized on the identity of the `events` array, which is what makes it correct
|
|
66
|
+
* without a reset: every batch is a distinct array, so a new batch cannot be served
|
|
67
|
+
* a previous one's answer, and a retry of the *same* array deliberately is. The
|
|
68
|
+
* promise is cached rather than its value, so two callers arriving before the first
|
|
69
|
+
* resolution completes still share it.
|
|
70
|
+
*
|
|
71
|
+
* Exported because the one-call-per-batch property is a requirement of the
|
|
72
|
+
* correlator, not a convenience of the fanout: a host wiring its own pair of sinks
|
|
73
|
+
* needs to be able to express it too.
|
|
74
|
+
*/
|
|
75
|
+
declare const shareCorrelationPerBatch: (correlate: SpanCorrelationResolver) => SpanCorrelationResolver;
|
|
76
|
+
|
|
77
|
+
export { OtlpLogTelemetrySink, OtlpTelemetrySink, type SignalFanoutOptions, type SignalFanoutSink, SpanCorrelationResolver, createSignalFanout, shareCorrelationPerBatch };
|