@osfactory/otel-hook 0.11.0 → 0.12.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 (49) hide show
  1. package/README.md +26 -1
  2. package/dist/{adapter-DiLknaTF.d.ts → adapter-DQiPu8xF.d.ts} +2 -2
  3. package/dist/cli.js +371 -65
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +3 -3
  6. package/dist/config.js +16 -3
  7. package/dist/config.js.map +1 -1
  8. package/dist/{destinations-BIl3gGzx.d.ts → destinations-DvqsPulb.d.ts} +1 -1
  9. package/dist/{events-CSD_YiJ2.d.ts → events-fcomX6d5.d.ts} +22 -0
  10. package/dist/{export-destinations-QWKGGEjk.d.ts → export-destinations-CI7z4n3i.d.ts} +11 -6
  11. package/dist/{filesystem-store-D3SCNmbX.d.ts → filesystem-store-CmnUlj1O.d.ts} +1 -1
  12. package/dist/{hook-BOecWGSz.d.ts → hook-vM_cgqS2.d.ts} +11 -5
  13. package/dist/index.d.ts +14 -14
  14. package/dist/index.js +389 -100
  15. package/dist/index.js.map +1 -1
  16. package/dist/install.d.ts +4 -4
  17. package/dist/install.js +9 -1
  18. package/dist/install.js.map +1 -1
  19. package/dist/integration.d.ts +16 -10
  20. package/dist/integration.js +341 -71
  21. package/dist/integration.js.map +1 -1
  22. package/dist/lifecycle.d.ts +3 -3
  23. package/dist/lifecycle.js +10 -2
  24. package/dist/lifecycle.js.map +1 -1
  25. package/dist/{memory-Cs51jyRk.d.ts → memory-DdU1U91y.d.ts} +2 -2
  26. package/dist/{metric-model-DDnWxL9d.d.ts → metric-model-C9lLqqpI.d.ts} +4 -1
  27. package/dist/model.d.ts +1 -1
  28. package/dist/model.js +9 -1
  29. package/dist/model.js.map +1 -1
  30. package/dist/{payload-ChtrEX6A.d.ts → payload-BT19hiVZ.d.ts} +1 -1
  31. package/dist/{ports-CeqLq31i.d.ts → ports-C3k_5eOQ.d.ts} +33 -2
  32. package/dist/providers.d.ts +10 -10
  33. package/dist/providers.js +10 -1
  34. package/dist/providers.js.map +1 -1
  35. package/dist/{registry-CcJNF3WY.d.ts → registry-gyJqaWmp.d.ts} +2 -2
  36. package/dist/runtime.d.ts +97 -9
  37. package/dist/runtime.js +257 -24
  38. package/dist/runtime.js.map +1 -1
  39. package/dist/{schema-DMnoU1V_.d.ts → schema-SpFM6YQY.d.ts} +24 -1
  40. package/dist/state.d.ts +4 -4
  41. package/dist/state.js +9 -1
  42. package/dist/state.js.map +1 -1
  43. package/dist/telemetry.d.ts +6 -6
  44. package/dist/telemetry.js +77 -22
  45. package/dist/telemetry.js.map +1 -1
  46. package/dist/testing.d.ts +10 -8
  47. package/dist/testing.js +109 -24
  48. package/dist/testing.js.map +1 -1
  49. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
- import { C as Clock, I as IdGenerator, g as StateStore, S as StateRecord, c as LogLevel, d as Logger, i as TelemetrySink } from './ports-CeqLq31i.js';
2
- import { b as CanonicalEvent } from './events-CSD_YiJ2.js';
1
+ import { C as Clock, I as IdGenerator, j as StateStore, i as StateRecord, c as LogLevel, d as Logger, l as TelemetrySink } from './ports-C3k_5eOQ.js';
2
+ import { b as CanonicalEvent } from './events-fcomX6d5.js';
3
3
  import { b as Attributes } from './primitives-CJ8-rn-f.js';
4
4
 
5
5
  /** Clock backed by the host process. */
@@ -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, f as CanonicalUsage } from './events-CSD_YiJ2.js';
5
+ import { b as CanonicalEvent, f as CanonicalUsage } from './events-fcomX6d5.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. */
@@ -207,6 +207,9 @@ declare const canonicalEventsToReadableSpans: (events: readonly CanonicalEvent[]
207
207
  *
208
208
  * ## What is never on a metric
209
209
  *
210
+ * Session context attributes (`docs/session-context.md`) are on every data point
211
+ * of an event that has them, so a new context starts a new series.
212
+ *
210
213
  * No account identity (`user.*`, `enduser.*`, `organization.id`), no content, no
211
214
  * paths, and no per-event ids (`otelhook.event.id`, tool-call ids, generation ids):
212
215
  * an id per data point is a new series per data point. `session.id` is the one
package/dist/model.d.ts CHANGED
@@ -2,7 +2,7 @@ import { z } from 'zod';
2
2
  import { a as AttributeValue } from './primitives-CJ8-rn-f.js';
3
3
  export { A as AttributePrimitive, b as Attributes, D as DETECTION_CONFIDENCE_RANK, c as DetectionConfidence, E as EpochMillis, d as EventId, I as InvocationId, M as MAX_ATTRIBUTE_ARRAY_LENGTH, e as MAX_ATTRIBUTE_STRING_LENGTH, f as MAX_IDENTIFIER_LENGTH, P as PROVIDER_ID_PATTERN, g as ProviderId, R as ResolvedProviderId, S as SessionId, h as SourceTransport, U as UNKNOWN_PROVIDER_ID, i as UnknownProviderId, W as WORKSPACE_ID_PATTERN, j as WorkspaceId, k as attributePrimitiveSchema, l as attributeValueSchema, m as attributesSchema, n as compareDetectionConfidence, o as detectionConfidenceSchema, p as durationMillisSchema, q as epochMillisSchema, r as eventIdSchema, s as invocationIdSchema, t as isUnknownProvider, u as nonEmptyStringSchema, v as providerIdSchema, w as resolvedProviderIdSchema, x as sequenceNumberSchema, y as sessionIdSchema, z as sourceTransportSchema, B as tokenCountSchema, C as workspaceIdSchema } from './primitives-CJ8-rn-f.js';
4
4
  export { C as CONTENT_HASH_PATTERN, a as ContentDisclosure, b as ContentFact, c as ContentKind, d as ContentRole, e as contentDisclosureSchema, f as contentFactSchema, g as contentFactsSchema, h as contentKindSchema, i as contentRoleSchema, j as isContentFactConsistent, k as isUnavailableContentFact } from './content-M9xIKG7h.js';
5
- export { C as CANONICAL_EVENT_TYPES, a as CacheCreationAccounting, b as CanonicalEvent, c as CanonicalEventInput, d as CanonicalEventOfType, e as CanonicalEventType, f as CanonicalUsage, g as CompactionPerformedEvent, h as CostFacts, E as EMPTY_DELTA_USAGE, i as ErrorRaisedEvent, j as EventOutcome, k as EventValidationResult, G as GenerationEndEvent, l as GenerationStartEvent, M as MAX_TARGET_HINT_PATHS, m as MAX_TARGET_PATH_LENGTH, n as ModelDescriptor, P as PromptSubmittedEvent, o as ProviderTotalAgreement, S as SUBAGENT_ID_PATTERN, p as SessionEndEvent, q as SessionStartEvent, r as SubagentEndEvent, s as SubagentId, t as SubagentStartEvent, T as TARGETED_EVENT_TYPES, u as TargetHint, v as TargetSource, w as TargetedEvent, x as TargetedEventType, y as ToolEndEvent, z as ToolKind, A as ToolStartEvent, U as UsageDeltaResult, B as UsageNormalizationError, D as UsageNormalizationIssue, F as UsageNormalizationResult, H as UsageReport, I as UsageTemporality, W as WorkspaceTarget, J as WorktreeKind, K as addUsage, L as cacheCreationAccountingSchema, N as canonicalEventSchema, O as canonicalEventTypeSchema, Q as canonicalUsageSchema, R as compactionPerformedEventSchema, V as compareEvents, X as costFactsSchema, Y as cumulativeToDelta, Z as errorRaisedEventSchema, _ as eventUsage, $ as generationEndEventSchema, a0 as generationStartEventSchema, a1 as isTargetedEvent, a2 as modelDescriptorSchema, a3 as normalizeUsage, a4 as normalizeUsageOrThrow, a5 as parseCanonicalEvent, a6 as promptSubmittedEventSchema, a7 as providerTotalAgreementSchema, a8 as sessionCwdHint, a9 as sessionEndEventSchema, aa as sessionStartEventSchema, ab as subagentEndEventSchema, ac as subagentIdSchema, ad as subagentStartEventSchema, ae as targetHintSchema, af as targetSourceSchema, ag as toReport, ah as toolEndEventSchema, ai as toolKindSchema, aj as toolStartEventSchema, ak as usageReportSchema, al as usageTemporalitySchema, am as validateCanonicalEvent, an as workspaceTargetSchema, ao as worktreeKindSchema } from './events-CSD_YiJ2.js';
5
+ export { C as CANONICAL_EVENT_TYPES, a as CacheCreationAccounting, b as CanonicalEvent, c as CanonicalEventInput, d as CanonicalEventOfType, e as CanonicalEventType, f as CanonicalUsage, g as CompactionPerformedEvent, h as CostFacts, E as EMPTY_DELTA_USAGE, i as ErrorRaisedEvent, j as EventOutcome, k as EventValidationResult, G as GenerationEndEvent, l as GenerationStartEvent, M as MAX_TARGET_HINT_PATHS, m as MAX_TARGET_PATH_LENGTH, n as ModelDescriptor, P as PromptSubmittedEvent, o as ProviderTotalAgreement, S as SUBAGENT_ID_PATTERN, p as SessionEndEvent, q as SessionStartEvent, r as SubagentEndEvent, s as SubagentId, t as SubagentStartEvent, T as TARGETED_EVENT_TYPES, u as TargetHint, v as TargetSource, w as TargetedEvent, x as TargetedEventType, y as ToolEndEvent, z as ToolKind, A as ToolStartEvent, U as UsageDeltaResult, B as UsageNormalizationError, D as UsageNormalizationIssue, F as UsageNormalizationResult, H as UsageReport, I as UsageTemporality, W as WorkspaceTarget, J as WorktreeKind, K as addUsage, L as cacheCreationAccountingSchema, N as canonicalEventSchema, O as canonicalEventTypeSchema, Q as canonicalUsageSchema, R as compactionPerformedEventSchema, V as compareEvents, X as costFactsSchema, Y as cumulativeToDelta, Z as errorRaisedEventSchema, _ as eventUsage, $ as generationEndEventSchema, a0 as generationStartEventSchema, a1 as isTargetedEvent, a2 as modelDescriptorSchema, a3 as normalizeUsage, a4 as normalizeUsageOrThrow, a5 as parseCanonicalEvent, a6 as promptSubmittedEventSchema, a7 as providerTotalAgreementSchema, a8 as sessionCwdHint, a9 as sessionEndEventSchema, aa as sessionStartEventSchema, ab as subagentEndEventSchema, ac as subagentIdSchema, ad as subagentStartEventSchema, ae as targetHintSchema, af as targetSourceSchema, ag as toReport, ah as toolEndEventSchema, ai as toolKindSchema, aj as toolStartEventSchema, ak as usageReportSchema, al as usageTemporalitySchema, am as validateCanonicalEvent, an as workspaceTargetSchema, ao as worktreeKindSchema } from './events-fcomX6d5.js';
6
6
  export { C as ConsumerAttributes, I as IdentityClaim, a as IdentityClaimFields, b as IdentityConflict, c as IdentityResolution, d as InvocationIdentity, R as ResolveIdentityInput, S as SourceProvenance, U as UNKNOWN_WORKSPACE_ID, W as WorkspaceIdentity, e as WorkspaceKeySource, f as consumerAttributesSchema, i as identityClaimFieldsSchema, g as identityClaimSchema, h as invocationIdentitySchema, r as resolveInvocationIdentity, s as sourceProvenanceSchema, u as unknownWorkspaceIdentity, w as workspaceIdentitySchema, j as workspaceKeySourceSchema } from './identity-BrVBs901.js';
7
7
 
8
8
  /**
package/dist/model.js CHANGED
@@ -832,7 +832,15 @@ var baseEventFields = {
832
832
  * factory, never by hand.
833
833
  */
834
834
  subagentId: subagentIdSchema.optional(),
835
- extensions: extensionsSchema.default(emptyExtensions)
835
+ extensions: extensionsSchema.default(emptyExtensions),
836
+ /**
837
+ * Attributes of the session context segment in force when the event
838
+ * occurred (`docs/session-context.md`), stamped by the core from a file a
839
+ * harness wrote. Exported on every record of the event, over the same keys
840
+ * from the Resource. Absent when no context applies. Set by the core only,
841
+ * never by an adapter.
842
+ */
843
+ contextAttributes: z9.record(z9.string().min(1).max(255), z9.union([z9.string(), z9.number(), z9.boolean()])).optional()
836
844
  };
837
845
  var event = (shape) => z9.strictObject({ ...baseEventFields, ...shape });
838
846
  var sessionStartEventSchema = event({
package/dist/model.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/model/version.ts","../src/model/primitives.ts","../src/model/extensions.ts","../src/model/content.ts","../src/model/usage.ts","../src/model/identity.ts","../src/model/target.ts","../src/model/events.ts","../src/errors/taxonomy.ts"],"sourcesContent":["import { z } from \"zod\";\n\n/**\n * Version of the canonical event model.\n *\n * Every emitted event carries this value. Consumers must treat an unknown\n * version as unreadable rather than guessing field semantics.\n *\n * Compatibility rules:\n * - Additive optional fields do not change the version.\n * - Renaming, removing, or re-interpreting a field increments the version.\n */\nexport const CANONICAL_SCHEMA_VERSION = 1 as const;\n\nexport type CanonicalSchemaVersion = typeof CANONICAL_SCHEMA_VERSION;\n\nexport const canonicalSchemaVersionSchema = z.literal(CANONICAL_SCHEMA_VERSION);\n","import { z } from \"zod\";\n\n/** Maximum length accepted for short identifier-like strings. */\nexport const MAX_IDENTIFIER_LENGTH = 256;\n\n/** Maximum length accepted for a single string attribute value. */\nexport const MAX_ATTRIBUTE_STRING_LENGTH = 4096;\n\n/** Maximum number of entries accepted in an attribute array value. */\nexport const MAX_ATTRIBUTE_ARRAY_LENGTH = 128;\n\nexport const nonEmptyStringSchema = z.string().min(1).max(MAX_IDENTIFIER_LENGTH);\n\n/** Wall-clock time as whole milliseconds since the Unix epoch. */\nexport const epochMillisSchema = z.number().int().min(0).max(8_640_000_000_000_000);\nexport type EpochMillis = z.infer<typeof epochMillisSchema>;\n\n/** Non-negative duration in milliseconds; may be fractional. */\nexport const durationMillisSchema = z.number().min(0).finite();\n\n/** Token counts are always non-negative integers. */\nexport const tokenCountSchema = z.number().int().min(0);\n\n/** Monotonically increasing per-invocation ordering key. */\nexport const sequenceNumberSchema = z.number().int().min(0);\n\nconst brandedIdSchema = (): z.ZodString => z.string().min(1).max(MAX_IDENTIFIER_LENGTH);\n\nexport const invocationIdSchema = brandedIdSchema().brand<\"InvocationId\">();\nexport type InvocationId = z.infer<typeof invocationIdSchema>;\n\nexport const sessionIdSchema = brandedIdSchema().brand<\"SessionId\">();\nexport type SessionId = z.infer<typeof sessionIdSchema>;\n\nexport const eventIdSchema = brandedIdSchema().brand<\"EventId\">();\nexport type EventId = z.infer<typeof eventIdSchema>;\n\n/**\n * Workspace identifiers are opaque, privacy-safe handles of the form\n * `<scheme>:<token>`. Filesystem paths cannot satisfy this pattern, which keeps\n * home directories and repository paths out of telemetry by construction.\n */\nexport const WORKSPACE_ID_PATTERN = /^[a-z][a-z0-9]{0,15}:[A-Za-z0-9_-]{8,128}$/;\nexport const workspaceIdSchema = z\n .string()\n .regex(WORKSPACE_ID_PATTERN, \"workspace id must be an opaque `<scheme>:<token>` handle\")\n .brand<\"WorkspaceId\">();\nexport type WorkspaceId = z.infer<typeof workspaceIdSchema>;\n\n/** Provider ids are lowercase, hyphenated, and stable across releases. */\nexport const PROVIDER_ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\nexport const providerIdSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(PROVIDER_ID_PATTERN, \"provider id must be lowercase and hyphenated\")\n .brand<\"ProviderId\">();\nexport type ProviderId = z.infer<typeof providerIdSchema>;\n\n/** Sentinel used whenever the source provider could not be established. */\nexport const UNKNOWN_PROVIDER_ID = \"unknown\" as const;\nexport type UnknownProviderId = typeof UNKNOWN_PROVIDER_ID;\n\nexport const resolvedProviderIdSchema = z.union([\n providerIdSchema,\n z.literal(UNKNOWN_PROVIDER_ID),\n]);\nexport type ResolvedProviderId = z.infer<typeof resolvedProviderIdSchema>;\n\nexport const isUnknownProvider = (value: ResolvedProviderId): value is UnknownProviderId =>\n value === UNKNOWN_PROVIDER_ID;\n\n/**\n * Attribute values are restricted to OpenTelemetry-compatible primitives.\n *\n * This restriction is a containment boundary, not a convenience: because no\n * nested object can be represented, a raw provider payload cannot be smuggled\n * out of an adapter through attributes or extensions.\n */\nexport const attributePrimitiveSchema = z.union([\n z.string().max(MAX_ATTRIBUTE_STRING_LENGTH),\n z.number().finite(),\n z.boolean(),\n]);\nexport type AttributePrimitive = z.infer<typeof attributePrimitiveSchema>;\n\nexport const attributeValueSchema = z.union([\n attributePrimitiveSchema,\n z.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH),\n]);\nexport type AttributeValue = z.infer<typeof attributeValueSchema>;\n\nexport const attributesSchema = z.record(z.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);\nexport type Attributes = z.infer<typeof attributesSchema>;\n\n/** Ordered confidence ladder for provider detection. */\nexport const detectionConfidenceSchema = z.enum([\"none\", \"weak\", \"strong\", \"exact\"]);\nexport type DetectionConfidence = z.infer<typeof detectionConfidenceSchema>;\n\nexport const DETECTION_CONFIDENCE_RANK: Readonly<Record<DetectionConfidence, number>> =\n Object.freeze({\n none: 0,\n weak: 1,\n strong: 2,\n exact: 3,\n });\n\nexport const compareDetectionConfidence = (a: DetectionConfidence, b: DetectionConfidence): number =>\n DETECTION_CONFIDENCE_RANK[a] - DETECTION_CONFIDENCE_RANK[b];\n\n/** How the observed data reached this process. */\nexport const sourceTransportSchema = z.enum([\n \"hook-stdin\",\n \"cli-argument\",\n \"library-call\",\n \"test-fixture\",\n]);\nexport type SourceTransport = z.infer<typeof sourceTransportSchema>;\n","import { z } from \"zod\";\n\nimport { attributeValueSchema, type AttributeValue } from \"./primitives.js\";\n\n/**\n * Extension keys must be namespaced: at least one dot-separated segment before\n * the leaf, e.g. `acme.deployment-tier`. Namespacing keeps provider- and\n * consumer-specific fields from colliding with core fields or each other.\n */\nexport const EXTENSION_KEY_PATTERN =\n /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;\n\n/** Namespaces owned by the core model; extensions may not use them. */\nexport const RESERVED_EXTENSION_NAMESPACES: readonly string[] = Object.freeze([\n \"otelhook\",\n \"otel\",\n \"telemetry\",\n]);\n\nexport const MAX_EXTENSION_ENTRIES = 64;\n\nexport const extensionKeyNamespace = (key: string): string => key.slice(0, key.indexOf(\".\"));\n\nexport const isReservedExtensionNamespace = (key: string): boolean =>\n RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));\n\nexport const isValidExtensionKey = (key: string): boolean =>\n EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);\n\n/**\n * Namespaced extension bag.\n *\n * Values are restricted to attribute primitives, so extensions cannot carry\n * nested provider payloads.\n */\nexport const extensionsSchema = z\n .record(z.string(), attributeValueSchema)\n .check((ctx) => {\n const keys = Object.keys(ctx.value);\n if (keys.length > MAX_EXTENSION_ENTRIES) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`,\n });\n }\n for (const key of keys) {\n if (!EXTENSION_KEY_PATTERN.test(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. \"acme.tier\"`,\n });\n continue;\n }\n if (isReservedExtensionNamespace(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`,\n });\n }\n }\n });\n\nexport type Extensions = Record<string, AttributeValue>;\n\nexport const EMPTY_EXTENSIONS: Extensions = Object.freeze({});\n\nexport const emptyExtensions = (): Extensions => ({});\n","import { z } from \"zod\";\n\nimport { nonEmptyStringSchema } from \"./primitives.js\";\n\n/** What kind of conversational or tool content a fact describes. */\nexport const contentKindSchema = z.enum([\n \"prompt\",\n \"response\",\n \"reasoning\",\n \"tool-input\",\n \"tool-output\",\n \"error-message\",\n \"system-instruction\",\n \"attachment\",\n]);\nexport type ContentKind = z.infer<typeof contentKindSchema>;\n\nexport const contentRoleSchema = z.enum([\"user\", \"assistant\", \"system\", \"tool\", \"unknown\"]);\nexport type ContentRole = z.infer<typeof contentRoleSchema>;\n\n/**\n * How much of the original content this fact discloses.\n *\n * - `omitted`: no text at all (the default posture).\n * - `masked`: a shape-preserving mask; non-whitespace characters replaced.\n * - `redacted`: text with secret-looking spans replaced by a placeholder.\n * - `raw`: verbatim text. Only reachable through explicit opt-in.\n */\nexport const contentDisclosureSchema = z.enum([\"omitted\", \"masked\", \"redacted\", \"raw\"]);\nexport type ContentDisclosure = z.infer<typeof contentDisclosureSchema>;\n\nexport const CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;\n\n/**\n * A privacy-safe description of content.\n *\n * Lengths and a stable hash are always present so consumers can measure and\n * correlate volume without receiving the content itself. `text` is present only\n * when the resolved privacy policy allows disclosure, and is produced solely by\n * the central privacy service.\n */\nexport const contentFactSchema = z.strictObject({\n kind: contentKindSchema,\n role: contentRoleSchema.optional(),\n /** Unicode code point count of the original content. */\n characterLength: z.number().int().min(0),\n /** UTF-8 byte length of the original content. */\n byteLength: z.number().int().min(0),\n /** Stable salted digest of the original content. */\n contentHash: z.string().regex(CONTENT_HASH_PATTERN),\n disclosure: contentDisclosureSchema,\n /** Disclosed text, bounded by the privacy policy. Absent when omitted. */\n text: z.string().optional(),\n /** True when `text` was cut short by the configured string bound. */\n truncated: z.boolean(),\n /** Number of secret-looking spans replaced while producing `text`. */\n secretsRedacted: z.number().int().min(0),\n /** Optional non-sensitive label, e.g. a MIME type or tool name. */\n label: nonEmptyStringSchema.optional(),\n});\nexport type ContentFact = z.infer<typeof contentFactSchema>;\n\nexport const contentFactsSchema = z.array(contentFactSchema).max(64);\n\n/**\n * Guard used in tests and at the sink boundary: an omitted fact must not carry\n * text, and a disclosing fact must carry it.\n */\nexport const isContentFactConsistent = (fact: ContentFact): boolean =>\n fact.disclosure === \"omitted\" ? fact.text === undefined : fact.text !== undefined;\n\n/**\n * A fact for a content kind the event can carry when the provider sent no text.\n *\n * Always `omitted` with zero length, regardless of the installation's content\n * mode: there is nothing to mask, redact, or export.\n */\nexport const isUnavailableContentFact = (fact: ContentFact): boolean =>\n fact.disclosure === \"omitted\" &&\n fact.text === undefined &&\n fact.characterLength === 0 &&\n fact.byteLength === 0;\n","import { z } from \"zod\";\n\nimport { tokenCountSchema } from \"./primitives.js\";\n\n/**\n * Whether an observation reports the change since the previous observation\n * (`delta`) or the running total for the session/generation (`cumulative`).\n *\n * The canonical model keeps temporality explicit rather than assuming one:\n * summing cumulative observations double-counts, and diffing delta observations\n * silently loses tokens.\n */\nexport const usageTemporalitySchema = z.enum([\"delta\", \"cumulative\"]);\nexport type UsageTemporality = z.infer<typeof usageTemporalitySchema>;\n\n/**\n * Whether the provider counts cache-creation tokens inside its input total or\n * reports them as a disjoint bucket.\n *\n * - `included-in-input`: `cacheCreationInputTokens` is a subset of `inputTokens`.\n * - `disjoint-from-input`: cache-creation tokens are billed in addition to\n * `inputTokens` and must be added when computing a total.\n * - `not-reported`: the provider exposes no cache-creation counter; the field is\n * pinned to zero.\n */\nexport const cacheCreationAccountingSchema = z.enum([\n \"included-in-input\",\n \"disjoint-from-input\",\n \"not-reported\",\n]);\nexport type CacheCreationAccounting = z.infer<typeof cacheCreationAccountingSchema>;\n\n/** Whether a provider-reported total agrees with the canonical computation. */\nexport const providerTotalAgreementSchema = z.enum([\"unreported\", \"agrees\", \"disagrees\"]);\nexport type ProviderTotalAgreement = z.infer<typeof providerTotalAgreementSchema>;\n\n/**\n * What an adapter reports, before normalization.\n *\n * `inputTokens` is *inclusive*: it counts every input token the provider\n * attributes to the call, including cache reads (and cache creation when the\n * provider folds it in). `outputTokens` is likewise inclusive of reasoning\n * output. Subset fields describe portions of those totals, never additions.\n */\nexport const usageReportSchema = z.strictObject({\n temporality: usageTemporalitySchema,\n /** Inclusive input tokens. */\n inputTokens: tokenCountSchema.optional(),\n /** Subset of `inputTokens` served from a prompt cache. */\n cachedInputTokens: tokenCountSchema.optional(),\n /** Tokens written to a prompt cache. */\n cacheCreationInputTokens: tokenCountSchema.optional(),\n /** Required when `cacheCreationInputTokens` is present and non-zero. */\n cacheCreationAccounting: cacheCreationAccountingSchema.optional(),\n /** Inclusive output tokens. */\n outputTokens: tokenCountSchema.optional(),\n /** Subset of `outputTokens` spent on reasoning. */\n reasoningOutputTokens: tokenCountSchema.optional(),\n /** Total exactly as the provider reported it, if it reported one. */\n providerTotalTokens: tokenCountSchema.optional(),\n});\nexport type UsageReport = z.infer<typeof usageReportSchema>;\n\n/**\n * Fully normalized usage.\n *\n * Derived fields (`uncachedInputTokens`, `totalTokens`,\n * `providerTotalAgreement`) are part of the schema and are re-checked on parse,\n * so an inconsistent object cannot exist. Construct values with\n * {@link normalizeUsage} rather than by hand.\n */\nexport const canonicalUsageSchema = z\n .strictObject({\n temporality: usageTemporalitySchema,\n inputTokens: tokenCountSchema,\n cachedInputTokens: tokenCountSchema,\n cacheCreationInputTokens: tokenCountSchema,\n cacheCreationAccounting: cacheCreationAccountingSchema,\n outputTokens: tokenCountSchema,\n reasoningOutputTokens: tokenCountSchema,\n /** Derived: input tokens that were neither cache reads nor cache writes. */\n uncachedInputTokens: tokenCountSchema,\n /** Derived: canonical billable total. */\n totalTokens: tokenCountSchema,\n providerTotalTokens: tokenCountSchema.optional(),\n providerTotalAgreement: providerTotalAgreementSchema,\n })\n .check((ctx) => {\n const usage = ctx.value;\n const push = (message: string): void => {\n ctx.issues.push({ code: \"custom\", input: usage, message });\n };\n\n if (usage.cachedInputTokens > usage.inputTokens) {\n push(\"cachedInputTokens must not exceed inputTokens (it is a subset)\");\n }\n if (usage.reasoningOutputTokens > usage.outputTokens) {\n push(\"reasoningOutputTokens must not exceed outputTokens (it is a subset)\");\n }\n if (usage.cacheCreationAccounting === \"not-reported\" && usage.cacheCreationInputTokens !== 0) {\n push(\"cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported\");\n }\n const creationInsideInput =\n usage.cacheCreationAccounting === \"included-in-input\" ? usage.cacheCreationInputTokens : 0;\n if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {\n push(\n \"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input\",\n );\n }\n const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;\n if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {\n push(`uncachedInputTokens must equal ${expectedUncached}`);\n }\n const creationOutsideInput =\n usage.cacheCreationAccounting === \"disjoint-from-input\" ? usage.cacheCreationInputTokens : 0;\n const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;\n if (usage.totalTokens !== expectedTotal) {\n push(`totalTokens must equal ${expectedTotal}`);\n }\n const expectedAgreement: ProviderTotalAgreement =\n usage.providerTotalTokens === undefined\n ? \"unreported\"\n : usage.providerTotalTokens === expectedTotal\n ? \"agrees\"\n : \"disagrees\";\n if (usage.providerTotalAgreement !== expectedAgreement) {\n push(`providerTotalAgreement must be ${expectedAgreement}`);\n }\n });\nexport type CanonicalUsage = z.infer<typeof canonicalUsageSchema>;\n\nexport type UsageNormalizationIssue = {\n readonly code:\n | \"invalid-report\"\n | \"cached-exceeds-input\"\n | \"reasoning-exceeds-output\"\n | \"cache-creation-exceeds-input\"\n | \"cache-creation-accounting-missing\";\n readonly message: string;\n};\n\nexport type UsageNormalizationResult =\n | { readonly status: \"ok\"; readonly usage: CanonicalUsage; readonly notes: readonly string[] }\n | { readonly status: \"invalid\"; readonly issues: readonly UsageNormalizationIssue[] };\n\n/**\n * Normalize a provider usage report into canonical usage.\n *\n * Deterministic rules:\n * 1. Absent counters default to `0`; `providerTotalTokens` stays absent.\n * 2. Non-integer, negative, or non-finite counters are rejected.\n * 3. A subset exceeding its total is rejected — never clamped — because\n * clamping would silently invent a billing story.\n * 4. `cacheCreationAccounting` defaults to `not-reported` when no cache-creation\n * tokens are reported, and is *required* when they are: guessing whether the\n * bucket is disjoint would mis-total every downstream cost calculation.\n * 5. A provider total that disagrees with the canonical total is preserved as\n * reported and flagged `disagrees`. Both numbers survive; neither is edited.\n */\nexport const normalizeUsage = (report: unknown): UsageNormalizationResult => {\n const parsed = usageReportSchema.safeParse(report);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map((issue) => ({\n code: \"invalid-report\" as const,\n message: `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n })),\n };\n }\n\n const input = parsed.data;\n const issues: UsageNormalizationIssue[] = [];\n const notes: string[] = [];\n\n const inputTokens = input.inputTokens ?? 0;\n const cachedInputTokens = input.cachedInputTokens ?? 0;\n const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;\n const outputTokens = input.outputTokens ?? 0;\n const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;\n\n let accounting: CacheCreationAccounting;\n if (cacheCreationInputTokens === 0) {\n accounting = input.cacheCreationAccounting ?? \"not-reported\";\n if (accounting !== \"not-reported\") {\n notes.push(\n `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`,\n );\n }\n } else if (input.cacheCreationAccounting === undefined) {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message:\n \"cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred\",\n });\n accounting = \"not-reported\";\n } else if (input.cacheCreationAccounting === \"not-reported\") {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message: \"cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens\",\n });\n accounting = \"not-reported\";\n } else {\n accounting = input.cacheCreationAccounting;\n }\n\n if (cachedInputTokens > inputTokens) {\n issues.push({\n code: \"cached-exceeds-input\",\n message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n if (reasoningOutputTokens > outputTokens) {\n issues.push({\n code: \"reasoning-exceeds-output\",\n message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`,\n });\n }\n\n const creationInsideInput = accounting === \"included-in-input\" ? cacheCreationInputTokens : 0;\n if (cachedInputTokens + creationInsideInput > inputTokens) {\n issues.push({\n code: \"cache-creation-exceeds-input\",\n message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const creationOutsideInput = accounting === \"disjoint-from-input\" ? cacheCreationInputTokens : 0;\n const totalTokens = inputTokens + creationOutsideInput + outputTokens;\n const providerTotalAgreement: ProviderTotalAgreement =\n input.providerTotalTokens === undefined\n ? \"unreported\"\n : input.providerTotalTokens === totalTokens\n ? \"agrees\"\n : \"disagrees\";\n\n if (providerTotalAgreement === \"disagrees\") {\n notes.push(\n `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`,\n );\n }\n\n const usage: CanonicalUsage = {\n temporality: input.temporality,\n inputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens,\n reasoningOutputTokens,\n uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,\n totalTokens,\n ...(input.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: input.providerTotalTokens }),\n providerTotalAgreement,\n };\n\n return { status: \"ok\", usage, notes };\n};\n\nexport class UsageNormalizationError extends Error {\n public readonly issues: readonly UsageNormalizationIssue[];\n\n public constructor(issues: readonly UsageNormalizationIssue[]) {\n super(`invalid usage report: ${issues.map((issue) => issue.message).join(\"; \")}`);\n this.name = \"UsageNormalizationError\";\n this.issues = issues;\n }\n}\n\n/** Convenience wrapper for call sites that treat invalid usage as a bug. */\nexport const normalizeUsageOrThrow = (report: unknown): CanonicalUsage => {\n const result = normalizeUsage(report);\n if (result.status === \"invalid\") {\n throw new UsageNormalizationError(result.issues);\n }\n return result.usage;\n};\n\nexport const EMPTY_DELTA_USAGE: CanonicalUsage = Object.freeze(\n normalizeUsageOrThrow({ temporality: \"delta\" }),\n);\n\nexport type UsageDeltaResult = {\n readonly usage: CanonicalUsage;\n /**\n * True when the current snapshot is smaller than the previous one on any\n * counter. That means the cumulative series restarted (new session, replayed\n * transcript, provider reset), so the current snapshot is emitted as the delta\n * instead of a negative difference.\n */\n readonly resetDetected: boolean;\n};\n\nconst requireCumulative = (usage: CanonicalUsage, label: string): void => {\n if (usage.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: `${label} must have cumulative temporality` },\n ]);\n }\n};\n\n/**\n * Convert two cumulative snapshots into a delta observation.\n *\n * Replay safety: re-processing the same snapshot yields an all-zero delta, and a\n * decreasing series is reported as a reset rather than a negative delta.\n * Accounting mode must match; mixing modes would make the subtraction meaningless.\n */\nexport const cumulativeToDelta = (\n previous: CanonicalUsage,\n current: CanonicalUsage,\n): UsageDeltaResult => {\n requireCumulative(previous, \"previous usage\");\n requireCumulative(current, \"current usage\");\n\n if (\n previous.cacheCreationAccounting !== current.cacheCreationAccounting &&\n previous.cacheCreationInputTokens !== 0 &&\n current.cacheCreationInputTokens !== 0\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot diff cumulative usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const resetDetected =\n current.inputTokens < previous.inputTokens ||\n current.cachedInputTokens < previous.cachedInputTokens ||\n current.cacheCreationInputTokens < previous.cacheCreationInputTokens ||\n current.outputTokens < previous.outputTokens ||\n current.reasoningOutputTokens < previous.reasoningOutputTokens;\n\n if (resetDetected) {\n return {\n usage: normalizeUsageOrThrow({ ...toReport(current), temporality: \"delta\" }),\n resetDetected: true,\n };\n }\n\n const usage = normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: current.inputTokens - previous.inputTokens,\n cachedInputTokens: current.cachedInputTokens - previous.cachedInputTokens,\n cacheCreationInputTokens:\n current.cacheCreationInputTokens - previous.cacheCreationInputTokens,\n cacheCreationAccounting: current.cacheCreationAccounting,\n outputTokens: current.outputTokens - previous.outputTokens,\n reasoningOutputTokens: current.reasoningOutputTokens - previous.reasoningOutputTokens,\n });\n\n return { usage, resetDetected: false };\n};\n\n/** Project canonical usage back onto the reported shape. */\nexport const toReport = (usage: CanonicalUsage): UsageReport => ({\n temporality: usage.temporality,\n inputTokens: usage.inputTokens,\n cachedInputTokens: usage.cachedInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n cacheCreationAccounting: usage.cacheCreationAccounting,\n outputTokens: usage.outputTokens,\n reasoningOutputTokens: usage.reasoningOutputTokens,\n ...(usage.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: usage.providerTotalTokens }),\n});\n\n/**\n * Add two delta observations. Cumulative usage is never summed, because two\n * running totals do not compose.\n */\nexport const addUsage = (a: CanonicalUsage, b: CanonicalUsage): CanonicalUsage => {\n if (a.temporality !== \"delta\" || b.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"only delta usage may be summed\" },\n ]);\n }\n const accounting =\n a.cacheCreationInputTokens === 0 && a.cacheCreationAccounting === \"not-reported\"\n ? b.cacheCreationAccounting\n : b.cacheCreationInputTokens === 0 && b.cacheCreationAccounting === \"not-reported\"\n ? a.cacheCreationAccounting\n : a.cacheCreationAccounting;\n\n if (\n a.cacheCreationInputTokens !== 0 &&\n b.cacheCreationInputTokens !== 0 &&\n a.cacheCreationAccounting !== b.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot sum usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n a.providerTotalTokens === undefined && b.providerTotalTokens === undefined\n ? undefined\n : (a.providerTotalTokens ?? 0) + (b.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: a.inputTokens + b.inputTokens,\n cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,\n cacheCreationInputTokens: a.cacheCreationInputTokens + b.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: a.outputTokens + b.outputTokens,\n reasoningOutputTokens: a.reasoningOutputTokens + b.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n","import { z } from \"zod\";\n\nimport {\n attributesSchema,\n detectionConfidenceSchema,\n DETECTION_CONFIDENCE_RANK,\n epochMillisSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n resolvedProviderIdSchema,\n sessionIdSchema,\n sourceTransportSchema,\n workspaceIdSchema,\n type DetectionConfidence,\n type InvocationId,\n type SessionId,\n type WorkspaceId,\n} from \"./primitives.js\";\n\n/**\n * Where a workspace identifier came from.\n *\n * Ordered from most to least stable. The source is recorded so consumers can\n * tell a repository-scoped identity from a directory-scoped one instead of\n * assuming they are comparable.\n */\nexport const workspaceKeySourceSchema = z.enum([\n \"git-remote\",\n \"git-root\",\n \"working-directory\",\n \"explicit\",\n \"unknown\",\n]);\nexport type WorkspaceKeySource = z.infer<typeof workspaceKeySourceSchema>;\n\n/**\n * Privacy-safe workspace identity.\n *\n * Only opaque handles and explicitly allowed labels are modelled. There is no\n * field for a filesystem path, so paths cannot be exported through this type.\n */\nexport const workspaceIdentitySchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n keySource: workspaceKeySourceSchema,\n /** Repository name only; never an owner path or URL with credentials. */\n repositoryName: nonEmptyStringSchema.optional(),\n vcsBranchName: nonEmptyStringSchema.optional(),\n /** Opaque handle for the checked-out revision. */\n vcsRevisionId: nonEmptyStringSchema.optional(),\n })\n .readonly();\nexport type WorkspaceIdentity = z.infer<typeof workspaceIdentitySchema>;\n\nexport const UNKNOWN_WORKSPACE_ID = \"unknown:0000000000000000\" as WorkspaceId;\n\nexport const unknownWorkspaceIdentity = (): WorkspaceIdentity =>\n workspaceIdentitySchema.parse({\n workspaceId: UNKNOWN_WORKSPACE_ID,\n keySource: \"unknown\",\n });\n\n/**\n * Provenance of an observation: which provider produced it and which adapter\n * interpreted it, with the confidence of that attribution.\n */\nexport const sourceProvenanceSchema = z\n .strictObject({\n providerId: resolvedProviderIdSchema,\n providerVersion: nonEmptyStringSchema.optional(),\n adapterId: nonEmptyStringSchema,\n adapterVersion: nonEmptyStringSchema,\n detectionConfidence: detectionConfidenceSchema,\n /** The provider's own name for the source event, e.g. a hook event name. */\n sourceEventName: nonEmptyStringSchema.optional(),\n transport: sourceTransportSchema,\n })\n .readonly();\nexport type SourceProvenance = z.infer<typeof sourceProvenanceSchema>;\n\n/**\n * Opaque, immutable metadata supplied by the embedding consumer.\n *\n * The library never interprets these values; it only carries and exports them.\n */\nexport const consumerAttributesSchema = attributesSchema.readonly();\nexport type ConsumerAttributes = z.infer<typeof consumerAttributesSchema>;\n\n/**\n * Immutable identity of a single hook invocation.\n *\n * Frozen on parse. There is deliberately no setter, no builder that mutates in\n * place, and no module-level instance: identity is passed explicitly so two\n * concurrent invocations can never observe each other's fields.\n */\nexport const invocationIdentitySchema = z\n .strictObject({\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Set when this invocation runs beneath another agent invocation. */\n parentInvocationId: invocationIdSchema.optional(),\n /** Root of the session tree when the provider exposes one. */\n rootSessionId: sessionIdSchema.optional(),\n /** Stable handle for the agent process/instance, when available. */\n agentInstanceId: nonEmptyStringSchema.optional(),\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n startedAt: epochMillisSchema,\n consumerAttributes: consumerAttributesSchema,\n })\n .readonly();\nexport type InvocationIdentity = z.infer<typeof invocationIdentitySchema>;\n\n/** Fields an identity claim may contribute. */\nexport const identityClaimFieldsSchema = z.strictObject({\n invocationId: invocationIdSchema.optional(),\n sessionId: sessionIdSchema.optional(),\n parentInvocationId: invocationIdSchema.optional(),\n rootSessionId: sessionIdSchema.optional(),\n agentInstanceId: nonEmptyStringSchema.optional(),\n workspace: workspaceIdentitySchema.optional(),\n startedAt: epochMillisSchema.optional(),\n});\nexport type IdentityClaimFields = z.infer<typeof identityClaimFieldsSchema>;\n\n/**\n * A claim about invocation identity from one source.\n *\n * Claims are evidence, not truth. Resolution keeps the highest-confidence claim\n * per field and refuses to merge disagreeing peers.\n */\nexport const identityClaimSchema = z.strictObject({\n /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */\n source: nonEmptyStringSchema,\n confidence: detectionConfidenceSchema,\n fields: identityClaimFieldsSchema,\n});\nexport type IdentityClaim = z.infer<typeof identityClaimSchema>;\n\nexport type IdentityConflict = {\n readonly field: keyof IdentityClaimFields;\n readonly confidence: DetectionConfidence;\n /** Rendered, non-sensitive representations of the disagreeing values. */\n readonly values: readonly string[];\n readonly sources: readonly string[];\n};\n\nexport type IdentityResolution =\n | { readonly status: \"resolved\"; readonly identity: InvocationIdentity }\n | {\n readonly status: \"conflict\";\n readonly conflicts: readonly IdentityConflict[];\n }\n | {\n readonly status: \"incomplete\";\n readonly missing: readonly (keyof IdentityClaimFields)[];\n }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nconst CLAIM_FIELDS = [\n \"invocationId\",\n \"sessionId\",\n \"parentInvocationId\",\n \"rootSessionId\",\n \"agentInstanceId\",\n \"workspace\",\n \"startedAt\",\n] as const satisfies readonly (keyof IdentityClaimFields)[];\n\nconst renderClaimValue = (value: unknown): string => {\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (value !== null && typeof value === \"object\" && \"workspaceId\" in value) {\n const { workspaceId } = value;\n return typeof workspaceId === \"string\" ? workspaceId : \"<workspace>\";\n }\n return \"<opaque>\";\n};\n\nexport type ResolveIdentityInput = {\n readonly claims: readonly IdentityClaim[];\n readonly provenance: SourceProvenance;\n /** Used only for fields no claim provides and that have a safe default. */\n readonly fallback?: {\n readonly startedAt?: number;\n readonly workspace?: WorkspaceIdentity;\n };\n readonly consumerAttributes?: Readonly<Record<string, unknown>>;\n};\n\n/**\n * Resolve identity from claims, failing closed.\n *\n * Rules:\n * 1. For each field, only claims at the highest confidence that provided it are\n * considered. Lower-confidence claims never fill in or override.\n * 2. Two distinct values at that highest confidence produce a `conflict`. The\n * invocation is then not attributed at all — a mislabelled session is worse\n * than a missing one.\n * 3. `invocationId` and `sessionId` are mandatory. Missing either yields\n * `incomplete`; neither is invented here.\n * 4. `startedAt` and `workspace` may come from an explicit fallback, because a\n * clock reading and an `unknown` workspace handle assert nothing false.\n */\nexport const resolveInvocationIdentity = (input: ResolveIdentityInput): IdentityResolution => {\n const parsedClaims: IdentityClaim[] = [];\n const issues: string[] = [];\n for (const [index, claim] of input.claims.entries()) {\n const parsed = identityClaimSchema.safeParse(claim);\n if (parsed.success) {\n parsedClaims.push(parsed.data);\n } else {\n issues.push(\n `claim[${index}]: ${parsed.error.issues.map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`).join(\", \")}`,\n );\n }\n }\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const conflicts: IdentityConflict[] = [];\n const selected: Record<string, unknown> = {};\n\n for (const field of CLAIM_FIELDS) {\n const contributors = parsedClaims.filter((claim) => claim.fields[field] !== undefined);\n if (contributors.length === 0) {\n continue;\n }\n const bestRank = Math.max(\n ...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence]),\n );\n const best = contributors.filter(\n (claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank,\n );\n const rendered = new Map<string, string[]>();\n for (const claim of best) {\n const key = JSON.stringify(claim.fields[field]);\n const sources = rendered.get(key) ?? [];\n sources.push(claim.source);\n rendered.set(key, sources);\n }\n if (rendered.size > 1) {\n const [firstBest] = best;\n conflicts.push({\n field,\n confidence: firstBest?.confidence ?? \"none\",\n values: best.map((claim) => renderClaimValue(claim.fields[field])),\n sources: best.map((claim) => claim.source),\n });\n continue;\n }\n const [winner] = best;\n if (winner !== undefined) {\n selected[field] = winner.fields[field];\n }\n }\n\n if (conflicts.length > 0) {\n return { status: \"conflict\", conflicts };\n }\n\n const missing: (keyof IdentityClaimFields)[] = [];\n if (selected.invocationId === undefined) {\n missing.push(\"invocationId\");\n }\n if (selected.sessionId === undefined) {\n missing.push(\"sessionId\");\n }\n if (missing.length > 0) {\n return { status: \"incomplete\", missing };\n }\n\n const startedAt = (selected.startedAt as number | undefined) ?? input.fallback?.startedAt;\n if (startedAt === undefined) {\n return { status: \"incomplete\", missing: [\"startedAt\"] };\n }\n const workspace =\n (selected.workspace as WorkspaceIdentity | undefined) ??\n input.fallback?.workspace ??\n unknownWorkspaceIdentity();\n\n const candidate = {\n invocationId: selected.invocationId as InvocationId,\n sessionId: selected.sessionId as SessionId,\n ...(selected.parentInvocationId === undefined\n ? {}\n : { parentInvocationId: selected.parentInvocationId as InvocationId }),\n ...(selected.rootSessionId === undefined\n ? {}\n : { rootSessionId: selected.rootSessionId as SessionId }),\n ...(selected.agentInstanceId === undefined\n ? {}\n : { agentInstanceId: selected.agentInstanceId as string }),\n provenance: input.provenance,\n workspace,\n startedAt,\n consumerAttributes: input.consumerAttributes ?? {},\n };\n\n const parsed = invocationIdentitySchema.safeParse(candidate);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n }\n return { status: \"resolved\", identity: parsed.data };\n};\n","import { z } from \"zod\";\n\nimport { nonEmptyStringSchema, workspaceIdSchema } from \"./primitives.js\";\n\n/**\n * Per-event workspace targeting (ADR 0008).\n *\n * A session's `workspace` is where the agent was *started*. An agent routinely\n * works somewhere else — in a linked git worktree beside the checkout it was\n * launched from — and the session-level identity cannot show that. A tool event\n * can: the file it edited, or the directory its shell command ran in, names the\n * worktree it actually touched.\n *\n * Two values model that, and the split between them is the privacy boundary:\n *\n * - {@link TargetHint} is what an adapter observed — local paths. It is an\n * in-process value only: it is never part of a {@link CanonicalEvent}, never\n * persisted, never exported. The core resolves it and drops it.\n * - {@link WorkspaceTarget} is what the core resolved — salted handles of the\n * worktree and its repository, the worktree's kind, the checked-out branch, and\n * what the evidence was. It travels on the event.\n */\n\n/**\n * What a target was derived from, strongest evidence first.\n *\n * - `tool-path` — a path the tool call itself named (an edited or read file, a\n * patch header).\n * - `shell-cwd` — the working directory the provider reports a shell command ran in.\n * - `session-cwd` — only the session's own directory was known; the event may\n * have reached elsewhere (e.g. a shell `cd`) without the provider saying so.\n */\nexport const targetSourceSchema = z.enum([\"tool-path\", \"shell-cwd\", \"session-cwd\"]);\nexport type TargetSource = z.infer<typeof targetSourceSchema>;\n\n/** Most paths one hint may name; a bound, not a sampling rule (all must agree). */\nexport const MAX_TARGET_HINT_PATHS = 8;\n\n/** Longest local path a hint may carry. Longer input is dropped, never truncated. */\nexport const MAX_TARGET_PATH_LENGTH = 4096;\n\nconst localPathSchema = z\n .string()\n .min(1)\n .max(MAX_TARGET_PATH_LENGTH)\n .refine((value) => !value.includes(\"\\u0000\"), \"path must not contain NUL\");\n\n/**\n * An adapter's observation of where a tool event pointed. **Carries local paths**\n * — in-process only, see the module note.\n *\n * Every path in one hint must resolve to the same worktree, or the event gets no\n * target at all: a patch touching two worktrees did not target either of them.\n */\nexport const targetHintSchema = z\n .strictObject({\n source: targetSourceSchema,\n paths: z.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),\n /** Absolute directory that relative `paths` resolve against. */\n baseDirectory: localPathSchema.optional(),\n })\n .readonly();\nexport type TargetHint = z.infer<typeof targetHintSchema>;\n\n/**\n * The weakest hint: the session's own directory. Every adapter gives it to a\n * session start and a prompt, and to a tool call that names no path.\n */\nexport const sessionCwdHint = (cwd: string | undefined): TargetHint | undefined =>\n cwd === undefined || cwd.length === 0 ? undefined : { source: \"session-cwd\", paths: [cwd] };\n\n/**\n * Whether a worktree is its repository's main checkout (`main`) or one added\n * beside it with `git worktree add` (`linked`).\n */\nexport const worktreeKindSchema = z.enum([\"main\", \"linked\"]);\nexport type WorktreeKind = z.infer<typeof worktreeKindSchema>;\n\n/**\n * The git worktree a tool event targeted. Exported; carries no path.\n *\n * `workspaceId` is derived exactly like a `git-root` workspace identity, so a\n * consumer holding the same salt can match it against one it derived itself.\n * `repositoryId` is the same derivation applied to the repository's main\n * worktree, so every worktree of one repository shares it — and for a main\n * worktree it equals `workspaceId`.\n */\nexport const workspaceTargetSchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n /** Branch checked out in that worktree; absent on a detached HEAD. */\n vcsBranchName: nonEmptyStringSchema.optional(),\n source: targetSourceSchema,\n /** `git-root` handle of the repository's main worktree; absent when there is none to name. */\n repositoryId: workspaceIdSchema.optional(),\n worktreeKind: worktreeKindSchema.optional(),\n })\n .readonly();\nexport type WorkspaceTarget = z.infer<typeof workspaceTargetSchema>;\n\n/**\n * Shape a provider's own subagent identifier must have to be exported.\n *\n * Identifier-shaped on purpose — no whitespace, no path separators — so a\n * malformed payload field cannot carry prose or a path onto the wire under an id\n * attribute. A value that does not fit is dropped, not repaired.\n */\nexport const SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;\nexport const subagentIdSchema = z.string().regex(SUBAGENT_ID_PATTERN);\nexport type SubagentId = z.infer<typeof subagentIdSchema>;\n","import { z } from \"zod\";\n\nimport {\n errorPhaseSchema,\n errorSeveritySchema,\n otelHookErrorCodeSchema,\n} from \"../errors/taxonomy.js\";\nimport { contentFactSchema, contentFactsSchema } from \"./content.js\";\nimport { extensionsSchema, emptyExtensions } from \"./extensions.js\";\nimport { sourceProvenanceSchema, workspaceIdentitySchema } from \"./identity.js\";\nimport { subagentIdSchema, workspaceTargetSchema } from \"./target.js\";\nimport {\n durationMillisSchema,\n epochMillisSchema,\n eventIdSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n sequenceNumberSchema,\n sessionIdSchema,\n tokenCountSchema,\n} from \"./primitives.js\";\nimport { canonicalUsageSchema, type CanonicalUsage } from \"./usage.js\";\nimport { canonicalSchemaVersionSchema } from \"./version.js\";\n\n/** Model being invoked. Model identifiers are not treated as sensitive. */\nexport const modelDescriptorSchema = z.strictObject({\n modelId: nonEmptyStringSchema,\n /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */\n vendor: nonEmptyStringSchema.optional(),\n family: nonEmptyStringSchema.optional(),\n});\nexport type ModelDescriptor = z.infer<typeof modelDescriptorSchema>;\n\nexport const costFactsSchema = z.strictObject({\n /** ISO 4217 code. */\n currency: z.string().length(3),\n amount: z.number().min(0).finite(),\n source: z.enum([\"provider-reported\", \"computed\"]),\n});\nexport type CostFacts = z.infer<typeof costFactsSchema>;\n\nexport const canonicalEventTypeSchema = z.enum([\n \"session.start\",\n \"session.end\",\n \"prompt.submitted\",\n \"generation.start\",\n \"generation.end\",\n \"tool.start\",\n \"tool.end\",\n \"subagent.start\",\n \"subagent.end\",\n \"compaction.performed\",\n \"error.raised\",\n]);\nexport type CanonicalEventType = z.infer<typeof canonicalEventTypeSchema>;\n\nexport const CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;\n\nconst outcomeSchema = z.enum([\"ok\", \"error\", \"cancelled\", \"timeout\", \"denied\", \"unknown\"]);\nexport type EventOutcome = z.infer<typeof outcomeSchema>;\n\n/**\n * Fields present on every canonical event.\n *\n * Identity fields are duplicated onto each event rather than referenced through\n * shared state, so an event is self-describing once it leaves the process.\n */\nconst baseEventFields = {\n schemaVersion: canonicalSchemaVersionSchema,\n eventId: eventIdSchema,\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Per-invocation ordering key. Stable across replays of the same input. */\n sequence: sequenceNumberSchema,\n occurredAt: epochMillisSchema,\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n /**\n * The provider's own id for the subagent this event was emitted inside (e.g.\n * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event\n * factory, never by hand.\n */\n subagentId: subagentIdSchema.optional(),\n extensions: extensionsSchema.default(emptyExtensions),\n} as const;\n\nconst event = <TShape extends z.ZodRawShape>(shape: TShape) =>\n z.strictObject({ ...baseEventFields, ...shape });\n\nexport const sessionStartEventSchema = event({\n type: z.literal(\"session.start\"),\n sessionKind: z.enum([\"interactive\", \"non-interactive\", \"unknown\"]),\n agentName: nonEmptyStringSchema.optional(),\n agentVersion: nonEmptyStringSchema.optional(),\n model: modelDescriptorSchema.optional(),\n /** The git worktree the session runs in, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const sessionEndEventSchema = event({\n type: z.literal(\"session.end\"),\n reason: z.enum([\"completed\", \"aborted\", \"error\", \"timeout\", \"unknown\"]),\n durationMillis: durationMillisSchema.optional(),\n /** Session totals, typically cumulative. */\n usage: canonicalUsageSchema.optional(),\n cost: costFactsSchema.optional(),\n});\n\nexport const promptSubmittedEventSchema = event({\n type: z.literal(\"prompt.submitted\"),\n promptSource: z.enum([\"user\", \"automation\", \"resumed\", \"unknown\"]),\n content: contentFactSchema.optional(),\n turnIndex: z.number().int().min(0).optional(),\n /** The git worktree the session runs in, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const generationStartEventSchema = event({\n type: z.literal(\"generation.start\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n requestedMaxOutputTokens: tokenCountSchema.optional(),\n inputContent: contentFactsSchema.optional(),\n});\n\nexport const generationEndEventSchema = event({\n type: z.literal(\"generation.end\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n outcome: outcomeSchema,\n stopReason: nonEmptyStringSchema.optional(),\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n /**\n * True when `usage` is known to cover only part of the generation (for\n * example the last model request of a multi-request turn); false when the\n * provider or harness said it is the whole. Absent: not stated. Meaningless\n * without `usage`.\n */\n usagePartial: z.boolean().optional(),\n cost: costFactsSchema.optional(),\n outputContent: contentFactsSchema.optional(),\n});\n\nexport const toolKindSchema = z.enum([\n \"read\",\n \"write\",\n \"execute\",\n \"search\",\n \"network\",\n \"delegate\",\n \"other\",\n \"unknown\",\n]);\nexport type ToolKind = z.infer<typeof toolKindSchema>;\n\nexport const toolStartEventSchema = event({\n type: z.literal(\"tool.start\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n toolKind: toolKindSchema,\n generationId: nonEmptyStringSchema.optional(),\n input: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const toolEndEventSchema = event({\n type: z.literal(\"tool.end\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n /** Present when the host asked for or recorded a permission decision. */\n permissionDecision: z.enum([\"allowed\", \"denied\", \"deferred\", \"not-required\"]).optional(),\n output: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const subagentStartEventSchema = event({\n type: z.literal(\"subagent.start\"),\n subagentInvocationId: invocationIdSchema,\n subagentType: nonEmptyStringSchema.optional(),\n /** 0 for the top-level agent; 1 for its direct children. */\n delegationDepth: z.number().int().min(0).max(64),\n model: modelDescriptorSchema.optional(),\n});\n\nexport const subagentEndEventSchema = event({\n type: z.literal(\"subagent.end\"),\n subagentInvocationId: invocationIdSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const compactionPerformedEventSchema = event({\n type: z.literal(\"compaction.performed\"),\n trigger: z.enum([\"automatic\", \"manual\", \"unknown\"]),\n /** Provider-reported context size before and after compaction, if known. */\n contextTokensBefore: tokenCountSchema.optional(),\n contextTokensAfter: tokenCountSchema.optional(),\n droppedMessageCount: z.number().int().min(0).optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const errorRaisedEventSchema = event({\n type: z.literal(\"error.raised\"),\n errorCode: otelHookErrorCodeSchema,\n severity: errorSeveritySchema,\n phase: errorPhaseSchema,\n retryable: z.boolean(),\n /** Error text is content: it is described, never embedded verbatim by default. */\n message: contentFactSchema.optional(),\n /** Non-sensitive, provider-agnostic short label. */\n detail: nonEmptyStringSchema.optional(),\n});\n\nexport const canonicalEventSchema = z.discriminatedUnion(\"type\", [\n sessionStartEventSchema,\n sessionEndEventSchema,\n promptSubmittedEventSchema,\n generationStartEventSchema,\n generationEndEventSchema,\n toolStartEventSchema,\n toolEndEventSchema,\n subagentStartEventSchema,\n subagentEndEventSchema,\n compactionPerformedEventSchema,\n errorRaisedEventSchema,\n]);\n\nexport type CanonicalEvent = z.infer<typeof canonicalEventSchema>;\nexport type CanonicalEventInput = z.input<typeof canonicalEventSchema>;\n\nexport type SessionStartEvent = z.infer<typeof sessionStartEventSchema>;\nexport type SessionEndEvent = z.infer<typeof sessionEndEventSchema>;\nexport type PromptSubmittedEvent = z.infer<typeof promptSubmittedEventSchema>;\nexport type GenerationStartEvent = z.infer<typeof generationStartEventSchema>;\nexport type GenerationEndEvent = z.infer<typeof generationEndEventSchema>;\nexport type ToolStartEvent = z.infer<typeof toolStartEventSchema>;\nexport type ToolEndEvent = z.infer<typeof toolEndEventSchema>;\nexport type SubagentStartEvent = z.infer<typeof subagentStartEventSchema>;\nexport type SubagentEndEvent = z.infer<typeof subagentEndEventSchema>;\nexport type CompactionPerformedEvent = z.infer<typeof compactionPerformedEventSchema>;\nexport type ErrorRaisedEvent = z.infer<typeof errorRaisedEventSchema>;\n\nexport type CanonicalEventOfType<TType extends CanonicalEventType> = Extract<\n CanonicalEvent,\n { type: TType }\n>;\n\n/**\n * The event types that may carry a resolved `target` (ADR 0008): a tool call\n * names the worktree it touched; a session start and a prompt name the one the\n * session runs in, so a consumer knows the session's place before its first\n * tool call.\n */\nexport const TARGETED_EVENT_TYPES = [\"session.start\", \"prompt.submitted\", \"tool.start\", \"tool.end\"] as const;\nexport type TargetedEventType = (typeof TARGETED_EVENT_TYPES)[number];\nexport type TargetedEvent = CanonicalEventOfType<TargetedEventType>;\n\nconst TARGETED: ReadonlySet<string> = new Set(TARGETED_EVENT_TYPES);\nexport const isTargetedEvent = (event: CanonicalEvent): event is TargetedEvent => TARGETED.has(event.type);\n\nexport type EventValidationResult =\n | { readonly status: \"ok\"; readonly event: CanonicalEvent }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nexport const validateCanonicalEvent = (value: unknown): EventValidationResult => {\n const parsed = canonicalEventSchema.safeParse(value);\n if (parsed.success) {\n return { status: \"ok\", event: parsed.data };\n }\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n};\n\n/** Parse or throw. Intended for fixtures and tests, not the hook path. */\nexport const parseCanonicalEvent = (value: unknown): CanonicalEvent =>\n canonicalEventSchema.parse(value);\n\n/** Usage carried by an event, if the event type can carry any. */\nexport const eventUsage = (event: CanonicalEvent): CanonicalUsage | undefined =>\n \"usage\" in event ? event.usage : undefined;\n\n/** Stable ordering: by sequence, then by timestamp, then by event id. */\nexport const compareEvents = (a: CanonicalEvent, b: CanonicalEvent): number =>\n a.sequence - b.sequence || a.occurredAt - b.occurredAt || a.eventId.localeCompare(b.eventId);\n","import { z } from \"zod\";\n\n/**\n * Closed set of error codes. Adding a code is a minor change; changing what a\n * code means is a breaking change.\n */\nexport const otelHookErrorCodeSchema = z.enum([\n /** Input was not usable at all (empty stdin, unparsable JSON). */\n \"invalid-input\",\n /** Input parsed but failed canonical schema validation. */\n \"schema-validation-failed\",\n /** No adapter claimed the input with sufficient confidence. */\n \"provider-unknown\",\n /** Several adapters claimed the input at the same confidence. */\n \"provider-detection-ambiguous\",\n /** An adapter threw or returned a malformed result. */\n \"provider-adapter-failure\",\n /** Two identity claims disagreed at equal confidence. */\n \"identity-conflict\",\n /** Required identity fields were absent. */\n \"identity-incomplete\",\n /** A usage report violated the canonical usage invariants. */\n \"usage-invalid\",\n /** The state store could not be read or written. */\n \"state-store-failure\",\n /** The telemetry sink rejected or could not deliver a batch. */\n \"telemetry-export-failure\",\n /** Content reached the sink boundary in a state the policy forbids. */\n \"privacy-policy-violation\",\n /** Configuration could not be resolved. */\n \"configuration-invalid\",\n /** A configured bound (events, batch size) dropped data. */\n \"limit-exceeded\",\n /**\n * No replay-stable delivery identifier was available for a callback while\n * deduplication was required.\n */\n \"delivery-identifier-unavailable\",\n \"delivery-claim-superseded\",\n /** Anything unanticipated. Always reported, never fatal to the host. */\n \"internal-error\",\n]);\nexport type OtelHookErrorCode = z.infer<typeof otelHookErrorCodeSchema>;\n\nexport const errorSeveritySchema = z.enum([\"warning\", \"error\"]);\nexport type ErrorSeverity = z.infer<typeof errorSeveritySchema>;\n\n/** Pipeline stage where a failure occurred. */\nexport const errorPhaseSchema = z.enum([\n \"configuration\",\n \"detection\",\n \"identity\",\n \"parsing\",\n \"normalization\",\n \"privacy\",\n \"state\",\n \"export\",\n \"shutdown\",\n]);\nexport type ErrorPhase = z.infer<typeof errorPhaseSchema>;\n\n/**\n * Which of the two safety postures a code participates in.\n *\n * - `fail-open`: the hook still reports success to the host agent. Telemetry may\n * be incomplete; the coding agent is never blocked.\n * - `fail-closed-attribution`: the observation is not attributed to a session or\n * provider. Data is dropped rather than labelled with a guess.\n */\nexport const failurePostureSchema = z.enum([\"fail-open\", \"fail-closed-attribution\"]);\nexport type FailurePosture = z.infer<typeof failurePostureSchema>;\n\nexport type ErrorCodeDescriptor = {\n readonly code: OtelHookErrorCode;\n readonly severity: ErrorSeverity;\n readonly posture: FailurePosture;\n /** Whether retrying the same input could succeed. */\n readonly retryable: boolean;\n readonly summary: string;\n};\n\nexport const ERROR_TAXONOMY: Readonly<Record<OtelHookErrorCode, ErrorCodeDescriptor>> =\n Object.freeze({\n \"invalid-input\": {\n code: \"invalid-input\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Input could not be read or decoded.\",\n },\n \"schema-validation-failed\": {\n code: \"schema-validation-failed\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"A canonical event failed schema validation and was dropped.\",\n },\n \"provider-unknown\": {\n code: \"provider-unknown\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"No adapter recognized the source provider; the input stays unattributed.\",\n },\n \"provider-detection-ambiguous\": {\n code: \"provider-detection-ambiguous\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Multiple adapters claimed the input at equal confidence.\",\n },\n \"provider-adapter-failure\": {\n code: \"provider-adapter-failure\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A provider adapter failed while parsing.\",\n },\n \"identity-conflict\": {\n code: \"identity-conflict\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Identity claims disagreed; attribution was declined.\",\n },\n \"identity-incomplete\": {\n code: \"identity-incomplete\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Required identity fields were missing; attribution was declined.\",\n },\n \"usage-invalid\": {\n code: \"usage-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A usage report violated the canonical usage invariants.\",\n },\n \"state-store-failure\": {\n code: \"state-store-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"State could not be read or written; derived values may be incomplete.\",\n },\n \"telemetry-export-failure\": {\n code: \"telemetry-export-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"The telemetry sink could not accept a batch.\",\n },\n \"privacy-policy-violation\": {\n code: \"privacy-policy-violation\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Content violated the resolved privacy policy and was dropped.\",\n },\n \"configuration-invalid\": {\n code: \"configuration-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Configuration could not be resolved; defaults apply.\",\n },\n \"limit-exceeded\": {\n code: \"limit-exceeded\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A configured bound was reached and data was dropped.\",\n },\n \"delivery-identifier-unavailable\": {\n code: \"delivery-identifier-unavailable\",\n severity: \"warning\",\n // Fail-open: the observation is still attributed and exported. Only the\n // at-most-once guarantee is missing, and refusing the telemetry to protect\n // a duplicate count would trade a certain loss for a possible one.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"No replay-stable delivery identifier was available; this callback was exported without deduplication.\",\n },\n \"delivery-claim-superseded\": {\n code: \"delivery-claim-superseded\",\n severity: \"warning\",\n // Fail-open, and specifically *not* silent. A peer reclaimed this callback's\n // claim while this process was still working on it, which means the\n // configured stale window is shorter than this installation's real worst\n // case. Both processes may now have exported the callback, so the\n // at-most-once guarantee did not hold for it — the only honest response is\n // to say so and let the operator raise the window.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"A delivery claim was reclaimed by another process before this one committed; the callback may have been exported twice.\",\n },\n \"internal-error\": {\n code: \"internal-error\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"An unexpected failure was contained.\",\n },\n });\n\nexport const describeErrorCode = (code: OtelHookErrorCode): ErrorCodeDescriptor =>\n ERROR_TAXONOMY[code];\n\n/** Outcome of attributing an observation to a provider and session. */\nexport const attributionOutcomeSchema = z.enum([\n /** Identity resolved; events carry provider and session identity. */\n \"attributed\",\n /** Identity could not be established safely; nothing was attributed. */\n \"declined\",\n /** Attribution was attempted and failed unexpectedly. */\n \"failed\",\n /** Input was recognized but intentionally carried no telemetry. */\n \"not-applicable\",\n]);\nexport type AttributionOutcome = z.infer<typeof attributionOutcomeSchema>;\n\nexport const attributionReasonSchema = z.enum([\n \"provider-unknown\",\n \"provider-detection-ambiguous\",\n \"identity-conflict\",\n \"identity-incomplete\",\n \"adapter-ignored-input\",\n \"adapter-failure\",\n \"invalid-input\",\n \"internal-error\",\n]);\nexport type AttributionReason = z.infer<typeof attributionReasonSchema>;\n"],"mappings":";AAAA,SAAS,SAAS;AAYX,IAAM,2BAA2B;AAIjC,IAAM,+BAA+B,EAAE,QAAQ,wBAAwB;;;AChB9E,SAAS,KAAAA,UAAS;AAGX,IAAM,wBAAwB;AAG9B,IAAM,8BAA8B;AAGpC,IAAM,6BAA6B;AAEnC,IAAM,uBAAuBA,GAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,qBAAqB;AAGxE,IAAM,oBAAoBA,GAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,MAAqB;AAI3E,IAAM,uBAAuBA,GAAE,OAAO,EAAE,IAAI,CAAC,EAAE,OAAO;AAGtD,IAAM,mBAAmBA,GAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAG/C,IAAM,uBAAuBA,GAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAE1D,IAAM,kBAAkB,MAAmBA,GAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,qBAAqB;AAE/E,IAAM,qBAAqB,gBAAgB,EAAE,MAAsB;AAGnE,IAAM,kBAAkB,gBAAgB,EAAE,MAAmB;AAG7D,IAAM,gBAAgB,gBAAgB,EAAE,MAAi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UAAU,GAAG,MAAM,KAAK,KAAK,GAAG,KAAK,QAAQ,KAAK,MAAM,OAAO;AAAA,IAClE;AAAA,EACF;AACF;AAGO,IAAM,sBAAsB,CAAC,UAClC,qBAAqB,MAAM,KAAK;AAG3B,IAAM,aAAa,CAACA,WACzB,WAAWA,SAAQA,OAAM,QAAQ;AAG5B,IAAM,gBAAgB,CAAC,GAAmB,MAC/C,EAAE,WAAW,EAAE,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,QAAQ,cAAc,EAAE,OAAO;","names":["z","z","z","z","z","z","z","z","z","parsed","z","z","z","z","z","z","event"]}
1
+ {"version":3,"sources":["../src/model/version.ts","../src/model/primitives.ts","../src/model/extensions.ts","../src/model/content.ts","../src/model/usage.ts","../src/model/identity.ts","../src/model/target.ts","../src/model/events.ts","../src/errors/taxonomy.ts"],"sourcesContent":["import { z } from \"zod\";\n\n/**\n * Version of the canonical event model.\n *\n * Every emitted event carries this value. Consumers must treat an unknown\n * version as unreadable rather than guessing field semantics.\n *\n * Compatibility rules:\n * - Additive optional fields do not change the version.\n * - Renaming, removing, or re-interpreting a field increments the version.\n */\nexport const CANONICAL_SCHEMA_VERSION = 1 as const;\n\nexport type CanonicalSchemaVersion = typeof CANONICAL_SCHEMA_VERSION;\n\nexport const canonicalSchemaVersionSchema = z.literal(CANONICAL_SCHEMA_VERSION);\n","import { z } from \"zod\";\n\n/** Maximum length accepted for short identifier-like strings. */\nexport const MAX_IDENTIFIER_LENGTH = 256;\n\n/** Maximum length accepted for a single string attribute value. */\nexport const MAX_ATTRIBUTE_STRING_LENGTH = 4096;\n\n/** Maximum number of entries accepted in an attribute array value. */\nexport const MAX_ATTRIBUTE_ARRAY_LENGTH = 128;\n\nexport const nonEmptyStringSchema = z.string().min(1).max(MAX_IDENTIFIER_LENGTH);\n\n/** Wall-clock time as whole milliseconds since the Unix epoch. */\nexport const epochMillisSchema = z.number().int().min(0).max(8_640_000_000_000_000);\nexport type EpochMillis = z.infer<typeof epochMillisSchema>;\n\n/** Non-negative duration in milliseconds; may be fractional. */\nexport const durationMillisSchema = z.number().min(0).finite();\n\n/** Token counts are always non-negative integers. */\nexport const tokenCountSchema = z.number().int().min(0);\n\n/** Monotonically increasing per-invocation ordering key. */\nexport const sequenceNumberSchema = z.number().int().min(0);\n\nconst brandedIdSchema = (): z.ZodString => z.string().min(1).max(MAX_IDENTIFIER_LENGTH);\n\nexport const invocationIdSchema = brandedIdSchema().brand<\"InvocationId\">();\nexport type InvocationId = z.infer<typeof invocationIdSchema>;\n\nexport const sessionIdSchema = brandedIdSchema().brand<\"SessionId\">();\nexport type SessionId = z.infer<typeof sessionIdSchema>;\n\nexport const eventIdSchema = brandedIdSchema().brand<\"EventId\">();\nexport type EventId = z.infer<typeof eventIdSchema>;\n\n/**\n * Workspace identifiers are opaque, privacy-safe handles of the form\n * `<scheme>:<token>`. Filesystem paths cannot satisfy this pattern, which keeps\n * home directories and repository paths out of telemetry by construction.\n */\nexport const WORKSPACE_ID_PATTERN = /^[a-z][a-z0-9]{0,15}:[A-Za-z0-9_-]{8,128}$/;\nexport const workspaceIdSchema = z\n .string()\n .regex(WORKSPACE_ID_PATTERN, \"workspace id must be an opaque `<scheme>:<token>` handle\")\n .brand<\"WorkspaceId\">();\nexport type WorkspaceId = z.infer<typeof workspaceIdSchema>;\n\n/** Provider ids are lowercase, hyphenated, and stable across releases. */\nexport const PROVIDER_ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\nexport const providerIdSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(PROVIDER_ID_PATTERN, \"provider id must be lowercase and hyphenated\")\n .brand<\"ProviderId\">();\nexport type ProviderId = z.infer<typeof providerIdSchema>;\n\n/** Sentinel used whenever the source provider could not be established. */\nexport const UNKNOWN_PROVIDER_ID = \"unknown\" as const;\nexport type UnknownProviderId = typeof UNKNOWN_PROVIDER_ID;\n\nexport const resolvedProviderIdSchema = z.union([\n providerIdSchema,\n z.literal(UNKNOWN_PROVIDER_ID),\n]);\nexport type ResolvedProviderId = z.infer<typeof resolvedProviderIdSchema>;\n\nexport const isUnknownProvider = (value: ResolvedProviderId): value is UnknownProviderId =>\n value === UNKNOWN_PROVIDER_ID;\n\n/**\n * Attribute values are restricted to OpenTelemetry-compatible primitives.\n *\n * This restriction is a containment boundary, not a convenience: because no\n * nested object can be represented, a raw provider payload cannot be smuggled\n * out of an adapter through attributes or extensions.\n */\nexport const attributePrimitiveSchema = z.union([\n z.string().max(MAX_ATTRIBUTE_STRING_LENGTH),\n z.number().finite(),\n z.boolean(),\n]);\nexport type AttributePrimitive = z.infer<typeof attributePrimitiveSchema>;\n\nexport const attributeValueSchema = z.union([\n attributePrimitiveSchema,\n z.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH),\n]);\nexport type AttributeValue = z.infer<typeof attributeValueSchema>;\n\nexport const attributesSchema = z.record(z.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);\nexport type Attributes = z.infer<typeof attributesSchema>;\n\n/** Ordered confidence ladder for provider detection. */\nexport const detectionConfidenceSchema = z.enum([\"none\", \"weak\", \"strong\", \"exact\"]);\nexport type DetectionConfidence = z.infer<typeof detectionConfidenceSchema>;\n\nexport const DETECTION_CONFIDENCE_RANK: Readonly<Record<DetectionConfidence, number>> =\n Object.freeze({\n none: 0,\n weak: 1,\n strong: 2,\n exact: 3,\n });\n\nexport const compareDetectionConfidence = (a: DetectionConfidence, b: DetectionConfidence): number =>\n DETECTION_CONFIDENCE_RANK[a] - DETECTION_CONFIDENCE_RANK[b];\n\n/** How the observed data reached this process. */\nexport const sourceTransportSchema = z.enum([\n \"hook-stdin\",\n \"cli-argument\",\n \"library-call\",\n \"test-fixture\",\n]);\nexport type SourceTransport = z.infer<typeof sourceTransportSchema>;\n","import { z } from \"zod\";\n\nimport { attributeValueSchema, type AttributeValue } from \"./primitives.js\";\n\n/**\n * Extension keys must be namespaced: at least one dot-separated segment before\n * the leaf, e.g. `acme.deployment-tier`. Namespacing keeps provider- and\n * consumer-specific fields from colliding with core fields or each other.\n */\nexport const EXTENSION_KEY_PATTERN =\n /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;\n\n/** Namespaces owned by the core model; extensions may not use them. */\nexport const RESERVED_EXTENSION_NAMESPACES: readonly string[] = Object.freeze([\n \"otelhook\",\n \"otel\",\n \"telemetry\",\n]);\n\nexport const MAX_EXTENSION_ENTRIES = 64;\n\nexport const extensionKeyNamespace = (key: string): string => key.slice(0, key.indexOf(\".\"));\n\nexport const isReservedExtensionNamespace = (key: string): boolean =>\n RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));\n\nexport const isValidExtensionKey = (key: string): boolean =>\n EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);\n\n/**\n * Namespaced extension bag.\n *\n * Values are restricted to attribute primitives, so extensions cannot carry\n * nested provider payloads.\n */\nexport const extensionsSchema = z\n .record(z.string(), attributeValueSchema)\n .check((ctx) => {\n const keys = Object.keys(ctx.value);\n if (keys.length > MAX_EXTENSION_ENTRIES) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`,\n });\n }\n for (const key of keys) {\n if (!EXTENSION_KEY_PATTERN.test(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. \"acme.tier\"`,\n });\n continue;\n }\n if (isReservedExtensionNamespace(key)) {\n ctx.issues.push({\n code: \"custom\",\n input: ctx.value,\n path: [key],\n message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`,\n });\n }\n }\n });\n\nexport type Extensions = Record<string, AttributeValue>;\n\nexport const EMPTY_EXTENSIONS: Extensions = Object.freeze({});\n\nexport const emptyExtensions = (): Extensions => ({});\n","import { z } from \"zod\";\n\nimport { nonEmptyStringSchema } from \"./primitives.js\";\n\n/** What kind of conversational or tool content a fact describes. */\nexport const contentKindSchema = z.enum([\n \"prompt\",\n \"response\",\n \"reasoning\",\n \"tool-input\",\n \"tool-output\",\n \"error-message\",\n \"system-instruction\",\n \"attachment\",\n]);\nexport type ContentKind = z.infer<typeof contentKindSchema>;\n\nexport const contentRoleSchema = z.enum([\"user\", \"assistant\", \"system\", \"tool\", \"unknown\"]);\nexport type ContentRole = z.infer<typeof contentRoleSchema>;\n\n/**\n * How much of the original content this fact discloses.\n *\n * - `omitted`: no text at all (the default posture).\n * - `masked`: a shape-preserving mask; non-whitespace characters replaced.\n * - `redacted`: text with secret-looking spans replaced by a placeholder.\n * - `raw`: verbatim text. Only reachable through explicit opt-in.\n */\nexport const contentDisclosureSchema = z.enum([\"omitted\", \"masked\", \"redacted\", \"raw\"]);\nexport type ContentDisclosure = z.infer<typeof contentDisclosureSchema>;\n\nexport const CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;\n\n/**\n * A privacy-safe description of content.\n *\n * Lengths and a stable hash are always present so consumers can measure and\n * correlate volume without receiving the content itself. `text` is present only\n * when the resolved privacy policy allows disclosure, and is produced solely by\n * the central privacy service.\n */\nexport const contentFactSchema = z.strictObject({\n kind: contentKindSchema,\n role: contentRoleSchema.optional(),\n /** Unicode code point count of the original content. */\n characterLength: z.number().int().min(0),\n /** UTF-8 byte length of the original content. */\n byteLength: z.number().int().min(0),\n /** Stable salted digest of the original content. */\n contentHash: z.string().regex(CONTENT_HASH_PATTERN),\n disclosure: contentDisclosureSchema,\n /** Disclosed text, bounded by the privacy policy. Absent when omitted. */\n text: z.string().optional(),\n /** True when `text` was cut short by the configured string bound. */\n truncated: z.boolean(),\n /** Number of secret-looking spans replaced while producing `text`. */\n secretsRedacted: z.number().int().min(0),\n /** Optional non-sensitive label, e.g. a MIME type or tool name. */\n label: nonEmptyStringSchema.optional(),\n});\nexport type ContentFact = z.infer<typeof contentFactSchema>;\n\nexport const contentFactsSchema = z.array(contentFactSchema).max(64);\n\n/**\n * Guard used in tests and at the sink boundary: an omitted fact must not carry\n * text, and a disclosing fact must carry it.\n */\nexport const isContentFactConsistent = (fact: ContentFact): boolean =>\n fact.disclosure === \"omitted\" ? fact.text === undefined : fact.text !== undefined;\n\n/**\n * A fact for a content kind the event can carry when the provider sent no text.\n *\n * Always `omitted` with zero length, regardless of the installation's content\n * mode: there is nothing to mask, redact, or export.\n */\nexport const isUnavailableContentFact = (fact: ContentFact): boolean =>\n fact.disclosure === \"omitted\" &&\n fact.text === undefined &&\n fact.characterLength === 0 &&\n fact.byteLength === 0;\n","import { z } from \"zod\";\n\nimport { tokenCountSchema } from \"./primitives.js\";\n\n/**\n * Whether an observation reports the change since the previous observation\n * (`delta`) or the running total for the session/generation (`cumulative`).\n *\n * The canonical model keeps temporality explicit rather than assuming one:\n * summing cumulative observations double-counts, and diffing delta observations\n * silently loses tokens.\n */\nexport const usageTemporalitySchema = z.enum([\"delta\", \"cumulative\"]);\nexport type UsageTemporality = z.infer<typeof usageTemporalitySchema>;\n\n/**\n * Whether the provider counts cache-creation tokens inside its input total or\n * reports them as a disjoint bucket.\n *\n * - `included-in-input`: `cacheCreationInputTokens` is a subset of `inputTokens`.\n * - `disjoint-from-input`: cache-creation tokens are billed in addition to\n * `inputTokens` and must be added when computing a total.\n * - `not-reported`: the provider exposes no cache-creation counter; the field is\n * pinned to zero.\n */\nexport const cacheCreationAccountingSchema = z.enum([\n \"included-in-input\",\n \"disjoint-from-input\",\n \"not-reported\",\n]);\nexport type CacheCreationAccounting = z.infer<typeof cacheCreationAccountingSchema>;\n\n/** Whether a provider-reported total agrees with the canonical computation. */\nexport const providerTotalAgreementSchema = z.enum([\"unreported\", \"agrees\", \"disagrees\"]);\nexport type ProviderTotalAgreement = z.infer<typeof providerTotalAgreementSchema>;\n\n/**\n * What an adapter reports, before normalization.\n *\n * `inputTokens` is *inclusive*: it counts every input token the provider\n * attributes to the call, including cache reads (and cache creation when the\n * provider folds it in). `outputTokens` is likewise inclusive of reasoning\n * output. Subset fields describe portions of those totals, never additions.\n */\nexport const usageReportSchema = z.strictObject({\n temporality: usageTemporalitySchema,\n /** Inclusive input tokens. */\n inputTokens: tokenCountSchema.optional(),\n /** Subset of `inputTokens` served from a prompt cache. */\n cachedInputTokens: tokenCountSchema.optional(),\n /** Tokens written to a prompt cache. */\n cacheCreationInputTokens: tokenCountSchema.optional(),\n /** Required when `cacheCreationInputTokens` is present and non-zero. */\n cacheCreationAccounting: cacheCreationAccountingSchema.optional(),\n /** Inclusive output tokens. */\n outputTokens: tokenCountSchema.optional(),\n /** Subset of `outputTokens` spent on reasoning. */\n reasoningOutputTokens: tokenCountSchema.optional(),\n /** Total exactly as the provider reported it, if it reported one. */\n providerTotalTokens: tokenCountSchema.optional(),\n});\nexport type UsageReport = z.infer<typeof usageReportSchema>;\n\n/**\n * Fully normalized usage.\n *\n * Derived fields (`uncachedInputTokens`, `totalTokens`,\n * `providerTotalAgreement`) are part of the schema and are re-checked on parse,\n * so an inconsistent object cannot exist. Construct values with\n * {@link normalizeUsage} rather than by hand.\n */\nexport const canonicalUsageSchema = z\n .strictObject({\n temporality: usageTemporalitySchema,\n inputTokens: tokenCountSchema,\n cachedInputTokens: tokenCountSchema,\n cacheCreationInputTokens: tokenCountSchema,\n cacheCreationAccounting: cacheCreationAccountingSchema,\n outputTokens: tokenCountSchema,\n reasoningOutputTokens: tokenCountSchema,\n /** Derived: input tokens that were neither cache reads nor cache writes. */\n uncachedInputTokens: tokenCountSchema,\n /** Derived: canonical billable total. */\n totalTokens: tokenCountSchema,\n providerTotalTokens: tokenCountSchema.optional(),\n providerTotalAgreement: providerTotalAgreementSchema,\n })\n .check((ctx) => {\n const usage = ctx.value;\n const push = (message: string): void => {\n ctx.issues.push({ code: \"custom\", input: usage, message });\n };\n\n if (usage.cachedInputTokens > usage.inputTokens) {\n push(\"cachedInputTokens must not exceed inputTokens (it is a subset)\");\n }\n if (usage.reasoningOutputTokens > usage.outputTokens) {\n push(\"reasoningOutputTokens must not exceed outputTokens (it is a subset)\");\n }\n if (usage.cacheCreationAccounting === \"not-reported\" && usage.cacheCreationInputTokens !== 0) {\n push(\"cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported\");\n }\n const creationInsideInput =\n usage.cacheCreationAccounting === \"included-in-input\" ? usage.cacheCreationInputTokens : 0;\n if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {\n push(\n \"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input\",\n );\n }\n const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;\n if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {\n push(`uncachedInputTokens must equal ${expectedUncached}`);\n }\n const creationOutsideInput =\n usage.cacheCreationAccounting === \"disjoint-from-input\" ? usage.cacheCreationInputTokens : 0;\n const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;\n if (usage.totalTokens !== expectedTotal) {\n push(`totalTokens must equal ${expectedTotal}`);\n }\n const expectedAgreement: ProviderTotalAgreement =\n usage.providerTotalTokens === undefined\n ? \"unreported\"\n : usage.providerTotalTokens === expectedTotal\n ? \"agrees\"\n : \"disagrees\";\n if (usage.providerTotalAgreement !== expectedAgreement) {\n push(`providerTotalAgreement must be ${expectedAgreement}`);\n }\n });\nexport type CanonicalUsage = z.infer<typeof canonicalUsageSchema>;\n\nexport type UsageNormalizationIssue = {\n readonly code:\n | \"invalid-report\"\n | \"cached-exceeds-input\"\n | \"reasoning-exceeds-output\"\n | \"cache-creation-exceeds-input\"\n | \"cache-creation-accounting-missing\";\n readonly message: string;\n};\n\nexport type UsageNormalizationResult =\n | { readonly status: \"ok\"; readonly usage: CanonicalUsage; readonly notes: readonly string[] }\n | { readonly status: \"invalid\"; readonly issues: readonly UsageNormalizationIssue[] };\n\n/**\n * Normalize a provider usage report into canonical usage.\n *\n * Deterministic rules:\n * 1. Absent counters default to `0`; `providerTotalTokens` stays absent.\n * 2. Non-integer, negative, or non-finite counters are rejected.\n * 3. A subset exceeding its total is rejected — never clamped — because\n * clamping would silently invent a billing story.\n * 4. `cacheCreationAccounting` defaults to `not-reported` when no cache-creation\n * tokens are reported, and is *required* when they are: guessing whether the\n * bucket is disjoint would mis-total every downstream cost calculation.\n * 5. A provider total that disagrees with the canonical total is preserved as\n * reported and flagged `disagrees`. Both numbers survive; neither is edited.\n */\nexport const normalizeUsage = (report: unknown): UsageNormalizationResult => {\n const parsed = usageReportSchema.safeParse(report);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map((issue) => ({\n code: \"invalid-report\" as const,\n message: `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n })),\n };\n }\n\n const input = parsed.data;\n const issues: UsageNormalizationIssue[] = [];\n const notes: string[] = [];\n\n const inputTokens = input.inputTokens ?? 0;\n const cachedInputTokens = input.cachedInputTokens ?? 0;\n const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;\n const outputTokens = input.outputTokens ?? 0;\n const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;\n\n let accounting: CacheCreationAccounting;\n if (cacheCreationInputTokens === 0) {\n accounting = input.cacheCreationAccounting ?? \"not-reported\";\n if (accounting !== \"not-reported\") {\n notes.push(\n `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`,\n );\n }\n } else if (input.cacheCreationAccounting === undefined) {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message:\n \"cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred\",\n });\n accounting = \"not-reported\";\n } else if (input.cacheCreationAccounting === \"not-reported\") {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message: \"cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens\",\n });\n accounting = \"not-reported\";\n } else {\n accounting = input.cacheCreationAccounting;\n }\n\n if (cachedInputTokens > inputTokens) {\n issues.push({\n code: \"cached-exceeds-input\",\n message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n if (reasoningOutputTokens > outputTokens) {\n issues.push({\n code: \"reasoning-exceeds-output\",\n message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`,\n });\n }\n\n const creationInsideInput = accounting === \"included-in-input\" ? cacheCreationInputTokens : 0;\n if (cachedInputTokens + creationInsideInput > inputTokens) {\n issues.push({\n code: \"cache-creation-exceeds-input\",\n message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const creationOutsideInput = accounting === \"disjoint-from-input\" ? cacheCreationInputTokens : 0;\n const totalTokens = inputTokens + creationOutsideInput + outputTokens;\n const providerTotalAgreement: ProviderTotalAgreement =\n input.providerTotalTokens === undefined\n ? \"unreported\"\n : input.providerTotalTokens === totalTokens\n ? \"agrees\"\n : \"disagrees\";\n\n if (providerTotalAgreement === \"disagrees\") {\n notes.push(\n `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`,\n );\n }\n\n const usage: CanonicalUsage = {\n temporality: input.temporality,\n inputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens,\n reasoningOutputTokens,\n uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,\n totalTokens,\n ...(input.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: input.providerTotalTokens }),\n providerTotalAgreement,\n };\n\n return { status: \"ok\", usage, notes };\n};\n\nexport class UsageNormalizationError extends Error {\n public readonly issues: readonly UsageNormalizationIssue[];\n\n public constructor(issues: readonly UsageNormalizationIssue[]) {\n super(`invalid usage report: ${issues.map((issue) => issue.message).join(\"; \")}`);\n this.name = \"UsageNormalizationError\";\n this.issues = issues;\n }\n}\n\n/** Convenience wrapper for call sites that treat invalid usage as a bug. */\nexport const normalizeUsageOrThrow = (report: unknown): CanonicalUsage => {\n const result = normalizeUsage(report);\n if (result.status === \"invalid\") {\n throw new UsageNormalizationError(result.issues);\n }\n return result.usage;\n};\n\nexport const EMPTY_DELTA_USAGE: CanonicalUsage = Object.freeze(\n normalizeUsageOrThrow({ temporality: \"delta\" }),\n);\n\nexport type UsageDeltaResult = {\n readonly usage: CanonicalUsage;\n /**\n * True when the current snapshot is smaller than the previous one on any\n * counter. That means the cumulative series restarted (new session, replayed\n * transcript, provider reset), so the current snapshot is emitted as the delta\n * instead of a negative difference.\n */\n readonly resetDetected: boolean;\n};\n\nconst requireCumulative = (usage: CanonicalUsage, label: string): void => {\n if (usage.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: `${label} must have cumulative temporality` },\n ]);\n }\n};\n\n/**\n * Convert two cumulative snapshots into a delta observation.\n *\n * Replay safety: re-processing the same snapshot yields an all-zero delta, and a\n * decreasing series is reported as a reset rather than a negative delta.\n * Accounting mode must match; mixing modes would make the subtraction meaningless.\n */\nexport const cumulativeToDelta = (\n previous: CanonicalUsage,\n current: CanonicalUsage,\n): UsageDeltaResult => {\n requireCumulative(previous, \"previous usage\");\n requireCumulative(current, \"current usage\");\n\n if (\n previous.cacheCreationAccounting !== current.cacheCreationAccounting &&\n previous.cacheCreationInputTokens !== 0 &&\n current.cacheCreationInputTokens !== 0\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot diff cumulative usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const resetDetected =\n current.inputTokens < previous.inputTokens ||\n current.cachedInputTokens < previous.cachedInputTokens ||\n current.cacheCreationInputTokens < previous.cacheCreationInputTokens ||\n current.outputTokens < previous.outputTokens ||\n current.reasoningOutputTokens < previous.reasoningOutputTokens;\n\n if (resetDetected) {\n return {\n usage: normalizeUsageOrThrow({ ...toReport(current), temporality: \"delta\" }),\n resetDetected: true,\n };\n }\n\n const usage = normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: current.inputTokens - previous.inputTokens,\n cachedInputTokens: current.cachedInputTokens - previous.cachedInputTokens,\n cacheCreationInputTokens:\n current.cacheCreationInputTokens - previous.cacheCreationInputTokens,\n cacheCreationAccounting: current.cacheCreationAccounting,\n outputTokens: current.outputTokens - previous.outputTokens,\n reasoningOutputTokens: current.reasoningOutputTokens - previous.reasoningOutputTokens,\n });\n\n return { usage, resetDetected: false };\n};\n\n/** Project canonical usage back onto the reported shape. */\nexport const toReport = (usage: CanonicalUsage): UsageReport => ({\n temporality: usage.temporality,\n inputTokens: usage.inputTokens,\n cachedInputTokens: usage.cachedInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n cacheCreationAccounting: usage.cacheCreationAccounting,\n outputTokens: usage.outputTokens,\n reasoningOutputTokens: usage.reasoningOutputTokens,\n ...(usage.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: usage.providerTotalTokens }),\n});\n\n/**\n * Add two delta observations. Cumulative usage is never summed, because two\n * running totals do not compose.\n */\nexport const addUsage = (a: CanonicalUsage, b: CanonicalUsage): CanonicalUsage => {\n if (a.temporality !== \"delta\" || b.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"only delta usage may be summed\" },\n ]);\n }\n const accounting =\n a.cacheCreationInputTokens === 0 && a.cacheCreationAccounting === \"not-reported\"\n ? b.cacheCreationAccounting\n : b.cacheCreationInputTokens === 0 && b.cacheCreationAccounting === \"not-reported\"\n ? a.cacheCreationAccounting\n : a.cacheCreationAccounting;\n\n if (\n a.cacheCreationInputTokens !== 0 &&\n b.cacheCreationInputTokens !== 0 &&\n a.cacheCreationAccounting !== b.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot sum usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n a.providerTotalTokens === undefined && b.providerTotalTokens === undefined\n ? undefined\n : (a.providerTotalTokens ?? 0) + (b.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: a.inputTokens + b.inputTokens,\n cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,\n cacheCreationInputTokens: a.cacheCreationInputTokens + b.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: a.outputTokens + b.outputTokens,\n reasoningOutputTokens: a.reasoningOutputTokens + b.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n","import { z } from \"zod\";\n\nimport {\n attributesSchema,\n detectionConfidenceSchema,\n DETECTION_CONFIDENCE_RANK,\n epochMillisSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n resolvedProviderIdSchema,\n sessionIdSchema,\n sourceTransportSchema,\n workspaceIdSchema,\n type DetectionConfidence,\n type InvocationId,\n type SessionId,\n type WorkspaceId,\n} from \"./primitives.js\";\n\n/**\n * Where a workspace identifier came from.\n *\n * Ordered from most to least stable. The source is recorded so consumers can\n * tell a repository-scoped identity from a directory-scoped one instead of\n * assuming they are comparable.\n */\nexport const workspaceKeySourceSchema = z.enum([\n \"git-remote\",\n \"git-root\",\n \"working-directory\",\n \"explicit\",\n \"unknown\",\n]);\nexport type WorkspaceKeySource = z.infer<typeof workspaceKeySourceSchema>;\n\n/**\n * Privacy-safe workspace identity.\n *\n * Only opaque handles and explicitly allowed labels are modelled. There is no\n * field for a filesystem path, so paths cannot be exported through this type.\n */\nexport const workspaceIdentitySchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n keySource: workspaceKeySourceSchema,\n /** Repository name only; never an owner path or URL with credentials. */\n repositoryName: nonEmptyStringSchema.optional(),\n vcsBranchName: nonEmptyStringSchema.optional(),\n /** Opaque handle for the checked-out revision. */\n vcsRevisionId: nonEmptyStringSchema.optional(),\n })\n .readonly();\nexport type WorkspaceIdentity = z.infer<typeof workspaceIdentitySchema>;\n\nexport const UNKNOWN_WORKSPACE_ID = \"unknown:0000000000000000\" as WorkspaceId;\n\nexport const unknownWorkspaceIdentity = (): WorkspaceIdentity =>\n workspaceIdentitySchema.parse({\n workspaceId: UNKNOWN_WORKSPACE_ID,\n keySource: \"unknown\",\n });\n\n/**\n * Provenance of an observation: which provider produced it and which adapter\n * interpreted it, with the confidence of that attribution.\n */\nexport const sourceProvenanceSchema = z\n .strictObject({\n providerId: resolvedProviderIdSchema,\n providerVersion: nonEmptyStringSchema.optional(),\n adapterId: nonEmptyStringSchema,\n adapterVersion: nonEmptyStringSchema,\n detectionConfidence: detectionConfidenceSchema,\n /** The provider's own name for the source event, e.g. a hook event name. */\n sourceEventName: nonEmptyStringSchema.optional(),\n transport: sourceTransportSchema,\n })\n .readonly();\nexport type SourceProvenance = z.infer<typeof sourceProvenanceSchema>;\n\n/**\n * Opaque, immutable metadata supplied by the embedding consumer.\n *\n * The library never interprets these values; it only carries and exports them.\n */\nexport const consumerAttributesSchema = attributesSchema.readonly();\nexport type ConsumerAttributes = z.infer<typeof consumerAttributesSchema>;\n\n/**\n * Immutable identity of a single hook invocation.\n *\n * Frozen on parse. There is deliberately no setter, no builder that mutates in\n * place, and no module-level instance: identity is passed explicitly so two\n * concurrent invocations can never observe each other's fields.\n */\nexport const invocationIdentitySchema = z\n .strictObject({\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Set when this invocation runs beneath another agent invocation. */\n parentInvocationId: invocationIdSchema.optional(),\n /** Root of the session tree when the provider exposes one. */\n rootSessionId: sessionIdSchema.optional(),\n /** Stable handle for the agent process/instance, when available. */\n agentInstanceId: nonEmptyStringSchema.optional(),\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n startedAt: epochMillisSchema,\n consumerAttributes: consumerAttributesSchema,\n })\n .readonly();\nexport type InvocationIdentity = z.infer<typeof invocationIdentitySchema>;\n\n/** Fields an identity claim may contribute. */\nexport const identityClaimFieldsSchema = z.strictObject({\n invocationId: invocationIdSchema.optional(),\n sessionId: sessionIdSchema.optional(),\n parentInvocationId: invocationIdSchema.optional(),\n rootSessionId: sessionIdSchema.optional(),\n agentInstanceId: nonEmptyStringSchema.optional(),\n workspace: workspaceIdentitySchema.optional(),\n startedAt: epochMillisSchema.optional(),\n});\nexport type IdentityClaimFields = z.infer<typeof identityClaimFieldsSchema>;\n\n/**\n * A claim about invocation identity from one source.\n *\n * Claims are evidence, not truth. Resolution keeps the highest-confidence claim\n * per field and refuses to merge disagreeing peers.\n */\nexport const identityClaimSchema = z.strictObject({\n /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */\n source: nonEmptyStringSchema,\n confidence: detectionConfidenceSchema,\n fields: identityClaimFieldsSchema,\n});\nexport type IdentityClaim = z.infer<typeof identityClaimSchema>;\n\nexport type IdentityConflict = {\n readonly field: keyof IdentityClaimFields;\n readonly confidence: DetectionConfidence;\n /** Rendered, non-sensitive representations of the disagreeing values. */\n readonly values: readonly string[];\n readonly sources: readonly string[];\n};\n\nexport type IdentityResolution =\n | { readonly status: \"resolved\"; readonly identity: InvocationIdentity }\n | {\n readonly status: \"conflict\";\n readonly conflicts: readonly IdentityConflict[];\n }\n | {\n readonly status: \"incomplete\";\n readonly missing: readonly (keyof IdentityClaimFields)[];\n }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nconst CLAIM_FIELDS = [\n \"invocationId\",\n \"sessionId\",\n \"parentInvocationId\",\n \"rootSessionId\",\n \"agentInstanceId\",\n \"workspace\",\n \"startedAt\",\n] as const satisfies readonly (keyof IdentityClaimFields)[];\n\nconst renderClaimValue = (value: unknown): string => {\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (value !== null && typeof value === \"object\" && \"workspaceId\" in value) {\n const { workspaceId } = value;\n return typeof workspaceId === \"string\" ? workspaceId : \"<workspace>\";\n }\n return \"<opaque>\";\n};\n\nexport type ResolveIdentityInput = {\n readonly claims: readonly IdentityClaim[];\n readonly provenance: SourceProvenance;\n /** Used only for fields no claim provides and that have a safe default. */\n readonly fallback?: {\n readonly startedAt?: number;\n readonly workspace?: WorkspaceIdentity;\n };\n readonly consumerAttributes?: Readonly<Record<string, unknown>>;\n};\n\n/**\n * Resolve identity from claims, failing closed.\n *\n * Rules:\n * 1. For each field, only claims at the highest confidence that provided it are\n * considered. Lower-confidence claims never fill in or override.\n * 2. Two distinct values at that highest confidence produce a `conflict`. The\n * invocation is then not attributed at all — a mislabelled session is worse\n * than a missing one.\n * 3. `invocationId` and `sessionId` are mandatory. Missing either yields\n * `incomplete`; neither is invented here.\n * 4. `startedAt` and `workspace` may come from an explicit fallback, because a\n * clock reading and an `unknown` workspace handle assert nothing false.\n */\nexport const resolveInvocationIdentity = (input: ResolveIdentityInput): IdentityResolution => {\n const parsedClaims: IdentityClaim[] = [];\n const issues: string[] = [];\n for (const [index, claim] of input.claims.entries()) {\n const parsed = identityClaimSchema.safeParse(claim);\n if (parsed.success) {\n parsedClaims.push(parsed.data);\n } else {\n issues.push(\n `claim[${index}]: ${parsed.error.issues.map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`).join(\", \")}`,\n );\n }\n }\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const conflicts: IdentityConflict[] = [];\n const selected: Record<string, unknown> = {};\n\n for (const field of CLAIM_FIELDS) {\n const contributors = parsedClaims.filter((claim) => claim.fields[field] !== undefined);\n if (contributors.length === 0) {\n continue;\n }\n const bestRank = Math.max(\n ...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence]),\n );\n const best = contributors.filter(\n (claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank,\n );\n const rendered = new Map<string, string[]>();\n for (const claim of best) {\n const key = JSON.stringify(claim.fields[field]);\n const sources = rendered.get(key) ?? [];\n sources.push(claim.source);\n rendered.set(key, sources);\n }\n if (rendered.size > 1) {\n const [firstBest] = best;\n conflicts.push({\n field,\n confidence: firstBest?.confidence ?? \"none\",\n values: best.map((claim) => renderClaimValue(claim.fields[field])),\n sources: best.map((claim) => claim.source),\n });\n continue;\n }\n const [winner] = best;\n if (winner !== undefined) {\n selected[field] = winner.fields[field];\n }\n }\n\n if (conflicts.length > 0) {\n return { status: \"conflict\", conflicts };\n }\n\n const missing: (keyof IdentityClaimFields)[] = [];\n if (selected.invocationId === undefined) {\n missing.push(\"invocationId\");\n }\n if (selected.sessionId === undefined) {\n missing.push(\"sessionId\");\n }\n if (missing.length > 0) {\n return { status: \"incomplete\", missing };\n }\n\n const startedAt = (selected.startedAt as number | undefined) ?? input.fallback?.startedAt;\n if (startedAt === undefined) {\n return { status: \"incomplete\", missing: [\"startedAt\"] };\n }\n const workspace =\n (selected.workspace as WorkspaceIdentity | undefined) ??\n input.fallback?.workspace ??\n unknownWorkspaceIdentity();\n\n const candidate = {\n invocationId: selected.invocationId as InvocationId,\n sessionId: selected.sessionId as SessionId,\n ...(selected.parentInvocationId === undefined\n ? {}\n : { parentInvocationId: selected.parentInvocationId as InvocationId }),\n ...(selected.rootSessionId === undefined\n ? {}\n : { rootSessionId: selected.rootSessionId as SessionId }),\n ...(selected.agentInstanceId === undefined\n ? {}\n : { agentInstanceId: selected.agentInstanceId as string }),\n provenance: input.provenance,\n workspace,\n startedAt,\n consumerAttributes: input.consumerAttributes ?? {},\n };\n\n const parsed = invocationIdentitySchema.safeParse(candidate);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n }\n return { status: \"resolved\", identity: parsed.data };\n};\n","import { z } from \"zod\";\n\nimport { nonEmptyStringSchema, workspaceIdSchema } from \"./primitives.js\";\n\n/**\n * Per-event workspace targeting (ADR 0008).\n *\n * A session's `workspace` is where the agent was *started*. An agent routinely\n * works somewhere else — in a linked git worktree beside the checkout it was\n * launched from — and the session-level identity cannot show that. A tool event\n * can: the file it edited, or the directory its shell command ran in, names the\n * worktree it actually touched.\n *\n * Two values model that, and the split between them is the privacy boundary:\n *\n * - {@link TargetHint} is what an adapter observed — local paths. It is an\n * in-process value only: it is never part of a {@link CanonicalEvent}, never\n * persisted, never exported. The core resolves it and drops it.\n * - {@link WorkspaceTarget} is what the core resolved — salted handles of the\n * worktree and its repository, the worktree's kind, the checked-out branch, and\n * what the evidence was. It travels on the event.\n */\n\n/**\n * What a target was derived from, strongest evidence first.\n *\n * - `tool-path` — a path the tool call itself named (an edited or read file, a\n * patch header).\n * - `shell-cwd` — the working directory the provider reports a shell command ran in.\n * - `session-cwd` — only the session's own directory was known; the event may\n * have reached elsewhere (e.g. a shell `cd`) without the provider saying so.\n */\nexport const targetSourceSchema = z.enum([\"tool-path\", \"shell-cwd\", \"session-cwd\"]);\nexport type TargetSource = z.infer<typeof targetSourceSchema>;\n\n/** Most paths one hint may name; a bound, not a sampling rule (all must agree). */\nexport const MAX_TARGET_HINT_PATHS = 8;\n\n/** Longest local path a hint may carry. Longer input is dropped, never truncated. */\nexport const MAX_TARGET_PATH_LENGTH = 4096;\n\nconst localPathSchema = z\n .string()\n .min(1)\n .max(MAX_TARGET_PATH_LENGTH)\n .refine((value) => !value.includes(\"\\u0000\"), \"path must not contain NUL\");\n\n/**\n * An adapter's observation of where a tool event pointed. **Carries local paths**\n * — in-process only, see the module note.\n *\n * Every path in one hint must resolve to the same worktree, or the event gets no\n * target at all: a patch touching two worktrees did not target either of them.\n */\nexport const targetHintSchema = z\n .strictObject({\n source: targetSourceSchema,\n paths: z.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),\n /** Absolute directory that relative `paths` resolve against. */\n baseDirectory: localPathSchema.optional(),\n })\n .readonly();\nexport type TargetHint = z.infer<typeof targetHintSchema>;\n\n/**\n * The weakest hint: the session's own directory. Every adapter gives it to a\n * session start and a prompt, and to a tool call that names no path.\n */\nexport const sessionCwdHint = (cwd: string | undefined): TargetHint | undefined =>\n cwd === undefined || cwd.length === 0 ? undefined : { source: \"session-cwd\", paths: [cwd] };\n\n/**\n * Whether a worktree is its repository's main checkout (`main`) or one added\n * beside it with `git worktree add` (`linked`).\n */\nexport const worktreeKindSchema = z.enum([\"main\", \"linked\"]);\nexport type WorktreeKind = z.infer<typeof worktreeKindSchema>;\n\n/**\n * The git worktree a tool event targeted. Exported; carries no path.\n *\n * `workspaceId` is derived exactly like a `git-root` workspace identity, so a\n * consumer holding the same salt can match it against one it derived itself.\n * `repositoryId` is the same derivation applied to the repository's main\n * worktree, so every worktree of one repository shares it — and for a main\n * worktree it equals `workspaceId`.\n */\nexport const workspaceTargetSchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n /** Branch checked out in that worktree; absent on a detached HEAD. */\n vcsBranchName: nonEmptyStringSchema.optional(),\n source: targetSourceSchema,\n /** `git-root` handle of the repository's main worktree; absent when there is none to name. */\n repositoryId: workspaceIdSchema.optional(),\n worktreeKind: worktreeKindSchema.optional(),\n })\n .readonly();\nexport type WorkspaceTarget = z.infer<typeof workspaceTargetSchema>;\n\n/**\n * Shape a provider's own subagent identifier must have to be exported.\n *\n * Identifier-shaped on purpose — no whitespace, no path separators — so a\n * malformed payload field cannot carry prose or a path onto the wire under an id\n * attribute. A value that does not fit is dropped, not repaired.\n */\nexport const SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;\nexport const subagentIdSchema = z.string().regex(SUBAGENT_ID_PATTERN);\nexport type SubagentId = z.infer<typeof subagentIdSchema>;\n","import { z } from \"zod\";\n\nimport {\n errorPhaseSchema,\n errorSeveritySchema,\n otelHookErrorCodeSchema,\n} from \"../errors/taxonomy.js\";\nimport { contentFactSchema, contentFactsSchema } from \"./content.js\";\nimport { extensionsSchema, emptyExtensions } from \"./extensions.js\";\nimport { sourceProvenanceSchema, workspaceIdentitySchema } from \"./identity.js\";\nimport { subagentIdSchema, workspaceTargetSchema } from \"./target.js\";\nimport {\n durationMillisSchema,\n epochMillisSchema,\n eventIdSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n sequenceNumberSchema,\n sessionIdSchema,\n tokenCountSchema,\n} from \"./primitives.js\";\nimport { canonicalUsageSchema, type CanonicalUsage } from \"./usage.js\";\nimport { canonicalSchemaVersionSchema } from \"./version.js\";\n\n/** Model being invoked. Model identifiers are not treated as sensitive. */\nexport const modelDescriptorSchema = z.strictObject({\n modelId: nonEmptyStringSchema,\n /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */\n vendor: nonEmptyStringSchema.optional(),\n family: nonEmptyStringSchema.optional(),\n});\nexport type ModelDescriptor = z.infer<typeof modelDescriptorSchema>;\n\nexport const costFactsSchema = z.strictObject({\n /** ISO 4217 code. */\n currency: z.string().length(3),\n amount: z.number().min(0).finite(),\n source: z.enum([\"provider-reported\", \"computed\"]),\n});\nexport type CostFacts = z.infer<typeof costFactsSchema>;\n\nexport const canonicalEventTypeSchema = z.enum([\n \"session.start\",\n \"session.end\",\n \"prompt.submitted\",\n \"generation.start\",\n \"generation.end\",\n \"tool.start\",\n \"tool.end\",\n \"subagent.start\",\n \"subagent.end\",\n \"compaction.performed\",\n \"error.raised\",\n]);\nexport type CanonicalEventType = z.infer<typeof canonicalEventTypeSchema>;\n\nexport const CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;\n\nconst outcomeSchema = z.enum([\"ok\", \"error\", \"cancelled\", \"timeout\", \"denied\", \"unknown\"]);\nexport type EventOutcome = z.infer<typeof outcomeSchema>;\n\n/**\n * Fields present on every canonical event.\n *\n * Identity fields are duplicated onto each event rather than referenced through\n * shared state, so an event is self-describing once it leaves the process.\n */\nconst baseEventFields = {\n schemaVersion: canonicalSchemaVersionSchema,\n eventId: eventIdSchema,\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Per-invocation ordering key. Stable across replays of the same input. */\n sequence: sequenceNumberSchema,\n occurredAt: epochMillisSchema,\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n /**\n * The provider's own id for the subagent this event was emitted inside (e.g.\n * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event\n * factory, never by hand.\n */\n subagentId: subagentIdSchema.optional(),\n extensions: extensionsSchema.default(emptyExtensions),\n /**\n * Attributes of the session context segment in force when the event\n * occurred (`docs/session-context.md`), stamped by the core from a file a\n * harness wrote. Exported on every record of the event, over the same keys\n * from the Resource. Absent when no context applies. Set by the core only,\n * never by an adapter.\n */\n contextAttributes: z.record(z.string().min(1).max(255), z.union([z.string(), z.number(), z.boolean()])).optional(),\n} as const;\n\nconst event = <TShape extends z.ZodRawShape>(shape: TShape) =>\n z.strictObject({ ...baseEventFields, ...shape });\n\nexport const sessionStartEventSchema = event({\n type: z.literal(\"session.start\"),\n sessionKind: z.enum([\"interactive\", \"non-interactive\", \"unknown\"]),\n agentName: nonEmptyStringSchema.optional(),\n agentVersion: nonEmptyStringSchema.optional(),\n model: modelDescriptorSchema.optional(),\n /** The git worktree the session runs in, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const sessionEndEventSchema = event({\n type: z.literal(\"session.end\"),\n reason: z.enum([\"completed\", \"aborted\", \"error\", \"timeout\", \"unknown\"]),\n durationMillis: durationMillisSchema.optional(),\n /** Session totals, typically cumulative. */\n usage: canonicalUsageSchema.optional(),\n cost: costFactsSchema.optional(),\n});\n\nexport const promptSubmittedEventSchema = event({\n type: z.literal(\"prompt.submitted\"),\n promptSource: z.enum([\"user\", \"automation\", \"resumed\", \"unknown\"]),\n content: contentFactSchema.optional(),\n turnIndex: z.number().int().min(0).optional(),\n /** The git worktree the session runs in, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const generationStartEventSchema = event({\n type: z.literal(\"generation.start\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n requestedMaxOutputTokens: tokenCountSchema.optional(),\n inputContent: contentFactsSchema.optional(),\n});\n\nexport const generationEndEventSchema = event({\n type: z.literal(\"generation.end\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n outcome: outcomeSchema,\n stopReason: nonEmptyStringSchema.optional(),\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n /**\n * True when `usage` is known to cover only part of the generation (for\n * example the last model request of a multi-request turn); false when the\n * provider or harness said it is the whole. Absent: not stated. Meaningless\n * without `usage`.\n */\n usagePartial: z.boolean().optional(),\n cost: costFactsSchema.optional(),\n outputContent: contentFactsSchema.optional(),\n});\n\nexport const toolKindSchema = z.enum([\n \"read\",\n \"write\",\n \"execute\",\n \"search\",\n \"network\",\n \"delegate\",\n \"other\",\n \"unknown\",\n]);\nexport type ToolKind = z.infer<typeof toolKindSchema>;\n\nexport const toolStartEventSchema = event({\n type: z.literal(\"tool.start\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n toolKind: toolKindSchema,\n generationId: nonEmptyStringSchema.optional(),\n input: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const toolEndEventSchema = event({\n type: z.literal(\"tool.end\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n /** Present when the host asked for or recorded a permission decision. */\n permissionDecision: z.enum([\"allowed\", \"denied\", \"deferred\", \"not-required\"]).optional(),\n output: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const subagentStartEventSchema = event({\n type: z.literal(\"subagent.start\"),\n subagentInvocationId: invocationIdSchema,\n subagentType: nonEmptyStringSchema.optional(),\n /** 0 for the top-level agent; 1 for its direct children. */\n delegationDepth: z.number().int().min(0).max(64),\n model: modelDescriptorSchema.optional(),\n});\n\nexport const subagentEndEventSchema = event({\n type: z.literal(\"subagent.end\"),\n subagentInvocationId: invocationIdSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const compactionPerformedEventSchema = event({\n type: z.literal(\"compaction.performed\"),\n trigger: z.enum([\"automatic\", \"manual\", \"unknown\"]),\n /** Provider-reported context size before and after compaction, if known. */\n contextTokensBefore: tokenCountSchema.optional(),\n contextTokensAfter: tokenCountSchema.optional(),\n droppedMessageCount: z.number().int().min(0).optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const errorRaisedEventSchema = event({\n type: z.literal(\"error.raised\"),\n errorCode: otelHookErrorCodeSchema,\n severity: errorSeveritySchema,\n phase: errorPhaseSchema,\n retryable: z.boolean(),\n /** Error text is content: it is described, never embedded verbatim by default. */\n message: contentFactSchema.optional(),\n /** Non-sensitive, provider-agnostic short label. */\n detail: nonEmptyStringSchema.optional(),\n});\n\nexport const canonicalEventSchema = z.discriminatedUnion(\"type\", [\n sessionStartEventSchema,\n sessionEndEventSchema,\n promptSubmittedEventSchema,\n generationStartEventSchema,\n generationEndEventSchema,\n toolStartEventSchema,\n toolEndEventSchema,\n subagentStartEventSchema,\n subagentEndEventSchema,\n compactionPerformedEventSchema,\n errorRaisedEventSchema,\n]);\n\nexport type CanonicalEvent = z.infer<typeof canonicalEventSchema>;\nexport type CanonicalEventInput = z.input<typeof canonicalEventSchema>;\n\nexport type SessionStartEvent = z.infer<typeof sessionStartEventSchema>;\nexport type SessionEndEvent = z.infer<typeof sessionEndEventSchema>;\nexport type PromptSubmittedEvent = z.infer<typeof promptSubmittedEventSchema>;\nexport type GenerationStartEvent = z.infer<typeof generationStartEventSchema>;\nexport type GenerationEndEvent = z.infer<typeof generationEndEventSchema>;\nexport type ToolStartEvent = z.infer<typeof toolStartEventSchema>;\nexport type ToolEndEvent = z.infer<typeof toolEndEventSchema>;\nexport type SubagentStartEvent = z.infer<typeof subagentStartEventSchema>;\nexport type SubagentEndEvent = z.infer<typeof subagentEndEventSchema>;\nexport type CompactionPerformedEvent = z.infer<typeof compactionPerformedEventSchema>;\nexport type ErrorRaisedEvent = z.infer<typeof errorRaisedEventSchema>;\n\nexport type CanonicalEventOfType<TType extends CanonicalEventType> = Extract<\n CanonicalEvent,\n { type: TType }\n>;\n\n/**\n * The event types that may carry a resolved `target` (ADR 0008): a tool call\n * names the worktree it touched; a session start and a prompt name the one the\n * session runs in, so a consumer knows the session's place before its first\n * tool call.\n */\nexport const TARGETED_EVENT_TYPES = [\"session.start\", \"prompt.submitted\", \"tool.start\", \"tool.end\"] as const;\nexport type TargetedEventType = (typeof TARGETED_EVENT_TYPES)[number];\nexport type TargetedEvent = CanonicalEventOfType<TargetedEventType>;\n\nconst TARGETED: ReadonlySet<string> = new Set(TARGETED_EVENT_TYPES);\nexport const isTargetedEvent = (event: CanonicalEvent): event is TargetedEvent => TARGETED.has(event.type);\n\nexport type EventValidationResult =\n | { readonly status: \"ok\"; readonly event: CanonicalEvent }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nexport const validateCanonicalEvent = (value: unknown): EventValidationResult => {\n const parsed = canonicalEventSchema.safeParse(value);\n if (parsed.success) {\n return { status: \"ok\", event: parsed.data };\n }\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n};\n\n/** Parse or throw. Intended for fixtures and tests, not the hook path. */\nexport const parseCanonicalEvent = (value: unknown): CanonicalEvent =>\n canonicalEventSchema.parse(value);\n\n/** Usage carried by an event, if the event type can carry any. */\nexport const eventUsage = (event: CanonicalEvent): CanonicalUsage | undefined =>\n \"usage\" in event ? event.usage : undefined;\n\n/** Stable ordering: by sequence, then by timestamp, then by event id. */\nexport const compareEvents = (a: CanonicalEvent, b: CanonicalEvent): number =>\n a.sequence - b.sequence || a.occurredAt - b.occurredAt || a.eventId.localeCompare(b.eventId);\n","import { z } from \"zod\";\n\n/**\n * Closed set of error codes. Adding a code is a minor change; changing what a\n * code means is a breaking change.\n */\nexport const otelHookErrorCodeSchema = z.enum([\n /** Input was not usable at all (empty stdin, unparsable JSON). */\n \"invalid-input\",\n /** Input parsed but failed canonical schema validation. */\n \"schema-validation-failed\",\n /** No adapter claimed the input with sufficient confidence. */\n \"provider-unknown\",\n /** Several adapters claimed the input at the same confidence. */\n \"provider-detection-ambiguous\",\n /** An adapter threw or returned a malformed result. */\n \"provider-adapter-failure\",\n /** Two identity claims disagreed at equal confidence. */\n \"identity-conflict\",\n /** Required identity fields were absent. */\n \"identity-incomplete\",\n /** A usage report violated the canonical usage invariants. */\n \"usage-invalid\",\n /** The state store could not be read or written. */\n \"state-store-failure\",\n /** The telemetry sink rejected or could not deliver a batch. */\n \"telemetry-export-failure\",\n /** Content reached the sink boundary in a state the policy forbids. */\n \"privacy-policy-violation\",\n /** Configuration could not be resolved. */\n \"configuration-invalid\",\n /** A configured bound (events, batch size) dropped data. */\n \"limit-exceeded\",\n /**\n * No replay-stable delivery identifier was available for a callback while\n * deduplication was required.\n */\n \"delivery-identifier-unavailable\",\n \"delivery-claim-superseded\",\n /** Anything unanticipated. Always reported, never fatal to the host. */\n \"internal-error\",\n]);\nexport type OtelHookErrorCode = z.infer<typeof otelHookErrorCodeSchema>;\n\nexport const errorSeveritySchema = z.enum([\"warning\", \"error\"]);\nexport type ErrorSeverity = z.infer<typeof errorSeveritySchema>;\n\n/** Pipeline stage where a failure occurred. */\nexport const errorPhaseSchema = z.enum([\n \"configuration\",\n \"detection\",\n \"identity\",\n \"parsing\",\n \"normalization\",\n \"privacy\",\n \"state\",\n \"export\",\n \"shutdown\",\n]);\nexport type ErrorPhase = z.infer<typeof errorPhaseSchema>;\n\n/**\n * Which of the two safety postures a code participates in.\n *\n * - `fail-open`: the hook still reports success to the host agent. Telemetry may\n * be incomplete; the coding agent is never blocked.\n * - `fail-closed-attribution`: the observation is not attributed to a session or\n * provider. Data is dropped rather than labelled with a guess.\n */\nexport const failurePostureSchema = z.enum([\"fail-open\", \"fail-closed-attribution\"]);\nexport type FailurePosture = z.infer<typeof failurePostureSchema>;\n\nexport type ErrorCodeDescriptor = {\n readonly code: OtelHookErrorCode;\n readonly severity: ErrorSeverity;\n readonly posture: FailurePosture;\n /** Whether retrying the same input could succeed. */\n readonly retryable: boolean;\n readonly summary: string;\n};\n\nexport const ERROR_TAXONOMY: Readonly<Record<OtelHookErrorCode, ErrorCodeDescriptor>> =\n Object.freeze({\n \"invalid-input\": {\n code: \"invalid-input\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Input could not be read or decoded.\",\n },\n \"schema-validation-failed\": {\n code: \"schema-validation-failed\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"A canonical event failed schema validation and was dropped.\",\n },\n \"provider-unknown\": {\n code: \"provider-unknown\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"No adapter recognized the source provider; the input stays unattributed.\",\n },\n \"provider-detection-ambiguous\": {\n code: \"provider-detection-ambiguous\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Multiple adapters claimed the input at equal confidence.\",\n },\n \"provider-adapter-failure\": {\n code: \"provider-adapter-failure\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A provider adapter failed while parsing.\",\n },\n \"identity-conflict\": {\n code: \"identity-conflict\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Identity claims disagreed; attribution was declined.\",\n },\n \"identity-incomplete\": {\n code: \"identity-incomplete\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Required identity fields were missing; attribution was declined.\",\n },\n \"usage-invalid\": {\n code: \"usage-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A usage report violated the canonical usage invariants.\",\n },\n \"state-store-failure\": {\n code: \"state-store-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"State could not be read or written; derived values may be incomplete.\",\n },\n \"telemetry-export-failure\": {\n code: \"telemetry-export-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"The telemetry sink could not accept a batch.\",\n },\n \"privacy-policy-violation\": {\n code: \"privacy-policy-violation\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Content violated the resolved privacy policy and was dropped.\",\n },\n \"configuration-invalid\": {\n code: \"configuration-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Configuration could not be resolved; defaults apply.\",\n },\n \"limit-exceeded\": {\n code: \"limit-exceeded\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A configured bound was reached and data was dropped.\",\n },\n \"delivery-identifier-unavailable\": {\n code: \"delivery-identifier-unavailable\",\n severity: \"warning\",\n // Fail-open: the observation is still attributed and exported. Only the\n // at-most-once guarantee is missing, and refusing the telemetry to protect\n // a duplicate count would trade a certain loss for a possible one.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"No replay-stable delivery identifier was available; this callback was exported without deduplication.\",\n },\n \"delivery-claim-superseded\": {\n code: \"delivery-claim-superseded\",\n severity: \"warning\",\n // Fail-open, and specifically *not* silent. A peer reclaimed this callback's\n // claim while this process was still working on it, which means the\n // configured stale window is shorter than this installation's real worst\n // case. Both processes may now have exported the callback, so the\n // at-most-once guarantee did not hold for it — the only honest response is\n // to say so and let the operator raise the window.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"A delivery claim was reclaimed by another process before this one committed; the callback may have been exported twice.\",\n },\n \"internal-error\": {\n code: \"internal-error\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"An unexpected failure was contained.\",\n },\n });\n\nexport const describeErrorCode = (code: OtelHookErrorCode): ErrorCodeDescriptor =>\n ERROR_TAXONOMY[code];\n\n/** Outcome of attributing an observation to a provider and session. */\nexport const attributionOutcomeSchema = z.enum([\n /** Identity resolved; events carry provider and session identity. */\n \"attributed\",\n /** Identity could not be established safely; nothing was attributed. */\n \"declined\",\n /** Attribution was attempted and failed unexpectedly. */\n \"failed\",\n /** Input was recognized but intentionally carried no telemetry. */\n \"not-applicable\",\n]);\nexport type AttributionOutcome = z.infer<typeof attributionOutcomeSchema>;\n\nexport const attributionReasonSchema = z.enum([\n \"provider-unknown\",\n \"provider-detection-ambiguous\",\n \"identity-conflict\",\n \"identity-incomplete\",\n \"adapter-ignored-input\",\n \"adapter-failure\",\n \"invalid-input\",\n \"internal-error\",\n]);\nexport type AttributionReason = z.infer<typeof attributionReasonSchema>;\n"],"mappings":";AAAA,SAAS,SAAS;AAYX,IAAM,2BAA2B;AAIjC,IAAM,+BAA+B,EAAE,QAAQ,wBAAwB;;;AChB9E,SAAS,KAAAA,UAAS;AAGX,IAAM,wBAAwB;AAG9B,IAAM,8BAA8B;AAGpC,IAAM,6BAA6B;AAEnC,IAAM,uBAAuBA,GAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,qBAAqB;AAGxE,IAAM,oBAAoBA,GAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,MAAqB;AAI3E,IAAM,uBAAuBA,GAAE,OAAO,EAAE,IAAI,CAAC,EAAE,OAAO;AAGtD,IAAM,mBAAmBA,GAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAG/C,IAAM,uBAAuBA,GAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAE1D,IAAM,kBAAkB,MAAmBA,GAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,qBAAqB;AAE/E,IAAM,qBAAqB,gBAAgB,EAAE,MAAsB;AAGnE,IAAM,kBAAkB,gBAAgB,EAAE,MAAmB;AAG7D,IAAM,gBAAgB,gBAAgB,EAAE,MAAiB;AAQzD,IAAM,uBAAuB;AAC7B,IAAM,oBAAoBA,GAC9B,OAAO,EACP,MAAM,sBAAsB,0DAA0D,EACtF,MAAqB;AAIjB,IAAM,sBAAsB;AAC5B,IAAM,mBAAmBA,GAC7B,OAAO,EACP,IAAI,CAAC,E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;AAAA,IACR,QAAQ,OAAO,MAAM,OAAO;AAAA,MAC1B,CAAC,UAAU,GAAG,MAAM,KAAK,KAAK,GAAG,KAAK,QAAQ,KAAK,MAAM,OAAO;AAAA,IAClE;AAAA,EACF;AACF;AAGO,IAAM,sBAAsB,CAAC,UAClC,qBAAqB,MAAM,KAAK;AAG3B,IAAM,aAAa,CAACA,WACzB,WAAWA,SAAQA,OAAM,QAAQ;AAG5B,IAAM,gBAAgB,CAAC,GAAmB,MAC/C,EAAE,WAAW,EAAE,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,QAAQ,cAAc,EAAE,OAAO;","names":["z","z","z","z","z","z","z","z","z","parsed","z","z","z","z","z","z","event"]}
@@ -1,7 +1,7 @@
1
1
  import * as zod from 'zod';
2
2
  import { z } from 'zod';
3
3
  import { g as ProviderId } from './primitives-CJ8-rn-f.js';
4
- import { d as ProviderCapabilities, P as ProviderAdapter } from './adapter-DiLknaTF.js';
4
+ import { d as ProviderCapabilities, P as ProviderAdapter } from './adapter-DQiPu8xF.js';
5
5
 
6
6
  /** Stable, hyphenated provider id for Claude Code. */
7
7
  declare const CLAUDE_CODE_PROVIDER_ID: string & zod.$brand<"ProviderId">;
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { OtelHookErrorInfo } from './errors.js';
3
- import { b as CanonicalEvent, J as WorktreeKind } from './events-CSD_YiJ2.js';
3
+ import { b as CanonicalEvent, J as WorktreeKind } from './events-fcomX6d5.js';
4
4
  import { E as EpochMillis, I as InvocationId, d as EventId, b as Attributes } from './primitives-CJ8-rn-f.js';
5
5
 
6
6
  /**
@@ -307,5 +307,36 @@ interface PayloadEnricher {
307
307
  readonly providerId: string;
308
308
  enrich(input: PayloadEnrichmentInput): Promise<PayloadEnrichment>;
309
309
  }
310
+ /**
311
+ * One window of a session's context: the attributes in force from `from`
312
+ * (inclusive) until `to` (exclusive), or open-ended when `to` is `null`.
313
+ * Attributes are already screened (see `sanitizeSessionContextAttributes`).
314
+ */
315
+ type SessionContextSegment = {
316
+ readonly from: EpochMillis;
317
+ readonly to: EpochMillis | null;
318
+ readonly attributes: Readonly<Record<string, string | number | boolean>>;
319
+ };
320
+ type SessionContextRequest = {
321
+ /** The detected provider, e.g. `claude-code`. The reader maps it to its directory name. */
322
+ readonly providerId: string;
323
+ /**
324
+ * The session whose context applies: always the invocation's session, which
325
+ * for a subagent event is its parent's — never the subagent's own id.
326
+ */
327
+ readonly sessionId: string;
328
+ };
329
+ /**
330
+ * Reads the session context a harness wrote for one agent session.
331
+ *
332
+ * A port for the same reason {@link WorktreeLocator} is one: the core decides
333
+ * when to ask and what of the answer reaches a record; the implementation only
334
+ * reads. Adapters never see it (ADR 0003). Implementations must never throw or
335
+ * reject: no file, an unreadable file, an invalid one, or one of an unknown
336
+ * version are all `undefined`, and the core then stamps nothing.
337
+ */
338
+ interface SessionContextReader {
339
+ read(request: SessionContextRequest): Promise<readonly SessionContextSegment[] | undefined>;
340
+ }
310
341
 
311
- export { type AppliedDelivery as A, type Clock as C, type EventIdSeed as E, type IdGenerator as I, LOG_LEVEL_RANK as L, type PayloadEnricher as P, type ReadCursor as R, type StateRecord as S, type TelemetryEmitResult as T, type WorktreeLocator as W, type InvocationIdSeed as a, type LocatedWorktree as b, type LogLevel as c, type Logger as d, type PayloadEnrichment as e, type PayloadEnrichmentInput as f, type StateStore as g, type StateValue as h, type TelemetrySink as i, appliedDeliverySchema as j, stateValueSchema as k, logLevelSchema as l, stateRecordSchema as s };
342
+ export { type AppliedDelivery as A, type Clock as C, type EventIdSeed as E, type IdGenerator as I, LOG_LEVEL_RANK as L, type PayloadEnricher as P, type ReadCursor as R, type SessionContextReader as S, type TelemetryEmitResult as T, type WorktreeLocator as W, type InvocationIdSeed as a, type LocatedWorktree as b, type LogLevel as c, type Logger as d, type PayloadEnrichment as e, type PayloadEnrichmentInput as f, type SessionContextRequest as g, type SessionContextSegment as h, type StateRecord as i, type StateStore as j, type StateValue as k, type TelemetrySink as l, appliedDeliverySchema as m, logLevelSchema as n, stateValueSchema as o, stateRecordSchema as s };
@@ -1,23 +1,23 @@
1
- import { e as ProviderContext, P as ProviderAdapter, d as ProviderCapabilities, b as DeliveryIdentifierSupport, A as AdapterDescription } from './adapter-DiLknaTF.js';
2
- export { D as DELIVERY_COMPONENT_PATTERN, a as DELIVERY_GAP_REASON_PATTERN, M as MAX_DELIVERY_COMPONENTS, c as MAX_DELIVERY_GAPS, f as ProviderDeliveryClaim, g as ProviderDeliveryGaps, h as ProviderDetection, i as ProviderDetectionInput, j as ProviderHookResponse, k as ProviderHookResponseInput, l as ProviderIdentityInput, m as ProviderParseInput, n as ProviderParseResult, S as SILENT_HOOK_RESPONSE, o as adapterSupports, p as asProviderId, q as deliveryComponentSchema, r as deliveryGapReasonSchema, s as deliveryIdentifierSupportSchema, t as describeAdapter, u as providerCapabilitiesSchema, v as providerDeliveryClaimSchema, w as providerDeliveryGapsSchema, x as providerDetectionSchema, y as providerHookResponseSchema, z as readDeliveryClaim, B as readDeliveryGap, C as unknownDetection } from './adapter-DiLknaTF.js';
3
- import { b as CanonicalEvent, u as TargetHint, q as SessionStartEvent, p as SessionEndEvent, P as PromptSubmittedEvent, l as GenerationStartEvent, G as GenerationEndEvent, A as ToolStartEvent, y as ToolEndEvent, t as SubagentStartEvent, r as SubagentEndEvent, g as CompactionPerformedEvent, i as ErrorRaisedEvent } from './events-CSD_YiJ2.js';
1
+ import { e as ProviderContext, P as ProviderAdapter, d as ProviderCapabilities, b as DeliveryIdentifierSupport, A as AdapterDescription } from './adapter-DQiPu8xF.js';
2
+ export { D as DELIVERY_COMPONENT_PATTERN, a as DELIVERY_GAP_REASON_PATTERN, M as MAX_DELIVERY_COMPONENTS, c as MAX_DELIVERY_GAPS, f as ProviderDeliveryClaim, g as ProviderDeliveryGaps, h as ProviderDetection, i as ProviderDetectionInput, j as ProviderHookResponse, k as ProviderHookResponseInput, l as ProviderIdentityInput, m as ProviderParseInput, n as ProviderParseResult, S as SILENT_HOOK_RESPONSE, o as adapterSupports, p as asProviderId, q as deliveryComponentSchema, r as deliveryGapReasonSchema, s as deliveryIdentifierSupportSchema, t as describeAdapter, u as providerCapabilitiesSchema, v as providerDeliveryClaimSchema, w as providerDeliveryGapsSchema, x as providerDetectionSchema, y as providerHookResponseSchema, z as readDeliveryClaim, B as readDeliveryGap, C as unknownDetection } from './adapter-DQiPu8xF.js';
3
+ import { b as CanonicalEvent, u as TargetHint, q as SessionStartEvent, p as SessionEndEvent, P as PromptSubmittedEvent, l as GenerationStartEvent, G as GenerationEndEvent, A as ToolStartEvent, y as ToolEndEvent, t as SubagentStartEvent, r as SubagentEndEvent, g as CompactionPerformedEvent, i as ErrorRaisedEvent } from './events-fcomX6d5.js';
4
4
  import { d as InvocationIdentity } from './identity-BrVBs901.js';
5
5
  import { d as EventId } from './primitives-CJ8-rn-f.js';
6
- import { P as ProviderRegistry } from './registry-CcJNF3WY.js';
7
- export { B as BUILT_IN_PROVIDERS, D as DetectionCandidate, R as RegistryDetectionResult, c as createProviderRegistry } from './registry-CcJNF3WY.js';
8
- import { v as ClaudeUsage } from './payload-ChtrEX6A.js';
9
- export { A as ANTIGRAVITY_CAPABILITIES, a as ANTIGRAVITY_HOOK_EVENT_NAMES, b as ANTIGRAVITY_PROVIDER_ID, c as AntigravityAdapterOptions, d as AntigravityHookEventName, C as CLAUDE_CODE_PROVIDER_ID, e as CLAUDE_HOOK_EVENT_NAMES, f as CODEX_ADAPTER_VERSION, g as CODEX_HOOK_EVENT_NAMES, h as CODEX_PROVIDER_ID, i as CURSOR_DECISION_EVENTS, j as CURSOR_HOOK_EVENT_NAMES, k as CURSOR_PROVIDER_ID, l as CURSOR_UNMODELLED_HOOK_EVENT_NAMES, m as ClaudeHookEventName, n as CodexHookEventName, o as CursorHookEventName, D as DEFAULT_GEMINI_CAPABILITIES, G as GEMINI_ADAPTER_VERSION, p as GEMINI_HOOK_EVENT_NAMES, q as GEMINI_PROVIDER_ID, r as GeminiAdapterOptions, s as GeminiHookEventName, t as createAntigravityAdapter, u as createGeminiCliAdapter } from './payload-ChtrEX6A.js';
10
- import { P as PayloadEnricher } from './ports-CeqLq31i.js';
6
+ import { P as ProviderRegistry } from './registry-gyJqaWmp.js';
7
+ export { B as BUILT_IN_PROVIDERS, D as DetectionCandidate, R as RegistryDetectionResult, c as createProviderRegistry } from './registry-gyJqaWmp.js';
8
+ import { v as ClaudeUsage } from './payload-BT19hiVZ.js';
9
+ export { A as ANTIGRAVITY_CAPABILITIES, a as ANTIGRAVITY_HOOK_EVENT_NAMES, b as ANTIGRAVITY_PROVIDER_ID, c as AntigravityAdapterOptions, d as AntigravityHookEventName, C as CLAUDE_CODE_PROVIDER_ID, e as CLAUDE_HOOK_EVENT_NAMES, f as CODEX_ADAPTER_VERSION, g as CODEX_HOOK_EVENT_NAMES, h as CODEX_PROVIDER_ID, i as CURSOR_DECISION_EVENTS, j as CURSOR_HOOK_EVENT_NAMES, k as CURSOR_PROVIDER_ID, l as CURSOR_UNMODELLED_HOOK_EVENT_NAMES, m as ClaudeHookEventName, n as CodexHookEventName, o as CursorHookEventName, D as DEFAULT_GEMINI_CAPABILITIES, G as GEMINI_ADAPTER_VERSION, p as GEMINI_HOOK_EVENT_NAMES, q as GEMINI_PROVIDER_ID, r as GeminiAdapterOptions, s as GeminiHookEventName, t as createAntigravityAdapter, u as createGeminiCliAdapter } from './payload-BT19hiVZ.js';
10
+ import { P as PayloadEnricher } from './ports-C3k_5eOQ.js';
11
11
  import 'zod';
12
12
  import './errors.js';
13
13
  import './taxonomy-DwhTtuWd.js';
14
14
  import './policy-CimmCfRp.js';
15
15
  import './content-M9xIKG7h.js';
16
16
  import './service-CbI9CObT.js';
17
- import './schema-DMnoU1V_.js';
17
+ import './schema-SpFM6YQY.js';
18
18
 
19
19
  /** Fields the factory supplies; an adapter never sets them itself. */
20
- type ManagedFields = "schemaVersion" | "eventId" | "invocationId" | "sessionId" | "sequence" | "provenance" | "workspace" | "extensions" | "subagentId" | "target" | "occurredAt";
20
+ type ManagedFields = "schemaVersion" | "eventId" | "invocationId" | "sessionId" | "sequence" | "provenance" | "workspace" | "extensions" | "subagentId" | "contextAttributes" | "target" | "occurredAt";
21
21
  type Draft<TEvent extends CanonicalEvent> = Omit<TEvent, ManagedFields> & {
22
22
  /** Defaults to the clock reading at build time. */
23
23
  readonly occurredAt?: number;